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 |
|---|---|---|---|---|---|---|---|---|---|
PyQt Designer where to write code? | 7,825,851 | 9 | 2011-10-19T18:00:27Z | 7,826,018 | 11 | 2011-10-19T18:13:31Z | [
"python",
"pyqt"
] | I have PyQT v.4.8.8 installed.When I draw layouts and I want to view the code , it comes with error that is unable to launch uic as in snapshot:

I can compile the .ui files manually in cmdLine. But I dont know where to put the code for slot,methods ,... | As the name says, the Qt designer is for interface *design* only. You cannot use it to write the code for the actual application logic. For this, you'll need a normal Python editor. The exact details on how to use designer files in Python are explained in [PyQt reference guide, Using Qt Designer](http://www.riverbankco... |
Python logging.info() not logging the message | 7,825,905 | 7 | 2011-10-19T18:03:56Z | 7,825,949 | 10 | 2011-10-19T18:07:15Z | [
"python",
"logging"
] | ```
parser_logger = logging.getLogger("CSHEL_parserlogger");
#logging.basicConfig()
parser_logger.addHandler(RotatingFileHandler(
"logfile", mode='a', maxBytes=7340032, backupCount=4,
encoding=None, delay=False))
#d = { 'clientip' : '192.168.0.1', 'user' : 'fblog... | You need to set the threshold level of the logger:
```
parser_logger.setLevel(logging.INFO)
```
When a logger is created, the level is set to `NOTSET`, and the root logger is created with level `WARNING`. See [the documentation](http://docs.python.org/dev/library/logging.html). |
HEAD request vs. GET request | 7,826,349 | 4 | 2011-10-19T18:39:03Z | 7,826,403 | 7 | 2011-10-19T18:43:01Z | [
"python",
"http",
"urllib2",
"head",
"pycurl"
] | I always had the idea that doing a `HEAD` request instead of a `GET` request was faster (no matter the size of the resource) and therefore had it advantages in certain solutions.
However, while making a `HEAD` request in Python (to a 5+ MB dynamic generated resource) I realized that it took the same time as making a `... | The server is taking the bulk of the time, not your requester or the network. If it's a dynamic resource, it's likely that the server doesn't know all the header information - in particular, Content-Length - until it's built it. So it has to build the whole thing whether you're doing HEAD or GET. |
how to show first 50 words of a text field in django template | 7,826,955 | 7 | 2011-10-19T19:26:12Z | 7,826,979 | 15 | 2011-10-19T19:28:17Z | [
"python",
"django"
] | I have a field like this in my Django template:
```
<p>{{news.description}}<p>
```
I wanna show the first 50 words of this field. How can I do it? | From [the documentation](https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#truncatewords):
```
{{ news.description|truncatewords:50 }}
``` |
Setting Mac OSX Application Menu menu bar item to other than "Python" in my python Qt application | 7,827,430 | 14 | 2011-10-19T20:04:33Z | 7,875,807 | 7 | 2011-10-24T12:43:52Z | [
"python",
"osx",
"qt",
"menubar"
] | I am writing a GUI application using python and Qt. When I launch my application on Mac, the first menu item in the Mac menu bar at the top of the screen is "Python". I would prefer the application name there to be the name of my application. How can I get my program name up there?
The following demo program creates a... | You seem to need an OSX .app for this to work, as the `Info.plist` file in there contains the user-visible name for the application that is put there. This defaults to Python, which is the title you see for the program menu. [This blog](http://aralbalkan.com/1675) post outlines the steps you need to take, while the [OS... |
Http POST Curl in python | 7,827,696 | 7 | 2011-10-19T20:28:27Z | 7,827,759 | 14 | 2011-10-19T20:33:57Z | [
"python",
"http",
"post",
"curl",
"opengraph"
] | I'm having trouble understanding how to issue an HTTP POST request using curl from inside of python.
I'm tying to post to facebook open graph. Here is the example they give which I'd like to replicate exactly in python.
```
curl -F 'access_token=...' \
-F 'message=Hello, Arjun. I like this new API.' \
https... | You can use [httplib](http://docs.python.org/library/httplib.html) to POST with Python or the higher level [urllib2](http://docs.python.org/library/urllib2.html)
```
import urllib
params = {}
params['access_token'] = '*****'
params['message'] = 'Hello, Arjun. I like this new API.'
params = urllib.urlencode(params)
... |
Indexable weak ordered set in Python | 7,828,444 | 10 | 2011-10-19T21:32:42Z | 7,829,569 | 23 | 2011-10-19T23:45:32Z | [
"python",
"inheritance",
"weak-references"
] | I was wondering if there is an easy way to build an indexable weak ordered set in Python. I tried to build one myself. Here's what I came up with:
```
"""
An indexable, ordered set of objects, which are held by weak reference.
"""
from nose.tools import *
import blist
import weakref
class WeakOrderedSet(blist.weakso... | The easiest way to is to take advantage of existing components in the standard library.
OrderedDict and the MutableSet ABC make it easy to write an OrderedSet.
Likewise, you can reuse the existing weakref.WeakSet and replace its underlying set() with an OrderedSet:
```
import collections, weakref
class OrderedSet(c... |
How to efficiently compare two unordered lists (not sets) in Python? | 7,828,867 | 44 | 2011-10-19T22:13:02Z | 7,828,896 | 8 | 2011-10-19T22:17:39Z | [
"python",
"algorithm",
"list",
"comparison"
] | ```
a = [1, 2, 3, 1, 2, 3]
b = [3, 2, 1, 3, 2, 1]
```
a & b should be considered equal, because they have exactly the same elements, only in different order.
The thing is, my actual lists will consist of objects (my class instances), not integers. | You can sort both:
```
sorted(a) == sorted(b)
```
A [counting sort](http://en.wikipedia.org/wiki/Counting_sort) could also be more efficient (but it requires the object to be hashable).
```
>>> from collections import Counter
>>> a = [1, 2, 3, 1, 2, 3]
>>> b = [3, 2, 1, 3, 2, 1]
>>> print (Counter(a) == Counter(b))
... |
How to efficiently compare two unordered lists (not sets) in Python? | 7,828,867 | 44 | 2011-10-19T22:13:02Z | 7,829,249 | 9 | 2011-10-19T23:00:33Z | [
"python",
"algorithm",
"list",
"comparison"
] | ```
a = [1, 2, 3, 1, 2, 3]
b = [3, 2, 1, 3, 2, 1]
```
a & b should be considered equal, because they have exactly the same elements, only in different order.
The thing is, my actual lists will consist of objects (my class instances), not integers. | If you know the items are always hashable, you can use a `Counter()` which is O(n)
If you know the items are always sortable, you can use `sorted()` which is O(n log n)
In the general case you can't rely on being able to sort, or has the elements, so you need a fallback like this, which is unfortunately O(n^2)
```
... |
How to efficiently compare two unordered lists (not sets) in Python? | 7,828,867 | 44 | 2011-10-19T22:13:02Z | 7,829,388 | 81 | 2011-10-19T23:20:37Z | [
"python",
"algorithm",
"list",
"comparison"
] | ```
a = [1, 2, 3, 1, 2, 3]
b = [3, 2, 1, 3, 2, 1]
```
a & b should be considered equal, because they have exactly the same elements, only in different order.
The thing is, my actual lists will consist of objects (my class instances), not integers. | **O(n)**: The *[Counter()](https://docs.python.org/3.5/library/collections.html#collections.Counter)* method is best (if your objects are hashable):
```
def compare(s, t):
return Counter(s) == Counter(t)
```
**O(n log n)**: The *[sorted()](https://docs.python.org/3.5/library/functions.html#sorted)* method is next... |
Using hashlib to compute md5 digest of a file in Python 3 | 7,829,499 | 12 | 2011-10-19T23:36:35Z | 7,829,550 | 8 | 2011-10-19T23:42:45Z | [
"python",
"python-3.x",
"hashlib"
] | With python 2.7 the following code computes the mD5 hexdigest of the content of a file.
(EDIT: well, not really as answers have shown, I just thought so).
```
import hashlib
def md5sum(filename):
f = open(filename, mode='rb')
d = hashlib.md5()
for buf in f.read(128):
d.update(buf)
return d.he... | ```
for buf in f.read(128):
d.update(buf)
```
.. updates the hash sequentially with each of the first 128 *bytes* values of the file. Since iterating over a `bytes` produces `int` objects, you get the following calls which cause the error you encountered in Python3.
```
d.update(97)
d.update(98)
d.update(99)
d.upda... |
Using hashlib to compute md5 digest of a file in Python 3 | 7,829,499 | 12 | 2011-10-19T23:36:35Z | 7,829,658 | 21 | 2011-10-19T23:59:49Z | [
"python",
"python-3.x",
"hashlib"
] | With python 2.7 the following code computes the mD5 hexdigest of the content of a file.
(EDIT: well, not really as answers have shown, I just thought so).
```
import hashlib
def md5sum(filename):
f = open(filename, mode='rb')
d = hashlib.md5()
for buf in f.read(128):
d.update(buf)
return d.he... | I think you wanted the for-loop to make successive calls to `f.read(128)`. That can be done using *iter()* and *functools.partial()*:
```
import hashlib
from functools import partial
def md5sum(filename):
with open(filename, mode='rb') as f:
d = hashlib.md5()
for buf in iter(partial(f.read, 128), ... |
Inverting Dictionaries in Python | 7,829,674 | 5 | 2011-10-20T00:02:49Z | 7,829,703 | 7 | 2011-10-20T00:08:33Z | [
"python",
"maps",
"dictionary"
] | I want to know which would be an efficient method to invert dictionaries in python. I also want to get rid of duplicate values by comparing the keys and choosing the larger over the smaller assuming they can be compared. Here is inverting a dictionary:
```
inverted = dict([[v,k] for k,v in d.items()])
``` | To remove duplicates by using the largest key, sort your dictionary iterator by value. The call to dict will use the last key inserted:
```
import operator
inverted = dict((v,k) for k,v in sorted(d.iteritems(), key=operator.itemgetter(1)))
``` |
PyQt4 MouseMove event without MousePress | 7,829,829 | 6 | 2011-10-20T00:31:23Z | 7,839,023 | 8 | 2011-10-20T16:18:27Z | [
"python",
"pyqt",
"mouseevent",
"pyqt4",
"mouseover"
] | I need to catch when a User moves the mouse over the GUI, but not when they're holding down the mouse button (which would do something different).
I can't find any conveniant method to do this,
except to periodically find the mouse position and check it to it's previous position...
Which would suck.
The mouseMoveEven... | The most straightforward way to do this is to install an event filter on qApp:
```
from PyQt4 import QtGui, QtCore
class Window(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
widget = QtGui.QWidget(self)
layout = QtGui.QVBoxLayout(widget)
self.edit = QtGui... |
Is there a way to get a list of column names in sqlite? | 7,831,371 | 19 | 2011-10-20T05:02:15Z | 7,831,685 | 47 | 2011-10-20T05:52:49Z | [
"python",
"database",
"sqlite"
] | I want to get a list of column names from a table in a database. Using pragma I get a list of tuples with a lot of unneeded information. Is there a way to get only the column names? So I might end up with something like this:
> [Column1, Column2, Column3, Column4]
The reason why I absolutely need this list is because... | You can use sqlite3 and [pep-249](http://www.python.org/dev/peps/pep-0249/)
```
import sqlite3
connection = sqlite3.connect('~/foo.sqlite')
cursor = connection.execute('select * from bar')
```
**cursor.description** is description of columns
```
names = list(map(lambda x: x[0], cursor.description))
```
Alternativel... |
Is there a way to get a list of column names in sqlite? | 7,831,371 | 19 | 2011-10-20T05:02:15Z | 18,788,347 | 8 | 2013-09-13T14:03:53Z | [
"python",
"database",
"sqlite"
] | I want to get a list of column names from a table in a database. Using pragma I get a list of tuples with a lot of unneeded information. Is there a way to get only the column names? So I might end up with something like this:
> [Column1, Column2, Column3, Column4]
The reason why I absolutely need this list is because... | An alternative to the **cursor.description** solution from [smallredstone](http://stackoverflow.com/users/975918/smallredstone) could be to use **row.keys()**:
```
import sqlite3
connection = sqlite3.connect('~/foo.sqlite')
connection.row_factory = sqlite3.Row
cursor = connection.execute('select * from bar')
# instead... |
Python Deleting Certain File Extensions | 7,833,715 | 5 | 2011-10-20T09:21:21Z | 7,833,781 | 14 | 2011-10-20T09:25:59Z | [
"python",
"logic",
"file-extension",
"delete-file"
] | I'm fairly new to Python, but I have gotten this code to work, and in fact, do what it's intended to do.
However, I'm wondering if there is a more efficient way to code this, perhaps to enhance the processing speed.
```
import os, glob
def scandirs(path):
for currentFile in glob.glob( os.path.join(path, '*') )... | Since you are recursing through subdirectories, use [os.walk](http://docs.python.org/library/os.html#os.walk):
```
import os
def scandirs(path):
for root, dirs, files in os.walk(path):
for currentFile in files:
print "processing file: " + currentFile
exts = ('.png', '.jpg')
... |
Get .wav file length or duration | 7,833,807 | 13 | 2011-10-20T09:27:59Z | 7,833,963 | 24 | 2011-10-20T09:38:44Z | [
"python",
"audio"
] | I'm looking for a way to find out the duration of a audio file (.wav) in python. So far i had a look at python `wave` library, `mutagen`, `pymedia`, `pymad` i was not able to get the duration of the wav file. `Pymad` gave me the duration but its not consistent.
Thanks in advance. | The duration is equal to the number of frames divided by the framerate (frames per second):
```
import wave
import contextlib
fname = '/tmp/test.wav'
with contextlib.closing(wave.open(fname,'r')) as f:
frames = f.getnframes()
rate = f.getframerate()
duration = frames / float(rate)
print(duration)
```
... |
Obtaining Client IP address from a WSGI app using Eventlet | 7,835,030 | 6 | 2011-10-20T11:09:44Z | 7,839,576 | 13 | 2011-10-20T17:10:20Z | [
"python",
"wsgi",
"eventlet"
] | I'm currently writing a basic dispatch model server based on the Python Eventlet library (http://eventlet.net/doc/). Having looked at the WSGI docs on Eventlet (http://eventlet.net/doc/modules/wsgi.html), I can see that the eventlet.wsgi.server function logs the x-forwarded-for header in addition to the client IP addre... | What you want is in the wsgi [environ](http://www.python.org/dev/peps/pep-0333/#environ-variables), specifically `environ['REMOTE_ADDR']`.
However, if there is a proxy involved, then `REMOTE_ADDR` will be the address of the proxy, and the client address will be included (most likely) in `HTTP_X_FORWARDED_FOR`.
Here's... |
Is PyCrypto safe and reliable to use? | 7,835,974 | 10 | 2011-10-20T12:33:53Z | 8,373,548 | 16 | 2011-12-04T05:43:00Z | [
"python",
"django",
"pycrypto"
] | I am planning on using PyCrypto for a project and I want to know whether PyCrypto is safe and reliable enough to use. How can I ensure that PyCrypto is encrypting data correctly according to the various encryption algorithms such as RSA and AES? | It depends.
Some parts of PyCrypto are really good. For example, the API for Crypto.Random (introduced in PyCrypto 2.1) was designed to be pretty foolproof, and the underlying algorithm it uses (Fortuna) was also designed to be pretty foolproof.
Other parts are just implementations of low-level crypto primitives, so ... |
Latex on python: \alpha and \beta don't work? | 7,836,730 | 13 | 2011-10-20T13:33:48Z | 7,836,817 | 30 | 2011-10-20T13:41:14Z | [
"python",
"matplotlib"
] | I'm using matplotlib to produce some graphics, and I'm using latex for the legends.
More specifically, I'm trying to use something like this:
```
loglog(x,x, '-r',label='$ \alpha $')
legend()
show()
```
However, this code does not present a legend on the figure, and gets error after I close the image.
I'm using the... | `\a` and `\b` have [special meaning](http://docs.python.org/reference/lexical_analysis.html#string-literals) inside a Python string literal.
I recommend that you use [raw strings](http://docs.python.org/reference/lexical_analysis.html#string-literals) whenever there's a backslash embedded inside a string:
```
r'$ \al... |
Generic one-to-one relation in Django | 7,837,330 | 11 | 2011-10-20T14:18:48Z | 9,295,723 | 11 | 2012-02-15T15:02:24Z | [
"python",
"django",
"django-models",
"django-admin",
"one-to-one"
] | I need to set up one-to-one relation which must also be generic. May be you can advice me a better design. So far I came up to the following models
```
class Event(models.Model):
# skip event related fields...
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerFiel... | I recently [came across this problem](http://stackoverflow.com/questions/9199000/reversing-a-unique-generic-foreign-key-and-returning-an-object-as-opposed-to-a). What you have done is fine, but you can generalise it a little bit more by creating a mixin that reverses the relationship transparently:
```
class Event(mod... |
What is the most efficient way to loop through dataframes with pandas? | 7,837,722 | 121 | 2011-10-20T14:46:14Z | 7,837,947 | 91 | 2011-10-20T15:02:16Z | [
"python",
"performance",
"for-loop",
"pandas"
] | I want to perform my own complex operations on financial data in dataframes in a sequential manner.
For example I am using the following MSFT CSV file taken from [Yahoo Finance](http://finance.yahoo.com/q/hp?s=MSFT):
```
Date,Open,High,Low,Close,Volume,Adj Close
2011-10-19,27.37,27.47,27.01,27.13,42880000,27.13
201... | Pandas is based on NumPy arrays.
The key to speed with NumPy arrays is to perform your operations on the whole array at once, never row-by-row or item-by-item.
For example, if `close` is a 1-d array, and you want the day-over-day percent change,
```
pct_change = close[1:]/close[:-1]
```
This computes the entire arra... |
What is the most efficient way to loop through dataframes with pandas? | 7,837,722 | 121 | 2011-10-20T14:46:14Z | 7,849,789 | 61 | 2011-10-21T13:04:53Z | [
"python",
"performance",
"for-loop",
"pandas"
] | I want to perform my own complex operations on financial data in dataframes in a sequential manner.
For example I am using the following MSFT CSV file taken from [Yahoo Finance](http://finance.yahoo.com/q/hp?s=MSFT):
```
Date,Open,High,Low,Close,Volume,Adj Close
2011-10-19,27.37,27.47,27.01,27.13,42880000,27.13
201... | You can loop through the rows by transposing and then calling iteritems:
```
for date, row in df.T.iteritems():
# do some logic here
```
I am not certain about efficiency in that case. To get the best possible performance in an iterative algorithm, you might want to explore writing it in [Cython](http://cython.org... |
What is the most efficient way to loop through dataframes with pandas? | 7,837,722 | 121 | 2011-10-20T14:46:14Z | 11,617,194 | 144 | 2012-07-23T17:09:39Z | [
"python",
"performance",
"for-loop",
"pandas"
] | I want to perform my own complex operations on financial data in dataframes in a sequential manner.
For example I am using the following MSFT CSV file taken from [Yahoo Finance](http://finance.yahoo.com/q/hp?s=MSFT):
```
Date,Open,High,Low,Close,Volume,Adj Close
2011-10-19,27.37,27.47,27.01,27.13,42880000,27.13
201... | The newest versions of pandas now include a built-in function for iterating over rows.
```
for index, row in df.iterrows():
# do some logic here
```
Or, if you want it faster use `itertuples()`
But, unutbu's suggestion to use numpy functions to avoid iterating over rows will produce the fastest code. |
What is the most efficient way to loop through dataframes with pandas? | 7,837,722 | 121 | 2011-10-20T14:46:14Z | 11,706,782 | 19 | 2012-07-29T04:53:26Z | [
"python",
"performance",
"for-loop",
"pandas"
] | I want to perform my own complex operations on financial data in dataframes in a sequential manner.
For example I am using the following MSFT CSV file taken from [Yahoo Finance](http://finance.yahoo.com/q/hp?s=MSFT):
```
Date,Open,High,Low,Close,Volume,Adj Close
2011-10-19,27.37,27.47,27.01,27.13,42880000,27.13
201... | I checked out `iterrows` after noticing [Nick Crawford's](http://stackoverflow.com/users/475872/nick-crawford) answer, but found that it yields (index, Series) tuples. Not sure which would work best for you, but I ended up using the `itertuples` method for my problem, which yields (index, row\_value1...) tuples.
There... |
What is the most efficient way to loop through dataframes with pandas? | 7,837,722 | 121 | 2011-10-20T14:46:14Z | 19,415,186 | 10 | 2013-10-16T22:38:11Z | [
"python",
"performance",
"for-loop",
"pandas"
] | I want to perform my own complex operations on financial data in dataframes in a sequential manner.
For example I am using the following MSFT CSV file taken from [Yahoo Finance](http://finance.yahoo.com/q/hp?s=MSFT):
```
Date,Open,High,Low,Close,Volume,Adj Close
2011-10-19,27.37,27.47,27.01,27.13,42880000,27.13
201... | Just as a small addition, you can also do an apply if you have a complex function that you apply to a single column:
<http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.apply.html>
```
df[b] = df[a].apply(lambda col: do stuff with col here)
``` |
What is the most efficient way to loop through dataframes with pandas? | 7,837,722 | 121 | 2011-10-20T14:46:14Z | 34,311,080 | 24 | 2015-12-16T11:39:44Z | [
"python",
"performance",
"for-loop",
"pandas"
] | I want to perform my own complex operations on financial data in dataframes in a sequential manner.
For example I am using the following MSFT CSV file taken from [Yahoo Finance](http://finance.yahoo.com/q/hp?s=MSFT):
```
Date,Open,High,Low,Close,Volume,Adj Close
2011-10-19,27.37,27.47,27.01,27.13,42880000,27.13
201... | Like what has been mentioned before, pandas object is most efficient when process the whole array at once. However for those who really need to loop through a pandas DataFrame to perform something, like me, I found at least three ways to do it. I have done a short test to see which one of the three is the least time co... |
Trouble understanding passing values and references in Python | 7,838,005 | 3 | 2011-10-20T15:06:38Z | 7,838,047 | 8 | 2011-10-20T15:09:58Z | [
"python",
"oop",
"reference",
"pass-by-reference"
] | Having issues with when objects are changed and when they aren't in Python. Here is my poorly contrived example below:
```
class person:
age = 21
class bar:
def __init__(self, arg1):
self.foo = arg1
self.foo.age = 23
def baz(arg1):
arg1.age = 27
def teh(arg1):
arg1 = [3,2,1]
Person1... | I can see three fundamental Python concepts that can shine some light on the question:
1) First, an assignment from a mutable object like in
```
self.foo = arg1
```
is like copying a pointer (and not the value pointed to): `self.foo` and `arg1` are the *same* object. That's why the line that follows,
```
self.foo.a... |
Single string or list of strings in a method | 7,838,015 | 7 | 2011-10-20T15:07:20Z | 7,838,054 | 8 | 2011-10-20T15:10:20Z | [
"python"
] | I have run into this several times. I'm dealing with a lot of methods that can accept a list of strings. Several times I have accidentally passed a single string and it gets broken apart into a list and each character is used, which isn't the desired behavior.
```
def test(a,b):
x = []
x.extend(a)
x.extend... | Use this
```
def test( x, *args ):
```
Now you can do
```
test( x, 'one' )
```
and
```
test( x, 'one', 'two' )
```
and
```
test( x, *['one', 'two',] )
``` |
pyinstaller seems not to find a data file | 7,838,606 | 7 | 2011-10-20T15:46:33Z | 7,887,341 | 9 | 2011-10-25T09:38:52Z | [
"python",
"pyinstaller"
] | Edit 3: I replaced `__file__` with `sys.argv[0]`, when I need to know the location of my script/executable. This is not exactly the same, but in my case it seems to run fine (at least on executable version...). Now everything is working fine, in one-file mode, with use of accepted answer's function to access resource f... | Firstly, it might be wise to do a print config\_file / os.path.exists(config\_file) before reading it, so you can be sure where the file is and if python can find it.
As to actually accessing it, `os.path.split(__file__)` looks almost correct, but I'm not sure it works properly under pyinstaller - the proper way of pa... |
Is there an overhead when nesting functions in Python? | 7,839,632 | 30 | 2011-10-20T17:14:56Z | 7,839,644 | 20 | 2011-10-20T17:16:17Z | [
"python",
"function",
"nested"
] | In Python, if I have a child function within a parent function, is the child function "initialised" (created) every time the parent function is called? Is there any overhead associated with nesting a function within another? | Yes, a new object would be created each time. It's likely not an issue unless you have it in a tight loop. Profiling will tell you if it's a problem.
```
In [80]: def foo():
....: def bar():
....: pass
....: return bar
....:
In [81]: id(foo())
Out[81]: 29654024
In [82]: id(foo())
Out[82]... |
Is there an overhead when nesting functions in Python? | 7,839,632 | 30 | 2011-10-20T17:14:56Z | 7,839,697 | 22 | 2011-10-20T17:20:40Z | [
"python",
"function",
"nested"
] | In Python, if I have a child function within a parent function, is the child function "initialised" (created) every time the parent function is called? Is there any overhead associated with nesting a function within another? | The code object is pre-compiled so that part has no overhead. The function object gets built on every invocation -- it binds the function name to the code object, records default variables, etc.
Executive summary: It's not free.
```
>>> from dis import dis
>>> def foo():
def bar():
pass
... |
Is there an overhead when nesting functions in Python? | 7,839,632 | 30 | 2011-10-20T17:14:56Z | 10,842,756 | 7 | 2012-05-31T23:52:47Z | [
"python",
"function",
"nested"
] | In Python, if I have a child function within a parent function, is the child function "initialised" (created) every time the parent function is called? Is there any overhead associated with nesting a function within another? | There is an impact, but in most situations it is so small that you shouldn't worry about it - most non-trivial applications probably already have performance bottlenecks whose impacts are several orders of magnitude larger than this one. Worry instead about the readability and reusability of the code.
Here some code t... |
Efficient Python to Python IPC | 7,839,786 | 11 | 2011-10-20T17:27:48Z | 7,839,930 | 9 | 2011-10-20T17:40:39Z | [
"python",
"ipc",
"inter-process-communicat"
] | What would be an [inter-process communication (IPC)](http://en.wikipedia.org/wiki/Inter-process_communication) framework\technique with the following requirements:
* Transfer native Python objects between two Python processes
* Efficient in time and CPU (RAM efficiency irrelevant)
* Cross-platform Win\Linux
* Nice to ... | Use [multiprocessing](http://docs.python.org/library/multiprocessing.html) to start with.
If you need multiple CPU's, look at [celery](http://celeryproject.org/). |
Efficient Python to Python IPC | 7,839,786 | 11 | 2011-10-20T17:27:48Z | 7,840,047 | 13 | 2011-10-20T17:51:53Z | [
"python",
"ipc",
"inter-process-communicat"
] | What would be an [inter-process communication (IPC)](http://en.wikipedia.org/wiki/Inter-process_communication) framework\technique with the following requirements:
* Transfer native Python objects between two Python processes
* Efficient in time and CPU (RAM efficiency irrelevant)
* Cross-platform Win\Linux
* Nice to ... | Native objects don't get shared between processes (due to reference counting).
Instead, you can pickle them and share them using unix domain sockets, mmap, zeromq, or an intermediary such a sqlite3 that is designed for concurrent accesses. |
Inheritance and base class method call python | 7,841,812 | 12 | 2011-10-20T20:24:26Z | 7,841,971 | 45 | 2011-10-20T20:40:41Z | [
"python",
"inheritance"
] | I would like a method in a base class to call another method in the same class instead of the overriding method in an inherited class.
I would like the following code to print out
Class B: 6
Class A: 9
Can this be done?
---
```
# Base class definition
class ClassA(object):
def __init__(self):
print("In... | Congratulations, you've discovered the motivating use case for Python's double-underscore name mangling :-)
For the details and a worked-out example see: <http://docs.python.org/tutorial/classes.html#private-variables> and at <http://docs.python.org/reference/expressions.html#atom-identifiers> .
Here's how to use it ... |
Filter directory when using shutil.copytree? | 7,842,044 | 5 | 2011-10-20T20:47:41Z | 7,842,204 | 7 | 2011-10-20T21:01:46Z | [
"python",
"shutil",
"copytree"
] | Is there a way I can filter a directory by using the absolute path to it?
```
shutil.copytree(directory,
target_dir,
ignore = shutil.ignore_patterns("/Full/Path/To/aDir/Common"))
```
This doesn't seem to work when trying to filter the "Common" Directory located under "`aDir`". If I do ... | You can make your own ignore function:
```
shutil.copytree('/Full/Path', 'target',
ignore=lambda directory, contents: ['Common'] if directory == '/Full/Path/To/aDir' else [])
```
Or, if you want to be able to call `copytree` with a relative path:
```
import os.path
def ignorePath(path):
def ignoref(d... |
Python return statement error " 'return' outside function" | 7,842,120 | 15 | 2011-10-20T20:54:35Z | 7,842,248 | 32 | 2011-10-20T21:05:09Z | [
"python"
] | When running the following code (in Python 2.7.1 on a mac with Mac OS X 10.7)
```
while True:
return False
```
I get the following error
```
SyntaxError: 'return' outside function
```
I've carefully checked for errant tabs and/or spaces. I can confirm that the code fails with the above error when I use the reco... | The *return* statement only makes sense inside functions:
```
def foo():
while True:
return False
``` |
Python return statement error " 'return' outside function" | 7,842,120 | 15 | 2011-10-20T20:54:35Z | 7,842,660 | 10 | 2011-10-20T21:45:38Z | [
"python"
] | When running the following code (in Python 2.7.1 on a mac with Mac OS X 10.7)
```
while True:
return False
```
I get the following error
```
SyntaxError: 'return' outside function
```
I've carefully checked for errant tabs and/or spaces. I can confirm that the code fails with the above error when I use the reco... | To break a loop, use `break` instead of `return`.
Or put the loop or control construct into a function, only functions can return values. |
Python return statement error " 'return' outside function" | 7,842,120 | 15 | 2011-10-20T20:54:35Z | 21,654,346 | 8 | 2014-02-09T02:09:46Z | [
"python"
] | When running the following code (in Python 2.7.1 on a mac with Mac OS X 10.7)
```
while True:
return False
```
I get the following error
```
SyntaxError: 'return' outside function
```
I've carefully checked for errant tabs and/or spaces. I can confirm that the code fails with the above error when I use the reco... | Use quit() in this context. 'break' expects to be inside a loop, and 'return' expects to be inside a function. |
How to convert numpy.recarray to numpy.array? | 7,842,157 | 11 | 2011-10-20T20:57:53Z | 7,842,620 | 9 | 2011-10-20T21:41:33Z | [
"python",
"numpy"
] | What's the best way to convert numpy's `recarray` to a normal array?
i could do a `.tolist()` first and then do an `array()` again, but that seems somewhat inefficient..
Example:
```
import numpy as np
a = np.recarray((2,), dtype=[('x', int), ('y', float), ('z', int)])
>>> a
rec.array([(30408891, 9.29440975618049... | By "normal array" I take it you mean a NumPy array of homogeneous dtype. Given a recarray, such as:
```
>>> a = np.array([(0, 1, 2),
(3, 4, 5)],[('x', int), ('y', float), ('z', int)]).view(np.recarray)
rec.array([(0, 1.0, 2), (3, 4.0, 5)],
dtype=[('x', '<i4'), ('y', '<f8'), ('z', '<i4')])
```
we ... |
Python equivalent to perl -pe? | 7,842,919 | 8 | 2011-10-20T22:15:26Z | 7,842,937 | 8 | 2011-10-20T22:18:24Z | [
"python",
"bash",
"pipe"
] | I need to pick some numbers out of some text files. I can pick out the lines I need with grep, but didn't know how to extract the numbers from the lines. A colleague showed me how to do this from bash with perl:
```
cat results.txt | perl -pe 's/.+(\d\.\d+)\.\n/\1 /'
```
However, I usually code in Python, not Perl. S... | Yes, you can use Python from the command line. `python -c <stuff>` will run `<stuff>` as Python code. Example:
```
python -c "import sys; print sys.path"
```
There isn't a direct equivalent to the `-p` option for Perl (the automatic input/output line-by-line processing), but that's mostly because Python doesn't use t... |
How to convert comma-delimited string to list in Python? | 7,844,118 | 47 | 2011-10-21T01:33:51Z | 7,844,128 | 71 | 2011-10-21T01:35:55Z | [
"python",
"parsing",
"list",
"tuples"
] | Given a string that is a sequence of several values separated by a commma:
```
mStr = 'A,B,C,D,E'
```
How do I convert the string to a list?
```
mList = ['A', 'B', 'C', 'D', 'E']
``` | You can use the str.split method.
```
>>> my_string = 'A,B,C,D,E'
>>> my_list = my_string.split(",")
>>> print my_list
['A', 'B', 'C', 'D', 'E']
```
If you want to convert it to a tuple, just
```
>>> print tuple(my_list)
('A', 'B', 'C', 'D', 'E')
```
If you are looking to append to a list, try this:
```
>>> my_lis... |
cannot import name HttpResponse | 7,845,482 | 4 | 2011-10-21T05:55:04Z | 7,845,509 | 13 | 2011-10-21T05:59:10Z | [
"python",
"django"
] | views.py
```
from django import HttpResponse
def hello(request):
return HttpResponse("Hello world ! ")
```
---
```
Request Method: GET
Request URL: http://127.0.0.1:8000/hello/
Django Version: 1.3.1
Exception Type: ImportError
Exception Value:
cannot import name HttpResponse
``` | You can try this: `from django.http import HttpResponse` |
SQLAlchemy 0.7 - maximum column length | 7,846,180 | 4 | 2011-10-21T07:18:51Z | 7,876,060 | 9 | 2011-10-24T13:06:06Z | [
"python",
"sqlalchemy"
] | I am using SQLAlchemy maximum column length recipe from my previous question ([SQLAlchemy - maximum column length](http://stackoverflow.com/questions/2317081/sqlalchemy-maximum-column-length)). Since I upgraded to SQLAlchemy 0.7, the LengthValidator cannot be installed using the following expression:
> > inst.impl.ext... | Below is Ants' solution rewritten with event system of SQLAlchemy:
```
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import ColumnProperty
from sqlalchemy import event
def check_string_length(cls, key, inst):
prop = inst.prop
# Only interested in simple columns, not relations
... |
How can I query the nearest record in a given coordinates(latitude and longitude of string type)? | 7,846,355 | 12 | 2011-10-21T07:36:05Z | 7,910,671 | 18 | 2011-10-27T01:03:16Z | [
"python",
"postgresql",
"postgis",
"geodjango"
] | I am using GeoDjango with PostGIS. Then I am into trouble on how to get the nearest record from the given coordinates from my postgres db table. | This this the answer using GeoDjango with PostGIS
Point coordinates must be a GEOSGeometry object. To make it use
```
from django.contrib.gis.geos import GEOSGeometry
point = GEOSGeometry('POINT(5 23)')
```
Then, let's imagine that you have a "Restaurant" model And coordinates of the point.
So, for the closest resta... |
Python scalable chat server | 7,847,089 | 8 | 2011-10-21T08:51:23Z | 7,847,481 | 10 | 2011-10-21T09:29:58Z | [
"python",
"multiprocessing",
"scalable"
] | I've just begun learning sockets with Python. So I've written some examples of chat servers and clients. Most of what I've seen on the internet seems to use threading module for (asynchronous) handling of clients' connections to server. I do understand that for scalable server you need to use some additional tricks, be... | Facebook needed a scalable server so they wrote [Tornado](http://www.tornadoweb.org/) (which uses async). [Twisted](http://twistedmatrix.com/trac/) is also famously scalable (it also uses async). [Gunicorn](http://gunicorn.org/) is also a top performer (it uses multiple processes). None of the fast, scalable tools that... |
List comprehension for loops Python | 7,847,624 | 19 | 2011-10-21T09:44:20Z | 7,847,680 | 12 | 2011-10-21T09:49:30Z | [
"python",
"inline",
"list-comprehension"
] | I use a lot of N dimensional arrays and it gets a pain to have to write such indented code and I know some codes can be replaced with list comprehensions and inline statements. For example:
```
for x in (0,1,2,3):
for y in (0,1,2,3):
if x < y:
print (x, y, x*y)
```
can be replaced with:
```
p... | As an alternative to writing loops N levels deep, you could use [`itertools.product()`](http://docs.python.org/library/itertools.html#itertools.product):
```
In [1]: import itertools as it
In [2]: for x, y in it.product((0,1,2,3),(0,1,2,3)):
...: if x < y:
...: print x, y, x*y
0 1 0
0 2 0
0 3 0
1 2... |
List comprehension for loops Python | 7,847,624 | 19 | 2011-10-21T09:44:20Z | 7,848,547 | 23 | 2011-10-21T11:07:15Z | [
"python",
"inline",
"list-comprehension"
] | I use a lot of N dimensional arrays and it gets a pain to have to write such indented code and I know some codes can be replaced with list comprehensions and inline statements. For example:
```
for x in (0,1,2,3):
for y in (0,1,2,3):
if x < y:
print (x, y, x*y)
```
can be replaced with:
```
p... | `sum` works here:
```
total = sum(x+y for x in (0,1,2,3) for y in (0,1,2,3) if x < y)
``` |
Celery - schedule periodic tasks starting at a specific time | 7,848,512 | 2 | 2011-10-21T11:02:56Z | 7,906,978 | 8 | 2011-10-26T18:12:54Z | [
"python",
"celery",
"scheduled-tasks"
] | **Edit :** I've accepted @bakennedy answer confirming my original thoughts, that is:
'Yes, but not out of the box'.
A good combo for this seems Celery + APSCheduler.
**Original question :**
What is the best way to schedule a periodic task starting at specific datetime?
(I'm not using cron for this considering I've ... | Celery seems like a good solution for your scheduling problem: Celery's PeriodicTasks have run time resolution in seconds.
You're using an appropriate tool here, but the crontab entry is not what you want. You want to use python's datetime.timedelta object; the crontab scheduler in celery.schedules has only minute res... |
Removing a file with only the python file object | 7,848,919 | 6 | 2011-10-21T11:44:16Z | 7,848,959 | 17 | 2011-10-21T11:48:01Z | [
"python"
] | Let's say that I open a file, that didn't previously exist, for writing:
```
f = open('/tmp/test.txt', 'w')
```
Once this line is executed the file '/tmp/test.txt' is created. What is the cleanest way to remove (delete) the file with only the file object (f) and not the path? | You cannot remove a file handle, only a file path, since multiple paths can [refer to the same file](http://en.wikipedia.org/wiki/Hard_link) and some files (like sockets) don't even have paths. Therefore:
```
import os
f = open('/tmp/test.txt', 'w')
os.unlink(f.name)
# You can still use f here, it's just only visible ... |
Argument is URL or path | 7,849,818 | 3 | 2011-10-21T13:08:08Z | 15,713,991 | 10 | 2013-03-30T01:43:20Z | [
"python",
"argv"
] | What is the standard practice in `Python` when I have a command-line application taking one argument which is
URL to a web page
or
path to a HTML file somewhere on disk
(only one)
is sufficient the code?
```
if "http://" in sys.argv[1]:
print "URL"
else:
print "path to file"
``` | ```
import urlparse
def is_url(url):
return urlparse.urlparse(url).scheme != ""
is_url(sys.argv[1])
``` |
Django and Shibboleth | 7,850,207 | 14 | 2011-10-21T13:38:18Z | 7,852,124 | 8 | 2011-10-21T16:02:45Z | [
"python",
"django",
"shibboleth",
"saml-2.0"
] | I'm investigating the options for using Shibboleth in a Django deployment. From what I've found, things look somewhat sparse. Can anyone comment on the following?
* Is anyone using the django\_shibboleth module (see <http://code.arcs.org.au/gitorious/django/django-shibboleth/trees/1.1>)? If so, what experiences have y... | I would recommend using the Shibboleth Native SP (apache mod\_shib). It's well tested, has a large user base, and is very stable.
I took a quick look at the [django\_shibboleth](https://github.com/sorrison/django-shibboleth) module, and it seems that it depends on mod\_shib, and doesn't do any SAML on it's own. In thi... |
What exactly should be set in PYTHONPATH? | 7,850,908 | 28 | 2011-10-21T14:28:49Z | 7,850,960 | 14 | 2011-10-21T14:31:59Z | [
"python"
] | I'm going through and writing a setup doc for other developers at work for a python project and I've been reading up on the `PYTHONPATH` environment variable. I'm looking at my current development system and think I have a few things set wrong that is causing my IDE (IntelliJ) to behave incorrectly when looking up the ... | You don't have to set either of them. PYTHONPATH can be set to point to additional directories with private libraries in them. If PYHONHOME is not set, Python defaults to using the directory where python.exe was found, so that dir should be in PATH. |
Ternary operator for NumPy ndarray? | 7,852,519 | 10 | 2011-10-21T16:38:12Z | 7,852,573 | 15 | 2011-10-21T16:43:07Z | [
"python",
"arrays",
"numpy",
"multidimensional-array"
] | Does NumPy have a ternary operator? For instance, in R there is a vectorized `if-else` function:
```
> ifelse(1:10 < 3,"a","b")
[1] "a" "a" "b" "b" "b" "b" "b" "b" "b" "b"
```
Is there anything equivalent in NumPy? | You are looking for `numpy.where()`:
```
>>> print numpy.where(numpy.arange(10) < 3, 'a', 'b')
['a', 'a', 'a', 'b', 'b', 'b', 'b', 'b', 'b', 'b']
```
NumPy even has a generalization (that maps 0, 1, 2, etc. to values, instead of mapping only True and False): `numpy.choose()`. |
How to convert a Python datetime object to seconds | 7,852,855 | 92 | 2011-10-21T17:09:59Z | 7,852,885 | 9 | 2011-10-21T17:13:36Z | [
"python",
"python-2.7"
] | Apologies for the simple question... I'm new to Python... I have searched around and nothing seems to be working.
I have a bunch of datetime objects and I want to calculate the number of seconds since a fixed time in the past for each one (for example since January 1, 1970).
```
import datetime
t = datetime.datetime(... | from the python docs:
```
timedelta.total_seconds()
```
Return the total number of seconds contained in the duration. Equivalent to
```
(td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
```
computed with true division enabled.
Note that for very large time intervals (greater than 270 years on ... |
How to convert a Python datetime object to seconds | 7,852,855 | 92 | 2011-10-21T17:09:59Z | 7,852,891 | 76 | 2011-10-21T17:14:09Z | [
"python",
"python-2.7"
] | Apologies for the simple question... I'm new to Python... I have searched around and nothing seems to be working.
I have a bunch of datetime objects and I want to calculate the number of seconds since a fixed time in the past for each one (for example since January 1, 1970).
```
import datetime
t = datetime.datetime(... | To get the Unix time (seconds since January 1, 1970):
```
>>> import datetime, time
>>> t = datetime.datetime(2011, 10, 21, 0, 0)
>>> time.mktime(t.timetuple())
1319148000.0
``` |
How to convert a Python datetime object to seconds | 7,852,855 | 92 | 2011-10-21T17:09:59Z | 7,852,969 | 96 | 2011-10-21T17:21:36Z | [
"python",
"python-2.7"
] | Apologies for the simple question... I'm new to Python... I have searched around and nothing seems to be working.
I have a bunch of datetime objects and I want to calculate the number of seconds since a fixed time in the past for each one (for example since January 1, 1970).
```
import datetime
t = datetime.datetime(... | For the special date of January 1, 1970 there are multiple options.
For any other starting date you need to get the difference between the two dates in seconds. Subtracting two dates gives a `timedelta` object, which as of Python 2.7 has a `total_seconds()` function.
```
>>> (t-datetime.datetime(1970,1,1)).total_seco... |
How to convert a Python datetime object to seconds | 7,852,855 | 92 | 2011-10-21T17:09:59Z | 22,180,855 | 12 | 2014-03-04T19:12:31Z | [
"python",
"python-2.7"
] | Apologies for the simple question... I'm new to Python... I have searched around and nothing seems to be working.
I have a bunch of datetime objects and I want to calculate the number of seconds since a fixed time in the past for each one (for example since January 1, 1970).
```
import datetime
t = datetime.datetime(... | `int (t.strftime("%s"))` also works |
How to convert a Python datetime object to seconds | 7,852,855 | 92 | 2011-10-21T17:09:59Z | 30,156,392 | 17 | 2015-05-10T20:36:48Z | [
"python",
"python-2.7"
] | Apologies for the simple question... I'm new to Python... I have searched around and nothing seems to be working.
I have a bunch of datetime objects and I want to calculate the number of seconds since a fixed time in the past for each one (for example since January 1, 1970).
```
import datetime
t = datetime.datetime(... | Starting from Python 3.3 this becomes super easy with the `datetime.timestamp()` method. This of course will only be useful if you need the number of seconds from 1970-01-01 UTC.
```
from datetime import datetime
dt = datetime.today() # Get timezone naive now
seconds = dt.timestamp()
```
The return value will be a f... |
How do I find an image contained within an image? | 7,853,628 | 6 | 2011-10-21T18:22:36Z | 15,147,009 | 10 | 2013-02-28T22:35:56Z | [
"python",
"image-processing",
"opencv"
] | I'm currently building what basically amounts to a cross between a search engine and a gallery for web comics that's focused on citing sources and giving authors credit.
I'm trying to figure out a way to search an image to find characters within it.
For example:
. To summarize (my understanding), template matching looks for an exact match of one image within another image.
Here'... |
Using a session cookie from selenium in urllib2 | 7,854,077 | 9 | 2011-10-21T19:03:22Z | 11,435,762 | 12 | 2012-07-11T15:11:28Z | [
"python",
"cookies",
"selenium",
"urllib2",
"session-cookies"
] | I'm trying to use Selenium to log into a website and then use urllib2 to make RESTy requests. In order for it to work though, I need urllib2 to be able to use the same session Selenium used.
The logging in with selenium worked great and I can call
```
self.driver.get_cookies()
```
and I have a list of all the cookie... | I was able to overcome this problem by using the `requests` library instead. I iterated over the cookies from selenium, and then passed them in a simple dictionary with `name:value` pairs.
```
all_cookies = self.driver.get_cookies()
cookies = {}
for s_cookie in all_cookies:
cookies[s_cookie["name"]]=s_cookie["v... |
Python - Should I put my helper functions inside or outside the class? | 7,855,237 | 26 | 2011-10-21T21:00:32Z | 7,855,829 | 35 | 2011-10-21T22:07:55Z | [
"python",
"class",
"design",
"pylint"
] | In Python, if some methods of a class need a helper function, but the helper function itself doesn't use anything in the class, should I put the helper function inside or outside the class?
I tried putting it inside but PyLint was complaining that this function could have been put outside...
Also, are there any good ... | When deciding where to put helper functions the question I ask is, "Is it only for this class?" If it can help in other places, then it goes at the module level; if it is indeed only for this class, then it goes in the class with either `staticmethod` (needs no class data to do its job) or `classmethod` (uses some clas... |
run web app with gevent | 7,855,343 | 14 | 2011-10-21T21:15:18Z | 7,857,201 | 23 | 2011-10-22T03:26:19Z | [
"python",
"gevent",
"gunicorn"
] | I want to try playing around with gevent as a web server and application framework. I don't see any way to "restart" the server or update the application code without killing and starting the whole python application again.
Is this just how it's done? Maybe it's just a matter of me understanding a different paradigm t... | Gunicorn has 3 gevent workers:
* -k gevent (using gunicorn's HTTP parser)
* -k gevent\_pywsgi (using gevent.pywsgi module)
* -k gevent\_wsgi (using gevent.wsgi module)
gevent.wsgi is a fast HTTP server based on libevent.
gevent.pywsgi is WSGI server implemented in Python.
The reason for existence of gevent.pywsgi i... |
Python's random module made inaccessible by Numpy's random module | 7,855,845 | 5 | 2011-10-21T22:09:04Z | 7,856,009 | 14 | 2011-10-21T22:34:41Z | [
"python",
"numpy",
"random-sample"
] | When I call `random.sample(arr,length)`
an error returns `random_sample() takes at most 1 positional argument (2 given)`. After some Googling I found out I'm calling Numpy's random sample function when I want to call the sample function of the random module. I've tried importing numpy under a different name, which does... | Sounds like you have something like
```
import random
from numpy import *
```
and `random` is getting clobbered by the numpy import. If you want to keep the `import *` then you'll need to rename `random`:
```
import random as rnd # or whatever name you like
from numpy import *
```
Alternatively, and probably bet... |
Python, command line argument parsing | 7,856,168 | 5 | 2011-10-21T23:01:21Z | 7,856,193 | 9 | 2011-10-21T23:04:04Z | [
"python",
"command-line-arguments"
] | How do you accept/parse command line arguments for a py file that has no class? Here is what I have inside my file test.py:
```
import sys
if __name__ == '__main__':
```
How do I get the arguments when the file is executed via command line? I call it via:
```
python test.py <arg1>
```
and obviously want the value ... | Look no further than [`sys.argv`](http://docs.python.org/library/sys.html#sys.argv), which is a list containing all arguments passed to the program. |
Parsing CSV / tab-delimited txt file with Python | 7,856,296 | 14 | 2011-10-21T23:19:45Z | 7,856,361 | 34 | 2011-10-21T23:29:32Z | [
"python",
"parsing",
"csv",
"dictionary"
] | I currently have a CSV file which, when opened in Excel, has a total of 5 columns. Only columns A and C are of any significance to me and the data in the remaining columns is irrelevant.
Starting on line 8 and then working in multiples of 7 (ie. lines 8, 15, 22, 29, 36 etc...), I am looking to create a dictionary with... | Start by turning the text into a list of lists. That will take care of the parsing part:
```
lol = list(csv.reader(open('text.txt', 'rb'), delimiter='\t'))
```
The rest can be done with indexed lookups:
```
d = dict()
key = lol[6][0] # cell A7
value = lol[6][3] # cell D7
d[key] = value # add the entry ... |
Is this a "pythonic" method of executing functions as a python switch statement for tuple values? | 7,857,837 | 5 | 2011-10-22T06:26:56Z | 7,857,880 | 10 | 2011-10-22T06:40:30Z | [
"python"
] | I have a situation where I have six possible situations which can relate to four different results. Instead of using an extended if/else statement, I was wondering if it would be more pythonic to use a dictionary to call the functions that I would call inside the if/else as a replacement for a "switch" statement, like ... | Consider this idiom instead:
```
>>> def run():
... print 'run'
...
>>> def walk():
... print 'walk'
...
>>> def talk():
... print 'talk'
>>> switch={'run':run,'walk':walk,'talk':talk}
>>> switch['run']()
run
```
I think it is a little more readable than the direction you are heading.
**edit**
And this wor... |
Is there a way to define the [ ] operator for an instance of class? | 7,858,516 | 2 | 2011-10-22T09:18:03Z | 7,858,534 | 7 | 2011-10-22T09:21:54Z | [
"python",
"object",
"operators"
] | I want to define class to represent a matrix
```
class matrix:
def __init__(self, mat):
self.mat = mat
self.dim = len(mat)
@classmethod
def withDim(matrix, dimension):
mat = [ [0]*dimension for i in range(dimension)]
return matrix(mat)
```
where `mat` is a list of lists, s... | operator[] calls `__getitem__`:
```
class A:
def __getitem__(self, index):
return index+1
a = A()
print(a[1]) # prints 2
```
You can implement [][] by returning a proxy object which represents the row and also responds to `__getitem__`. Or, you can accept tuple as index and use `A[i,j]` syntax. |
Run Python scripts from Windows command line, argument not passed | 7,860,872 | 12 | 2011-10-22T16:22:53Z | 13,417,863 | 10 | 2012-11-16T13:46:25Z | [
"python",
"windows",
"command-line",
"command-line-arguments"
] | I have a bunch of scripts written in Python. I run them from a Windows command prompt like
```
c:> my_script.py arg1 arg2 arg3
```
This works in every computer and every Windows version since many years ago. Just now it this has broken on my Windows 7 system. The script is loaded and executed. But none of the argumen... | I had the same problem with Windows 7 / Python, and eventualy found that I had to set up correct file associations AND update two registry entries through regedit.
It is all described in this excelent article:
<http://eli.thegreenplace.net/2010/12/14/problem-passing-arguments-to-python-scripts-on-windows/> |
Check if a geopoint with latitude and longitude is within a shapefile | 7,861,196 | 12 | 2011-10-22T17:10:39Z | 13,433,127 | 13 | 2012-11-17T17:49:28Z | [
"python",
"geolocation",
"geocoding",
"geospatial",
"shapefile"
] | Whats the way to check if a geopoint is within the area of a given shapefile? I maneged to load a shapefile in python, but can't get any further. | This is an adaptation of yosukesabai's answer.
I wanted to ensure that the point I was searching for was in the same projection system as the shapefile, so I've added code for that.
I couldn't understand why he was doing a contains test on `ply = feat_in.GetGeometryRef()` (in my testing things seemed to work just as ... |
Check if a geopoint with latitude and longitude is within a shapefile | 7,861,196 | 12 | 2011-10-22T17:10:39Z | 18,749,373 | 12 | 2013-09-11T19:11:49Z | [
"python",
"geolocation",
"geocoding",
"geospatial",
"shapefile"
] | Whats the way to check if a geopoint is within the area of a given shapefile? I maneged to load a shapefile in python, but can't get any further. | Another option is to use Shapely (a Python library based on GEOS, the engine for PostGIS) and Fiona (which is basically for reading/writing files):
```
import fiona
import shapely
with fiona.open("path/to/shapefile.shp") as fiona_collection:
# In this case, we'll assume the shapefile only has one record/layer (e... |
JPype doesn't work inside thread? | 7,861,299 | 4 | 2011-10-22T17:22:30Z | 7,861,440 | 7 | 2011-10-22T17:44:48Z | [
"java",
"python",
"porting"
] | I tested out a simple hello world line to test out JPype:
jpype.java.lang.System.out.println("hello world")
It works great inside the context of a "main" python program. However, inside the context of a running thread, I get the following response:
```
#
# A fatal error has been detected by the Java Runtime Environm... | citing from the [JPype documentation](http://jpype.sourceforge.net/doc/user-guide/userguide.html#python_threads):
> Python Threads
>
> For the most part, python threads based on OS level threads (i.e posix threads), will work without problem. The only thing to remember is to call `jpype.attachThreadToJVM()` in the thr... |
Python Selenium accessing HTML source | 7,861,775 | 40 | 2011-10-22T18:38:26Z | 7,866,938 | 82 | 2011-10-23T15:08:06Z | [
"python",
"selenium"
] | How can I get the [HTML](http://en.wikipedia.org/wiki/HTML) source in a variable using the Selenium module with Python?
I wanted to do something like this:
```
from selenium import webdriver
browser = webdriver.Firefox()
browser.get(raw_input("Enter URL: "))
if "whatever" in html_source:
# Do something
else:
... | You need to call the `page_source` property. See below.
```
from selenium import webdriver
browser = webdriver.Firefox()
browser.get(raw_input("Enter URL: "))
html_source = browser.page_source
if "whatever" in html_source:
# do something
else:
# do something else
``` |
Performance of scipy.weave.inline | 7,861,930 | 2 | 2011-10-22T19:05:26Z | 7,866,609 | 7 | 2011-10-23T14:13:34Z | [
"python",
"performance"
] | I am a Python novice who is trying to learn a bit about this fantastic programming language. I have tried using scipy.weave.inline to speed up some computation. Just to learn a bit, I tried to implement a matrix multiplication using scipy.weave.inline. I have not included any error handling - just trying it out to bett... | You implemented a naive matrix multiplication algorithm, which `scipy.weave` compiles to fast machine code.
However, there are non-obvious, more CPU cache efficient [algorithms for matrix multiplication](http://en.wikipedia.org/wiki/Matrix_multiplication#Algorithms_for_efficient_matrix_multiplication) (which usually s... |
Consistent way to redirect both stdin & stdout to files in python using optparse | 7,862,987 | 12 | 2011-10-22T22:18:39Z | 7,864,158 | 12 | 2011-10-23T03:28:52Z | [
"python",
"stdout",
"stdin",
"optparse"
] | I've got a dozen programs that can accept input via stdin or an option, and I'd like to implement the same features in a similar way for the output.
The optparse code looks like this:
```
parser.add_option('-f', '--file',
default='-',
help='Specifies the input file. The default is stdin.')
parser.add_o... | For input files you could use [`fileinput`](http://docs.python.org/library/fileinput.html) module. It follows common convention for input files: if no files given or filename is '-' it reads stdin, otherwise it reads from files given at a command-line.
There is no need in `-f` and `--file` options. If your program alw... |
Consistent way to redirect both stdin & stdout to files in python using optparse | 7,862,987 | 12 | 2011-10-22T22:18:39Z | 11,721,741 | 10 | 2012-07-30T12:37:21Z | [
"python",
"stdout",
"stdin",
"optparse"
] | I've got a dozen programs that can accept input via stdin or an option, and I'd like to implement the same features in a similar way for the output.
The optparse code looks like this:
```
parser.add_option('-f', '--file',
default='-',
help='Specifies the input file. The default is stdin.')
parser.add_o... | If you can use [`argparse`](http://docs.python.org/library/argparse) (i.e. Python 2.7+), it has built-in support for what you want: straight from [`argparse` doc](http://docs.python.org/library/argparse#printing-help)
> The `FileType` factory creates objects that can be passed to the type argument of `ArgumentParser.a... |
Change Program Flow based on Available Libraries | 7,863,224 | 4 | 2011-10-22T23:10:29Z | 7,863,243 | 7 | 2011-10-22T23:16:01Z | [
"python",
"matplotlib",
"graph"
] | I am developing a Python model that will support graphing if the correct modules are installed. I would like the source code to be the same if possible, IE, if the graphing model can't load, graphing would be ignored from the menu logic.
How can I accomplish this? | Attempt an import and set a flag if fails. Then use the flag to determine whether to offer graphic output:
```
try:
import Tkinter
gui_installed = True
except ImportError:
gui_installed = False
...
result = somecalc()
if gui_installed:
display_with_gui(result)
else:
display_as_text(result)
``` |
When would `if False` execute in Python? | 7,863,394 | 4 | 2011-10-22T23:50:10Z | 7,863,403 | 7 | 2011-10-22T23:52:44Z | [
"python"
] | While browsing some code, I came across this line:
```
if False: #shedskin
```
I understand that [Shedskin](http://code.google.com/p/shedskin/) is a kind of Python -> C++ compiler, but I can't understand that line.
Shouldn't `if False:` never execute? What's going on here?
For context:
This is the whole block:
``... | It will never get executed. It's one way to temporarily disable part of the code. |
When would `if False` execute in Python? | 7,863,394 | 4 | 2011-10-22T23:50:10Z | 7,863,470 | 7 | 2011-10-23T00:06:28Z | [
"python"
] | While browsing some code, I came across this line:
```
if False: #shedskin
```
I understand that [Shedskin](http://code.google.com/p/shedskin/) is a kind of Python -> C++ compiler, but I can't understand that line.
Shouldn't `if False:` never execute? What's going on here?
For context:
This is the whole block:
``... | It won't execute, because it isn't supposed to. The `if False:` is there to intentionally prevent the next line from executing, because that code's only purpose is seemingly to help Shed Skin infer type information about the argument to the `AStar()` function.
You can see another example of this [in `httplib`](http://... |
Rock Paper Scissors in Python | 7,863,471 | 4 | 2011-10-23T00:06:47Z | 7,863,548 | 7 | 2011-10-23T00:30:45Z | [
"python",
"python-3.x"
] | I am trying to write a Python program and I am having a hard time getting my score. I have written it as a value returning function and every time I run the program it seems to skip the step where it retrieves the score unless I include an else statement which it will automatcially jump the the else statement.
I will a... | There's so much wrong with this, it's hard to know where to start (but don't get discouraged)...
First of all, it looks like (mostly from your use of `input` vs. `raw_input` and your parens with your print statements) you're using Python 3, which already is going to limit the amount of help you get. Most people are st... |
passing **settings info to unittest from nose | 7,864,285 | 4 | 2011-10-23T04:06:14Z | 7,869,763 | 7 | 2011-10-23T22:40:32Z | [
"python",
"pyramid"
] | I'm running my unit tests using nose.
I have .ini files such as production.ini, development.ini, local.ini. Finally, I have a test.ini file which looks like:
```
[app:main]
use = config:local.ini
# Add additional test specific configuration options as necessary.
sqlalchemy.url = sqlite:///%(here)s/tests.db
```
In m... | You will need to parse the settings from the INI file yourself. Pylons used to do this automatically for you by just hard-coding a load for "test.ini". The two options you have are 1) just load the INI settings via `settings = paste.deploy.appconfig('test.ini')` or 2) loading the actual WSGI app yourself, like if you w... |
multiprocessing.Pool - PicklingError: Can't pickle <type 'thread.lock'>: attribute lookup thread.lock failed | 7,865,430 | 13 | 2011-10-23T09:51:29Z | 7,865,512 | 16 | 2011-10-23T10:11:37Z | [
"python",
"threadpool",
"multiprocessing",
"pickle"
] | `multiprocessing.Pool` is driving me crazy...
I want to upgrade many packages, and for every one of them I have to check whether there is a greater version or not. This is done by the `check_one` function.
The main code is in the `Updater.update` method: there I create the Pool object and call the `map()` method.
... | multiprocessing passes tasks (which include `check_one` and `data`) to the worker processes through a `Queue.Queue`. Everything put in the `Queue.Queue` must be pickable. `Queue`s themselves are not pickable:
```
import multiprocessing as mp
import Queue
def foo(queue):
pass
pool=mp.Pool()
q=Queue.Queue()
pool.... |
Instantiating class retains references | 7,865,451 | 3 | 2011-10-23T09:56:38Z | 7,865,459 | 10 | 2011-10-23T09:59:01Z | [
"python",
"class",
"object",
"reference"
] | In Python, I instantiate a class twice and store them into 2 different variables. Why does the second object contain a copy of the first object? I know it's a copy because I change the values in one object and it does not change the other. Example:
I have the following class:
```
class HistoricalData:
dataPoints ... | You've declared a [`class` variable](http://docs.python.org/tutorial/classes.html#class-objects), not an [instance variable](http://docs.python.org/tutorial/classes.html#instance-objects).
Class variables are shared among *all instances* of the `class`. This means that when you update one `HistoricalData` `object`, yo... |
Selenium - Python - drop-down menu option value | 7,867,537 | 35 | 2011-10-23T16:40:46Z | 7,972,225 | 32 | 2011-11-01T20:05:49Z | [
"python",
"selenium",
"selenium-webdriver",
"web-scraping",
"webdriver"
] | I need to select an element from a drop-down menu.
For example, open this:
```
<select id="fruits01" class="select" name="fruits">
<option value="0">Choose your fruits:</option>
<option value="1">Banana</option>
<option value="2">Mango</option>
</select>
```
1. So first I have to click on it. I do this:
... | Unless your click is firing some kind of ajax call to populate your list, you don't actually need to execute the click.
Just find the element and then enumerate the options, selecting the option(s) you want.
Here is an example:
```
from selenium import webdriver
b = webdriver.Firefox()
b.find_element_by_xpath("//sel... |
Selenium - Python - drop-down menu option value | 7,867,537 | 35 | 2011-10-23T16:40:46Z | 28,613,320 | 44 | 2015-02-19T17:47:51Z | [
"python",
"selenium",
"selenium-webdriver",
"web-scraping",
"webdriver"
] | I need to select an element from a drop-down menu.
For example, open this:
```
<select id="fruits01" class="select" name="fruits">
<option value="0">Choose your fruits:</option>
<option value="1">Banana</option>
<option value="2">Mango</option>
</select>
```
1. So first I have to click on it. I do this:
... | Selenium provides a convenient [`Select` class](http://selenium-python.readthedocs.org/en/latest/api.html#selenium.webdriver.support.select.Select) to work with `select -> option` constructs:
```
from selenium import webdriver
from selenium.webdriver.support.ui import Select
driver = webdriver.Firefox()
driver.get('u... |
python: re.sub's replace function doesn't accept extra arguments - how to avoid global variable? | 7,868,554 | 6 | 2011-10-23T19:23:20Z | 7,868,598 | 11 | 2011-10-23T19:30:52Z | [
"python",
"global-variables"
] | I'm trying to increment all timestamps (of the form 'HH:MM:SS') in a text file by a number of seconds specified by a command-line parameter to my program.
Here's a simplified version of my effort so far:
```
import re
from datetime import datetime, timedelta
time_diff = timedelta(seconds=10)
def replace_time(matcho... | You can wrap a function in a closure like this:
```
def increment_by(time_diff):
def replace_time(matchobj):
if matchobj.group(1) not in [None, '']:
return (datetime.strptime(matchobj.group(1), "%H:%M:%S") + time_diff).strftime("%H:%M:%S")
return replace_time
time_diff = timedelta(seconds=... |
Concatenate Numpy arrays without copying | 7,869,095 | 35 | 2011-10-23T20:50:00Z | 7,869,472 | 31 | 2011-10-23T21:49:51Z | [
"python",
"multidimensional-array",
"numpy"
] | In Numpy, I can concatenate two arrays end-to-end with `np.append` or `np.concatenate`:
```
>>> X = np.array([[1,2,3]])
>>> Y = np.array([[-1,-2,-3],[4,5,6]])
>>> Z = np.append(X, Y, axis=0)
>>> Z
array([[ 1, 2, 3],
[-1, -2, -3],
[ 4, 5, 6]])
```
But these make copies of their input arrays:
```
>>>... | The memory belonging to a Numpy array must be contiguous. If you allocated the arrays separately, they are randomly scattered in memory, and there is no way to represent them as a view Numpy array.
If you know beforehand how many arrays you need, you can instead start with one big array that you allocate beforehand, a... |
MongoDB - Upsert with increment | 7,869,144 | 8 | 2011-10-23T20:58:22Z | 7,873,886 | 13 | 2011-10-24T09:56:25Z | [
"python",
"mongodb",
"pymongo"
] | I am trying to run the following query:
```
data = {
'user_id':1,
'text':'Lorem ipsum',
'$inc':{'count':1},
'$set':{'updated':datetime.now()},
}
self.db.collection('collection').update({'user_id':1}, data, upsert=True)
```
but the two '$' queries cause it to fail. Is it possible to do this within one... | First of all, when you ask a question like this it's very helpful to add information on why it's failing (e.g. copy the error).
Your query fails because you're mixing $ operators with document overrides. You should use the $set operator for the `user_id` and text fields as well (although the `user_id` part in your upd... |
How to make python argparse mutually exclusive group arguments without prefix? | 7,869,345 | 35 | 2011-10-23T21:27:18Z | 7,869,444 | 30 | 2011-10-23T21:44:24Z | [
"python",
"argparse"
] | Python2.7 argparse only accepts optional arguments (prefixed) in mutually exclusive groups:
```
parser = argparse.ArgumentParser(prog='mydaemon')
action = parser.add_mutually_exclusive_group(required=True)
action.add_argument('--start', action='store_true', help='Starts %(prog)s daemon')
action.add_argument('--stop', ... | It sounds like you want a positional argument instead of mutually exclusive options. You can use 'choices' to restrict the possible acceptable options.
```
parser = ArgumentParser()
parser.add_argument('action', choices=('start', 'stop', 'restart'))
```
This produces a usage line that looks like this:
```
usage: foo... |
How to make python argparse mutually exclusive group arguments without prefix? | 7,869,345 | 35 | 2011-10-23T21:27:18Z | 8,621,697 | 39 | 2011-12-24T00:00:44Z | [
"python",
"argparse"
] | Python2.7 argparse only accepts optional arguments (prefixed) in mutually exclusive groups:
```
parser = argparse.ArgumentParser(prog='mydaemon')
action = parser.add_mutually_exclusive_group(required=True)
action.add_argument('--start', action='store_true', help='Starts %(prog)s daemon')
action.add_argument('--stop', ... | For all the abilities and options in `argparse` I don't think you'll ever get a "canned" usage string that looks like what you want.
That said, have you looked at sub-parsers since your original post?
Here's a barebones implementation:
```
import argparse
parser = argparse.ArgumentParser(prog='mydaemon')
sp = parse... |
How to make python argparse mutually exclusive group arguments without prefix? | 7,869,345 | 35 | 2011-10-23T21:27:18Z | 12,530,968 | 8 | 2012-09-21T12:51:34Z | [
"python",
"argparse"
] | Python2.7 argparse only accepts optional arguments (prefixed) in mutually exclusive groups:
```
parser = argparse.ArgumentParser(prog='mydaemon')
action = parser.add_mutually_exclusive_group(required=True)
action.add_argument('--start', action='store_true', help='Starts %(prog)s daemon')
action.add_argument('--stop', ... | Building on Adam's answer... if you wanted to specify a default you could always do the following so they can effectively leave it blank.
```
import argparse
ActionHelp = """
Start = Starts the daemon (default)
Stop = Stops the daemon
Restart = Restarts the daemon
"""
parser = argparse.ArgumentParser(... |
How to make python argparse mutually exclusive group arguments without prefix? | 7,869,345 | 35 | 2011-10-23T21:27:18Z | 26,992,149 | 9 | 2014-11-18T10:35:06Z | [
"python",
"argparse"
] | Python2.7 argparse only accepts optional arguments (prefixed) in mutually exclusive groups:
```
parser = argparse.ArgumentParser(prog='mydaemon')
action = parser.add_mutually_exclusive_group(required=True)
action.add_argument('--start', action='store_true', help='Starts %(prog)s daemon')
action.add_argument('--stop', ... | from [pymotw](http://pymotw.com/2/argparse/index.html#module-argparse)
```
import argparse
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument('-a', action='store_true')
group.add_argument('-b', action='store_true')
print parser.parse_args()
```
output:
$ python ar... |
Manipulating Lists within lists in python | 7,870,008 | 4 | 2011-10-23T23:23:36Z | 7,870,019 | 7 | 2011-10-23T23:25:50Z | [
"python",
"nested-lists"
] | I'm having trouble wrapping my head around dealing with lists within lists in python (I am rather new at programming).
Now how would I access each nested list position and then manipulate the position of the nested list's values to, for example, change their order while maintaining the position of the nested list in t... | Use a list comprehension to get the new elements, and optionally slice-assign to replace the existing elements in the list.
```
new_aList = [list(reversed(x)) for x in aList]
aList[:] = [list(reversed(x)) for x in aList]
``` |
Check if file system is case-insensitive in Python | 7,870,041 | 12 | 2011-10-23T23:29:50Z | 7,870,076 | 16 | 2011-10-23T23:38:38Z | [
"python",
"filesystems",
"ntfs",
"hfs+"
] | Is there a simple way to check in Python if a file system is case insensitive? I'm thinking in particular of file systems like HFS+ (OSX) and NTFS (Windows), where you can access the same file as foo, Foo or FOO, even though the file case is preserved. | ```
import os
import tempfile
# By default mkstemp() creates a file with
# a name that begins with 'tmp' (lowercase)
tmphandle, tmppath = tempfile.mkstemp()
if os.path.exists(tmppath.upper()):
# Case insensitive.
else:
# Case sensitive.
``` |
Python main call within class | 7,870,869 | 9 | 2011-10-24T02:42:39Z | 7,870,887 | 21 | 2011-10-24T02:47:42Z | [
"python",
"pydev"
] | I haven't done much python - coming from a C/Java background - so excuse me for asking such a simple question. I am using Pydev in Eclipse to write this simple program, and all I want it to do is to execute my main function:
```
class Example():
if __name__ == '__main__':
Example().main() <----- What goes ... | Well, first, you need to actually define a function before you can run it (and it doesn't need to be called `main`). For instance:
```
class Example(object):
def run(self):
print "Hello, world!"
if __name__ == '__main__':
Example().run()
```
You don't need to use a class, though - if all you want to ... |
Clojure equivalent to Python's "any" and "all" functions? | 7,871,295 | 26 | 2011-10-24T04:26:52Z | 7,871,326 | 38 | 2011-10-24T04:33:42Z | [
"python",
"clojure"
] | Are there built in functions in Clojure similar to Python's `any` and `all` functions?
For example, in Python, it's `all([True, 1, 'non-empty string']) == True`. | `(every? f data)` [[docs](http://clojure.github.com/clojure/clojure.core-api.html#clojure.core/every?)] is the same as `all(f(x) for x in data)`.
`(some f data)` [[docs](http://clojure.github.com/clojure/clojure.core-api.html#clojure.core/some)] is like `any(f(x) for x in data)` except that it returns the value of `f(... |
How to know who is importing me in python? | 7,871,319 | 5 | 2011-10-24T04:32:08Z | 7,871,699 | 7 | 2011-10-24T05:46:05Z | [
"python",
"import"
] | How can I find out what file is importing a particular file in python?
Consider the following example:
```
#a.py
import cmn
....
#b.py
import cmn
...
#cmn.py
#Here, I want to know which file (a.py or b.py)
#is importing this one.
#Is it possible to do this?
...
```
All the files `a.py`, `b.py` and `cmn.py` are in ... | The *namedtuple* code in the *collections* module has an example of how (and when) to do this:
```
#cmn.py
import sys
print 'I am being imported by', sys._getframe(1).f_globals.get('__name__')
```
One limitation of this approach is that the outermost module is always named `__main__`. If that is the case, the name of... |
Is non-blocking Redis pubsub possible? | 7,871,526 | 18 | 2011-10-24T05:13:19Z | 7,871,561 | 7 | 2011-10-24T05:21:11Z | [
"python",
"redis"
] | I want to use redis' pubsub to transmit some messages, but don't want be blocked using `listen`, like the code below:
```
import redis
rc = redis.Redis()
ps = rc.pubsub()
ps.subscribe(['foo', 'bar'])
rc.publish('foo', 'hello world')
for item in ps.listen():
if item['type'] == 'message':
print item['chan... | I don't think that would be possible. A Channel doesn't have any "current data", you subscribe to a channel and start receiving messages that are being pushed by other clients on the channel, hence it is a blocking API. Also if you look at the Redis [Commands documentation](http://redis.io/commands/subscribe) for pub/s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.