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 does "pip install" raise a SyntaxError? | 8,548,030 | 67 | 2011-12-17T21:23:32Z | 17,141,376 | 43 | 2013-06-17T06:14:19Z | [
"python",
"pip"
] | I'm trying to use pip to install a package. I try to run `pip install` from the Python shell, but I get a `SyntaxError`. Why do I get this error? How do I use pip to install the package?
```
>>> pip install selenium
^
SyntaxError: invalid syntax
``` | Use the command line, not the Python shell (DOS, PowerShell in Windows, Terminal in Mac or Linux).
```
C:\Program Files\Python2.7\Scripts> pip install XYZ
``` |
Why does "pip install" raise a SyntaxError? | 8,548,030 | 67 | 2011-12-17T21:23:32Z | 31,867,014 | 20 | 2015-08-06T22:47:03Z | [
"python",
"pip"
] | I'm trying to use pip to install a package. I try to run `pip install` from the Python shell, but I get a `SyntaxError`. Why do I get this error? How do I use pip to install the package?
```
>>> pip install selenium
^
SyntaxError: invalid syntax
``` | To run pip as of Python 3.4, just follow the instructions on Python's page: [Installing Python Modules](https://docs.python.org/3/installing/).
```
python -m pip install SomePackage
``` |
Is there a way for BaseRequestHandler classes to be statful? | 8,549,177 | 4 | 2011-12-18T01:17:39Z | 8,549,272 | 7 | 2011-12-18T01:44:36Z | [
"python",
"sockets",
"namespaces",
"socketserver"
] | **Short Question**
Using my examples below, is there a Pythonic way to share `my_object`'s actual instance with with the BaseRequestHandler class?
**Background**
By definition, the BaseRequestHandler class creates a new instance for each request. Because of this, I am struggling to try find a solution on how to ge... | You could pass the object through the server instance:
```
self.server = SocketServer.TCPServer((self.host, self.port), ProtocolHandler)
self.server.my_object = self.my_object
```
The [documentation](http://docs.python.org/library/socketserver.html#server-objects) indicates that you can have access to the server inst... |
Formatting text output with Scrapy in Python | 8,549,875 | 4 | 2011-12-18T04:45:44Z | 8,550,397 | 8 | 2011-12-18T07:15:21Z | [
"python",
"text",
"web-scraping",
"scrapy"
] | I'm trying to scrape pages using a Scrapy spider and then save those pages into a .txt file in a readable form. The code I'm using to do this is:
```
def parse_item(self, response):
self.log('Hi, this is an item page! %s' % response.url)
hxs = HtmlXPathSelector(response)
title = hxs.select('... | My answer in comments for code:
```
import re
import codecs
#...
#...
#extract() returns list, so you need to take first element
title = hxs.select('/html/head/title/text()').extract() [0]
content = hxs.select('//*[@id="content"]')
#instead of using BeautifulSoup for this task, you can use folowing
content = content.... |
How do setuptools, distribute, and pip relate to one another? | 8,550,062 | 33 | 2011-12-18T05:47:39Z | 8,550,546 | 56 | 2011-12-18T08:04:28Z | [
"python",
"pip",
"setuptools",
"distribute"
] | I've been teaching myself Python through the book "Learn Python The Hard Way" (2nd Edition). In exercise 46 it told me to read up on Pip, Distribute, and a few other packages.
The documentation for pip was clear enough. It allows me to install/uninstall, and upgrade packages. Reading the documentation for distribute, ... | [***2014-10 TL;DR:***
`distribute` is dead, use `pip`, the new `setuptools`, and, for binary distributions, `wheels`. More below.]
---
**[Original answer]**
[Distribute](http://pypi.python.org/pypi/distribute) ~~is~~ was a fork of the older [setuptools](http://pypi.python.org/pypi/setuptools) so nearly all comments ... |
Can scrapy be used to scrape dynamic content from websites that are using AJAX? | 8,550,114 | 75 | 2011-12-18T06:03:11Z | 8,594,831 | 53 | 2011-12-21T18:51:42Z | [
"javascript",
"python",
"ajax",
"screen-scraping",
"scrapy"
] | I have recently been learning Python and am dipping my hand into building a web-scraper. It's nothing fancy at all; its only purpose is to get the data off of a betting website and have this data put into Excel.
Most of the issues are solvable and I'm having a good little mess around. However I'm hitting a massive hur... | Webkit based browsers (like Google Chrome or Safari) has built-in developer tools. In Chrome you can open it `Menu->Tools->Developer Tools`. The `Network` tab allows you to see all information about every request and response:

In the bottom of the pi... |
Can scrapy be used to scrape dynamic content from websites that are using AJAX? | 8,550,114 | 75 | 2011-12-18T06:03:11Z | 14,136,641 | 56 | 2013-01-03T10:05:36Z | [
"javascript",
"python",
"ajax",
"screen-scraping",
"scrapy"
] | I have recently been learning Python and am dipping my hand into building a web-scraper. It's nothing fancy at all; its only purpose is to get the data off of a betting website and have this data put into Excel.
Most of the issues are solvable and I'm having a good little mess around. However I'm hitting a massive hur... | Here is a simple example of using scrapy with ajax request.
Let see the site <http://www.rubin-kazan.ru/guestbook.html> All messages are loaded with an ajax request. My goal is to fetch this messages with all their attributes (author, date, ...).

Whe... |
Can scrapy be used to scrape dynamic content from websites that are using AJAX? | 8,550,114 | 75 | 2011-12-18T06:03:11Z | 17,697,329 | 24 | 2013-07-17T10:27:39Z | [
"javascript",
"python",
"ajax",
"screen-scraping",
"scrapy"
] | I have recently been learning Python and am dipping my hand into building a web-scraper. It's nothing fancy at all; its only purpose is to get the data off of a betting website and have this data put into Excel.
Most of the issues are solvable and I'm having a good little mess around. However I'm hitting a massive hur... | Many times when crawling we run into problems where content that is rendered on the page is generated with Javascript and therefore scrapy is unable to crawl for it (eg. ajax requests, jQuery craziness).
However, if you use Scrapy along with the web testing framework Selenium then we are able to crawl anything display... |
Can scrapy be used to scrape dynamic content from websites that are using AJAX? | 8,550,114 | 75 | 2011-12-18T06:03:11Z | 24,373,576 | 15 | 2014-06-23T19:12:54Z | [
"javascript",
"python",
"ajax",
"screen-scraping",
"scrapy"
] | I have recently been learning Python and am dipping my hand into building a web-scraper. It's nothing fancy at all; its only purpose is to get the data off of a betting website and have this data put into Excel.
Most of the issues are solvable and I'm having a good little mess around. However I'm hitting a massive hur... | Another solution would be to implement a download handler or download handler middleware. The following is an example of middleware using selenium with headless phantomjs webdriver:
```
class JsDownload(object):
@check_spider_middleware
def process_request(self, request, spider):
driver = webdriver.PhantomJS(exec... |
python dictionary of dictionaries | 8,550,912 | 8 | 2011-12-18T09:46:03Z | 8,550,942 | 11 | 2011-12-18T09:52:18Z | [
"python",
"dictionary"
] | From another function, I have tuples like this `('falseName', 'realName', positionOfMistake)`, eg. `('Milter', 'Miller', 4)`.
I need to write a function that make a dictionary like this:
```
D={realName:{falseName:[positionOfMistake], falseName:[positionOfMistake]...},
realName:{falseName:[positionOfMistake]...}..... | If it is only to add a new tuple and you are sure that there is no collisions in the inner dictionary you can do this:
```
def addNameToDictionary(d, tup):
if tup[0] not in d:
d[tup[0]] = {}
d[tup[0]][tup[1]] = [tup[2]]
``` |
python dictionary of dictionaries | 8,550,912 | 8 | 2011-12-18T09:46:03Z | 8,550,946 | 10 | 2011-12-18T09:52:56Z | [
"python",
"dictionary"
] | From another function, I have tuples like this `('falseName', 'realName', positionOfMistake)`, eg. `('Milter', 'Miller', 4)`.
I need to write a function that make a dictionary like this:
```
D={realName:{falseName:[positionOfMistake], falseName:[positionOfMistake]...},
realName:{falseName:[positionOfMistake]...}..... | Using `collections.defaultdict` is a big time-saver when you're building dicts and don't know beforehand which keys you're going to have.
Here it's used twice: for the resulting dict, and for each of the values in the dict.
```
import collections
def aggregate_names(errors):
result = collections.defaultdict(lamb... |
python dictionary of dictionaries | 8,550,912 | 8 | 2011-12-18T09:46:03Z | 8,551,025 | 7 | 2011-12-18T10:03:51Z | [
"python",
"dictionary"
] | From another function, I have tuples like this `('falseName', 'realName', positionOfMistake)`, eg. `('Milter', 'Miller', 4)`.
I need to write a function that make a dictionary like this:
```
D={realName:{falseName:[positionOfMistake], falseName:[positionOfMistake]...},
realName:{falseName:[positionOfMistake]...}..... | dictionary's setdefault is a good way to update an existing dict entry if it's there, or create a new one if it's not all in one go:
Looping style:
```
# This is our sample data
data = [("Milter", "Miller", 4), ("Milter", "Miler", 4), ("Milter", "Malter", 2)]
# dictionary we want for the result
dictionary = {}
# lo... |
Default Values for Models in Google App Engine | 8,551,602 | 6 | 2011-12-18T12:09:45Z | 8,551,643 | 8 | 2011-12-18T12:17:40Z | [
"python",
"google-app-engine",
"model",
"default-value"
] | Is it possible to set default values for models ? For example consider this model from Appengine Documentation
```
from google.appengine.ext import db
class Pet(db.Model):
name = db.StringProperty(required=True)
type = db.StringProperty(required=True, choices=set(["cat", "dog", "bird"]))
birthdate = db.Da... | Use the default attribute, e.g.
```
class Pet(db.Model):
name = db.StringProperty(required=True, default="(unnamed)")
``` |
How do I run Python code from Sublime Text 2? | 8,551,735 | 236 | 2011-12-18T12:36:37Z | 8,552,149 | 286 | 2011-12-18T13:49:54Z | [
"python",
"ide",
"sublimetext2",
"sublimetext"
] | I want to set up a complete Python IDE in Sublime Text 2.
I want to know how to run the Python code from within the editor. Is it done using build system? How do I do it ? | Tools -> Build System -> (choose) Python then:
**To Run:**
```
Tools -> Build
-or-
Ctrl + B
CMD + B (OSX)
```
*This would start your file in the console which should be at the bottom of the editor.*
**To Stop:**
```
Ctrl + Break or Tools -> Cancel Build
```
You can find out wher... |
How do I run Python code from Sublime Text 2? | 8,551,735 | 236 | 2011-12-18T12:36:37Z | 9,607,682 | 52 | 2012-03-07T19:19:38Z | [
"python",
"ide",
"sublimetext2",
"sublimetext"
] | I want to set up a complete Python IDE in Sublime Text 2.
I want to know how to run the Python code from within the editor. Is it done using build system? How do I do it ? | Edit %APPDATA%\Sublime Text 2\Python\Python.sublime-build
Change content to:
```
{
"cmd": ["C:\\python27\\python.exe", "-u", "$file"],
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"selector": "source.python"
}
```
change the "c:\python27" part to any version of python you have in your system. |
How do I run Python code from Sublime Text 2? | 8,551,735 | 236 | 2011-12-18T12:36:37Z | 11,619,129 | 9 | 2012-07-23T19:25:38Z | [
"python",
"ide",
"sublimetext2",
"sublimetext"
] | I want to set up a complete Python IDE in Sublime Text 2.
I want to know how to run the Python code from within the editor. Is it done using build system? How do I do it ? | You can use [SublimeREPL](https://packagecontrol.io/packages/SublimeREPL) (you need to have [Package Control](https://packagecontrol.io) installed first). |
How do I run Python code from Sublime Text 2? | 8,551,735 | 236 | 2011-12-18T12:36:37Z | 14,833,803 | 40 | 2013-02-12T13:35:12Z | [
"python",
"ide",
"sublimetext2",
"sublimetext"
] | I want to set up a complete Python IDE in Sublime Text 2.
I want to know how to run the Python code from within the editor. Is it done using build system? How do I do it ? | **To RUN** press `Ctrl``B` (answer by [matiit](http://stackoverflow.com/a/8552149/985454))
But when `Ctrl``B` **does not work**, Sublime Text probably can't find the Python Interpreter. When trying to run your program, see the log and find the reference to Python in path.
```
[cmd: [u'python', u'-u', u'C:\\scripts\\... |
How do I run Python code from Sublime Text 2? | 8,551,735 | 236 | 2011-12-18T12:36:37Z | 17,111,996 | 36 | 2013-06-14T15:26:27Z | [
"python",
"ide",
"sublimetext2",
"sublimetext"
] | I want to set up a complete Python IDE in Sublime Text 2.
I want to know how to run the Python code from within the editor. Is it done using build system? How do I do it ? | On Mac OS X, save your file with a .py extension. Press â+B. It runs in a window below.
 |
How to get last record | 8,551,952 | 20 | 2011-12-18T13:13:32Z | 8,551,979 | 47 | 2011-12-18T13:19:06Z | [
"python",
"sqlalchemy",
"flask"
] | I need to get last record from db. I'm using sqlalchemy.
At the moment, i'm doing like that:
```
obj = ObjectRes.query.all()
return str(obj[-1].id)
```
But it's too heavy query. How can i get last record better? | Take a look at [`Query.first()`](http://www.sqlalchemy.org/docs/orm/query.html#sqlalchemy.orm.query.Query.first). If you specify a [sort](http://www.sqlalchemy.org/docs/orm/query.html#sqlalchemy.orm.query.Query.order_by) on the right column, the first will be your last. An example could look like this:
```
obj = sessi... |
Form sending error, Flask | 8,552,675 | 36 | 2011-12-18T15:20:52Z | 8,557,394 | 54 | 2011-12-19T05:20:25Z | [
"python",
"forms",
"flask"
] | There is form with two `<input type="submit">`. But when i'm sending it, second submit causes error.
*layout*:
```
<form action="{{ url_for('index') }}" method="post">
<input type="submit" name="add" value="Like">
<input type="submit" name="remove" value="Dislike">
</form>
```
*main.py*:
```
...
if request.... | As @Blubber points out, the issue is that Flask raises an HTTP error when it fails to find a key in the `args` and `form` dictionaries. What Flask assumes by default is that if you are asking for a particular key *and it's not there* then something got left out of the request and the entire request is invalid.
There a... |
Remove all javascript tags and style tags from html with python and the lxml module | 8,554,035 | 11 | 2011-12-18T19:01:19Z | 8,554,251 | 32 | 2011-12-18T19:37:46Z | [
"python",
"html",
"lxml"
] | I am parsing an html document using the <http://lxml.de/> library. So far I have figured out how to strip tags from an html document [In lxml, how do I remove a tag but retain all contents?](http://stackoverflow.com/questions/4681317/in-lxml-how-do-i-remove-a-tag-but-retain-all-contents) but the method described in tha... | Below is an example to do what you want. For an HTML document, `Cleaner` is a better general solution to the problem than using `strip_elements`, because in cases like this you want to strip out more than just the `<script>` tag; you also want to get rid of things like `onclick=function()` attributes on other tags.
``... |
Is this deque thread-safe in python? | 8,554,153 | 4 | 2011-12-18T19:20:47Z | 8,554,182 | 11 | 2011-12-18T19:26:17Z | [
"python",
"thread-safety",
"deque"
] | I can't decide whether the following deque is thread-safe.
In short, I've created a class with a deque that displays its contents every 1 sec in a new thread (so it won't pause the main program while printing).
The deque is filled from the main thread, so basically there SHOULD be a chance of collision.
HOWEVER, ... | Deque is thread-safe (<http://docs.python.org/library/collections.html#deque-objects>) for appends and pops from opposite sides. [Beneath here](https://docs.python.org/2/library/queue.html#Queue.Full), the docs only mention that append() and popleft() are thread-safe.
There is a thread-safe implementation of the Queue... |
Creating a PNG file in Python | 8,554,282 | 6 | 2011-12-18T19:42:56Z | 25,835,368 | 19 | 2014-09-14T16:21:29Z | [
"python",
"image",
"png"
] | I have an application where I would like to be able to generate PNG images from data in Python. I've done some searching and found "PIL" which looked pretty outdated. Is there some other library that would be better for this?
Thanks, | Simple PNG files can be generated quite easily from pure Python code - all you need is the standard zlib module and some bytes-encoding to write the chunks. Here is a complete example that the casual reader may use as a starter for its own png generator:
```
#! /usr/bin/python
""" Converts a list of list into gray-sca... |
Personalizing Online Assignments for a Statistics Class | 8,554,562 | 14 | 2011-12-18T20:27:54Z | 8,554,862 | 9 | 2011-12-18T21:14:42Z | [
"python",
"ruby-on-rails",
"ruby",
"exams"
] | I teach undergraduate statistics, and am interested in administering personalized online assignments. I have already solved one portion of the puzzle, the generation of multiple version of a question using `latex/markdown` + `knitr/sweave`, using `seeds`.
I am now interested in developing a web-based system, that woul... | The way you have worded your question it's not really clear why you have to mark the students' work *online*. Especially since you say that you generate assignments using sweave. If you use R to generate the (randomised) questions, then you really have to use R to mark them (or output the data set).
For my courses, I ... |
removing leading 0 from matplotlib tick label formatting | 8,555,652 | 4 | 2011-12-18T23:22:43Z | 8,555,837 | 8 | 2011-12-18T23:58:58Z | [
"python",
"plot",
"matplotlib"
] | How can I change the ticklabels of numeric decimal data (say between 0 and 1) to be "0", ".1", ".2" rather than "0.0", "0.1", "0.2" in matplotlib? For example,
```
hist(rand(100))
xticks([0, .2, .4, .6, .8])
```
will format the labels as "0.0", "0.2", etc. I know that this gets rid of the leading "0" from "0.0" and t... | Although I am not sure it is the best way, you can use a [`matplotlib.ticker.FuncFormatter`](http://matplotlib.sourceforge.net/api/ticker_api.html#matplotlib.ticker.FuncFormatter) to do this. For example, define the following function.
```
def my_formatter(x, pos):
"""Format 1 as 1, 0 as 0, and all values whose ab... |
Difference between xreadlines and for-looping a file | 8,555,722 | 11 | 2011-12-18T23:35:09Z | 8,555,746 | 16 | 2011-12-18T23:39:27Z | [
"python",
"file"
] | Having a file object in Python 2.7:
```
f = open('my_file', 'r')
```
What would be the difference between for-looping the file (most common way) and using the `xreadlines()` function:
```
for line in f:
# Do something with line
```
and
```
for line in f.xreadlines():
# Do something with line
```
I mean, b... | From [docs.python.org](http://docs.python.org/library/stdtypes.html?highlight=xreadlines#file.xreadlines)
```
file.xreadlines()
This method returns the same thing as iter(f).
New in version 2.1.
Deprecated since version 2.3: Use for line in file instead.
```
... and it's better to use the `with` keyword when workin... |
Python - How to extract the last x elements from a list | 8,556,076 | 16 | 2011-12-19T00:46:16Z | 8,556,080 | 41 | 2011-12-19T00:47:58Z | [
"python"
] | If the length of a python list is greater than a given value (say 10), then I want to extract the last 10 elements in that list into a new list.
How can I do this?
I tried getting the difference between len(my\_list) - 10 and use it as: new\_list = [(len(my\_list) - 10):] which does not work
Any suggestions?
Thanks in... | it's just as simple as:
```
my_list[-10:]
``` |
Python - How to extract the last x elements from a list | 8,556,076 | 16 | 2011-12-19T00:46:16Z | 8,556,144 | 9 | 2011-12-19T01:01:44Z | [
"python"
] | If the length of a python list is greater than a given value (say 10), then I want to extract the last 10 elements in that list into a new list.
How can I do this?
I tried getting the difference between len(my\_list) - 10 and use it as: new\_list = [(len(my\_list) - 10):] which does not work
Any suggestions?
Thanks in... | The Python tutorial has a section how to use list slicing: <http://docs.python.org/tutorial/introduction.html#lists>
In your case, it is as simple as writing:
```
new_list = my_list[-10:]
``` |
Python - How to extract the last x elements from a list | 8,556,076 | 16 | 2011-12-19T00:46:16Z | 8,556,149 | 7 | 2011-12-19T01:02:28Z | [
"python"
] | If the length of a python list is greater than a given value (say 10), then I want to extract the last 10 elements in that list into a new list.
How can I do this?
I tried getting the difference between len(my\_list) - 10 and use it as: new\_list = [(len(my\_list) - 10):] which does not work
Any suggestions?
Thanks in... | This shows how to chop a long list into a maximum size and put the rest in a new list. It's not exactly what you're asking about, but it may be what you really want:
```
>>> list1 = [10, 20, 30, 40, 50, 60, 70]
>>> max_size = 5
>>> list2 = list1[max_size:]
>>> list2
[60, 70]
>>> list1 = list1[:max_size]
>>> list1
[10,... |
What does & mean in python | 8,556,206 | 4 | 2011-12-19T01:15:18Z | 8,556,214 | 10 | 2011-12-19T01:16:50Z | [
"python"
] | Hi I came across the following code
```
numdigits = len(cardNumber)
oddeven = numdigits & 1
```
what exactly is going on here? I'm not sure what the "&" is doing. | ## Answer
The `&` symbol is a bitwise AND operator. Used with 1, it basically masks the value to extract the lowest bit, or in other words will tell you if the value is even or odd.
## More Info on Python's `&` operator
For more information, see: <http://wiki.python.org/moin/BitwiseOperators>
## Why it Works to che... |
how to subquery in queryset in django? | 8,556,297 | 16 | 2011-12-19T01:35:46Z | 8,556,387 | 10 | 2011-12-19T01:55:06Z | [
"python",
"django"
] | how can i have a subquery in django's queryset? for example if i have:
```
select name, age from person, employee where person.id = employee.id and
employee.id in (select id from employee where employee.company = 'Private')
```
this is what i have done yet.
```
Person.objects.value('name', 'age')
Employee.objects.fi... | ```
ids = Employee.objects.filter(company='Private').values_list('id', flat=True)
Person.objects.filter(id__in=ids).values('name', 'age')
``` |
how to subquery in queryset in django? | 8,556,297 | 16 | 2011-12-19T01:35:46Z | 20,873,877 | 14 | 2014-01-01T22:17:34Z | [
"python",
"django"
] | how can i have a subquery in django's queryset? for example if i have:
```
select name, age from person, employee where person.id = employee.id and
employee.id in (select id from employee where employee.company = 'Private')
```
this is what i have done yet.
```
Person.objects.value('name', 'age')
Employee.objects.fi... | as mentioned by ypercube your use case doesn't require subquery.
but anyway since many people land into this page to learn how to do sub-query here is how its done.
```
employee_query = Employee.objects.filter(company='Private').only('id').all()
Person.objects.value('name', 'age').filter(id__in=employee_query)
```
S... |
Generate RFC 3339 timestamp in Python | 8,556,398 | 22 | 2011-12-19T01:57:52Z | 8,556,555 | 18 | 2011-12-19T02:33:33Z | [
"python",
"datetime",
"iso8601",
"rfc3339"
] | I'm trying to generate an [RFC 3339](http://tools.ietf.org/html/rfc3339) UTC timestamp in Python. So far I've been able to do the following:
```
>>> d = datetime.datetime.now()
>>> print d.isoformat('T')
2011-12-18T20:46:00.392227
```
My problem is with setting the UTC offset.
According to the [docs](http://docs.pyt... | Timezones are a pain, which is probably why they chose not to include them in the datetime library.
try pytz, it has the tzinfo your looking for:
<http://pytz.sourceforge.net/>
Or, just use UTC, and throw a "Z" on the end to mark the "timezone" as UTC.
```
d = datetime.datetime.utcnow() # <-- get time in UTC
print d... |
Generate RFC 3339 timestamp in Python | 8,556,398 | 22 | 2011-12-19T01:57:52Z | 8,556,584 | 8 | 2011-12-19T02:38:44Z | [
"python",
"datetime",
"iso8601",
"rfc3339"
] | I'm trying to generate an [RFC 3339](http://tools.ietf.org/html/rfc3339) UTC timestamp in Python. So far I've been able to do the following:
```
>>> d = datetime.datetime.now()
>>> print d.isoformat('T')
2011-12-18T20:46:00.392227
```
My problem is with setting the UTC offset.
According to the [docs](http://docs.pyt... | [Further down](http://docs.python.org/library/datetime.html#tzinfo-objects) in the same doc that you linked to, it explains how to implement it, giving some examples, including full code for a `UTC` class (representing UTC), a `FixedOffset` class (representing a timezone with a fixed offset from UTC, as opposed to a ti... |
Generate RFC 3339 timestamp in Python | 8,556,398 | 22 | 2011-12-19T01:57:52Z | 27,987,813 | 7 | 2015-01-16T15:54:55Z | [
"python",
"datetime",
"iso8601",
"rfc3339"
] | I'm trying to generate an [RFC 3339](http://tools.ietf.org/html/rfc3339) UTC timestamp in Python. So far I've been able to do the following:
```
>>> d = datetime.datetime.now()
>>> print d.isoformat('T')
2011-12-18T20:46:00.392227
```
My problem is with setting the UTC offset.
According to the [docs](http://docs.pyt... | In Python 3.3+:
```
>>> from datetime import datetime, timezone
>>> local_time = datetime.now(timezone.utc).astimezone()
>>> local_time.isoformat()
'2015-01-16T16:52:58.547366+01:00'
```
On older Python versions, if all you need is an aware datetime object representing the current time... |
setuptools troubles -- excluding packages, including data files | 8,556,996 | 10 | 2011-12-19T04:06:24Z | 11,669,299 | 11 | 2012-07-26T12:27:56Z | [
"python",
"configuration",
"setuptools"
] | I'm fairly new to setuptools. I've seen a few similar questions and it drives a little bit insane that I've seemed to follow advice I saw but setuptools still does something different than what I want.
Here is the structure of my project:
```
.
..
package1/
__init__.py
abc.py
...
tests/
__init__.py
... | You should create a new file called `MANIFEST.in` in the root level of your package, then follow these instructions:
1. To control which files end up in your tar file, create a new file called `MANIFEST.in` in the root level of your package. For example, you can exclude whole directories from your distribution, using ... |
setuptools troubles -- excluding packages, including data files | 8,556,996 | 10 | 2011-12-19T04:06:24Z | 26,288,078 | 12 | 2014-10-09T21:20:23Z | [
"python",
"configuration",
"setuptools"
] | I'm fairly new to setuptools. I've seen a few similar questions and it drives a little bit insane that I've seemed to follow advice I saw but setuptools still does something different than what I want.
Here is the structure of my project:
```
.
..
package1/
__init__.py
abc.py
...
tests/
__init__.py
... | `find_packages` uses `fnmatchcase` for its exclude filtering. You can test if your exclusion pattern matches a package name as follows:
```
>>> from fnmatch import fnmatchcase
>>> fnmatchcase('my.package.name.tests', 'tests')
False
```
Assuming all the tests in your project live in package names ending in `tests` or ... |
Check if file is a named pipe (fifo) in python? | 8,558,884 | 13 | 2011-12-19T08:47:27Z | 8,558,940 | 23 | 2011-12-19T08:52:37Z | [
"python",
"pipe"
] | I communicate with a named pipe, but I would like to check if it really is a named pipe BEFORE opening it.
I check in Google but there is nothing, `os.path.isfile()` returns `False`, and I really need to check it. | You can try:
```
import stat, os
stat.S_ISFIFO(os.stat(path).st_mode)
```
[docs](http://docs.python.org/library/stat.html#S_ISFIFO) |
python sum function forloop | 8,559,495 | 2 | 2011-12-19T09:46:37Z | 8,559,530 | 11 | 2011-12-19T09:49:09Z | [
"python",
"sum"
] | I am just wondering.. How can I sum over different elements in a for loop?
```
for element in [(2,7),(9,11)] :
g=sum(element[1]-element[0]+1)
print g
```
If I remove 'sum', I get:
```
6
3
``` | I'm not sure what you do want to get. Is it this?
```
>>> print sum(element[1]-element[0]+1 for element in [(2,7), (9,11)])
9
```
This [generator expression](http://docs.python.org/reference/expressions.html#generator-expressions) is equivalent to
```
temp = []
for element in [(2,7), (9,11)]:
temp.append(element... |
pytest: assert almost equal | 8,560,131 | 22 | 2011-12-19T10:41:54Z | 8,560,171 | 26 | 2011-12-19T10:44:50Z | [
"python",
"unit-testing",
"py.test"
] | How to do `assert almost equal` with py.test for floats without resorting to something like:
```
assert x - 0.00001 <= y <= x + 0.00001
```
UPD.
More specifically it will be useful to know a neat solution for quickly compare pairs of float, without unpacking them:
```
assert (1.32, 2.4) == i_return_tuple_of_two_flo... | You will have to specify what is "almost" for you:
```
assert abs(x-y) < 0.0001
```
and although its a completely different question:
```
assert all([i==j for i,j in zip(tuple1,tuple2)])
``` |
pytest: assert almost equal | 8,560,131 | 22 | 2011-12-19T10:41:54Z | 8,560,182 | 11 | 2011-12-19T10:45:55Z | [
"python",
"unit-testing",
"py.test"
] | How to do `assert almost equal` with py.test for floats without resorting to something like:
```
assert x - 0.00001 <= y <= x + 0.00001
```
UPD.
More specifically it will be useful to know a neat solution for quickly compare pairs of float, without unpacking them:
```
assert (1.32, 2.4) == i_return_tuple_of_two_flo... | Something like
```
assert round(x-y, 5) == 0
```
That is what [unittest](http://docs.python.org/library/unittest.html#unittest.TestCase.assertAlmostEqual) does
For the second part
```
assert all(round(x-y, 5) == 0 for x,y in zip((1.32, 2.4), i_return_tuple_of_two_floats()))
```
Probably better to wrap that in a fu... |
pytest: assert almost equal | 8,560,131 | 22 | 2011-12-19T10:41:54Z | 16,092,955 | 16 | 2013-04-18T20:58:25Z | [
"python",
"unit-testing",
"py.test"
] | How to do `assert almost equal` with py.test for floats without resorting to something like:
```
assert x - 0.00001 <= y <= x + 0.00001
```
UPD.
More specifically it will be useful to know a neat solution for quickly compare pairs of float, without unpacking them:
```
assert (1.32, 2.4) == i_return_tuple_of_two_flo... | If you have access to NumPy it has great functions for floating point comparison that already do pairwise comparison: <http://docs.scipy.org/doc/numpy-dev/reference/routines.testing.html>.
Then you can do something like:
```
numpy.testing.assert_allclose(i_return_tuple_of_two_floats(), (1.32, 2.4))
``` |
Python "in" does not check for type? | 8,560,320 | 14 | 2011-12-19T10:59:43Z | 8,560,378 | 15 | 2011-12-19T11:04:56Z | [
"python",
"unit-testing",
"types",
"boolean",
"identity"
] | ```
>>> False in [0]
True
>>> type(False) == type(0)
False
```
The reason I stumbled upon this:
For my unit-testing I created lists of valid and invalid example values for each of my types. (with 'my types' I mean, they are not 100% equal to the python types)
So I want to iterate the list of all values and expect the... | The problem is not the missing type checking, but because in Python `bool` is a subclass of `int`. Try this:
```
>>> False == 0
True
>>> isinstance(False, int)
True
``` |
Removing duplicate columns and rows from a NumPy 2D array | 8,560,440 | 19 | 2011-12-19T11:10:27Z | 8,564,438 | 13 | 2011-12-19T16:37:02Z | [
"python",
"numpy",
"scipy",
"duplicate-removal"
] | I'm using a 2D shape array to store pairs of longitudes+latitudes. At one point, I have to merge two of these 2D arrays, and then remove any duplicated entry. I've been searching for a function similar to numpy.unique, but I've had no luck. Any implementation I've been
thinking on looks very "unoptimizied". For example... | Here's one idea, it'll take a little bit of work but could be quite fast. I'll give you the 1d case and let you figure out how to extend it to 2d. The following function finds the unique elements of of a 1d array:
```
import numpy as np
def unique(a):
a = np.sort(a)
b = np.diff(a)
b = np.r_[1, b]
retur... |
Removing duplicate columns and rows from a NumPy 2D array | 8,560,440 | 19 | 2011-12-19T11:10:27Z | 8,567,929 | 28 | 2011-12-19T21:41:44Z | [
"python",
"numpy",
"scipy",
"duplicate-removal"
] | I'm using a 2D shape array to store pairs of longitudes+latitudes. At one point, I have to merge two of these 2D arrays, and then remove any duplicated entry. I've been searching for a function similar to numpy.unique, but I've had no luck. Any implementation I've been
thinking on looks very "unoptimizied". For example... | This should do the trick:
```
def unique_rows(a):
a = np.ascontiguousarray(a)
unique_a = np.unique(a.view([('', a.dtype)]*a.shape[1]))
return unique_a.view(a.dtype).reshape((unique_a.shape[0], a.shape[1]))
```
Example:
```
>>> a = np.array([[1, 1], [2, 3], [1, 1], [5, 4], [2, 3]])
>>> unique_rows(a)
arra... |
Using Python to sign into website, fill in a form, then sign out | 8,560,959 | 10 | 2011-12-19T11:54:54Z | 8,561,033 | 7 | 2011-12-19T12:00:19Z | [
"python",
"html",
"forms",
"website",
"urllib"
] | As part of my quest to become better at Python I am now attempting to sign in to a website I frequent, send myself a private message, and then sign out. So far, I've managed to sign in (using urllib, cookiejar and urllib2). However, I cannot work out how to fill in the required form to send myself a message.
The form ... | ```
import urllib
import urllib2
name = "name field"
data = {
"name" : name
}
encoded_data = urllib.urlencode(data)
content = urllib2.urlopen("http://www.abc.com/messages.php?action=send",
encoded_data)
print content.readlines()
```
just replace `http://www.abc.com/messages.php?action=send` ... |
Troubleshooting OSError: out of pty devices | 8,561,121 | 5 | 2011-12-19T12:08:08Z | 8,561,167 | 9 | 2011-12-19T12:12:19Z | [
"python",
"linux",
"pty"
] | From time to time I'm getting an OSError exception with the message 'out of pty devices' when calling `pty.openpty()` (it's happening when a bunch of instances of my scripts run concurrently).
What is the limit that I'm hitting? How can I get around this?
CentOS 5.6, Python 2.4 | In my Ubuntu Linux, the max number of open ptys is given by:
```
cat /proc/sys/kernel/pty/max
```
This value is configurable in:
```
/etc/sysctl.conf
```
All this info, and much more can be found in:
```
man pty
``` |
How can you define a variable that will never be matched in Python? | 8,561,277 | 2 | 2011-12-19T12:20:04Z | 8,561,371 | 8 | 2011-12-19T12:27:28Z | [
"python"
] | Part of my code relies on a comparison between two items, and it may end up comparing against a variable that doesn't exist. As such I will go through and put in filler variable values for the sets to make sure they both are defined and can be compared.
However, if I add a filler value I don't want it to be possible t... | How about simply:
```
missing = object()
```
and then use `missing` in comparisons (it won't compare equal to any other object, including `None`). |
Declarative GTK | 8,561,674 | 5 | 2011-12-19T12:55:44Z | 8,561,713 | 11 | 2011-12-19T12:59:20Z | [
"python",
"qt",
"user-interface",
"gtk",
"declarative"
] | TL;DR: Is there a library for declarative UI creation using GTK? Preferrably with Python support.
---
I'm a Python/Django developer, most of my experience about user interfaces is from the web, where declarative, loosely coupled UI designs are standard. Recently I've had to create a GUI app using Java/Swing for a sch... | I think what you're looking for is [`gtk.Builder`](http://www.pygtk.org/docs/pygtk/class-gtkbuilder.html). Basically, `gtk.Builder` objects can be used to load a `.ui` file that contains xml data that describes the widgets for the user interface and the callbacks to the events that should be exposed by the code. The `.... |
Using Design by Contract in Python | 8,563,464 | 34 | 2011-12-19T15:23:32Z | 8,960,616 | 13 | 2012-01-22T11:08:54Z | [
"python",
"design-by-contract"
] | I am looking to start using DBC on a large number of Python-based projects at work and am wondering what experiences others have had with it. So far my research turned up the following:
* <http://www.python.org/dev/peps/pep-0316/> - PEP 316 that is supposed to standardize design by contract for Python which has been d... | The PEP you found hasn't yet been accepted, so there isn't a standard or accepted way of doing this (yet -- you could always implement the PEP yourself!). However, there are a few different approaches, as you have found.
Probably the most light-weight is just to simply use Python decorators. There's a set of decorator... |
Using Design by Contract in Python | 8,563,464 | 34 | 2011-12-19T15:23:32Z | 18,155,429 | 9 | 2013-08-09T20:49:16Z | [
"python",
"design-by-contract"
] | I am looking to start using DBC on a large number of Python-based projects at work and am wondering what experiences others have had with it. So far my research turned up the following:
* <http://www.python.org/dev/peps/pep-0316/> - PEP 316 that is supposed to standardize design by contract for Python which has been d... | In my experience design-by-contract is worth doing, even without language support. For methods that aren't overridden assertions, along with docstrings are sufficient for both pre- and postconditions. For methods that are overridden we split the method in two: a public method which check the pre- and post-conditions, a... |
django: generic class view + POST = HTTP 405 (Method not allowed) | 8,563,482 | 12 | 2011-12-19T15:24:57Z | 8,565,218 | 14 | 2011-12-19T17:43:42Z | [
"python",
"django",
"http",
"http-status-code-405"
] | Recently I've started converting some of the view functions to Generic Views.
Converting the function which was expected to handle POST request (via AJAX form) results in "405 Method not allowed" HTTP exception.
I'm sure is **not** about CSRF: Ajax sends valid token, changing the generic view back to view function (in ... | I suppose you are using class-based views. If so then you need to define `post` method in your view or use mixin which does it (`django.views.generic.edit.ProcessFormView` for example). If you want to fully understand why this is necessary then look at [`dispatch`](https://code.djangoproject.com/browser/django/trunk/dj... |
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 126: ordinal not in range(128) | 8,564,668 | 6 | 2011-12-19T16:55:11Z | 8,564,717 | 8 | 2011-12-19T16:58:31Z | [
"python",
"xml",
"csv",
"encode"
] | Okay, I have read through many similar questions, and I believe I am following the advice correctly, but somehow my code is still not working.
I have parsed an xml file. I have read on here that the output is now unicode. I am using the csv writer to write output to a file.
So, in my code I have tried to encode in ut... | When you call `mystring.encode(...`, it's not changing the string in-place; it returns a new string. |
import rpy quietly | 8,564,741 | 5 | 2011-12-19T17:00:06Z | 8,565,063 | 8 | 2011-12-19T17:30:03Z | [
"python",
"rpy2"
] | My question is analogous to [this one](http://stackoverflow.com/questions/5319344/is-there-a-way-to-suppress-motd-when-starting-up-r) but in the context of importing R to Python via RPy. Specifically, when I run
```
from rpy import *
```
at the beginning of my python script, there is a chunk of message dumped to the ... | Here is simple but not beatiful hack:
```
# define somewhere following:
import sys
import os
from contextlib import contextmanager
@contextmanager
def quiet():
sys.stdout = sys.stderr = open(os.devnull, "w")
try:
yield
finally:
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr_... |
Compile fortran module with f2py | 8,564,771 | 2 | 2011-12-19T17:02:23Z | 8,572,676 | 7 | 2011-12-20T08:36:36Z | [
"python",
"fortran",
"f2py"
] | I have a Fortran module which I am trying to compile with f2py (listed below). When I remove the module declaration and leave the subroutine in the file by itself, everything works fine. However, if the module is declared as shown below, I get the following results:
```
> f2py.py -c -m its --compiler=mingw itimes-s2.f... | You are trying to have a Fortran module in a Python module. If you want that, the names must be different, e.g.
```
f2py.py -c -m SOMEDIFFERENTNAME itimes-s2.f
```
The result will be called as `pythonmodule.fortranmodule.yourfunction()`.
Otherwise it worked on my machine. |
How do I create a new database in MongoDB using PyMongo? | 8,566,618 | 30 | 2011-12-19T19:45:59Z | 8,566,951 | 58 | 2011-12-19T20:13:15Z | [
"python",
"mongodb",
"pymongo"
] | Can I create a new database simply by connecting to the MongoDB server, or is there another way to create it using Python? If so, how is this done? | mongodb creates databases and collections automatically for you if they don't exist already.
for using python library with mongo, check out their [documentation](http://api.mongodb.org/python/2.1/tutorial.html) and examples.
```
>>> from pymongo import Connection
>>> connection = Connection()
>>> db = connection['tes... |
How do I remove a query from a url? | 8,567,171 | 8 | 2011-12-19T20:31:49Z | 8,588,800 | 11 | 2011-12-21T11:04:45Z | [
"python",
"url",
"scrapy",
"web-crawler"
] | I am using scrapy to crawl a site which seems to be appending random values to the query string at the end of each URL. This is turning the crawl into a sort of an infinite loop.
How do i make scrapy to neglect the query string part of the URL's? | See [urllib.urlparse](http://docs.python.org/release/3.1.3/library/urllib.parse.html)
Example code:
```
from urlparse import urlparse
o = urlparse('http://url.something.com/bla.html?querystring=stuff')
url_without_query_string = o.scheme + "://" + o.netloc + o.path
```
Example output:
```
Python 2.6.1 (r261:67515,... |
How do I remove a query from a url? | 8,567,171 | 8 | 2011-12-19T20:31:49Z | 8,620,843 | 8 | 2011-12-23T21:36:08Z | [
"python",
"url",
"scrapy",
"web-crawler"
] | I am using scrapy to crawl a site which seems to be appending random values to the query string at the end of each URL. This is turning the crawl into a sort of an infinite loop.
How do i make scrapy to neglect the query string part of the URL's? | There is a function `url_query_cleaner` in `w3lib.url` module (used by scrapy itself) to clean urls keeping only a list of allowed arguments. |
Calling a Python function from a shell script | 8,567,526 | 9 | 2011-12-19T21:02:16Z | 8,567,571 | 17 | 2011-12-19T21:05:56Z | [
"python",
"bash",
"shell",
"configuration-files"
] | I am trying to figure out how to call a Python function from a shell script.
I have a Python file with multiple functions and I need to use the values returned by them in my shell script. Is there a way to do it.
I am doing this in order to read a config file using Python and getting the values in shell. Is there any... | You can send the result of your functions to the standard output by asking the Python interpreter to print the result:
```
python -c 'import test; print test.get_foo()'
```
The `-c` option simply asks Python to execute some Python commands.
In order to store the result in a variable, you can therefore do:
```
RESUL... |
print float to n decimal places including trailing 0's | 8,568,233 | 6 | 2011-12-19T22:10:51Z | 8,568,297 | 23 | 2011-12-19T22:16:40Z | [
"python",
"floating-point"
] | I need to print or convert a float number to 15 decimal place string even if the the result has many trailing 0s eg:
1.6 becomes 1.6000000000000000
I tried round(6.2,15) but it returns 6.2000000000000002 adding a rounding error
I also saw various people online who put the float into a string and then added trailing ... | ## For Python versions in 2.6+ and 3.x
You can use the [`str.format`](http://docs.python.org/library/stdtypes.html#str.format) method. Examples:
```
>>> print '{0:.16f}'.format(1.6)
1.6000000000000001
>>> print '{0:.15f}'.format(1.6)
1.600000000000000
```
Note the `1` at the end of the first example is rounding err... |
Python Twisted integration with Cmd module | 8,568,241 | 6 | 2011-12-19T22:11:59Z | 8,570,010 | 9 | 2011-12-20T02:13:16Z | [
"python",
"twisted",
"stdin",
"tab-completion",
"python-cmd"
] | I like Python's [Twisted](http://twistedmatrix.com) and [Cmd](http://docs.python.org/library/cmd.html). I want to use them together.
I got some things working, but so far I haven't figured out how to make tab-completion work, because I don't see how to receive tab keypres events right away (without pressing Enter) in ... | You have a couple of difficulties with this approach:
* `Cmd.onecmd` is not going to do any tab processing.
* Even if it did, your terminal needs to be in cbreak mode in order for individual keystrokes to make it to the Python interpreter (`tty.setcbreak` can take care of that).
* As you know, `Cmd.cmdloop` is not rea... |
PyQt: Getting file name for file dropped in app | 8,568,500 | 10 | 2011-12-19T22:35:19Z | 8,580,720 | 11 | 2011-12-20T19:15:06Z | [
"python",
"drag-and-drop",
"pyqt",
"pyqt4"
] | I am trying to set up an application that will accept havin files dropped into it. So, I am looking for a way to extract the path when they are dropped in.
Right now, I have drag and drop enabled for the right part of the application, and it will accept text dropped in, but I do not know how to handle having a file dr... | The [`QMimeData`](http://doc.qt.io/qt-4.8/qmimedata.html) class has methods for dealing with `dropped urls`:
```
def dragEnterEvent(self, event):
if event.mimeData().hasUrls():
event.accept()
else:
event.ignore()
def dropEvent(self, event):
for url in event.mimeData().urls():
path ... |
Get the string within brackets in Python | 8,569,201 | 9 | 2011-12-20T00:00:04Z | 8,569,258 | 27 | 2011-12-20T00:07:21Z | [
"python",
"regex"
] | I have a sample string `<alpha.Customer[cus_Y4o9qMEZAugtnW] active_card=<alpha.AlphaObject[card] ...>, created=1324336085, description='Customer for My Test App', livemode=False>`
I only want the value `cus_Y4o9qMEZAugtnW` and NOT `card` (which is inside another `[]`)
How could I do it in easiest possible way in Pyth... | How about:
```
import re
s = "alpha.Customer[cus_Y4o9qMEZAugtnW] ..."
m = re.search(r"\[([A-Za-z0-9_]+)\]", s)
print m.group(1)
```
For me this prints:
```
cus_Y4o9qMEZAugtnW
```
Note that the call to `re.search(...)` finds the first match to the regular expression, so it doesn't find the `[card]` unless you repea... |
PyQt:How do i set different header sizes for individual headers? | 8,569,798 | 4 | 2011-12-20T01:33:25Z | 8,580,461 | 9 | 2011-12-20T18:53:09Z | [
"python",
"resize",
"pyqt",
"pyqt4",
"qheaderview"
] | I have a list containing lists with two items,a word and a number.This list will be presented using a tablewidget.
My aim is to produce a table with two columns and with the neccessary rows,but the header of the column which will have the words should be larger than the numbers column.
I could use resize columns to c... | There are a few methods of the [`QHeaderView`](http://developer.qt.nokia.com/doc/qt-4.8/qheaderview.html) class that will probably do what you want.
The simplest is:
```
table.horizontalHeader().setStretchLastSection(True)
```
This will ensure that the last column is automatically resized to fit the available space ... |
Run Python Script on Selected File | 8,570,288 | 9 | 2011-12-20T03:01:42Z | 8,570,432 | 14 | 2011-12-20T03:24:52Z | [
"python",
"windows",
"contextmenu"
] | I would like to write a python script that would upload any file I select in Windows Explorer. The idea is to select any file in Windows Explorer, right-click to display file's Context Menu and select a command from there... something like "Upload to Web Server".
After the command is selected, the Python runs a script... | Assuming Windows 7, If you open a folder and type "shell:sendto" in the address bar then hit enter you'll be taken to the context menu. You can add a .cmd file with the following in it.
```
@echo off
cls
python C:\Your\File\uploadscript.py %1
```
This should execute your python script passing in the file (%1) as a pa... |
Check element exists in array | 8,570,606 | 31 | 2011-12-20T03:55:59Z | 8,570,619 | 8 | 2011-12-20T03:58:12Z | [
"python"
] | In PHP there a function called [`isset()`](http://php.net/isset) to check if something (like an array index) exists and has a value. How about Python?
I need to use this on arrays because I get "IndexError: list index out of range" sometimes.
I guess I *could* use try/catching, but that's a last resort. | ```
`e` in ['a', 'b', 'c'] # evaluates as False
`b` in ['a', 'b', 'c'] # evaluates as True
```
**EDIT**: With the clarification, new answer:
Note that PHP arrays are vastly different from Python's, combining arrays and dicts into one confused structure. Python arrays always have indices from `0` to `len(arr) - 1`, ... |
Check element exists in array | 8,570,606 | 31 | 2011-12-20T03:55:59Z | 8,570,694 | 64 | 2011-12-20T04:08:53Z | [
"python"
] | In PHP there a function called [`isset()`](http://php.net/isset) to check if something (like an array index) exists and has a value. How about Python?
I need to use this on arrays because I get "IndexError: list index out of range" sometimes.
I guess I *could* use try/catching, but that's a last resort. | Look before you leap (LBYL):
```
if idx < len(array):
array[idx]
else:
# handle this
```
Easier to ask forgiveness than permission (EAFP):
```
try:
array[idx]
except IndexError:
# handle this
```
In python, EAFP seems to be the preferred style (in contrast with LBYL usually preferred in C). Here's a... |
Check element exists in array | 8,570,606 | 31 | 2011-12-20T03:55:59Z | 8,570,700 | 33 | 2011-12-20T04:09:58Z | [
"python"
] | In PHP there a function called [`isset()`](http://php.net/isset) to check if something (like an array index) exists and has a value. How about Python?
I need to use this on arrays because I get "IndexError: list index out of range" sometimes.
I guess I *could* use try/catching, but that's a last resort. | ## EAFP vs. LBYL
I understand your dilemma, but Python is not PHP and coding style known as **Easier to Ask for Forgiveness than for Permission** (or [**EAFP**](http://docs.python.org/glossary.html#term-eafp) in short) is **a common coding style in Python**.
See the source (from [documentation](http://docs.python.org... |
See call stack while debugging in Pydev | 8,572,680 | 7 | 2011-12-20T08:37:02Z | 8,572,820 | 12 | 2011-12-20T08:50:34Z | [
"python",
"debugging",
"pydev",
"callstack"
] | Is there a way to see the call stack while debugging python in Pydev? | This is the "**Debug**" view of the "*Debug*" perspective :

You can see that I was inside a `failUnlessEqual` method, called by `test_01a`, called by a `new_method`... |
Django. How to locate slow tests? | 8,573,944 | 5 | 2011-12-20T10:21:47Z | 16,900,394 | 7 | 2013-06-03T15:29:58Z | [
"python",
"django",
"unit-testing",
"testing"
] | How to locate slow django tests? How to locate tests, on which test runner can 'stuck'? Do you know any good custom django test runners, that can provide more detailed information on test performance? | You can get Django to print the tests it's running with:
```
./manage.py test -v 3
```
This will print the name of the test, run it, then print "ok". So you can figure out which test is slow. |
python try-finally | 8,574,856 | 11 | 2011-12-20T11:42:37Z | 8,574,879 | 16 | 2011-12-20T11:44:33Z | [
"python",
"exception",
"try-catch",
"finally"
] | Why does the exception raised in `foo` whizz by unnoticed, but the exception raised in `bar` is thrown?
```
def foo():
try:
raise StandardError('foo')
finally:
return
def bar():
try:
raise StandardError('bar')
finally:
pass
foo()
bar()
``` | From the [Python documentation](http://docs.python.org/reference/compound_stmts.html#the-try-statement):
> If the finally clause raises another exception or executes a return or break statement, the saved exception is lost. |
How to show matplotlib plots in python | 8,575,062 | 9 | 2011-12-20T11:57:50Z | 8,575,092 | 8 | 2011-12-20T12:00:04Z | [
"python",
"matplotlib"
] | I am sure the configuration of matplotlib for python is correct since I have used it to plot some figures.
But today it just stop working for some reason. I tested it with really simple code like:
```
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 5, 0.1)
y = np.sin(x)
plt.plot(x, y)
```
there's... | You must use `plt.show()` at the end in order to see the plot |
How to show matplotlib plots in python | 8,575,062 | 9 | 2011-12-20T11:57:50Z | 8,575,569 | 14 | 2011-12-20T12:38:56Z | [
"python",
"matplotlib"
] | I am sure the configuration of matplotlib for python is correct since I have used it to plot some figures.
But today it just stop working for some reason. I tested it with really simple code like:
```
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 5, 0.1)
y = np.sin(x)
plt.plot(x, y)
```
there's... | In matplotlib you have two main options:
1. Create your plots and draw them at the end:
```
import matplotlib.pyplot as plt
plt.plot(x, y)
plt.plot(z, t)
plt.show()
```
2. Create your plots and draw them as soon as they are created:
```
import matplotlib.pyplot as plt
from matplotlib impo... |
How to mock a function defined in a module of a package? | 8,575,713 | 13 | 2011-12-20T12:50:09Z | 8,575,791 | 9 | 2011-12-20T12:56:33Z | [
"python",
"mocking"
] | I've got a following structure:
```
|-- dirBar
| |-- __init__.py
| |-- bar.py
|-- foo.py
`-- test.py
```
bar.py
```
def returnBar():
return 'Bar'
```
foo.py
```
from dirBar.bar import returnBar
def printFoo():
print returnBar()
```
test.py
```
from mock import Mock
from foo import printFoo
from dir... | Just import the `bar` module before the `foo` module and mock it:
```
from mock import Mock
from dirBar import bar
bar.returnBar = Mock(return_value='Foo')
from foo import printFoo
printFoo()
```
When you are importing the `returnBar` in `foo.py`, you are binding the value of the module to a variable called `retur... |
How to mock a function defined in a module of a package? | 8,575,713 | 13 | 2011-12-20T12:50:09Z | 8,575,844 | 7 | 2011-12-20T13:01:07Z | [
"python",
"mocking"
] | I've got a following structure:
```
|-- dirBar
| |-- __init__.py
| |-- bar.py
|-- foo.py
`-- test.py
```
bar.py
```
def returnBar():
return 'Bar'
```
foo.py
```
from dirBar.bar import returnBar
def printFoo():
print returnBar()
```
test.py
```
from mock import Mock
from foo import printFoo
from dir... | I'm guessing you are going to mock the function `returnBar`, you'd like to use [`patch` decorator](http://www.voidspace.org.uk/python/mock/patch.html):
```
from mock import patch
from foo import printFoo
@patch('foo.returnBar')
def test_printFoo(mockBar):
mockBar.return_value = 'Foo'
printFoo()
test_printFo... |
Employing dynamic data for graphs | 8,575,781 | 7 | 2011-12-20T12:55:43Z | 8,576,733 | 14 | 2011-12-20T14:09:45Z | [
"javascript",
"jquery",
"python",
"django"
] | I am aiming to build a site that will contain a lot of user generated data, hopefully.
I'm in my first year of self learning programming: Python, Django, MySQL, HTML and Javascript.
I can chart dummy data on a table just fine, but I'm now looking at turning that data into nice colorful looking graphs.
I am in my firs... | How are the plots (typically) placed on the web page?
Here's the usual API schema for javascript-based data visualization libraries:
i. **pre-allocate a *div* as the chart container** in your markup (or template); typically using an *id selector* using an id selector, like so:
```
<div id="chart1"> </div>
```
Often... |
How to create objects on the fly in python? | 8,575,895 | 5 | 2011-12-20T13:05:06Z | 8,576,049 | 14 | 2011-12-20T13:15:15Z | [
"python",
"django",
"object"
] | How do I create objects on the fly in Python? I often want to pass information to my Django templates which is formatted like this:
```
{'test': [a1, a2, b2], 'test2': 'something else', 'test3': 1}
```
which makes the template look untidy. so I think it's better to just create an object which is like:
```
class test... | You can use built-in [type function](http://docs.python.org/library/functions.html#type):
```
testobj = type('testclass', (object,),
{'test':[a1,a2,b2], 'test2':'something else', 'test3':1})()
```
But in this specific case (data object for Django templates), you should use @Xion's solution. |
How to create objects on the fly in python? | 8,575,895 | 5 | 2011-12-20T13:05:06Z | 8,576,099 | 18 | 2011-12-20T13:19:27Z | [
"python",
"django",
"object"
] | How do I create objects on the fly in Python? I often want to pass information to my Django templates which is formatted like this:
```
{'test': [a1, a2, b2], 'test2': 'something else', 'test3': 1}
```
which makes the template look untidy. so I think it's better to just create an object which is like:
```
class test... | In Django templates, the dot notation (`testobj.test`) can resolve to the Python's `[]` operator. This means that all you need is an ordinary dict:
```
testobj = {'test':[a1,a2,b2], 'test2':'something else', 'test3':1}
```
Pass it as `testobj` variable to your template and you can freely use `{{ testobj.test }}` and ... |
How to only keep nodes in networkx-graph with 2+ outgoing edges or 0 outgoing edges? | 8,576,737 | 6 | 2011-12-20T14:09:53Z | 8,577,381 | 10 | 2011-12-20T15:01:33Z | [
"python",
"networkx"
] | I have Directed Graph in networkx. I want to only keep those nodes which have two or more than two outgoing edges or no outgoing edge at all. How do I do this?
or
How do I removes nodes which have exactly one outgoing edge in a networkx graph. | You can find the nodes in graph `G` with one outgoing edge using the `out_degree` method:
```
outdeg = G.out_degree()
to_remove = [n for n in outdeg if outdeg[n] == 1]
```
Removing is then:
```
G.remove_nodes_from(to_remove)
```
If you prefer to create a new graph instead of modifying the existing graph in place, c... |
How to declare a long string in Python? | 8,577,027 | 17 | 2011-12-20T14:33:00Z | 8,577,073 | 17 | 2011-12-20T14:35:11Z | [
"python"
] | I have a really long string in python:
```
long_string = '
this is a really
really
really
long
string
'
```
However, since the string spans multiple lines, python doesn't recognize this as a string. How do I fix this? | ```
long_string = '''
this is a really
really
really
long
string
'''
```
`"""` does the same thing. |
How to declare a long string in Python? | 8,577,027 | 17 | 2011-12-20T14:33:00Z | 8,577,087 | 17 | 2011-12-20T14:36:30Z | [
"python"
] | I have a really long string in python:
```
long_string = '
this is a really
really
really
long
string
'
```
However, since the string spans multiple lines, python doesn't recognize this as a string. How do I fix this? | You can use either
```
long_string = 'fooo' \
'this is really long' \
'string'
```
or if you need linebreaks
```
long_string_that_has_linebreaks = '''foo
this is really long
'''
``` |
How to declare a long string in Python? | 8,577,027 | 17 | 2011-12-20T14:33:00Z | 8,578,229 | 46 | 2011-12-20T15:58:19Z | [
"python"
] | I have a really long string in python:
```
long_string = '
this is a really
really
really
long
string
'
```
However, since the string spans multiple lines, python doesn't recognize this as a string. How do I fix this? | You can also do this, which is nice because you have better control over the whitespace inside of the string:
```
long_string = (
'Lorem ipsum dolor sit amet, consectetur adipisicing elit, '
'sed do eiusmod tempor incididunt ut labore et dolore magna '
'aliqua. Ut enim ad minim veniam, quis nostrud exercit... |
creating a tmp file in python | 8,577,137 | 9 | 2011-12-20T14:40:48Z | 8,577,225 | 7 | 2011-12-20T14:49:01Z | [
"python"
] | I have this function that references the path of a file:
```
some_obj.file_name(FILE_PATH)
```
where FILE\_PATH is a string of the path of a file, i.e. 'H:/path/FILE\_NAME.ext'
I want to create a file FILE\_NAME.ext inside my python script with the content of a string:
```
some_string = 'this is some content'
```
... | There is a [`tempfile` module](http://docs.python.org/library/tempfile.html) for python, but a simple file creation also does the trick:
```
new_file = open("path/to/FILE_NAME.ext", "w")
```
Now you can write to it using the `write` method:
```
new_file.write('this is some content')
```
---
With the `tempfile` mod... |
creating a tmp file in python | 8,577,137 | 9 | 2011-12-20T14:40:48Z | 8,577,226 | 36 | 2011-12-20T14:49:09Z | [
"python"
] | I have this function that references the path of a file:
```
some_obj.file_name(FILE_PATH)
```
where FILE\_PATH is a string of the path of a file, i.e. 'H:/path/FILE\_NAME.ext'
I want to create a file FILE\_NAME.ext inside my python script with the content of a string:
```
some_string = 'this is some content'
```
... | I think you're looking for this: <http://docs.python.org/library/tempfile.html>
```
import tempfile
f = tempfile.NamedTemporaryFile(delete=False)
f.close()
f.name
``` |
Python config parser to get all the values from a section? | 8,578,430 | 16 | 2011-12-20T16:14:01Z | 8,578,508 | 50 | 2011-12-20T16:19:57Z | [
"python"
] | I want to get all the values from a section using config parser
I used this but it gives only the first value
```
def ConfigSectionMap(section):
dict1 = {}
options = Config.options(section)
for option in options:
try:
dict1[option] = Config.get(section, option)
if dict1[option] == -1:
De... | Make it a dict:
```
dict(Config.items('Section'))
``` |
Python ElementTree: Parsing a string and getting ElementTree instance | 8,580,234 | 18 | 2011-12-20T18:33:39Z | 8,580,309 | 22 | 2011-12-20T18:41:03Z | [
"python",
"xml",
"elementtree"
] | I have a string containing XML data that is returned from an http request.
I am using [ElementTree](http://docs.python.org/library/xml.etree.elementtree.html) to parse the data, and I want to then search recursively for an element.
According to [this question](http://stackoverflow.com/questions/1319385/need-help-usin... | When you use `ElementTree.fromstring()` what you're getting back is basically the root of the tree, so if you create a new tree like this `ElementTree.ElementTree(root)` you'll get you're looking for.
So, to make it clearer:
```
from xml.etree import ElementTree
tree = ElementTree.ElementTree(ElementTree.fromstring(<... |
Scala equivalent to Python returning multiple items | 8,580,561 | 19 | 2011-12-20T19:01:47Z | 8,580,581 | 31 | 2011-12-20T19:03:16Z | [
"python",
"scala"
] | In Python it's possible to do something like this:
```
def blarg():
return "blargidy", "blarg"
i, j = blargh()
```
Is there something similar available in scala? | You can return a tuple:
```
def blarg = ("blargidy", "blarg")
val (i, j) = blarg
```
Note the pattern-matching syntax for parallel variable assignment: this works for any pattern, not just for tuples. So for instance:
```
val list = 1 :: 2 :: 3 :: Nil
val x :: y = list // x = 1 and y = 2 :: 3 :: Nil
``` |
Amazon SES SMTP with Django | 8,580,754 | 20 | 2011-12-20T19:18:04Z | 8,601,736 | 24 | 2011-12-22T09:22:40Z | [
"python",
"django",
"smtp",
"amazon-web-services",
"amazon-ses"
] | I'm trying to use Amazon's new SMTP service for SES with Django 1.3.1 but I'm not having much luck.
I've created my SES SMTP credentials and have this in my settings:
```
EMAIL_USE_TLS = True
EMAIL_HOST = 'email-smtp.us-east-1.amazonaws.com'
EMAIL_HOST_USER = 'my-smtp-user'
EMAIL_HOST_PASSWORD = 'my-smtp-password'
EM... | Thanks everyone for the recommendations but I finally found a much simpler solution that would allow me to use Django's built-in mail classes so I can still get my admin error email reports etc.
Thanks to this little beauty I was able to use SES SMTP without any problems:
<https://github.com/bancek/django-smtp-ssl>
... |
Python subprocess call with arguments having multiple quotations | 8,581,140 | 5 | 2011-12-20T19:56:10Z | 8,581,347 | 8 | 2011-12-20T20:14:06Z | [
"python",
"subprocess"
] | I use the following command in bash to execute a Python script.
```
python myfile.py -c "'USA'" -g "'CA'" -0 "'2011-10-13'" -1 "'2011-10-27'"
```
I'm writing a Python script to wrap around this one. I'm currently having to use os.system (I know, it's crappy) since I can't figure out how to get the quotes to work with... | You don't need to escape the values. To the process everything is passed as a string.
You can use the shlex module to figure out what is the best way to pass variables:
```
import shlex
shlex.split('python myfile.py -c "USA" -g "CA" -0 "2011-10-13" -1 "2011-10-27"')
['python',
'myfile.py',
'-c',
'USA',
'-g',
'C... |
Python background color of main frame | 8,581,776 | 3 | 2011-12-20T20:49:51Z | 8,581,978 | 7 | 2011-12-20T21:05:38Z | [
"python",
"tkinter"
] | I want my main frame to have the background color black. Here is what I tried:
```
#!/usr/bin/python
import tkinter
from tkinter import *
root = Tk()
root.geometry("363x200")
root.resizable(0,0)
root.title("Emsg Server")
root.option_add("*background", "black")
v = StringVar()
Field = Message(root, textvariable=v, w... | Try to use
```
root.configure(background='black')
```
instead of
```
root.option_add("*background", "black")
```
As an extra: you don't need two import statements, the second one is enough. |
"Iterate" a function's return values | 8,581,804 | 3 | 2011-12-20T20:52:02Z | 8,581,862 | 8 | 2011-12-20T20:56:28Z | [
"python"
] | Suppose I have a function which consults some external stateful service and returns a value from it, for simplicity let's assume the value is an integer:
```
i = 10
def foo():
global i
i -= 1
return i
```
It's clear that I can call this function 9 times before it returns a falsy value (the 10th call will ... | This can actually be done using the built-in [`iter()`](http://docs.python.org/library/functions.html#iter), if you provide two arguments instead of one then the first is expected to be a function that will be called repeatedly until the return value of the function reaches the sentinel value:
```
for x in iter(foo, 0... |
Class wrapper around file -- proper way to close file handle when no longer referenced | 8,582,076 | 8 | 2011-12-20T21:13:50Z | 8,582,813 | 9 | 2011-12-20T22:29:59Z | [
"garbage-collection",
"python",
"resource-cleanup"
] | I've got a class that wraps some file handling functionality I need. Another class creates an instance of the `filehandler` and uses it for an indeterminate amount of time. Eventually, the `caller` is destroyed, which destroys the only reference to the `filehandler`.
What is the best way to have the `filehandler` clos... | `__del__` is not, by itself, a bad thing. You just have to be extra careful to not create reference cycles in objects that have `__del__` defined. If you do find yourself needing to create cycles (parent refers to child which refers back to parent) then you will want to use the `weakref` module.
So, `__del__` is okay,... |
Determining frequency of an array in Python | 8,582,559 | 7 | 2011-12-20T22:02:31Z | 8,582,746 | 9 | 2011-12-20T22:22:36Z | [
"python",
"transform",
"fft",
"text-processing"
] | I have a sample file filled with floating point numbers as follows:
```
-0.02 3.04 3.04 3.02 3.02 3.06 3.04 3.02 3.04 3.02 3.04 3.02
3.04 3.02 3.04 3.04 3.04 3.02 3.04 3.02 3.04 3.02 3.04 3.02
3.06 3.02 3.04 3.02 3.04 3.02 3.02 3.06 3.04 3.02 3.04 3.02
3.04 3.02 3.... | It's not clear from your question exactly what the values in the file represent. But assuming that they indicate consecutive voltage samples, you can load the file into a Numpy array using
```
import numpy as np
data = np.array([float(f) for f in file(filename).read().split()])
```
and then compute the Fourier transf... |
Why do Python's math.ceil() and math.floor() operations return floats instead of integers? | 8,582,741 | 105 | 2011-12-20T22:22:09Z | 8,582,781 | 15 | 2011-12-20T22:27:05Z | [
"python",
"math"
] | Can someone explain this (straight from the [docs](http://docs.python.org/library/math.html#number-theoretic-and-representation-functions)- emphasis mine):
> **math.ceil(x)** Return the ceiling of x *as a float*, the smallest *integer* value greater than or equal to x.
>
> **math.floor(x)** Return the floor of x *as a... | Because python's math library is a thin wrapper around the C math library which returns floats. |
Why do Python's math.ceil() and math.floor() operations return floats instead of integers? | 8,582,741 | 105 | 2011-12-20T22:22:09Z | 8,582,794 | 62 | 2011-12-20T22:28:09Z | [
"python",
"math"
] | Can someone explain this (straight from the [docs](http://docs.python.org/library/math.html#number-theoretic-and-representation-functions)- emphasis mine):
> **math.ceil(x)** Return the ceiling of x *as a float*, the smallest *integer* value greater than or equal to x.
>
> **math.floor(x)** Return the floor of x *as a... | The range of floating point numbers usually exceeds the range of integers. By returning a floating point value, the functions can return a sensible value for input values that lie outside the representable range of integers.
Consider: If `floor()` returned an integer, what should `floor(1.0e30)` return?
Now, while Py... |
Why do Python's math.ceil() and math.floor() operations return floats instead of integers? | 8,582,741 | 105 | 2011-12-20T22:22:09Z | 8,582,845 | 57 | 2011-12-20T22:33:28Z | [
"python",
"math"
] | Can someone explain this (straight from the [docs](http://docs.python.org/library/math.html#number-theoretic-and-representation-functions)- emphasis mine):
> **math.ceil(x)** Return the ceiling of x *as a float*, the smallest *integer* value greater than or equal to x.
>
> **math.floor(x)** Return the floor of x *as a... | As pointed out by other answers, in python they return floats probably because of historical reasons to prevent overflow problems. However, they return integers in python 3.
```
>>> import math
>>> type(math.floor(3.1))
<class 'int'>
>>> type(math.ceil(3.1))
<class 'int'>
```
You can find more information in [PEP 314... |
Why do Python's math.ceil() and math.floor() operations return floats instead of integers? | 8,582,741 | 105 | 2011-12-20T22:22:09Z | 8,582,849 | 9 | 2011-12-20T22:34:12Z | [
"python",
"math"
] | Can someone explain this (straight from the [docs](http://docs.python.org/library/math.html#number-theoretic-and-representation-functions)- emphasis mine):
> **math.ceil(x)** Return the ceiling of x *as a float*, the smallest *integer* value greater than or equal to x.
>
> **math.floor(x)** Return the floor of x *as a... | The source of your confusion is evident in your comment:
> The whole point of ceil/floor operations is to convert floats to integers!
The point of the ceil and floor operations is to round floating-point data to *integral values*. Not to do a type conversion. Users who need to get *integer* values can do an explicit ... |
Stop pygtk GUI from locking up during long-running process | 8,583,975 | 5 | 2011-12-21T01:07:00Z | 8,584,339 | 7 | 2011-12-21T02:12:33Z | [
"python",
"multithreading",
"pygtk"
] | I have a process that will take a while (maybe a minute or two) to complete. When I call this from my pygtk GUI the window locks up (darkens and prevents user action) after about 10 seconds.
I'd like to stop this from happening, but I'm not sure how. I thought multithreading would be the answer, but it doesn't seem to... | Please find below a modified version of the second example that works for me:
```
import threading
import time
import gtk, gobject, glib
gobject.threads_init()
class Test():
def __init__(self):
self.counter = 0
self.label = gtk.Label()
self.progress_bar = gtk.ProgressBar()
self.pr... |
Multithreaded file copy is far slower than a single thread on a multicore CPU | 8,584,797 | 2 | 2011-12-21T03:37:18Z | 8,584,809 | 7 | 2011-12-21T03:39:28Z | [
"python",
"multithreading",
"file",
"copy",
"queue"
] | I am trying to write a multithreaded program in Python to accelerate the copying of (under 1000) .csv files. The multithreaded code runs even slower than the sequential approach. I timed the code with `profile.py`. I am sure I must be doing something wrong but I'm not sure what.
**The Environment:**
* Quad core CPU.
... | Of course it's slower. The hard drives are having to seek between the files constantly. Your belief that multi-threading would make this task faster is completely unjustified. The limiting speed is how fast you can read data from or write data to the disk, and every seek from one file to another is a loss of time that ... |
Get last inserted value from MySQL using SQLAlchemy | 8,585,346 | 5 | 2011-12-21T05:14:06Z | 8,586,823 | 8 | 2011-12-21T08:22:21Z | [
"python",
"mysql",
"sqlalchemy",
"declarative"
] | I've just run across a fairly vexing problem, and after testing I have found that NONE of the available answers are sufficient.
I have seen various suggestions but none seem to be able to return the last inserted value for an auto\_increment field in MySQL.
I have seen examples that mention the use of session.flush()... | The problem is you are setting `defaul` for the auto increment. So when it run the insert into query the log of server is
```
2011-12-21 13:44:26,561 INFO sqlalchemy.engine.base.Engine.0x...1150 INSERT INTO tblfoo (`ModelID`, `ModelName`, `ModelMemo`) VALUES (%s, %s, %s)
2011-12-21 13:44:26,561 INFO sqlalchemy.engine.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.