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 |
|---|---|---|---|---|---|---|---|---|---|
Is there a difference between developing a web2py app on Windows or Linux? | 5,444,798 | 2 | 2011-03-26T19:35:52Z | 5,446,275 | 9 | 2011-03-27T00:10:00Z | [
"python",
"web2py"
] | I recall setting up other frameworks in a Windows environment were extremely painful :) | It's actually extremely easy to set up web2py on Windows -- it will literally take you about a minute. Just go to the [download page](http://www.web2py.com/examples/default/download), download the "For Windows" version, unzip the downloaded file, and click the 'web2py.exe' file in the 'web2py' folder. Voilà -- you're ... |
Compare if two variables reference the same object in python | 5,445,080 | 28 | 2011-03-26T20:27:38Z | 5,445,089 | 52 | 2011-03-26T20:29:04Z | [
"python"
] | How to check whether two variables reference the same object?
```
x = ['a', 'b', 'c']
y = x # x and y reference the same object
z = ['a', 'b', 'c'] # x and z reference different objects
``` | Thats what `is` is for: `x is y` |
Compare if two variables reference the same object in python | 5,445,080 | 28 | 2011-03-26T20:27:38Z | 5,445,090 | 7 | 2011-03-26T20:29:11Z | [
"python"
] | How to check whether two variables reference the same object?
```
x = ['a', 'b', 'c']
y = x # x and y reference the same object
z = ['a', 'b', 'c'] # x and z reference different objects
``` | `y is x` will be True, `y is z` will be `False`. |
String In python with my unicode? | 5,445,250 | 8 | 2011-03-26T20:57:58Z | 5,445,292 | 10 | 2011-03-26T21:03:26Z | [
"python",
"unicode",
"python-3.x"
] | ```
Python 3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> str_version = 'ááááá¶á'
>>> type(str_version)
<class 'str'>
>>> print (str_version)
ááááá¶á
>>> unicode_version = 'ááááá¶á'.decode(... | There is nothing wrong with your string! You just have confused `encode()` and `decode()`. The string is meaningful symbols. To turn it into bytes that could be stored in a file or transmitted over the Internet, use `encode()` with an *encoding* like UTF-8. Each encoding is a scheme for converting meaningful symbols to... |
String In python with my unicode? | 5,445,250 | 8 | 2011-03-26T20:57:58Z | 5,445,307 | 7 | 2011-03-26T21:05:32Z | [
"python",
"unicode",
"python-3.x"
] | ```
Python 3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> str_version = 'ááááá¶á'
>>> type(str_version)
<class 'str'>
>>> print (str_version)
ááááá¶á
>>> unicode_version = 'ááááá¶á'.decode(... | You're reading the 2.x docs. `str.decode()` (and `bytes.encode()`) was dropped in 3.x. And `str` is already a Unicode string; there's no need to decode it. |
printing list in python properly | 5,445,970 | 37 | 2011-03-26T23:04:20Z | 5,445,983 | 85 | 2011-03-26T23:06:15Z | [
"python",
"string"
] | So I have a list:
`['x', 3, 'b']`
And I want the output to be:
`[x, 3, b]`
How can I do this in python?
If I do `str(['x', 3, 'b'])`, I get one with quotes, but I don't want quotes. | ```
mylist = ['x', 3, 'b']
print '[%s]' % ', '.join(map(str, mylist))
``` |
interpolation with python numpy | 5,446,365 | 8 | 2011-03-27T00:27:02Z | 5,446,403 | 10 | 2011-03-27T00:36:34Z | [
"python",
"numpy",
"interpolation"
] | I have an array of samples y, and corresponding x values. Some y-values may be missing and I'd like to use linear interpolation to compute them. What is the best way of doing it with python (I'm using numpy arrays). If you could provide me a sample code that would be great.
thanks | See the interpolation method in the numpy documentation that has examples:
<http://docs.scipy.org/doc/numpy/reference/generated/numpy.interp.html>
There are also a more extensive set of methods available through scipy:
<http://docs.scipy.org/doc/scipy/reference/interpolate.html> |
data type not understood | 5,446,522 | 18 | 2011-03-27T01:10:10Z | 5,446,579 | 31 | 2011-03-27T01:24:39Z | [
"python",
"matrix",
"numpy"
] | I'm trying to use a matrix to compute stuff. The code is this
```
import numpy as np
# some code
mmatrix = np.zeros(nrows, ncols)
print mmatrix[0, 0]
```
but I get 'data type not understood', and it works if I do it from terminal. | Try:
```
mmatrix = np.zeros((nrows, ncols))
```
Since the shape parameter has to be an int or sequence of ints
<http://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html>
Otherwise you are passing `ncols` to `np.zeros` as the dtype. |
"ValueError: zero length field name in format" error in Python 3.0,3.1,3.2 | 5,446,964 | 101 | 2011-03-27T03:11:24Z | 5,447,119 | 107 | 2011-03-27T04:01:55Z | [
"python",
"debugging"
] | I'm trying learn Python (3 to be more specific) and I'm getting this error:
```
ValueError: zero length field name in format
```
I googled it and I found out you need to specify the numbers:
```
a, b = 0, 1
if a < b:
print('a ({0}) is less than b ({1})'.format(a, b))
else:
print('a ({0}) is not less than b... | I'm gonna guess that you are running python 2.6 by accident somehow.
This feature is only available for at least 3.1 if you are using python 3, or 2.7 if you are using python 2. |
"ValueError: zero length field name in format" error in Python 3.0,3.1,3.2 | 5,446,964 | 101 | 2011-03-27T03:11:24Z | 8,498,327 | 134 | 2011-12-14T00:54:29Z | [
"python",
"debugging"
] | I'm trying learn Python (3 to be more specific) and I'm getting this error:
```
ValueError: zero length field name in format
```
I googled it and I found out you need to specify the numbers:
```
a, b = 0, 1
if a < b:
print('a ({0}) is less than b ({1})'.format(a, b))
else:
print('a ({0}) is not less than b... | Python 2.6 and 3.0 require the field numbers. [In Python 2.7 and later](http://docs.python.org/library/string.html) and 3.1 and later, they can be omitted.
> Changed in version 2.7: The positional argument specifiers can be
> omitted, so '{} {}' is equivalent to '{0} {1}'.
```
python2.6.4>>> print '|{0:^12}|{1:^12}|'... |
Running Scapy on Windows with Python 2.7 | 5,447,461 | 24 | 2011-03-27T05:32:54Z | 7,738,697 | 16 | 2011-10-12T10:32:28Z | [
"python",
"windows",
"python-2.7",
"scapy"
] | I like to use Scapy with Python v2.7 under Windows 7.
* How can I install the required module pypcap for Python 2.7?
* Will it be possible to make Python scripts depending on Scapy into standalone Windows applications using a distribution tool such as py2exe?
The particular Python distribution I am using is Enthought... | **Q: how can i install required module pypcap**
Using Scapy with Windows 7 is possible, but it does not exactly work out of the box. An install guide can be found here:
<http://www.secdev.org/projects/scapy/doc/installation.html#windows>
I strongly recommend to switch to python 2.6, as this will make your live much ... |
Running Scapy on Windows with Python 2.7 | 5,447,461 | 24 | 2011-03-27T05:32:54Z | 27,040,800 | 19 | 2014-11-20T13:26:53Z | [
"python",
"windows",
"python-2.7",
"scapy"
] | I like to use Scapy with Python v2.7 under Windows 7.
* How can I install the required module pypcap for Python 2.7?
* Will it be possible to make Python scripts depending on Scapy into standalone Windows applications using a distribution tool such as py2exe?
The particular Python distribution I am using is Enthought... | In case someone needs **Scapy for 64-bit** + **Python 2.7**, I've uploaded the binaries here:
### <https://github.com/Kondziowy/scapy_win64>
* [**dnet-1.12.win-amd64-py2.7.exe**](https://github.com/Kondziowy/scapy_win64/raw/master/win64/dnet-1.12.win-amd64-py2.7.exe)
* [**pcap-1.1.win-amd64-py2.7.exe**](https://githu... |
Best way to remove an item from a Python dictionary? | 5,447,494 | 71 | 2011-03-27T05:47:07Z | 5,447,509 | 62 | 2011-03-27T05:51:10Z | [
"python",
"dictionary"
] | What is the best way to remove an item from a dictionary when the item's key is unknown? Here's a simple approach:
```
for key, item in some_dict.items():
if item is item_to_remove:
del some_dict[key]
```
Are there better ways? Is there anything wrong with mutating (deleting items) from the dictionary whi... | Be aware that you're currently testing for object identity (`is` only returns `True` if both operands are represented by the same object in memory - this is not always the case with two object that compare equal with `==`). If you are doing this on purpose, then you could rewrite your code as
```
some_dict = {key: val... |
Best way to remove an item from a Python dictionary? | 5,447,494 | 71 | 2011-03-27T05:47:07Z | 5,447,515 | 7 | 2011-03-27T05:52:23Z | [
"python",
"dictionary"
] | What is the best way to remove an item from a dictionary when the item's key is unknown? Here's a simple approach:
```
for key, item in some_dict.items():
if item is item_to_remove:
del some_dict[key]
```
Are there better ways? Is there anything wrong with mutating (deleting items) from the dictionary whi... | `items()` returns a list, and it is that list you are iterating, so mutating the dict in the loop doesn't matter here. If you were using `iteritems()` instead, mutating the dict in the loop [would be problematic](http://docs.python.org/library/stdtypes.html#dict.iteritems), and likewise for `viewitems()` in Python 2.7.... |
Best way to remove an item from a Python dictionary? | 5,447,494 | 71 | 2011-03-27T05:47:07Z | 5,447,527 | 71 | 2011-03-27T05:55:31Z | [
"python",
"dictionary"
] | What is the best way to remove an item from a dictionary when the item's key is unknown? Here's a simple approach:
```
for key, item in some_dict.items():
if item is item_to_remove:
del some_dict[key]
```
Are there better ways? Is there anything wrong with mutating (deleting items) from the dictionary whi... | ```
>>> dic = {'a':1, 'b':2}
>>> dic
{'a': 1, 'b': 2}
>>> dic.pop('c', 0)
0
>>> dic.pop('a', 0)
1
>>> dic
{'b': 2}
``` |
Best way to remove an item from a Python dictionary? | 5,447,494 | 71 | 2011-03-27T05:47:07Z | 5,448,005 | 34 | 2011-03-27T08:18:39Z | [
"python",
"dictionary"
] | What is the best way to remove an item from a dictionary when the item's key is unknown? Here's a simple approach:
```
for key, item in some_dict.items():
if item is item_to_remove:
del some_dict[key]
```
Are there better ways? Is there anything wrong with mutating (deleting items) from the dictionary whi... | ```
a = {'name': 'your_name','class': 4}
if 'name' in a: del a['name']
``` |
Best way to remove an item from a Python dictionary? | 5,447,494 | 71 | 2011-03-27T05:47:07Z | 5,448,359 | 7 | 2011-03-27T09:34:35Z | [
"python",
"dictionary"
] | What is the best way to remove an item from a dictionary when the item's key is unknown? Here's a simple approach:
```
for key, item in some_dict.items():
if item is item_to_remove:
del some_dict[key]
```
Are there better ways? Is there anything wrong with mutating (deleting items) from the dictionary whi... | I'd build a list of keys that need removing, then remove them. It's simple, efficient and avoids any problem about simultaneously iterating over and mutating the dict.
```
keys_to_remove = [key for key, value in some_dict.iteritems()
if value == value_to_remove]
for key in keys_to_remove:
del som... |
Best way to remove an item from a Python dictionary? | 5,447,494 | 71 | 2011-03-27T05:47:07Z | 14,742,820 | 24 | 2013-02-07T03:04:54Z | [
"python",
"dictionary"
] | What is the best way to remove an item from a dictionary when the item's key is unknown? Here's a simple approach:
```
for key, item in some_dict.items():
if item is item_to_remove:
del some_dict[key]
```
Are there better ways? Is there anything wrong with mutating (deleting items) from the dictionary whi... | A simple comparison between *del* and *pop()*:
```
import timeit
code = """
results = {'A': 1, 'B': 2, 'C': 3}
del results['A']
del results['B']
"""
print timeit.timeit(code, number=100000)
code = """
results = {'A': 1, 'B': 2, 'C': 3}
results.pop('A')
results.pop('B')
"""
print timeit.timeit(code, number=100000)
```
... |
How can I use Pika to send and receive RabbitMQ messages? | 5,448,936 | 4 | 2011-03-27T11:30:29Z | 5,449,755 | 10 | 2011-03-27T14:12:36Z | [
"python",
"rabbitmq",
"amqp"
] | I'm having some issue getting Pika to work with routing keys or exchanges in a way that's consistent with it AMQP or RabbitMQ documentation. I understand that the RabbitMQ documentation uses an older version of Pika, so I have disregarded their example code.
What I'm trying to do is define a queue, "order" and have tw... | As it turns out, my understanding of AMQP was incomplete.
The idea is as following:
**Client**:
The client after getting the connection should not care about anything else but the name of the exchange and the routing key. That is we don't know which queue this will end up in.
```
channel.basic_publish(exchange='ord... |
Sending out twitter retweets with Python | 5,449,091 | 4 | 2011-03-27T12:05:45Z | 5,449,242 | 7 | 2011-03-27T12:39:46Z | [
"python",
"twitter"
] | I wanted to know if this was possible- I want to use Python to retweet every tweet a person sends out. If yes then how can I implement this? | Unfortunately, [python-twitter](http://code.google.com/p/python-twitter/) does *not yet* support the Twitter [Retweet REST call](http://dev.twitter.com/doc/post/statuses/retweet/:id).
You'll have to make that call directly yourself (using direct calls to api.\_FetchURL) or apply the patch in [issue 130](http://code.go... |
Python's equivalent for Ruby's define_method? | 5,449,244 | 3 | 2011-03-27T12:39:56Z | 5,449,293 | 12 | 2011-03-27T12:48:11Z | [
"python",
"ruby"
] | Is there a Python equivalent for Ruby's `define_method`, which would allow dynamic generation of class methods?
(as can be seen in Wikipedia's [Ruby example code](http://en.wikipedia.org/wiki/Ruby_%28programming_language%29#Metaprogramming)) | Functions are first-class objects in Python and can be assigned to attributes of a class or an instance. One way to do the same thing as in the Wikipedia example is:
```
colours = {"black": "000",
"red": "f00",
"green": "0f0",
"yellow": "ff0",
"blue": "00f",
"mage... |
Python 2D Array access with Points (x,y) | 5,450,067 | 2 | 2011-03-27T15:05:28Z | 5,450,087 | 7 | 2011-03-27T15:09:08Z | [
"python"
] | Good Evening mates,
I'm new to python programming, and I was just wondering if you can access a 2D array in python using Points/Coordinate?
Example you have a point:
**point** = (1,2)
and you have a matrix, then you access a certain part of the matrix using a coordinate
Matrix[**point**] = *a sample value here*
Th... | The popular [NumPy package](http://numpy.org/) provides multidimensional arrays that support indexing by tuples:
```
import numpy
a = numpy.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]])
print a[1, 2]
point = (1, 2)
print a[point]
```
Without any external libraries, there is no such thing as a "two-dimensional array" in Py... |
what's the difference between matplotlib.pyplot and matplotlib.figure? | 5,450,207 | 9 | 2011-03-27T15:29:37Z | 5,450,333 | 11 | 2011-03-27T15:54:10Z | [
"python",
"wxpython",
"matplotlib"
] | i'm just getting into matplotlib.
I see some examples of matplotlib.pyplot used, but when integrating matplotlib with wxpython i often see matplotlib.figure like
```
from matplotlib.figure import Figure
...
vboxFigure = wx.BoxSizer(wx.VERTICAL)
self.figure = Figure()
self.axes = self.figure.add_subplot(111)
t = [1... | Pyplot is the Matlab-like state-machine API, matplotlib.figure.Figure is part of the object-oriented API. See e.g. [this tutorial](http://web.archive.org/web/20100830233506/http://matplotlib.sourceforge.net/leftwich_tut.txt) to get started with the object-oriented API. If you want to create a wx app, [you will most lik... |
Keys are not unique for a python dictionary! | 5,451,261 | 2 | 2011-03-27T18:18:26Z | 5,451,361 | 13 | 2011-03-27T18:33:26Z | [
"python",
"dictionary",
"hashtable"
] | A stupid newbie question here
For a python dictionary q `len(set(q.keys())) != len(q.keys())`. Is that even possible? | This can happen if you violate a requirement of `dict`, and change its hash.
When an object is used in a `dict`, its hash value must not change, and its equality to other objects must not change. Other properties *may* change, as long as they don't affect how it appears to the dict.
(This does *not* mean that a hash ... |
Converting timezone-aware datetime to local time in Python | 5,452,555 | 26 | 2011-03-27T21:24:13Z | 5,452,709 | 40 | 2011-03-27T21:50:31Z | [
"python",
"django",
"datetime",
"iso8601"
] | How do you convert a timezone-aware datetime object to the equivalent non-timezone-aware datetime for the local timezone?
My particular application uses Django (although, this is in reality a generic Python question):
```
import iso8601
```
....
```
date_str="2010-10-30T17:21:12Z"
```
....
```
d = iso8601.parse_d... | In general, to convert an arbitrary timezone-aware datetime to a naive (local) datetime, I'd use the `pytz` module and `astimezone` to convert to local time, and `replace` to make the datetime naive:
```
In [76]: import pytz
In [77]: est=pytz.timezone('US/Eastern')
In [78]: d.astimezone(est)
Out[78]: datetime.dateti... |
Converting timezone-aware datetime to local time in Python | 5,452,555 | 26 | 2011-03-27T21:24:13Z | 12,009,299 | 39 | 2012-08-17T16:09:04Z | [
"python",
"django",
"datetime",
"iso8601"
] | How do you convert a timezone-aware datetime object to the equivalent non-timezone-aware datetime for the local timezone?
My particular application uses Django (although, this is in reality a generic Python question):
```
import iso8601
```
....
```
date_str="2010-10-30T17:21:12Z"
```
....
```
d = iso8601.parse_d... | In recent versions of Django (at least 1.4.1):
```
from django.utils.timezone import localtime
result = localtime(some_time_object)
``` |
Python regex to match text in single quotes, ignoring escaped quotes (and tabs/newlines) | 5,452,655 | 7 | 2011-03-27T21:42:04Z | 5,453,821 | 12 | 2011-03-28T01:31:03Z | [
"python",
"regex"
] | Given a file of text, where the character I want to match are delimited by single-quotes, but might have zero or one escaped single-quote, as well as zero or more tabs and newline characters (not escaped) - I want to match the text only. Example:
```
menu_item = 'casserole';
menu_item = 'meat
loaf';
menu_... | This tested script should do the trick:
```
import re
re_sq_long = r"""
# Match single quoted string with escaped stuff.
' # Opening literal quote
( # $1: Capture string contents
[^'\\]* # Zero or more non-', non-backslash
(?: # "unroll-the-loop"!
\\. ... |
String to list in Python | 5,453,026 | 11 | 2011-03-27T22:50:57Z | 5,453,032 | 25 | 2011-03-27T22:51:56Z | [
"python",
"string",
"list"
] | Hi I'm pretty new at programming and I'm trying to split a string:
```
'QH QD JC KD JS'
```
into a list like:
```
['QH', 'QD', 'JC', 'KD', 'JS']
```
I have tried splitting but it didn't seem to work. How would I go about doing this?
Thanks | ```
>>> 'QH QD JC KD JS'.split()
['QH', 'QD', 'JC', 'KD', 'JS']
```
[`split`](http://docs.python.org/library/stdtypes.html#str.split):
> Return a list of the words in the
> string, using `sep` as the delimiter
> string. If `maxsplit` is given, at most
> `maxsplit` splits are done (thus, the
> list will have at most `... |
Is it possible to modify lines in a file in-place? | 5,453,267 | 23 | 2011-03-27T23:39:58Z | 5,463,419 | 22 | 2011-03-28T18:31:27Z | [
"python",
"file-io"
] | Is it possible to parse a file line by line, and edit a line in-place while going through the lines? | > Is it possible to parse a file line by line, and edit a line in-place while going through the lines?
It can be simulated using a backup file as stdlib's [`fileinput` module](http://docs.python.org/library/fileinput) does.
Here's an example script that removes lines that do not satisfy `some_condition` from files gi... |
Matplotlib svg as string and not a file | 5,453,375 | 11 | 2011-03-28T00:01:24Z | 5,453,692 | 15 | 2011-03-28T01:01:46Z | [
"python",
"django",
"svg",
"matplotlib"
] | I'd like to use Matplotlib and pyplot to generate an svg image to be used in a Django framework. as of now I have it generating image files that are link to by the page, but is there a way to directly get with the svg image as a unicode string without having to write to the file system? | Try using `StringIO` to avoid writing any file-like object to disk.
```
import matplotlib.pyplot as plt
import StringIO
from matplotlib import numpy as np
x = np.arange(0,np.pi*3,.1)
y = np.sin(x)
fig = plt.figure()
plt.plot(x,y)
imgdata = StringIO.StringIO()
fig.savefig(imgdata, format='svg')
imgdata.seek(0) # re... |
override builtin "and" | 5,453,546 | 3 | 2011-03-28T00:32:21Z | 5,453,559 | 7 | 2011-03-28T00:35:39Z | [
"python",
"override"
] | can the primitive "and" be overridden?
for instance If I try to do something like this
```
class foo():
def __and__(self,other):
return "bar"
```
this gets outputted
```
>> foo() and 4
4
>> foo().__and__(4)
'bar'
```
my intuition is that the built in and cannot be overridden and shouldn't be overridde... | `__and__` overrides the bitwise operator `&`, not the logic operator.
To give your class boolean logic handling, define a `__nonzero__` method: <http://docs.python.org/reference/datamodel.html#object.__nonzero__> |
Create a tuple from a string and a list of strings | 5,453,979 | 7 | 2011-03-28T02:09:20Z | 5,454,008 | 13 | 2011-03-28T02:15:17Z | [
"python",
"string",
"list",
"tuples"
] | I need to combine a string along with a list of strings into a tuple so I can use it as a dictionary key. This is going to be in an inner loop so speed is important.
The list will be small (usually 1, but occasionally 2 or 3 items).
What is the fastest way to do this?
Before:
```
my_string == "foo"
my_list == ["bar... | I can't speak for performance, but this is definitely the simplest I can think of:
```
my_tuple = tuple([my_string] + my_list)
``` |
How efficient is Python's max function | 5,454,030 | 2 | 2011-03-28T02:18:36Z | 5,454,036 | 11 | 2011-03-28T02:19:37Z | [
"python",
"performance",
"python-3.x",
"big-o"
] | The function `max()` which returns the maximum element from a list . . . what is its running time (in Python 3) in terms of [Big O notation](http://en.wikipedia.org/wiki/Big_O_notation)? | It's O(n), since it must check every element. If you want better performance for max, you can use the [heapq](http://docs.python.org/library/heapq.html) module. However, you have to [negate each value](http://stackoverflow.com/questions/2501457/what-do-i-use-for-a-max-heap-implementation-in-python), since `heapq` provi... |
Python: How to match nested parentheses with regex? | 5,454,322 | 8 | 2011-03-28T03:22:47Z | 5,454,348 | 10 | 2011-03-28T03:27:34Z | [
"python",
"regex",
"nested"
] | I'm trying to match a mathematical-expression-like string, that have nested parentheses.
```
import re
p = re.compile('\(.+\)')
str = '(((1+0)+1)+1)'
print p.findall(s)
```
> ['(((1+0)+1)+1)']
I wanted it to match all the enclosed expressions, such as (1+0), ((1+0)+1)...
I don't even care if it matches unwanted o... | Regex languages aren't powerful enough to matching arbitrarily nested constructs. For that you need a push-down automaton (i.e., a parser). There are several such tools available, such as [PLY](http://www.dabeaz.com/ply/).
Python also provides a [parser library](http://docs.python.org/library/parser.html) for its own ... |
Python: How to match nested parentheses with regex? | 5,454,322 | 8 | 2011-03-28T03:22:47Z | 5,454,441 | 7 | 2011-03-28T03:44:04Z | [
"python",
"regex",
"nested"
] | I'm trying to match a mathematical-expression-like string, that have nested parentheses.
```
import re
p = re.compile('\(.+\)')
str = '(((1+0)+1)+1)'
print p.findall(s)
```
> ['(((1+0)+1)+1)']
I wanted it to match all the enclosed expressions, such as (1+0), ((1+0)+1)...
I don't even care if it matches unwanted o... | The regular expression tries to match as much of the text as possible, thereby consuming all of your string. It doesn't look for additional matches of the regular expression on parts of that string. That's why you only get one answer.
The solution is to not use regular expressions. If you are actually trying to parse ... |
Python: How to match nested parentheses with regex? | 5,454,322 | 8 | 2011-03-28T03:22:47Z | 5,454,510 | 19 | 2011-03-28T03:56:22Z | [
"python",
"regex",
"nested"
] | I'm trying to match a mathematical-expression-like string, that have nested parentheses.
```
import re
p = re.compile('\(.+\)')
str = '(((1+0)+1)+1)'
print p.findall(s)
```
> ['(((1+0)+1)+1)']
I wanted it to match all the enclosed expressions, such as (1+0), ((1+0)+1)...
I don't even care if it matches unwanted o... | As others have mentioned, regular expressions are not the way to go for nested constructs. I'll give a basic example using [pyparsing](http://pyparsing.wikispaces.com/):
```
import pyparsing # make sure you have this installed
thecontent = pyparsing.Word(pyparsing.alphanums) | '+' | '-'
parens = pyparsing.nestedE... |
Python: How to match nested parentheses with regex? | 5,454,322 | 8 | 2011-03-28T03:22:47Z | 12,280,660 | 8 | 2012-09-05T11:42:39Z | [
"python",
"regex",
"nested"
] | I'm trying to match a mathematical-expression-like string, that have nested parentheses.
```
import re
p = re.compile('\(.+\)')
str = '(((1+0)+1)+1)'
print p.findall(s)
```
> ['(((1+0)+1)+1)']
I wanted it to match all the enclosed expressions, such as (1+0), ((1+0)+1)...
I don't even care if it matches unwanted o... | There is [a new regular engine module](http://pypi.python.org/pypi/regex) being prepared to replace the existing one in Python. It introduces a lot of new functionality, including recursive calls.
```
import regex
s = 'aaa(((1+0)+1)+1)bbb'
result = regex.search(r'''
(?<rec> #capturing group rec
\( #open parenthesis... |
How to reverse order of keys in python dict? | 5,455,606 | 10 | 2011-03-28T06:57:57Z | 5,455,632 | 7 | 2011-03-28T07:00:45Z | [
"python",
"dictionary",
"reverse"
] | This is my code :
```
a = {0:'000000',1:'11111',3:'333333',4:'444444'}
for i in a:
print i
```
it shows:
```
0
1
3
4
```
but I want it to show:
```
4
3
1
0
```
so, what can I do? | Try:
```
for i in sorted(a.keys(), reverse=True):
print i
``` |
How to reverse order of keys in python dict? | 5,455,606 | 10 | 2011-03-28T06:57:57Z | 5,455,636 | 10 | 2011-03-28T07:00:59Z | [
"python",
"dictionary",
"reverse"
] | This is my code :
```
a = {0:'000000',1:'11111',3:'333333',4:'444444'}
for i in a:
print i
```
it shows:
```
0
1
3
4
```
but I want it to show:
```
4
3
1
0
```
so, what can I do? | Dictionaries are unordered so you cannot reverse them. The order of the current output is arbitrary.
That said, you can order the keys of course:
```
for i in sorted(a.keys(), reverse=True):
print a[i];
```
but this gives you the reverse order of the *sorted* keys, not necessarily the reverse order of the keys h... |
How to reverse order of keys in python dict? | 5,455,606 | 10 | 2011-03-28T06:57:57Z | 5,455,639 | 20 | 2011-03-28T07:01:16Z | [
"python",
"dictionary",
"reverse"
] | This is my code :
```
a = {0:'000000',1:'11111',3:'333333',4:'444444'}
for i in a:
print i
```
it shows:
```
0
1
3
4
```
but I want it to show:
```
4
3
1
0
```
so, what can I do? | The order keys are iterated in is arbitrary. It was only a coincidence that they were in sorted order.
```
>>> a = {0:'000000',1:'11111',3:'333333',4:'444444'}
>>> a.keys()
[0, 1, 3, 4]
>>> sorted(a.keys())
[0, 1, 3, 4]
>>> reversed(sorted(a.keys()))
<listreverseiterator object at 0x02B0DB70>
>>> list(reversed(sorted(... |
Exit code when python script has unhandled exception | 5,456,157 | 6 | 2011-03-28T08:03:01Z | 5,456,201 | 9 | 2011-03-28T08:08:17Z | [
"python",
"exit-code"
] | I need a method to run a python script file, and if the script fails with an unhandled exception python should exit with a non-zero exit code. My first try was something like this:
```
import sys
if __name__ == '__main__':
try:
import <unknown script>
except:
sys.exit(-1)
```
But it breaks a l... | Python already does what you're asking:
```
$ python -c "raise RuntimeError()"
Traceback (most recent call last):
File "<string>", line 1, in <module>
RuntimeError
$ echo $?
1
```
After some edits from the OP, perhaps you want:
```
import subprocess
proc = subprocess.Popen(['/usr/bin/python', 'script-name'])
proc... |
How to make a Python script standalone executable to run without ANY dependency? | 5,458,048 | 217 | 2011-03-28T11:04:09Z | 5,458,078 | 12 | 2011-03-28T11:06:41Z | [
"python",
"executable"
] | I'm building a Python application and don't want to force my clients to install Python and modules. I also want to make my application closed-source.
So, is there a way to compile Python scripts to standalone executables? | you may like [py2exe](http://wiki.python.org/moin/Py2Exe). you'll also find in there infos for doing it on linux |
How to make a Python script standalone executable to run without ANY dependency? | 5,458,048 | 217 | 2011-03-28T11:04:09Z | 5,458,250 | 52 | 2011-03-28T11:22:56Z | [
"python",
"executable"
] | I'm building a Python application and don't want to force my clients to install Python and modules. I also want to make my application closed-source.
So, is there a way to compile Python scripts to standalone executables? | I have had some success with [pyinstaller](http://www.pyinstaller.org/). Works on linux as well as windows. |
How to make a Python script standalone executable to run without ANY dependency? | 5,458,048 | 217 | 2011-03-28T11:04:09Z | 5,458,478 | 14 | 2011-03-28T11:43:57Z | [
"python",
"executable"
] | I'm building a Python application and don't want to force my clients to install Python and modules. I also want to make my application closed-source.
So, is there a way to compile Python scripts to standalone executables? | And a third option is [`cx_Freeze`](http://cx-freeze.sourceforge.net/), which is cross-platform. |
How to make a Python script standalone executable to run without ANY dependency? | 5,458,048 | 217 | 2011-03-28T11:04:09Z | 5,458,807 | 83 | 2011-03-28T12:12:41Z | [
"python",
"executable"
] | I'm building a Python application and don't want to force my clients to install Python and modules. I also want to make my application closed-source.
So, is there a way to compile Python scripts to standalone executables? | You can use [py2exe](http://www.py2exe.org/) as already answered and use [cython](http://cython.org/) to convert your key `.py` files in `.pyc`, C compiled files, like `.dll` in Windows and `.so` in linux, much harder to revert than common `.pyo` and `.pyc` files (and also gain in performance!) |
How to make a Python script standalone executable to run without ANY dependency? | 5,458,048 | 217 | 2011-03-28T11:04:09Z | 18,693,145 | 31 | 2013-09-09T07:11:55Z | [
"python",
"executable"
] | I'm building a Python application and don't want to force my clients to install Python and modules. I also want to make my application closed-source.
So, is there a way to compile Python scripts to standalone executables? | You might wish to investigate [Nuitka](http://nuitka.net/). It takes python source code and converts it in to C++ API calls. Then it compiles into an executable binary (ELF on Linux). It has been around for a few years now and supports a wide range of Python versions.
You will probably also get a performance improveme... |
Using Django auth User model as a Foreignkey and reverse relations | 5,458,358 | 12 | 2011-03-28T11:32:14Z | 5,458,384 | 7 | 2011-03-28T11:34:31Z | [
"python",
"django"
] | I am using the `User` model from `django.contrib.auth.models`. I have another model called `Post` which references `User` through a foreign key.
The problem is when I try to access a logged in user's posts through
```
request.user.post_set.order_by('-timestamp')
```
I get an error, `User` object has no attribute `po... | ```
Post.objects.filter(user=request.user).order_by('-timestamp')
``` |
Using Django auth User model as a Foreignkey and reverse relations | 5,458,358 | 12 | 2011-03-28T11:32:14Z | 5,463,353 | 17 | 2011-03-28T18:26:41Z | [
"python",
"django"
] | I am using the `User` model from `django.contrib.auth.models`. I have another model called `Post` which references `User` through a foreign key.
The problem is when I try to access a logged in user's posts through
```
request.user.post_set.order_by('-timestamp')
```
I get an error, `User` object has no attribute `po... | Have you included the application containing the Post model in your settings.py installed apps?
e.g.
```
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'tes... |
Tkinter: "Python may not be configured for Tk" | 5,459,444 | 23 | 2011-03-28T13:10:45Z | 5,459,492 | 23 | 2011-03-28T13:14:36Z | [
"python",
"python-3.x",
"tkinter"
] | Today I wanted to start working with Tkinter, but I have some problems.
```
Python 3.2 (r32:88445, Mar 28 2011, 04:14:07)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from tkinter import *
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "... | Install `tk-devel` (or a similarly-named package) before building Python. |
Tkinter: "Python may not be configured for Tk" | 5,459,444 | 23 | 2011-03-28T13:10:45Z | 5,459,513 | 16 | 2011-03-28T13:15:47Z | [
"python",
"python-3.x",
"tkinter"
] | Today I wanted to start working with Tkinter, but I have some problems.
```
Python 3.2 (r32:88445, Mar 28 2011, 04:14:07)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from tkinter import *
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "... | According to <http://wiki.python.org/moin/TkInter> :
> If it fails with "No module named \_tkinter", your Python configuration needs to be modified to include this module (which is an extension module implemented in C). Do **not** edit Modules/Setup (it is out of date). You may have to install Tcl and Tk (when using R... |
Learning Perl from Python perspective | 5,460,418 | 11 | 2011-03-28T14:25:34Z | 5,461,433 | 8 | 2011-03-28T15:38:22Z | [
"python",
"perl",
"scripting"
] | I am fairly familiar with python, from a system automation and tool building prospective; I am a sysadm by trade. I recently started a new job at a company that wants to standardise on perl, for which I know none. So I need to get up to speed on perl pretty quickly and was hoping someone could point to some helpful ref... | I know you already have a book, but from your description I would have recommended [Automating System Administration with Perl](http://oreilly.com/catalog/9780596006396) |
Learning Perl from Python perspective | 5,460,418 | 11 | 2011-03-28T14:25:34Z | 5,462,247 | 16 | 2011-03-28T16:43:51Z | [
"python",
"perl",
"scripting"
] | I am fairly familiar with python, from a system automation and tool building prospective; I am a sysadm by trade. I recently started a new job at a company that wants to standardise on perl, for which I know none. So I need to get up to speed on perl pretty quickly and was hoping someone could point to some helpful ref... | Crank through the Llama (it will be easy) and when you're done with that check out [Effective Perl Programming](http://www.effectiveperlprogramming.com/toc) and/or [Modern Perl](http://www.onyxneon.com/books/modern_perl/index.html). They'll help you avoid the mistakes encouraged by all the crappy tutorials written in 1... |
Learning Perl from Python perspective | 5,460,418 | 11 | 2011-03-28T14:25:34Z | 5,466,186 | 7 | 2011-03-28T23:21:28Z | [
"python",
"perl",
"scripting"
] | I am fairly familiar with python, from a system automation and tool building prospective; I am a sysadm by trade. I recently started a new job at a company that wants to standardise on perl, for which I know none. So I need to get up to speed on perl pretty quickly and was hoping someone could point to some helpful ref... | Some translations of typical python idioms into perl:
* List comprehension `[x * x for x in range(10)]` becomes `map {$_ * $_} 0..9`
* Filter `filter(x > 5, range(10))` becomes `grep {$_ > 5} 0..9`
* A function `def f(x, y): return x + y` becomes `sub f { my ($x, $y) = @_; $x + $y }`
As a quick reference for built-in... |
Run BASH built-in commands in Python? | 5,460,923 | 15 | 2011-03-28T15:01:33Z | 5,461,020 | 12 | 2011-03-28T15:09:55Z | [
"python",
"bash",
"command",
"subprocess"
] | Is there a way to run the BASH built-in commands from Python?
I tried:
```
subprocess.Popen(['bash','history'],shell=True, stdout=PIPE)
subprocess.Popen('history', shell=True, executable = "/bin/bash", stdout=subprocess.PIPE)
os.system('history')
```
and many variations thereof. I would like to run `history` or `f... | ```
subprocess.Popen(["bash", "-c", "type type"])
```
this calls bash and tells bash to run the string `type type`, which runs the builtin command `type` on the argument `type`.
output: `type is a shell builtin`
the part after `-c` has to be one string. this will not work: `["bash", "-c", "type", "type"]` |
Run BASH built-in commands in Python? | 5,460,923 | 15 | 2011-03-28T15:01:33Z | 5,485,749 | 16 | 2011-03-30T11:36:03Z | [
"python",
"bash",
"command",
"subprocess"
] | Is there a way to run the BASH built-in commands from Python?
I tried:
```
subprocess.Popen(['bash','history'],shell=True, stdout=PIPE)
subprocess.Popen('history', shell=True, executable = "/bin/bash", stdout=subprocess.PIPE)
os.system('history')
```
and many variations thereof. I would like to run `history` or `f... | I finally found a solution that works.
```
from subprocess import Popen, PIPE, STDOUT
shell_command = 'bash -i -c "history -r; history"'
event = Popen(shell_command, shell=True, stdin=PIPE, stdout=PIPE,
stderr=STDOUT)
output = event.communicate()
```
Thank you everyone for the input. |
python: check if IP or DNS | 5,461,322 | 3 | 2011-03-28T15:30:55Z | 5,461,379 | 7 | 2011-03-28T15:34:17Z | [
"python",
"regex",
"dns",
"ip"
] | how can one check if variable contains DNS name or IP address in python ? | You can use [re](http://docs.python.org/library/re.html) module of Python to check if the contents of the variable is a ip address.
Example for the ip address :
```
import re
my_ip = "192.168.1.1"
is_valid = re.match("^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[... |
call list of function using list comprehension | 5,461,571 | 15 | 2011-03-28T15:46:40Z | 5,461,597 | 9 | 2011-03-28T15:48:37Z | [
"python",
"list",
"function",
"list-comprehension"
] | can I call a list of functions and use list comprehension?
```
def func1():return 1
def func2():return 2
def func3():return 3
fl = [func1,func2,func3]
fl[0]()
fl[1]()
fl[2]()
```
I know I can do
```
for f in fl:
f()
```
but can I do below ?
```
[f() for f in fl]
```
A additional question for those kind peopl... | ```
>>> [f() for f in fl]
[1, 2, 3]
```
Absolutely :) |
call list of function using list comprehension | 5,461,571 | 15 | 2011-03-28T15:46:40Z | 5,467,772 | 10 | 2011-03-29T04:06:12Z | [
"python",
"list",
"function",
"list-comprehension"
] | can I call a list of functions and use list comprehension?
```
def func1():return 1
def func2():return 2
def func3():return 3
fl = [func1,func2,func3]
fl[0]()
fl[1]()
fl[2]()
```
I know I can do
```
for f in fl:
f()
```
but can I do below ?
```
[f() for f in fl]
```
A additional question for those kind peopl... | Of course you can as Fábio Diniz said :),
However for the class method when used as a callable, an object must be given as an argument:
```
fobj= F()
for f in fobj.fl:
f(fobj)
```
The object must be given as an argument to the callable because when you look at the definition of the method `def funcX(self):` the... |
Pythonic shortcut for doubly nested for loops? | 5,462,047 | 11 | 2011-03-28T16:25:16Z | 5,462,097 | 13 | 2011-03-28T16:29:25Z | [
"python",
"for-loop",
"tuples",
"nested-loops"
] | Consider if I had a function that took a tuple argument (x,y), where x was in the range(X), and y in the range(Y), the normal way of doing it would be:
```
for x in range(X):
for y in range(Y):
function(x,y)
```
is there a way to do
```
for xy in something_like_range(X,Y):
function(xy)
```
such that... | You can use [product from itertools](http://docs.python.org/library/itertools.html#itertools.product)
```
>>> from itertools import product
>>>
>>> for x,y in product(range(3), range(4)):
... print (x,y)
...
(0, 0)
(0, 1)
(0, 2)
(0, 3)
(1, 0)
(1, 1)
(1, 2)
(1, 3)
... and so on
```
Your code would look like:
```... |
Control formatting of the argparse help argument list? | 5,462,873 | 17 | 2011-03-28T17:42:38Z | 5,464,440 | 12 | 2011-03-28T20:03:02Z | [
"python",
"argparse"
] | ```
import argparse
parser = argparse.ArgumentParser(prog='tool')
args = [('-u', '--upf', 'ref. upf', dict(required='True')),
('-s', '--skew', 'ref. skew', {}),
('-m', '--model', 'ref. model', {})]
for args1, args2, desc, options in args:
parser.add_argument(args1, args2, help=desc, **options)
p... | You could supply `formatter_class` argument:
```
parser = argparse.ArgumentParser(prog='tool',
formatter_class=lambda prog: argparse.HelpFormatter(prog,max_help_position=27))
args = [('-u', '--upf', 'ref. upf', dict(required='True')),
('-s', '--skew', 'ref. skew', {}),
('-m', '--model', 'ref. model'... |
Multiline log records in syslog | 5,463,992 | 32 | 2011-03-28T19:26:29Z | 5,544,143 | 30 | 2011-04-04T20:46:21Z | [
"python",
"logging",
"syslog",
"rsyslog"
] | So I've configured my Python application to log to syslog with Python's SysLogHandler, and everything works fine. Except for multi-line handling. Not that I need to emit multiline log records so badly (I do a little), but I need to be able to read Python's exceptions. I'm using Ubuntu with rsyslog 4.2.0. This is what I... | OK, figured it out finally...
rsyslog by default escapes all weird characters (ASCII < 32), and this include newlines (as well as tabs and others). Simply add this to your rsyslog config to turn this off:
```
$EscapeControlCharactersOnReceive off
``` |
Multiline log records in syslog | 5,463,992 | 32 | 2011-03-28T19:26:29Z | 10,338,722 | 30 | 2012-04-26T17:50:51Z | [
"python",
"logging",
"syslog",
"rsyslog"
] | So I've configured my Python application to log to syslog with Python's SysLogHandler, and everything works fine. Except for multi-line handling. Not that I need to emit multiline log records so badly (I do a little), but I need to be able to read Python's exceptions. I'm using Ubuntu with rsyslog 4.2.0. This is what I... | Alternatively, if you want to keep your syslog intact on one line for parsing, you can just replace the characters when viewing the log.
```
tail -f /var/log/syslog | sed 's/#012/\n\t/g'
``` |
matplotlib write text in the margin | 5,464,315 | 11 | 2011-03-28T19:53:02Z | 5,464,530 | 22 | 2011-03-28T20:11:19Z | [
"python",
"graph",
"matplotlib",
"plot"
] | If I make a graph using pylab from matlotlib like so...
```
import pylab as p
x = [0,1,2]
y = [2,4,6]
p.plot(x,y)
p.show()
```
I want to use the p.text function to add text to the graph. However, I want to put the text in the margin outside of the data window. The text function only accepts x,y coordinates that corre... | You can use the [`figtext`](http://matplotlib.sourceforge.net/api/pyplot_api.html?highlight=figtext#matplotlib.pyplot.figtext) function. Only note that the coordinates are 0-1, so something like the following places text to the left of the vertical axis:
```
p.figtext(0.05, 0.5, 'foo')
```
See the linked docs for mor... |
How to tell if a date is between two other dates in Python? | 5,464,410 | 10 | 2011-03-28T20:01:08Z | 5,464,465 | 7 | 2011-03-28T20:05:21Z | [
"python",
"compare",
"date"
] | I have the following codes:
```
if date in (start, end):
print 'in between'
else:
print 'No!'
```
date, start and end are all variables with the format of 1/1. What should I do to have it print out the right result? i tried date as 10/2, start as 3/14 and end as 11/7 and it's print 'No!', which means ... | Use `datetime.date`:
<http://docs.python.org/library/datetime.html#datetime.date>
`<` operator is overloaded specially for you.
`date1 < date2` - date1 is considered less than date2 when date1 precedes date2 in time.
```
>>> from datetime import date
>>> d1 = date(2011, 3, 28)
>>> d2 = date(2011, 3, 22)
>>> d3 = da... |
How to tell if a date is between two other dates in Python? | 5,464,410 | 10 | 2011-03-28T20:01:08Z | 5,464,467 | 35 | 2011-03-28T20:05:27Z | [
"python",
"compare",
"date"
] | I have the following codes:
```
if date in (start, end):
print 'in between'
else:
print 'No!'
```
date, start and end are all variables with the format of 1/1. What should I do to have it print out the right result? i tried date as 10/2, start as 3/14 and end as 11/7 and it's print 'No!', which means ... | If you convert all your dates to [`datetime.date`](http://docs.python.org/library/datetime.html#date-objects), you can write the following:
```
if start <= date <= end:
print "in between"
else:
print "No!"
``` |
How to tell if a date is between two other dates in Python? | 5,464,410 | 10 | 2011-03-28T20:01:08Z | 5,464,965 | 14 | 2011-03-28T20:56:25Z | [
"python",
"compare",
"date"
] | I have the following codes:
```
if date in (start, end):
print 'in between'
else:
print 'No!'
```
date, start and end are all variables with the format of 1/1. What should I do to have it print out the right result? i tried date as 10/2, start as 3/14 and end as 11/7 and it's print 'No!', which means ... | As you are still not satisfied, I have another answer for you. Without using datetime and year.
It just uses built-in tuples and comparing them:
```
d1 = (3, 28)
d2 = (3, 31)
d3 = (4, 2)
if d1 < d2 < d3:
print("BETWEEN!")
else:
print("NOT!")
```
You can create tuple like these easily:
```
day = 16
month = 4... |
How to have same text in two links with restructured text? | 5,464,627 | 45 | 2011-03-28T20:20:34Z | 5,465,330 | 9 | 2011-03-28T21:32:35Z | [
"python",
"restructuredtext"
] | Here is what I would like to do:
```
1. `link <http://www.google.com>`__
2. `link <http://www.yahoo.com>`__
```
To obtain:
```
<ol>
<li><a href="http://www.google.com">link</a></li>
<li><a href="http://www.yahoo.com">link</a></li>
</ol>
```
The context is a list of publications, where I want them all to have a link... | I think you'll want to use anonymous hyperlinks:
```
1. `link`__
2. `link`__
__ http://www.google.com
__ http://www.yahoo.com
```
Keep in mind that the order they're referred to in the document is important. More information can be found [here](http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#anony... |
How to have same text in two links with restructured text? | 5,464,627 | 45 | 2011-03-28T20:20:34Z | 14,067,756 | 73 | 2012-12-28T09:59:28Z | [
"python",
"restructuredtext"
] | Here is what I would like to do:
```
1. `link <http://www.google.com>`__
2. `link <http://www.yahoo.com>`__
```
To obtain:
```
<ol>
<li><a href="http://www.google.com">link</a></li>
<li><a href="http://www.yahoo.com">link</a></li>
</ol>
```
The context is a list of publications, where I want them all to have a link... | The warning
> (WARNING/2) Duplicate explicit target name:foo
occurs when you use the same text for two different links in "Named hyperlink references":
```
`Foo <http://example.org>`_
`Foo <http://example.com>`_
```
To circumvent it, use *anonymous* [hyperlink references](http://docutils.sourceforge.net/docs/ref/rs... |
Simple way to transcode mp3 to ogg in python (live)? | 5,464,912 | 7 | 2011-03-28T20:51:28Z | 5,465,280 | 7 | 2011-03-28T21:27:57Z | [
"python",
"audio",
"transcoding"
] | I'm searching for a library / module that can transcode an MP3 (other formats are a plus) to OGG, on the fly.
What I need this for: I'm writing a relatively small web app, for personal use, that will allow people to listen their music via a browser. For the listening part, I intend to use the new and mighty `<audio>` ... | You know, there's no shame in using `subprocess` to call external utilities. For example, you could construct pipes like:
```
#!/usr/bin/env python
import subprocess
frommp3 = subprocess.Popen(['mpg123', '-w', '-', '/tmp/test.mp3'], stdout=subprocess.PIPE)
toogg = subprocess.Popen(['oggenc', '-'], stdin=frommp3.stdout... |
Syntax to call random function from a list | 5,465,455 | 14 | 2011-03-28T21:46:10Z | 5,465,474 | 20 | 2011-03-28T21:49:16Z | [
"python"
] | From this thread:
[How do I perform a random event in Python by picking a random variable?](http://stackoverflow.com/questions/3998908/how-do-i-perform-a-random-event-in-python-by-picking-a-random-variable)
I learned that it's possible to put some functions into a list, and by using `random.choice()`, call one of them... | With the parentheses you call the function. What you want is assigning them to the list and call the choice later:
```
my_list = [func_test_1, func_test_2, func_test_3]
random.choice(my_list)()
``` |
Python nonlocal statement in a class definition | 5,466,238 | 7 | 2011-03-28T23:31:28Z | 5,467,009 | 7 | 2011-03-29T01:41:58Z | [
"python",
"class",
"python-3.x",
"python-nonlocal"
] | I'm trying to perform some analysis of scope in Python 3 source code and I'm stuck with how the nonlocal statement statement works inside a class definition.
As I understand it, the class definition executes its body inside a new namespace (call it dict) and binds the class name to the result of type(name, bases, dict... | Lexical scoping applies only to function namespaces, otherwise methods defined inside a class would be able to "see" the class level attributes (which is by design - those attributes must instead be accessed as attributes of `self` inside the method).
The same limitations that cause the class level variables to be ski... |
Embedded interactive shell in IPython | 5,466,342 | 6 | 2011-03-28T23:48:06Z | 29,907,148 | 8 | 2015-04-27T22:34:02Z | [
"python",
"embed",
"ipython"
] | Before switching to IPython v0.11 (using Python 2.6.1), it was possible to embed an interactive IPython shell using for example [this](http://stackoverflow.com/questions/499705/can-i-use-ipython-in-an-embedded-interactive-python-console), e.g.
```
from IPython.Shell import IPShellEmbed
ipshell = IPShellEmbed()
ipshell... | These days (3.0+) all you need to do is:
```
from IPython import embed; embed()
```
If you mean embedding another IPython shell in IPython (recursively), there was a long time that this was not supported, but that problem was patched last year. |
How can I print a literal "{}" characters in python string and also use .format on it? | 5,466,451 | 510 | 2011-03-29T00:04:53Z | 5,466,472 | 18 | 2011-03-29T00:08:20Z | [
"python",
"string",
"format"
] | ```
x = " \{ Hello \} {0} "
print x.format(42)
```
gives me : `Key Error: Hello\\`
I want to print the output: `{Hello} 42` | Try this:
`x = "{{ Hello }} {0}"` |
How can I print a literal "{}" characters in python string and also use .format on it? | 5,466,451 | 510 | 2011-03-29T00:04:53Z | 5,466,473 | 34 | 2011-03-29T00:08:22Z | [
"python",
"string",
"format"
] | ```
x = " \{ Hello \} {0} "
print x.format(42)
```
gives me : `Key Error: Hello\\`
I want to print the output: `{Hello} 42` | You escape it by doubling the braces.
Eg:
```
x = "{{ Hello }} {0}"
print x.format(42)
``` |
How can I print a literal "{}" characters in python string and also use .format on it? | 5,466,451 | 510 | 2011-03-29T00:04:53Z | 5,466,475 | 21 | 2011-03-29T00:08:31Z | [
"python",
"string",
"format"
] | ```
x = " \{ Hello \} {0} "
print x.format(42)
```
gives me : `Key Error: Hello\\`
I want to print the output: `{Hello} 42` | Try doing this:
```
x = " {{ Hello }} {0} "
print x.format(42)
``` |
How can I print a literal "{}" characters in python string and also use .format on it? | 5,466,451 | 510 | 2011-03-29T00:04:53Z | 5,466,478 | 661 | 2011-03-29T00:08:55Z | [
"python",
"string",
"format"
] | ```
x = " \{ Hello \} {0} "
print x.format(42)
```
gives me : `Key Error: Hello\\`
I want to print the output: `{Hello} 42` | You need to double the `{{` and `}}`:
```
>>> x = " {{ Hello }} {0} "
>>> print x.format(42)
' { Hello } 42 '
```
Here's the relevant part of the [Python documentation for format string syntax](http://docs.python.org/library/string.html#formatstrings):
> Format strings contain âreplacement fieldsâ surrounded by ... |
Get bbox in data coordinates in matplotlib | 5,466,539 | 3 | 2011-03-29T00:19:18Z | 5,467,116 | 8 | 2011-03-29T02:06:40Z | [
"python",
"matplotlib",
"transformation"
] | I have the `bbox` of a `matplotlib.patches.Rectangle` object (a bar from a bar graph) in display coordinates, like this:
```
Bbox(array([[ 0., 0.],[ 1., 1.]])
```
But I would like that not in display coordinates but data coordinates. I'm pretty sure this requires a transform. What's the method for doing this? | I'm not sure how you got the Bbox in display coordinates. Almost everything the user interacts with is in data coordinates (those look like axis or data coordinates to me, not display pixels). The following should fully explain the transforms as they apply to Bboxes:
```
from matplotlib import pyplot as plt
bars = plt... |
'too many values to unpack', iterating over a dict. key=>string, value=>list | 5,466,618 | 112 | 2011-03-29T00:32:14Z | 5,466,625 | 169 | 2011-03-29T00:34:07Z | [
"python"
] | I am getting the `'too many values to unpack'` error. Any idea how I can fix this?
```
first_names = ['foo', 'bar']
last_names = ['gravy', 'snowman']
fields = {
'first_names': first_names,
'last_name': last_names,
}
for field, possible_values in fields: # error happens on this line
``` | You need to use something like [iteritems](http://docs.python.org/library/stdtypes.html#dict.iteritems).
```
for field, possible_values in fields.iteritems():
print field, possible_values
```
See [this answer](http://stackoverflow.com/a/3294899/1489538) for more information on iterating through dictionaries, such... |
'too many values to unpack', iterating over a dict. key=>string, value=>list | 5,466,618 | 112 | 2011-03-29T00:32:14Z | 5,466,632 | 25 | 2011-03-29T00:35:36Z | [
"python"
] | I am getting the `'too many values to unpack'` error. Any idea how I can fix this?
```
first_names = ['foo', 'bar']
last_names = ['gravy', 'snowman']
fields = {
'first_names': first_names,
'last_name': last_names,
}
for field, possible_values in fields: # error happens on this line
``` | You want to use [iteritems](http://docs.python.org/library/stdtypes.html#dict.iteritems). This returns an iterator over the dictionary, which gives you a tuple(key, value)
```
>>> for field, values in fields.iteritems():
... print field, values
...
first_names ['foo', 'bar']
last_name ['gravy', 'snowman']
```
Yo... |
'too many values to unpack', iterating over a dict. key=>string, value=>list | 5,466,618 | 112 | 2011-03-29T00:32:14Z | 28,842,588 | 26 | 2015-03-03T21:48:23Z | [
"python"
] | I am getting the `'too many values to unpack'` error. Any idea how I can fix this?
```
first_names = ['foo', 'bar']
last_names = ['gravy', 'snowman']
fields = {
'first_names': first_names,
'last_name': last_names,
}
for field, possible_values in fields: # error happens on this line
``` | For Python 3.x `iteritems` has been removed. Use [items](https://docs.python.org/3.4/library/stdtypes.html#dict.items) instead.
```
for field, possible_values in fields.items():
print(field, possible_values)
``` |
Default server in multiple server configuration of distutils in ~/.pypirc | 5,467,463 | 3 | 2011-03-29T03:04:25Z | 5,518,168 | 11 | 2011-04-01T19:54:38Z | [
"python",
"distutils",
"pypi"
] | I want to have multiple PyPI servers in my `~/.pypirc` file so I can easily publish to different servers, depending on the project.
My use-case is this, I have some internal projects that I want to publish to an internal PyPI server (`https://pypi.internal`), and I have some public projects that I want to publish to t... | It's strange that there isn't built-in support for setting a default, but here are two options which may help you work around it.
**Option 1:** Probably the simplest solution would be to leave your **~/.pypirc** script intact and create shell aliases for your internal and public uploads. This may give you more control... |
Uploading images using Django Admin? | 5,467,691 | 9 | 2011-03-29T03:48:27Z | 5,467,830 | 20 | 2011-03-29T04:16:33Z | [
"python",
"django",
"django-models",
"django-admin"
] | Is there an easy way to include file upload capabilities to the admin interface in Django? I saw this [question](http://stackoverflow.com/questions/925305/uploading-multiple-images-in-django-admin) but I'm not well versed in Javascript.
Is there any magick I can add to the models.py or admin.py files that will allow m... | Forgive me if I'm wrong, but it sounds like you don't need anything more than the default admin widget for an [`ImageField`.](http://docs.djangoproject.com/en/dev/ref/models/fields/#imagefield)
This satisfies:
1. Uploading images using Django Admin
2. Including a profile picture (singular) to go with a celebrity.
Al... |
How to write a custom decorator in django? | 5,469,159 | 38 | 2011-03-29T07:23:27Z | 5,469,376 | 40 | 2011-03-29T07:44:30Z | [
"python",
"django",
"permissions",
"decorator"
] | The problem -
```
@is_premium_user
def sample_view:
.......
......
```
I want certain views accesible to only the premium users of the website.
And how can I use this decorator across various applications in my project? | You don't have to write your own decorator for this as [`user_passes_test`](http://docs.djangoproject.com/en/1.4/topics/auth/#limiting-access-to-logged-in-users-that-pass-a-test) is already included in Django.
And there's a snippet ([`group_required_decorator`](http://djangosnippets.org/snippets/1703/)) that extends t... |
How to write a custom decorator in django? | 5,469,159 | 38 | 2011-03-29T07:23:27Z | 6,122,181 | 28 | 2011-05-25T09:22:54Z | [
"python",
"django",
"permissions",
"decorator"
] | The problem -
```
@is_premium_user
def sample_view:
.......
......
```
I want certain views accesible to only the premium users of the website.
And how can I use this decorator across various applications in my project? | Played around with the various links above and couldn't get them working and then came across this really simple one which I adapted. <http://code.activestate.com/recipes/498217-custom-django-login_required-decorator/>
```
from django.http import HttpResponseRedirect
def authors_only(function):
def wrap(request, *a... |
How to get the index of a maximum element in a numpy array along one axis | 5,469,286 | 36 | 2011-03-29T07:35:46Z | 5,469,326 | 56 | 2011-03-29T07:39:43Z | [
"python",
"numpy",
"max",
"indices"
] | I have a 2 dimensional NumPy array. I know how to get the maximum values over axes:
```
>>> a = array([[1,2,3],[4,3,1]])
>>> amax(a,axis=0)
array([4, 3, 3])
```
How can I get the indices of the maximum elements? So I would like as output `array([1,1,0])` | ```
>>> a.argmax(axis=0)
array([1, 1, 0])
``` |
How to get the index of a maximum element in a numpy array along one axis | 5,469,286 | 36 | 2011-03-29T07:35:46Z | 13,535,599 | 41 | 2012-11-23T20:52:54Z | [
"python",
"numpy",
"max",
"indices"
] | I have a 2 dimensional NumPy array. I know how to get the maximum values over axes:
```
>>> a = array([[1,2,3],[4,3,1]])
>>> amax(a,axis=0)
array([4, 3, 3])
```
How can I get the indices of the maximum elements? So I would like as output `array([1,1,0])` | ```
>>> import numpy as np
>>> a = np.array([[1,2,3],[4,3,1]])
>>> i,j = np.unravel_index(a.argmax(), a.shape)
>>> a[i,j]
4
``` |
How to get the index of a maximum element in a numpy array along one axis | 5,469,286 | 36 | 2011-03-29T07:35:46Z | 23,554,004 | 11 | 2014-05-08T22:58:16Z | [
"python",
"numpy",
"max",
"indices"
] | I have a 2 dimensional NumPy array. I know how to get the maximum values over axes:
```
>>> a = array([[1,2,3],[4,3,1]])
>>> amax(a,axis=0)
array([4, 3, 3])
```
How can I get the indices of the maximum elements? So I would like as output `array([1,1,0])` | `argmax()` will only return the first occurrence for each row.
<http://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html>
If you ever need to do this for a shaped array, this works better than `unravel`:
```
import numpy as np
a = np.array([[1,2,3], [4,3,1]]) # Can be of any shape
indices = np.where(a =... |
Run a .bat file using python code | 5,469,301 | 22 | 2011-03-29T07:37:20Z | 5,469,427 | 16 | 2011-03-29T07:49:46Z | [
"python",
"batch-file"
] | I try to run a `.bat` file in Windows using Python script.
`ask.bat` file:
```
Application.exe work.xml
```
I write Python code :
```
import os
os.system("D:\xxx1\xxx2XMLnew\otr.bat ")
```
Output: when try to run the file its just give a blink of the command prompt, and the work is not performing.
Note: I try wit... | This has already been answered in detail on SO. Check out this thread, It should answer all your questions:
[Python subprocess](http://stackoverflow.com/questions/1818774/python-subprocess)
I've tried it myself with this code:
**batchtest.py**
```
from subprocess import Popen
p = Popen("batch.bat", cwd=r"C:\Path\to\... |
Run a .bat file using python code | 5,469,301 | 22 | 2011-03-29T07:37:20Z | 13,803,538 | 14 | 2012-12-10T15:05:48Z | [
"python",
"batch-file"
] | I try to run a `.bat` file in Windows using Python script.
`ask.bat` file:
```
Application.exe work.xml
```
I write Python code :
```
import os
os.system("D:\xxx1\xxx2XMLnew\otr.bat ")
```
Output: when try to run the file its just give a blink of the command prompt, and the work is not performing.
Note: I try wit... | ```
import subprocess
filepath="D:/path/to/batch/myBatch.bat"
p = subprocess.Popen(filepath, shell=True, stdout = subprocess.PIPE)
stdout, stderr = p.communicate()
print p.returncode # is 0 if success
``` |
Python decorator, self is mixed up | 5,469,956 | 13 | 2011-03-29T08:45:16Z | 5,470,017 | 23 | 2011-03-29T08:51:19Z | [
"python",
"decorator"
] | I am new to Python decorators (wow, great feature!), and I have trouble getting the following to work because the `self` argument gets sort of mixed up.
```
#this is the decorator
class cacher(object):
def __init__(self, f):
self.f = f
self.cache = {}
def __call__(self, *args):
fname ... | Use the [descriptor protocol](http://docs.python.org/reference/datamodel.html#implementing-descriptors) like this:
```
import functools
class cacher(object):
def __init__(self, f):
self.f = f
self.cache = {}
def __call__(self, *args):
fname = self.f.__name__
if (fname not in ... |
Python Number Limit | 5,470,693 | 11 | 2011-03-29T09:52:12Z | 5,470,740 | 32 | 2011-03-29T09:56:10Z | [
"python",
"numbers",
"limit",
"bit"
] | I know in most, if not all programming languages, integers, floats etc all have a maximum amount they can hold, either unsigned or signed. Eg pascal's int type can only hold up to 32768 ~.
What i wanted to know was, what is the limit on python's int and floating point variables. I tried a little program to produce ext... | Earlier Versions had a limit on `int` but its removed now, so you can say there is no limit, it depends on the memory of your computer. Check [this article](http://www.daniweb.com/software-development/python/threads/71008). |
Why is shutil.rmtree() so slow? | 5,470,939 | 3 | 2011-03-29T10:14:39Z | 5,471,261 | 7 | 2011-03-29T10:44:11Z | [
"python",
"rm"
] | I went to check how to remove a directory in Python, and was led to use [shutil.rmtree()](http://docs.python.org/library/shutil#shutil.rmtree). It's speed surprised me, as compared to what I'd expect from a `rm --recursive`. Are there faster alternatives, short of using [subprocess](http://docs.python.org/library/subpr... | [The implementation](http://svn.python.org/view/python/branches/release27-maint/Lib/shutil.py?view=markup) does a lot of extra processing:
```
def rmtree(path, ignore_errors=False, onerror=None):
"""Recursively delete a directory tree.
If ignore_errors is set, errors are ignored; otherwise, if onerror
is set, it is c... |
TypeError: 'str' does not support the buffer interface | 5,471,158 | 201 | 2011-03-29T10:36:10Z | 5,471,273 | 36 | 2011-03-29T10:44:52Z | [
"python",
"string",
"gzip"
] | ```
plaintext = input("Please enter the text you want to compress")
filename = input("Please enter the desired filename")
with gzip.open(filename + ".gz", "wb") as outfile:
outfile.write(plaintext)
```
The above python code is giving me following error:
```
Traceback (most recent call last):
File "C:/Users/Anku... | You can not serialize a Python 3 'string' to bytes without explict conversion to some encoding.
```
outfile.write(plaintext.encode('utf-8'))
```
is possibly what you want. Also this works for both python 2.x and 3.x. |
TypeError: 'str' does not support the buffer interface | 5,471,158 | 201 | 2011-03-29T10:36:10Z | 5,471,280 | 23 | 2011-03-29T10:45:19Z | [
"python",
"string",
"gzip"
] | ```
plaintext = input("Please enter the text you want to compress")
filename = input("Please enter the desired filename")
with gzip.open(filename + ".gz", "wb") as outfile:
outfile.write(plaintext)
```
The above python code is giving me following error:
```
Traceback (most recent call last):
File "C:/Users/Anku... | For Python 3.x you can convert your text to raw bytes through:
```
bytes("my data", "encoding")
```
For example:
```
bytes("attack at dawn", "utf-8")
```
The object returned will work with `outfile.write`. |
TypeError: 'str' does not support the buffer interface | 5,471,158 | 201 | 2011-03-29T10:36:10Z | 5,471,351 | 237 | 2011-03-29T10:51:27Z | [
"python",
"string",
"gzip"
] | ```
plaintext = input("Please enter the text you want to compress")
filename = input("Please enter the desired filename")
with gzip.open(filename + ".gz", "wb") as outfile:
outfile.write(plaintext)
```
The above python code is giving me following error:
```
Traceback (most recent call last):
File "C:/Users/Anku... | If you use Python3x then `string` is not the same type as for Python 2.x, you must cast it to bytes (encode it).
```
plaintext = input("Please enter the text you want to compress")
filename = input("Please enter the desired filename")
with gzip.open(filename + ".gz", "wb") as outfile:
outfile.write(bytes(plaintext... |
TypeError: 'str' does not support the buffer interface | 5,471,158 | 201 | 2011-03-29T10:36:10Z | 24,860,337 | 75 | 2014-07-21T08:07:35Z | [
"python",
"string",
"gzip"
] | ```
plaintext = input("Please enter the text you want to compress")
filename = input("Please enter the desired filename")
with gzip.open(filename + ".gz", "wb") as outfile:
outfile.write(plaintext)
```
The above python code is giving me following error:
```
Traceback (most recent call last):
File "C:/Users/Anku... | There is an easier solution to this problem.
You just need to add a `t` to the mode so it becomes `wt`. This causes Python to open the file as a text file and not binary. Then everything will just work.
The complete program becomes this:
```
plaintext = input("Please enter the text you want to compress")
filename = ... |
Which should I be using: urlparse or urlsplit? | 5,472,160 | 16 | 2011-03-29T12:02:51Z | 5,472,236 | 10 | 2011-03-29T12:08:51Z | [
"python",
"urllib",
"urlparse",
"urlsplit"
] | Which [URL parsing function pair](http://docs.python.org/py3k/library/urllib.parse.html) should I be using and why?
* [`urlparse`](http://docs.python.org/py3k/library/urllib.parse.html#urllib.parse.urlparse) and [`urlunparse`](http://docs.python.org/py3k/library/urllib.parse.html#urllib.parse.urlunparse), or
* [`urlsp... | Directly from [the docs you linked yourself](http://docs.python.org/py3k/library/urllib.parse.html#urllib.parse.urlsplit):
> `urllib.parse.urlsplit(urlstring, scheme='', allow_fragments=True)`
> This is similar to `urlparse()`, but does not split the params from the URL. This should generally be used instead of `url... |
Regular expression to confirm whether a string is a valid identifier in Python | 5,474,008 | 8 | 2011-03-29T14:18:13Z | 10,134,719 | 13 | 2012-04-13T03:06:47Z | [
"python",
"regex",
"for-loop",
"identifier"
] | I have the following definition for an Identifier:
```
Identifier --> letter{ letter| digit}
```
Basically I have an identifier function that gets a string from a file and tests it to make sure that it's a valid identifier as defined above.
I've tried this:
```
if re.match('\w+(\w\d)?', i):
return True
else:... | From [official reference](http://docs.python.org/reference/lexical_analysis.html#identifiers): `identifier ::= (letter|"_") (letter | digit | "_")*`
So the regular expression is:
```
^[^\d\W]\w*\Z
```
Example (for Python 2 just omit `re.UNICODE`):
```
import re
identifier = re.compile(r"^[^\d\W]\w*\Z", re.UNICODE)
... |
Use of OR as branch control in FP | 5,474,514 | 19 | 2011-03-29T14:51:55Z | 5,474,668 | 12 | 2011-03-29T15:02:26Z | [
"python",
"functional-programming",
"lisp",
"scheme"
] | I undertook an interview last week in which I learnt a few things about python I didn't know about (or rather realise how they could be used), first up and the content of this question is the use of `or` for the purposes of branch control.
So, for example, if we run:
```
def f():
# do something. I'd use ... but t... | Your interviewers must have had a "functional background" way back. It used to be common to write
```
(or (some-condition) (some-side-effect))
```
but in CL and in Scheme implementation that support it, it is much better written with `unless`. Same goes for `and` vs `when`.
So, to be more concrete -- it's not more f... |
Python: Built-in Keyboard Signal/Interrupts | 5,475,456 | 10 | 2011-03-29T16:01:57Z | 6,146,569 | 11 | 2011-05-27T00:29:46Z | [
"python",
"linux",
"signals"
] | I currently need to provide multiple keyboard interrupts for a program. Is there an easy way to do this with the signal class? I currently use the `SIGINT`/`Ctrl+C` but I can't find any other keyboard mappings.
Would be nice to have more than 2 signals. How can I either define more signals or is there a better way to ... | The `Ctrl+\` that has been mentioned is interpreted by your terminal software, and the key binding is configured through `stty`. Unless you have some way of customizing your terminal software you'll only be able to use the few signals that are already built in.
Depending on how much functionality you need or how far y... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.