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 |
|---|---|---|---|---|---|---|---|---|---|
bpython-like autocomplete and parameter description in Emacs Python Mode? | 7,602,169 | 9 | 2011-09-29T19:06:26Z | 7,633,655 | 10 | 2011-10-03T10:17:02Z | [
"python",
"emacs",
"bpython"
] | I've been using [bpython](http://bpython-interpreter.org) for a while now for all of my Python interpreting needs. It's delightful, particularly when you're using unfamiliar new libraries, or libraries with a multitude of functions. In any case, it's nice to have a bpython interpreter running alongside what I'm doing, ... | You're not completely crazy.
`python-mode` can integrate with `eldoc-mode` to display the arg spec of the function you're calling at point. Just do `M-x eldoc-mode` while you're in a python file to turn it on and it should start working. It talks to an inferior python buffer to inspect the functions directly, so it sh... |
(unicode error) 'unicodeescape' codec can't decode bytes - string with '\u' | 7,602,171 | 17 | 2011-09-29T19:06:31Z | 7,602,511 | 12 | 2011-09-29T19:38:04Z | [
"python",
"unicode",
"future-proof"
] | Writing my code for Python 2.6, but with Python 3 in mind, I thought it was a good idea to put
```
from __future__ import unicode_literals
```
at the top of some modules. In other words, I am asking for troubles (to avoid them in the future), but I might be missing some important knowledge here. I want to be able to ... | AFAIK, all that `from __future__ import unicode_literals` does is to make all **string literals** of unicode type, instead of string type. That is:
```
>>> type('')
<type 'str'>
>>> from __future__ import unicode_literals
>>> type('')
<type 'unicode'>
```
But `str` and `unicode` are still different types, and they be... |
Temporarily Disabling Django Caching | 7,602,904 | 17 | 2011-09-29T20:15:31Z | 7,603,746 | 32 | 2011-09-29T21:43:37Z | [
"python",
"django"
] | How do you disable Django caching on a per checkout basis?
Back before Django 1.3, I could disable caching for my local development checkout by specifying `CACHE_BACKEND = None`, in a settings\_local.py imported by settings.py. The settings\_local.py was ignored by SVN, so I could always ensure my local environment di... | <https://docs.djangoproject.com/en/1.3/topics/cache/>
Dummy Caching (for development) - this doesn't actually cache so you could have it on your development side.
```
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
}
}
``` |
Check for [] operator | 7,604,380 | 6 | 2011-09-29T23:11:16Z | 7,604,410 | 13 | 2011-09-29T23:15:46Z | [
"python"
] | How do I check whether an object supports [] operation in Python? I think of something like the following:
```
if supports(obj, ?[]?):
print("Supports")
``` | You don't "check for support". You just use it:
```
try:
a = obj[whatever]
except TypeError:
# whatever your fall-back plan is when obj doesn't support [] (__getitem__)
```
Writing your own `isinstance` is always the wrong thing to do. A new type that doesn't inherit from the collections ABC classes can still... |
Better to 'try' something and catch the exception or test if its possible first to avoid an exception? | 7,604,636 | 58 | 2011-09-29T23:55:29Z | 7,604,664 | 8 | 2011-09-29T23:59:32Z | [
"python",
"exception-handling",
"if-statement",
"try-catch",
"pep"
] | Should I test `if` something is valid or just `try` to do it and catch the exception?
* Is there any solid documentation saying that one way is preferred?
* Is one way more *pythonic*?
For example, should I:
```
if len(my_list) >= 4:
x = my_list[3]
else:
x = 'NO_ABC'
```
Or:
```
try:
x = my_list[3]
exc... | In this particular case, you should use something else entirely:
```
x = myDict.get("ABC", "NO_ABC")
```
In general, though: If you expect the test to fail frequently, use `if`. If the test is expensive relative to just trying the operation and catching the exception if it fails, use `try`. If neither one of these co... |
Better to 'try' something and catch the exception or test if its possible first to avoid an exception? | 7,604,636 | 58 | 2011-09-29T23:55:29Z | 7,604,717 | 67 | 2011-09-30T00:09:27Z | [
"python",
"exception-handling",
"if-statement",
"try-catch",
"pep"
] | Should I test `if` something is valid or just `try` to do it and catch the exception?
* Is there any solid documentation saying that one way is preferred?
* Is one way more *pythonic*?
For example, should I:
```
if len(my_list) >= 4:
x = my_list[3]
else:
x = 'NO_ABC'
```
Or:
```
try:
x = my_list[3]
exc... | You should prefer `try/except` over `if/else` if that results in
* speed-ups (for example by preventing extra lookups)
* cleaner code (less lines/easier to read)
Often, these go hand-in-hand.
---
**speed-ups**
In the case of trying to find an element in a long list by:
```
try:
x = my_list[index]
except Index... |
Maximum and Minimum values for ints | 7,604,966 | 238 | 2011-09-30T01:01:06Z | 7,604,981 | 289 | 2011-09-30T01:03:49Z | [
"python",
"integer"
] | I am looking for minimum and maximum values for integers in python. For eg., in Java, we have `Integer.MIN_VALUE` and `Integer.MAX_VALUE`. Is there something like this in python? | In Python 2, there's `sys.maxint`:
```
>>> sys.maxint
9223372036854775807
```
And you can calculate the minimum value with `-sys.maxint - 1` as seen [here](http://docs.python.org/library/stdtypes.html#numeric-types-int-float-long-complex). Of course Python just switches from plain to long integers once you exceed thi... |
Maximum and Minimum values for ints | 7,604,966 | 238 | 2011-09-30T01:01:06Z | 7,604,998 | 52 | 2011-09-30T01:07:12Z | [
"python",
"integer"
] | I am looking for minimum and maximum values for integers in python. For eg., in Java, we have `Integer.MIN_VALUE` and `Integer.MAX_VALUE`. Is there something like this in python? | In Python integers will automatically switch from a fixed-size `int` representation into a variable width [`long`](http://docs.python.org/library/sys.html#sys.long_info) representation once you pass the value [`sys.maxint`](http://docs.python.org/library/sys.html#sys.maxint), which is either 231 - 1 or 263 - 1 dependin... |
Maximum and Minimum values for ints | 7,604,966 | 238 | 2011-09-30T01:01:06Z | 26,121,781 | 84 | 2014-09-30T13:12:26Z | [
"python",
"integer"
] | I am looking for minimum and maximum values for integers in python. For eg., in Java, we have `Integer.MIN_VALUE` and `Integer.MAX_VALUE`. Is there something like this in python? | **sys.maxint** constant has been removed from Python 3.0 onward, instead use **sys.maxsize**

Refer : <https://docs.python.org/3/whatsnew/3.0.html> |
Maximum and Minimum values for ints | 7,604,966 | 238 | 2011-09-30T01:01:06Z | 37,300,370 | 15 | 2016-05-18T12:58:58Z | [
"python",
"integer"
] | I am looking for minimum and maximum values for integers in python. For eg., in Java, we have `Integer.MIN_VALUE` and `Integer.MAX_VALUE`. Is there something like this in python? | If you just need a number that's bigger than all others, you can use
```
float('inf')
```
in similar fashion, a number smaller than all others:
```
float('-inf')
```
This works in both python 2 and 3. |
SQLAlchemy - build query filter dynamically from dict | 7,604,967 | 20 | 2011-09-30T01:01:14Z | 7,605,366 | 29 | 2011-09-30T02:25:58Z | [
"python",
"sqlalchemy"
] | So I have a dict passed from a web page. I want to build the query dynamically based on the dict. I know I can do:
```
session.query(myClass).filter_by(**web_dict)
```
However, that only works when the values are an exact match. I need to do 'like' filtering. My best attempt using the `__dict__` attribute:
```
for k... | You're on the right track!
First thing you want to do different is access attributes using `getattr`, not `__dict__`; `getattr` will always do the right thing, even when (as may be the case for more convoluted models) a mapped attribute isn't a column property.
The other missing piece is that you can specify `filter(... |
Python ConfigParser interpolation from foreign section | 7,605,124 | 13 | 2011-09-30T01:35:22Z | 7,605,298 | 9 | 2011-09-30T02:11:08Z | [
"python",
"python-2.7",
"python-2.x",
"python-2.4"
] | With Python ConfigParser, is it possible to use interpolation across foreign sections? My mind seems to tell me I've seen that it's possible somewhere, but I can't find it when searching.
This example doesn't work, but it's to give an idea of what I'm trying to do.
```
[section1]
root = /usr
[section2]
root = /usr/l... | In python 3.2 and up this is perfectly valid:
```
[Common]
home_dir: /Users
library_dir: /Library
system_dir: /System
macports_dir: /opt/local
[Frameworks]
Python: 3.2
path: ${Common:system_dir}/Library/Frameworks/
[Arthur]
nickname: Two Sheds
last_name: Jackson
my_dir: ${Common:home_dir}/twosheds
my_pictures: ${my_... |
Parsing a tab delimited file into separate lists or strings | 7,605,374 | 9 | 2011-09-30T02:27:02Z | 7,605,409 | 15 | 2011-09-30T02:34:40Z | [
"python",
"parsing",
"tabs",
"delimited"
] | I am trying to take a tab delimited file with two columns, Name and Age, which reads in as this:
'Name\tAge\nMark\t32\nMatt\t29\nJohn\t67\nJason\t45\nMatt\t12\nFrank\t11\nFrank\t34\nFrank\t65\nFrank\t78\n'
And simply create two lists, one with names (called names, without heading) and one with the ages (called ages, ... | Using the [csv module](http://docs.python.org/library/csv.html#module-csv), you might do something like this:
```
import csv
names=[]
ages=[]
with open('data.csv','r') as f:
next(f) # skip headings
reader=csv.reader(f,delimiter='\t')
for name,age in reader:
names.append(name)
ages.append(a... |
Parsing a tab delimited file into separate lists or strings | 7,605,374 | 9 | 2011-09-30T02:27:02Z | 7,605,434 | 8 | 2011-09-30T02:41:25Z | [
"python",
"parsing",
"tabs",
"delimited"
] | I am trying to take a tab delimited file with two columns, Name and Age, which reads in as this:
'Name\tAge\nMark\t32\nMatt\t29\nJohn\t67\nJason\t45\nMatt\t12\nFrank\t11\nFrank\t34\nFrank\t65\nFrank\t78\n'
And simply create two lists, one with names (called names, without heading) and one with the ages (called ages, ... | tab delimited data is within the domain of the `csv` module:
```
>>> corpus = 'Name\tAge\nMark\t32\nMatt\t29\nJohn\t67\nJason\t45\nMatt\t12\nFrank\t11\nFrank\t34\nFrank\t65\nFrank\t78\n'
>>> import StringIO
>>> infile = StringIO.StringIO(corpus)
```
pretend `infile` was just a regular `file`...
```
>>> import csv
>>... |
Passing a List to Python From Command Line | 7,605,631 | 12 | 2011-09-30T03:22:02Z | 7,605,705 | 13 | 2011-09-30T03:37:11Z | [
"python",
"command-line",
"command-line-arguments",
"command-line-parsing"
] | I would like to make my python script run from the command line when supplies with some arguments. However, one of the arguments should be a list of options specific to one segment of the script. Would string parsing be the only way to do this by actually constructing the list after the "command line list" string is sp... | [argparse](http://docs.python.org/library/argparse.html#module-argparse) is nice for this, it's in the standard library as of 2.7 and 3.2 but otherwise a `pip install` away.
Your main concern of specifying a variable-length list can be addressed by making the list interpreted as a single argument in the shell by using... |
Passing a List to Python From Command Line | 7,605,631 | 12 | 2011-09-30T03:22:02Z | 7,606,377 | 17 | 2011-09-30T05:45:22Z | [
"python",
"command-line",
"command-line-arguments",
"command-line-parsing"
] | I would like to make my python script run from the command line when supplies with some arguments. However, one of the arguments should be a list of options specific to one segment of the script. Would string parsing be the only way to do this by actually constructing the list after the "command line list" string is sp... | **Program:**
```
import sys, ast, getopt, types
def main(argv):
arg_dict={}
switches={'li':list,'di':dict,'tu':tuple}
singles=''.join([x[0]+':' for x in switches])
long_form=[x+'=' for x in switches]
d={x[0]+':':'--'+x for x in switches}
try:
opts, args = getopt... |
Is there a way to directly send a python output to clipboard? | 7,606,062 | 10 | 2011-09-30T04:48:38Z | 7,606,100 | 15 | 2011-09-30T04:54:09Z | [
"python",
"linux",
"clipboard"
] | For example, if a python script will spit out a string giving the path of a newly written file that I'm going to edit immediately after running the script, it would be very nice to have it directly sent to the system clipboard rather than `STDOUT`. | You can use an external program, [`xsel`](http://www.vergenet.net/~conrad/software/xsel/):
```
from subprocess import Popen, PIPE
p = Popen(['xsel','-pi'], stdin=PIPE)
p.communicate(input='Hello, World')
```
With `xsel`, you can set the clipboard you want to work on.
* `-p` works with the `PRIMARY` selection. That's... |
Is there a way to directly send a python output to clipboard? | 7,606,062 | 10 | 2011-09-30T04:48:38Z | 7,606,174 | 8 | 2011-09-30T05:07:46Z | [
"python",
"linux",
"clipboard"
] | For example, if a python script will spit out a string giving the path of a newly written file that I'm going to edit immediately after running the script, it would be very nice to have it directly sent to the system clipboard rather than `STDOUT`. | This is not really a Python question but a shell question. You already can send the output of a Python script (or any command) to the clipboard instead of standard out, by piping the output of the Python script into the `xclip` command.
```
myscript.py | xclip
```
If `xclip` is not already installed on your system (i... |
Python unintuitive member variable behaviour | 7,606,582 | 2 | 2011-09-30T06:14:06Z | 7,606,608 | 7 | 2011-09-30T06:17:32Z | [
"python",
"class",
"variables"
] | This script:
```
class testa():
a = []
class testb():
def __init__(self):
self.a = []
ta1 = testa(); ta1.a.append(1); ta2 = testa(); ta2.a.append(2)
tb1 = testb(); tb1.a.append(1); tb2 = testb(); tb2.a.append(2)
print ta1.a, ta2.a, tb1.a, tb2.a
```
produces this output:
```
[1, 2] [1, 2] [1] [2]
`... | In `testa` the variable `a` is a *class variable* and is shared between all instances. `ta1.a` and `ta2.a` refer to the same list.
In `testb` the variable `a` is an *object variable*. Each instance has its own value.
See [Class and Object Variables](http://www.ibiblio.org/g2swap/byteofpython/read/class-and-object-var... |
Multiple domains and subdomains on a single Pyramid instance | 7,607,807 | 14 | 2011-09-30T08:27:39Z | 7,608,141 | 24 | 2011-09-30T09:01:04Z | [
"python",
"sqlalchemy",
"pyramid"
] | I'm looking to have multiple domains and subdomains on a single Pyramid instance. However, I can't seem to find any documentation on it. The last [question](http://stackoverflow.com/questions/5274813/routing-subdomains-in-pyramid) referred to a glossary with very little information and no examples. Do any of you have a... | Pyramid is just a WSGI application. This means it's dependent on the HTTP\_HOST environ key (set by the Host header) to determine the host of the application. It's all relative. Point-being that Pyramid has no restrictions on what it can accept, thus the world is your oyster and you can set it up to limit content to va... |
In Matplotlib, is there a way to know the list of available output format | 7,608,066 | 20 | 2011-09-30T08:53:25Z | 7,608,273 | 26 | 2011-09-30T09:14:07Z | [
"python",
"matplotlib"
] | According to Matplotlib documentation, `matplotlib.figure.save_fig`takes an optional argument `format` (see [matplotlib.figure documentation](http://matplotlib.sourceforge.net/api/figure_api.html#matplotlib.figure.Figure.savefig)).
This parameters takes 'one of the file extensions supported by the active backend' (as ... | If you create a figure, you can get the available supported file format with the canvas object :
```
import matplotlib.pyplot as plt
fig = plt.figure()
print fig.canvas.get_supported_filetypes()
>>> {
'svgz': 'Scalable Vector Graphics',
'ps': 'Postscript',
'emf': 'Enhanced Metafile',
'rgba': 'Raw RGBA... |
PyPy on Windows 7 x64? | 7,608,503 | 6 | 2011-09-30T09:33:43Z | 7,609,593 | 8 | 2011-09-30T11:19:12Z | [
"python",
"win64",
"pypy"
] | I am trying to use PyPy on a Windows 7 x64 machine but do not find any way to do it.
Apparently there is a win32 binary, but no x64 binary or installation guide.
I am currently using Python 2.7.2 win64 (Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on win32).
Installation from sources raise... | PyPy is not compatible with 64bit windows. Primary reason is that sizeof(void\*) != sizeof(long) which is a bit annoying. Contributions are more than welcome :) |
Replacing particular elements in a list | 7,609,335 | 7 | 2011-09-30T10:51:15Z | 7,609,352 | 11 | 2011-09-30T10:52:55Z | [
"python",
"list"
] | Code:
```
>>> mylist = ['abc','def','ghi']
>>> mylist
['abc', 'def', 'ghi']
>>> for i,v in enumerate(mylist):
... if v=='abc':
... mylist[i] = 'XXX'
...
>>> mylist
['XXX', 'def', 'ghi']
>>>
```
Here, I try to replace all the occurrences of `'abc'` with `'XXX'`. Is there a shorter way to do this? | Use a [list comprehension](http://docs.python.org/tutorial/datastructures.html#list-comprehensions) with a ternary operation / [conditional expression](http://docs.python.org/reference/expressions.html#conditional-expressions):
```
['XXX' if item == 'abc' else item for item in mylist]
``` |
Replacing particular elements in a list | 7,609,335 | 7 | 2011-09-30T10:51:15Z | 7,609,353 | 14 | 2011-09-30T10:53:01Z | [
"python",
"list"
] | Code:
```
>>> mylist = ['abc','def','ghi']
>>> mylist
['abc', 'def', 'ghi']
>>> for i,v in enumerate(mylist):
... if v=='abc':
... mylist[i] = 'XXX'
...
>>> mylist
['XXX', 'def', 'ghi']
>>>
```
Here, I try to replace all the occurrences of `'abc'` with `'XXX'`. Is there a shorter way to do this? | Instead of using an explicit for loop, you can use a [list comprehension](http://docs.python.org/tutorial/datastructures.html#list-comprehensions). This allows you to iterate over all the elements in the list and filter them or map them to a new value.
In this case you can use a [conditional expression](http://en.wiki... |
Python Convert Unicode-Hex utf-8 strings to Unicode strings | 7,609,776 | 5 | 2011-09-30T11:36:45Z | 7,609,883 | 8 | 2011-09-30T11:46:09Z | [
"python",
"unicode",
"utf-8"
] | Have `s = u'Gaga\xe2\x80\x99s'` but need to convert to `t = u'Gaga\u2019s'`
How can this be best achieved? | ```
s = u'Gaga\xe2\x80\x99s'
t = u'Gaga\u2019s'
x = s.encode('raw-unicode-escape').decode('utf-8')
assert x==t
print(x)
```
yields
```
Gagaâs
``` |
Python Convert Unicode-Hex utf-8 strings to Unicode strings | 7,609,776 | 5 | 2011-09-30T11:36:45Z | 7,610,946 | 7 | 2011-09-30T13:18:34Z | [
"python",
"unicode",
"utf-8"
] | Have `s = u'Gaga\xe2\x80\x99s'` but need to convert to `t = u'Gaga\u2019s'`
How can this be best achieved? | Where ever you decoded the original string, it was likely decoded with latin-1 or a close relative. Since latin-1 is the first 256 codepoints of Unicode, this works:
```
>>> s = u'Gaga\xe2\x80\x99s'
>>> s.encode('latin-1').decode('utf8')
u'Gaga\u2019s'
``` |
What is the -m switch for in Python? | 7,610,001 | 43 | 2011-09-30T11:58:29Z | 7,610,082 | 48 | 2011-09-30T12:05:11Z | [
"python"
] | Could you explain to me what the difference is between calling
```
python -m mymod1 mymod2.py args
```
and
```
python mymod1.py mymod2.py args
```
It seems in both cases `mymod1.py` is called and `sys.argv` is
```
['mymod1.py', 'mymod2.py', 'args']
```
So what is the `-m` switch for? | The first line of the `Rationale` section of [PEP 338](http://www.python.org/dev/peps/pep-0338/) says:
> Python 2.4 adds the command line switch -m to allow modules to be located using the Python module namespace for execution as scripts. The motivating examples were standard library modules such as pdb and profile, a... |
Python: how to keep only first 50 char of a string | 7,610,694 | 5 | 2011-09-30T12:58:11Z | 7,610,712 | 12 | 2011-09-30T12:59:44Z | [
"python",
"string"
] | I have a string which
```
x = "very_long_string_more_than_50_char_long"
```
I want to keep only first 50 char and delete the rest.
how would i do that?
thanks | ```
x = x[:50]
```
For details on *slices* like this, refer to the [documentation](http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange). |
Do I need to use a web framework for a simple website? | 7,611,759 | 3 | 2011-09-30T14:21:55Z | 7,612,742 | 7 | 2011-09-30T15:32:56Z | [
"python",
"frameworks",
"pyramid"
] | The site won't be that complicated and will resemble a modern blog (users, messages, news and other similar features).
Do I need to use a framework for this, and if so, which is best?
Pyramid, Django? | You certainly don't need a webframework to create a simple website. Given that you're new to python and interested in building a python website, I imagine this implies: you're interested in learning python. If you're exclusively interested in learning django-python, there's no reason you can't jump in to django, as Ron... |
Checking if Two Massive Python Dictionaries are Equivalent | 7,611,854 | 6 | 2011-09-30T14:29:40Z | 7,611,921 | 8 | 2011-09-30T14:34:25Z | [
"python",
"dictionary",
"transformation",
"python-2.7"
] | I have a massive python dictionary with over 90,000 entries. For reasons I won't get into, I need to store this dictionary in my database and then at a later point recompile dictionary from the database entries.
I am trying to set up a procedure to verify that my storage and recompilation was faithful and that my new ... | The most obvious approach is of course:
```
if oldDict != newDict
print "**Failure to rebuild, new dictionary is different from the old"
```
That ought to be the fastest possible, since it relies on Python's internals to do the comparison.
*UPDATE*: It seems you're not after "equal", but something weaker. I think ... |
Django MakeMessages missing xgettext in Windows | 7,612,259 | 12 | 2011-09-30T14:57:56Z | 7,612,773 | 14 | 2011-09-30T15:36:13Z | [
"python",
"django",
"windows-7",
"xgettext"
] | Running Django on Windows 7.
I'm currently trying to translate a couple of Django templates using the instructions found in the django book chapter 19. I've added a translation tag to the template, loaded I18N, and modified django settings. Then I run django-admin.py makemessages -l en to create the po files. All fold... | please see <http://code.djangoproject.com/ticket/1157>. you do not need cygwin. try these files: <http://sourceforge.net/projects/gettext/files/>
EDIT:
<http://ftp.gnome.org/pub/gnome/binaries/win32/dependencies/gettext-tools-0.17.zip>
<http://ftp.gnome.org/pub/gnome/binaries/win32/dependencies/gettext-runtime-0.17-... |
python subprocess and unicode execv() arg 2 must contain only strings | 7,612,727 | 11 | 2011-09-30T15:31:34Z | 7,612,747 | 16 | 2011-09-30T15:33:28Z | [
"python",
"unicode",
"subprocess"
] | I have a django site where I need to call a script using subprocess. The subprocess call works when I'm using ascii characters but when I try to issue arguments that are utf-8 encoded, I get an error:
```
execv() arg 2 must contain only strings.
```
The string `u'Wiadomo\u015b\u0107'` is coming from a postgres db. Th... | You should encode the Unicode strings in the encoding your program expects. If you know the program expects UTF-8:
```
u'Wiadomo\u015b\u0107'.encode('utf8')
```
If you don't know what encoding you need, you could try your platform's default encoding:
```
u'Wiadomo\u015b\u0107'.encode()
``` |
Open Source Software For Transcribing Speech in Audio Files | 7,613,089 | 17 | 2011-09-30T16:06:44Z | 7,617,134 | 13 | 2011-09-30T23:44:52Z | [
"java",
"python",
"speech-recognition",
"speech-to-text",
"cmusphinx"
] | Can anyone recommend reliable open source software for transcribing English speech in wav files? The two main programs I've researched are [Sphinx](http://cmusphinx.sourceforge.net/) and [Julius](http://julius.sourceforge.jp/en_index.php), but I've never been able to get either to work, and the documentation with each ... | > Why can't it read a wav?
It tells you that the file has wrong sampling rate (8000) instead of requested (16000). Sampling rate is very important for speech recognition software.
> Why can't it read /dev/dsp?
In recent versions of Ubuntu pulseaudio framework is used instead of OSS. The version you are trying is usi... |
Python Error Codes are upshifted | 7,616,187 | 6 | 2011-09-30T21:15:36Z | 7,616,210 | 7 | 2011-09-30T21:18:52Z | [
"python"
] | Consider a python script error.py
```
import sys
sys.exit(3)
```
Invoking
```
python error.py; echo $?
```
yields the expected "3". However, consider runner.py
```
import os
result = os.system("python error.py")
print result
```
yields 768. It seems that somehow the result of python code has been leftshifted by 8... | From the [docs](http://docs.python.org/library/os.html#os.system):
> On Unix, the return value is the exit status of the process encoded in
> the format specified for wait(). Note that POSIX does not specify the
> meaning of the return value of the C system() function, so the return
> value of the Python function is s... |
Get selected item in listbox and call another function storing the selected for it | 7,616,541 | 3 | 2011-09-30T22:03:42Z | 7,617,619 | 7 | 2011-10-01T01:46:09Z | [
"python",
"listbox",
"tkinter",
"tk"
] | I have a canvas that calls `createCategoryMeny(x)` when it is clicked.
This function just creates a `Toplevel()` window,
```
def createCategoryMenu(tableNumber):
##Not interesting below:
categoryMenu = Toplevel()
categoryMenu.title("Mesa numero: " + str(tableNumber))
categoryMenu.geometry("400x400+10... | For one, don't use `lambda`. It's useful for a narrow range of problems and this isn't one of them. Create a proper function, they are much easier to write and maintain.
Once you do that, you can call `curselection` to get the current selection. You say you tried that but your example code doesn't show what you tried,... |
Python: print "word" in [] == False | 7,616,691 | 4 | 2011-09-30T22:27:49Z | 7,616,706 | 11 | 2011-09-30T22:30:26Z | [
"python"
] | Going a bit mental here trying to work out what this does in python:
```
print "word" in [] == False
```
Why does this print `False`? | Perhaps a more clear example of this unusual behaviour is the following:
```
>>> print 'word' in ['word']
True
>>> print 'word' in ['word'] == True
False
```
---
Your example is equivalent to:
```
print ("word" in []) and ([] == False)
```
This is because two boolean expressions can be combined, with the intention... |
ElementTree's iter() equivalent in Python2.6 | 7,616,800 | 12 | 2011-09-30T22:45:36Z | 7,616,863 | 8 | 2011-09-30T22:56:09Z | [
"python",
"xml",
"python-2.6",
"elementtree"
] | I have this code with ElementTree that works well with Python 2.7.
I needed to get all the nodes with the name "A" under "X/Y" node.
```
from xml.etree.ElementTree import ElementTree
verboseNode = topNode.find("X/Y")
nodes = list(verboseNode.iter("A"))
```
However, when I tried to run it with Python 2.6, I got this ... | Note that `iter` *is* available in Python 2.6 (and even 2.5 - otherwise, there'd be a notice in the [docs](http://docs.python.org/library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree.iter)), so you don't really need a replacement.
You can, however, use [`findall`](http://docs.python.org/library/xml.etr... |
ElementTree's iter() equivalent in Python2.6 | 7,616,800 | 12 | 2011-09-30T22:45:36Z | 7,616,868 | 15 | 2011-09-30T22:56:28Z | [
"python",
"xml",
"python-2.6",
"elementtree"
] | I have this code with ElementTree that works well with Python 2.7.
I needed to get all the nodes with the name "A" under "X/Y" node.
```
from xml.etree.ElementTree import ElementTree
verboseNode = topNode.find("X/Y")
nodes = list(verboseNode.iter("A"))
```
However, when I tried to run it with Python 2.6, I got this ... | Not sure if this is what you are looking for, as `iter()` appears to be around in 2.6, but there's `getiterator()`
<http://docs.python.org/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.getiterator> |
pil png activestate on windows 7 ZLIB (PNG/ZIP) support not available | 7,616,987 | 2 | 2011-09-30T23:17:33Z | 7,618,116 | 7 | 2011-10-01T04:20:31Z | [
"python",
"windows",
"python-imaging-library",
"activestate",
"activepython"
] | I'm trying to port a python program from OS X to Windows 7.
This program processes a png with tkinter
eg
```
self.logoImg = ImageTk.PhotoImage(Image.open('GrowthPathLogo.png'))
```
The code is failing with
IOError: decoder zip not available
I've tried installing pip with pypm.
Then I try building it with pip.
At the... | Try the build [here](http://www.lfd.uci.edu/~gohlke/pythonlibs/#pil) that's maintained by Christoph Gohlke. To build PIL yourself you need several libraries as mentioned in the README: libjpeg, zlib, freetype2, and littleCMS. Read USAGE.txt in [zlib125-dll.zip](http://zlib.net/zlib125-dll.zip) for instructions on linki... |
Python regex string matching? | 7,616,998 | 26 | 2011-09-30T23:19:16Z | 7,617,017 | 48 | 2011-09-30T23:21:28Z | [
"python",
"regex",
"pattern-matching"
] | I'm having a hell of a time trying to transfer my experience with javascript regex to Python.
I'm just trying to get this to work:
```
print(re.match('e','test'))
```
...but it prints None. If I do:
```
print(re.match('e','est'))
```
It matches... does it by default match the beginning of the string? When it does ... | `re.match` implicitly adds `^` to the start of your regex. In other words, it only matches at the start of the string.
`re.search` will retry at all positions.
Generally speaking, I recommend using `re.search` and adding `^` explicitly when you want it.
<http://docs.python.org/library/re.html> |
Python regex string matching? | 7,616,998 | 26 | 2011-09-30T23:19:16Z | 7,617,036 | 8 | 2011-09-30T23:25:32Z | [
"python",
"regex",
"pattern-matching"
] | I'm having a hell of a time trying to transfer my experience with javascript regex to Python.
I'm just trying to get this to work:
```
print(re.match('e','test'))
```
...but it prints None. If I do:
```
print(re.match('e','est'))
```
It matches... does it by default match the beginning of the string? When it does ... | the docs is clear i think.
> re.match(pattern, string[, flags])¶
>
> ```
> If zero or more characters **at the beginning of string** match the
> ```
>
> regular expression pattern, return a corresponding MatchObject
> instance. Return None if the string does not match the pattern; note
> that this is different from a... |
PDB won't stop on breakpoint | 7,617,066 | 6 | 2011-09-30T23:29:58Z | 28,277,178 | 9 | 2015-02-02T11:52:50Z | [
"python",
"pdb"
] | I'm quite new with debugging directly with pdb and I am having some issues debugging my Django application. Here is what I'm doing:
```
python -m pdb manage.py runserver
(pdb) b core/views.py:22
Breakpoint 2 at /Users/raphaelcruzeiro/Documents/Projects/pdb_test/core/views.py:22
(Pdb) c
```
However the execution passe... | I've been through the same problem.
Try something like `python -m pdb ./manage.py runserver --nothreading --noreload 127.0.0.1:8080`. It solved the issue for me.
It seems that breakpoints with PDB are thread-specific, and the `--nothreading` and `--noreload` options are necessary to avoid some forking that may confus... |
TypeError: 'str' does not support the buffer interface - python | 7,617,937 | 4 | 2011-10-01T03:23:21Z | 7,617,980 | 12 | 2011-10-01T03:35:40Z | [
"python",
"python-3.x",
"pickle"
] | I'm currently doing an online Python puzzle series, and I've gotten to a problem where you need to unload a pickled file. I read the documentation on it, but I kept getting
`TypeError: 'str' does not support the buffer interface`
...so I search on Google and arrive at a question on SO with a similar problem. The answ... | Open the pickle file in binary mode: `favorite_color = pickle.load(open("save.p", "rb"))`. |
My python interpreter does not recognize strings | 7,618,503 | 3 | 2011-10-01T06:05:33Z | 7,618,528 | 7 | 2011-10-01T06:12:11Z | [
"python",
"syntax-error",
"python-idle"
] | Newbie disclaimer: I am new to Python and just started using IDLE to play around with Python.
My problem is the interpreter does not recognize strings, whether enclosed in ¨¨ or ´´.
I configured IDLE to use UTF-8. but it does not seem to be an IDLE issue. What I tried is to test this string in the interpreter dir... | You need to use `""` or `''`, not `¨¨`, `´´` or any other fancy characters. |
python program to read a matrix from a given file | 7,618,858 | 4 | 2011-10-01T07:25:32Z | 7,618,906 | 16 | 2011-10-01T07:36:47Z | [
"python"
] | i have a text file which contains matrix of N \* M dimensions ,
for example the input.txt file contains the following
```
0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0
0,0,2,1,0,2,0,0,0,0
0,0,2,1,1,2,2,0,0,1
0,0,1,2,2,1,1,0,0,2
1,0,1,1,1,2,1,0,... | Consider
```
f = open ( 'input.txt' , 'r')
l = [ map(int,line.split(',')) for line in f ]
print l
```
produces
```
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 2,... |
NLTK Chunking and walking the results tree | 7,619,109 | 8 | 2011-10-01T08:28:56Z | 7,619,376 | 9 | 2011-10-01T09:31:03Z | [
"python",
"text-parsing",
"nltk",
"chunking"
] | I'm using NLTK RegexpParser to extract noungroups and verbgroups from tagged tokens.
How do I walk the resulting tree to find only the chunks that are NP or V groups?
```
from nltk.chunk import RegexpParser
grammar = '''
NP: {<DT>?<JJ>*<NN>*}
V: {<V.*>}'''
chunker = RegexpParser(grammar)
token = [] ## Some tokens fr... | This should work:
```
for n in chunked:
if isinstance(n, nltk.tree.Tree):
if n.node == 'NP':
do_something_with_subtree(n)
else:
do_something_with_leaf(n)
``` |
Multiple Python Processes slow | 7,619,259 | 4 | 2011-10-01T09:01:16Z | 7,619,452 | 7 | 2011-10-01T09:44:23Z | [
"python",
"performance",
"http",
"unix",
"task"
] | I have a python script which goes off and makes a number of HTTP and urllib requests to various domains.
We have a huge amount of domains to processes and need to do this as quickly as possible.
As HTTP requests are slow (i.e. they could time out of there is no website on the domain) I run a number of the scripts at a... | Check the `ulimit` and `quota` for the box and the user running the scripts. `/etc/security/limits.conf` may also contain resource restrictions that you might want to modify.
`ulimit -n` will show the max number of open file descriptors allowed.
* Might this have been exceeded with all of the open sockets?
* Is the s... |
Python xlrd: suppress warning messages | 7,619,319 | 6 | 2011-10-01T09:19:29Z | 15,315,188 | 9 | 2013-03-09T19:52:46Z | [
"python",
"xlrd"
] | I am using `xlrd` to process Excel files. I am running a script on a folder that contains many files, and I am printing messages related to the files. However, for each file I run, I get the following xlrd-generated error message as well:
```
WARNING *** OLE2 inconsistency: SSCS size is 0 but SSAT size is non-zero
```... | The answer by John works, but has a small problem:
xlrd writes that warning message and the following newline character separately to the logfile. Therefore you will get an empty line in your stdout instead of the message, if you use the filter class proposed by John. You shouldn't simply filter out all newlines from ... |
Python list comprehension - simple | 7,619,868 | 7 | 2011-10-01T11:13:53Z | 7,619,879 | 17 | 2011-10-01T11:15:39Z | [
"python",
"list-comprehension"
] | I have a list and I want to use a certain function only on those entries of it that fulfills a certain condition - leaving the other entries unmodified.
Example: Say I want to multiply by 2 only those elements who are even.
```
a_list = [1, 2, 3, 4, 5]
```
Wanted result:
```
a_list => [1, 4, 3, 8, 5]
```
But `[ele... | Use a [conditional expression](http://docs.python.org/whatsnew/2.5.html#pep-308-conditional-expressions):
```
[x * 2 if x % 2 == 0 else x
for x in a_list]
```
(Math geek's note: you can also solve this particular case with
```
[x * (2 - x % 2) for x in a_list]
```
but I'd prefer the first option anyway ;) |
How do you tell pyximport to use the cython --cplus option? | 7,620,003 | 14 | 2011-10-01T11:39:14Z | 7,620,240 | 14 | 2011-10-01T12:37:03Z | [
"c++",
"python",
"cython"
] | pyximport is super handy but I can't figure out how to get it to engage the C++ language options for Cython. From the command line you'd run `cython --cplus foo.pyx`. How do you achieve the equivalent with pyximport? Thanks! | One way to make Cython create C++ files is to use a pyxbld file. For example, create `foo.pyxbld` containing the following:
```
def make_ext(modname, pyxfilename):
from distutils.extension import Extension
return Extension(name=modname,
sources=[pyxfilename],
language=... |
Stubbing out functions or classes | 7,620,382 | 4 | 2011-10-01T13:05:17Z | 7,620,445 | 13 | 2011-10-01T13:14:51Z | [
"python",
"stub",
"stubbing"
] | Can you explain the concept `stubbing out functions or classes` taken from [this article](http://diveintopython.net/object_oriented_framework/defining_classes.html)?
```
class Loaf:
pass
```
> This class doesn't define any methods or attributes, but syntactically, there needs to be something in the definition, so... | > stubbing out functions or classes
This refers to writing classes or functions but not yet implementing them. For example, maybe I create a class:
```
class Foo(object):
def bar(self):
pass
def tank(self):
pass
```
I've stubbed out the functions because I haven't yet implemented them. H... |
easy_install downloading directory | 7,621,103 | 3 | 2011-10-01T15:23:13Z | 9,477,870 | 16 | 2012-02-28T07:17:09Z | [
"python",
"easy-install"
] | I'm trying to install a python script packaged in egg format using easy\_install. The problem is that easy\_install downloads dependencies to /tmp. However, my tmp dir only has 4mb of free space (I am working with a NAS drive, set up this way).
Is there a way of specifying the download directory? --help doesn't seem t... | Set TMPDIR environment variable such as following:
```
export TMPDIR="/opt/tmp"
```
I think this is a better way than rewriting the easy\_install.py. You need to ensure the path exists. |
Python: logging module - globally | 7,621,897 | 24 | 2011-10-01T17:48:22Z | 7,622,029 | 50 | 2011-10-01T18:10:11Z | [
"python",
"logging",
"module",
"global-variables"
] | Hey I was wondering how to implement a global logger that could be used everywhere with your own settings:
I have
```
class customLogger(logging.Logger):
...
```
in a file with its formatters and other stuff.
The logger works perfectly on its own.
I import this module in my main.py file and create an object like... | Use logging.getLogger(name) to create a named global logger.
( <https://docs.python.org/3/library/logging.html#logging.getLogger> )
**main.py**
```
import log
logger = log.setup_custom_logger('root')
logger.debug('main message')
import submodule
```
**log.py**
```
import logging
def setup_custom_logger(name):
... |
Unable to use easy_install to install Python modules | 7,622,562 | 10 | 2011-10-01T19:52:49Z | 7,622,611 | 13 | 2011-10-01T20:01:12Z | [
"python",
"module",
"installation",
"setuptools",
"easy-install"
] | I am trying to use `easy_install` to install a module called **requests** by doing
```
easy_install requests
```
This worked fine a week ago when I was using Python 2.6.5 but today I installed Python 2.7.2 and then tried to `import requests` in one of my scripts but it failed. I then tried reinstalling requests with ... | Did you try using `sudo` like this?
```
sudo easy_install requests
```
Or specify the install directory to a directory that you have write privileges.
```
easy_install --install-dir=/home/foo/bar
```
But you should really use [PIP](http://www.pip-installer.org/en/latest/index.html) instead of `easy_install`. It is ... |
Using SSH in python | 7,622,739 | 2 | 2011-10-01T20:22:43Z | 7,622,993 | 13 | 2011-10-01T21:08:10Z | [
"python",
"ssh"
] | I need to connect with other server via SSH using Python, execute few comands and assign result of each command to differrent variables.
What is the simplest way to do it?
I've tried [SSHController](http://www.goldb.org/sshpython.html), but I think, I've screwed up something with prompt, and the script is waiting f... | There are a number of ways to use SSH from within Python. The general approaches are:
* Call the local `ssh` binary using [subprocess.Popen()](http://docs.python.org/library/subprocess.html) or similar (suitable only for gathering the results in batch)
* Call and control the local `ssh` binary using [pexpect](http://w... |
Combining generators | 7,623,052 | 2 | 2011-10-01T21:22:15Z | 7,623,175 | 7 | 2011-10-01T21:47:37Z | [
"python",
"python-3.x"
] | I have a function that returns a list via yield. I use this function as follows:
```
myList = []
for i in range(10):
myList = myList + list(myListGenerator(i))
pickleFile = open("mystuff.dat", "wb")
pickle.dump(myList, pickleFile)
pickleFile.close()
```
I'm just wondering if this is the most efficient way to pic... | You can combine the results of the generators (created using a generator expression) into a single list with [`itertools.chain.from_iterable`](http://docs.python.org/library/itertools.html#itertools.chain.from_iterable):
```
pickle.dump(list(itertools.chain.from_iterable(
myListGenerator(i) for i in rang... |
Deleting list elements based on condition | 7,623,715 | 9 | 2011-10-01T23:54:07Z | 7,623,750 | 12 | 2011-10-02T00:01:56Z | [
"python",
"list",
"elements"
] | I have a list of lists: `[word, good freq, bad freq, change_status]`
```
list_1 = [['good',100, 20, 0.2],['bad', 10, 0, 0.0],['change', 1, 2, 2]]
```
I would like to delete from the list all elements which don't satisfy a condition.
So if `change_status > 0.3 and bad_freq < 5` then I would like to delete that the el... | ```
list_1 = [['good',100, 20, 0.2],['bad', 10, 0, 0.0],['change', 1, 2, 2]]
list_1 = [item for item in list_1 if item[2] >= 5 or item[3] >= 0.3]
```
You can also use `if not (item[2] < 5 and item[3] < 0.3)` for the condition if you want. |
Removing indent in PYDEV | 7,623,795 | 3 | 2011-10-02T00:12:39Z | 7,623,803 | 7 | 2011-10-02T00:14:59Z | [
"python",
"pydev"
] | I am using pydev for python development. I am facing issue while removing indentation for a block of statement.
If I have to add indentation I used to press **SHIFT + down** arrow key until I reach the end of block of statements which I want to indent and then press the TAB key.This is how i used to add indent for a b... | I don't know Pydev, but in most editors Shift+Tab will do the trick. |
Python if statement doesn't work as expected | 7,623,818 | 3 | 2011-10-02T00:18:40Z | 7,623,837 | 9 | 2011-10-02T00:21:19Z | [
"python",
"printing",
"random",
"if-statement"
] | I currently have the code:
```
fleechance = random.randrange(1,5)
print fleechance
if fleechance == 1 or 2:
print "You failed to run away!"
elif fleechance == 4 or 3:
print "You got away safely!"
```
fleechance is constantly printing as 3 or 4, but I continue to get the result "You failed to run away!" ,can a... | The expression `fleechance == 1 or 2` is equivalent to `(fleechance == 1) or (2)`. The number `2` is always considered âtrueâ.
Try this:
```
if fleechance in (1, 2):
```
EDIT: In your situation (only 2 possibilities), the following will be even better:
```
if fleechance <= 2:
print "You failed to run away!"... |
Python C API doesn't load module | 7,624,529 | 3 | 2011-10-02T03:59:24Z | 8,859,538 | 7 | 2012-01-14T01:58:12Z | [
"python",
"c",
"python-c-api",
"python-embedding"
] | I'm trying to load a python module that contains a math and numpy import in C, using the C API. I can load and run the module but, if I import the math module it doesn't work.
I'm using Arch Linux, Python 2.7.2 and gcc.
Here the codes:
```
#include <stdio.h>
#include <stdlib.h>
#include <python2.7/Python.h>
int ma... | The `PySys_SetPath(".")` cleared the python path, so it could no longer find any library whatsoever. What you really need to do is import sys.path and then append your string to it:
```
PyObject *sys = PyImport_ImportModule("sys");
PyObject *path = PyObject_GetAttrString(sys, "path");
PyList_Append(path, PyString_From... |
Converting an OpenCV Image to Black and White | 7,624,765 | 24 | 2011-10-02T05:23:26Z | 7,637,687 | 47 | 2011-10-03T16:17:18Z | [
"python",
"image-processing",
"opencv",
"computer-vision"
] | How do you convert a grayscale OpenCV image to black and white? I see a [similar question](http://stackoverflow.com/questions/1585535/convert-rgb-to-black-white-in-opencv) has already been asked, but I'm using OpenCV 2.3, and the proposed solution no longer seems to work.
I'm trying to convert a greyscale image to bla... | Step-by-step answer similar to the one you refer to, using the new cv2 Python bindings:
**1. Read a grayscale image**
```
import cv2
im_gray = cv2.imread('grayscale_image.png', cv2.CV_LOAD_IMAGE_GRAYSCALE)
```
**2. Convert grayscale image to binary**
```
(thresh, im_bw) = cv2.threshold(im_gray, 128, 255, cv2.THRESH... |
python: is it possible to require that arguments to the functions are all keyword? | 7,624,840 | 2 | 2011-10-02T05:53:19Z | 7,624,932 | 14 | 2011-10-02T06:22:14Z | [
"python",
"function",
"coding-style",
"python-3.x"
] | To avoid the obvious bugs, I'd like to prevent the use of positional arguments with some functions. Is there any way to achieve that? | Only Python 3 can do it properly (and you used the python3 tag, so it's fine):
```
def function(*, x, y, z):
print(x,y,z)
```
using `**kwargs` will let the user input **any** argument unless you check later. Also, it will hide the real arguments names from introspection.
`**kwargs` is not the answer for this pro... |
How can I use boto to stream a file out of Amazon S3 to Rackspace Cloudfiles? | 7,624,900 | 11 | 2011-10-02T06:09:28Z | 7,625,197 | 15 | 2011-10-02T07:54:34Z | [
"python",
"amazon-s3",
"boto",
"rackspace",
"cloudfiles"
] | I'm copying a file from S3 to Cloudfiles, and I would like to avoid writing the file to disk. The Python-Cloudfiles library has an object.stream() call that looks to be what I need, but I can't find an equivalent call in boto. I'm hoping that I would be able to do something like:
```
shutil.copyfileobj(s3Object.stream... | The Key object in boto, which represents on object in S3, can be used like an iterator so you should be able to do something like this:
```
>>> import boto
>>> c = boto.connect_s3()
>>> bucket = c.lookup('garnaat_pub')
>>> key = bucket.lookup('Scan1.jpg')
>>> for bytes in key:
... write bytes to output stream
```
O... |
How can I use boto to stream a file out of Amazon S3 to Rackspace Cloudfiles? | 7,624,900 | 11 | 2011-10-02T06:09:28Z | 16,890,018 | 10 | 2013-06-03T04:29:35Z | [
"python",
"amazon-s3",
"boto",
"rackspace",
"cloudfiles"
] | I'm copying a file from S3 to Cloudfiles, and I would like to avoid writing the file to disk. The Python-Cloudfiles library has an object.stream() call that looks to be what I need, but I can't find an equivalent call in boto. I'm hoping that I would be able to do something like:
```
shutil.copyfileobj(s3Object.stream... | I figure at least some of the people seeing this question will be like me, and will want a way to stream a file from boto line by line (or comma by comma, or any other delimiter). Here's a simple way to do that:
```
def getS3ResultsAsIterator(self, aws_access_info, key, prefix):
s3_conn = S3Connection(**aw... |
Django models.Model superclass | 7,625,010 | 3 | 2011-10-02T06:51:49Z | 7,625,017 | 9 | 2011-10-02T06:53:26Z | [
"python",
"django"
] | I would like to create a models.Model class that doesn't became part of the database but just an interface to other models (I want to avoid repeating code).
Something like that:
```
class Interface(models.Model):
a = models.IntegerField()
b = models.TextField()
class Foo(Interface):
c = models.IntegerFie... | ["Abstract base classes"](https://docs.djangoproject.com/en/dev/topics/db/models/#abstract-base-classes)
> Abstract base classes are useful when you want to put some common information into a number of other models. You write your base class and put `abstract=True` in the Meta class. This model will then not be used t... |
Download CSV directly into Python CSV parser | 7,625,079 | 3 | 2011-10-02T07:17:12Z | 7,625,096 | 8 | 2011-10-02T07:24:16Z | [
"python",
"parsing",
"csv"
] | I'm trying to download CSV content from morningstar and then parse its contents. If I inject the HTTP content directly into Python's CSV parser, the result is not formatted correctly. Yet, if I save the HTTP content to a file (/tmp/tmp.csv), and then import the file in the python's csv parser the result is correct. In ... | The problem results from the fact that iteration over a file is done line-by-line whereas iteration over a string is done character-by-character.
You want [`StringIO`](http://docs.python.org/library/stringio)/[`cStringIO`](http://docs.python.org/library/stringio#module-cStringIO) (Python 2) or [`io.StringIO`](http://d... |
How do you use a variable as an index when slicing strings in Python? | 7,625,326 | 3 | 2011-10-02T08:28:22Z | 7,625,339 | 8 | 2011-10-02T08:31:22Z | [
"python",
"string",
"slice"
] | I've been trying to slice two characters out of a string using a loop, but instead of grabbing two characters, it only grabs one.
I've tried:
```
input[i:i+1]
```
and
```
input[i:(i+1)]
```
but neither seems to work.
How do I use a variable for slicing?
The full routine:
```
def StringTo2ByteList(input):
# ... | The slice values aren't the start and end *characters* of the slice, they're the start and end **points**. If you want to slice two elements then your stop must be **2** greater than your start.
```
input[i:i+2]
``` |
type=dict in argparse.add_argument() | 7,625,786 | 8 | 2011-10-02T10:17:19Z | 18,003,926 | 23 | 2013-08-01T20:29:54Z | [
"python",
"argparse"
] | I'm trying to set up a dictionary as optional argument (using argparse); the following line is what I have so far:
```
parser.add_argument('-i','--image', type=dict, help='Generate an image map from the input file (syntax: {\'name\': <name>, \'voids\': \'#08080808\', \'0\': \'#00ff00ff\', \'100%%\': \'#ff00ff00\'}).')... | Necroing this: `json.loads` works here, too. It doesn't seem too dirty.
```
import json
import argparse
test = '{"name": "img.png","voids": "#00ff00ff","0": "#ff00ff00","100%": "#f80654ff"}'
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input', type=json.loads)
args = parser.parse_args(['-i', test... |
Python/Django: sending emails in the background | 7,626,071 | 13 | 2011-10-02T11:30:27Z | 7,626,112 | 18 | 2011-10-02T11:40:52Z | [
"python",
"django",
"django-email"
] | Imagine a situation in which a user performs an action on a website and admins are notified.
Imagine there are 20 admins to notify. By using normal methods for sending emails with Django the user will have to wait until all the emails are sent before being able to proceed.
How can I send all the emails in a separate p... | Use [celery](http://celeryproject.org/) as a task queue and [django-celery-email](http://pypi.python.org/pypi/django-celery-email) which is an Django e-mail backend that dispatches e-mail sending to a celery task. |
Using Google OAuth on localhost | 7,626,299 | 16 | 2011-10-02T12:27:56Z | 7,636,026 | 11 | 2011-10-03T13:58:33Z | [
"python",
"oauth",
"google-api",
"google-api-client"
] | I started to use OAuth with Python and Django. I need it for Google APIs. I working on localhost, so I can't register a domain for url-callback. I've read about that Google OAuth could be used with anonymous domain. Can't find, how and where I can do that?
## Edit:
I have this view:
```
def authentication(request):
... | Just to be clear, you can use the web application flow with localhost while developing on either OAuth 1.0 or OAuth 2.0. OAuth 2.0 should be preferred as it's the mechanism we are focussed on. The user experience for OAuth 2.0 is going to be substantially better.
There's nothing stopping you from using localhost as yo... |
Python's logging module misses "captureWarnings" function | 7,627,075 | 4 | 2011-10-02T14:50:44Z | 7,627,108 | 8 | 2011-10-02T15:00:33Z | [
"python",
"logging",
"warnings"
] | Python's standard logging module is [supposed to contain a useful captureWarnings function](http://docs.python.org/library/logging.html#logging.captureWarnings) that allows integration between the logging and the [warnings](http://www.google.com/url?sa=t&source=web&cd=1&ved=0CCEQFjAA&url=http://docs.python.org/library/... | Unfortunately, there is no such method in [Python 2.6.5's logging module](http://docs.python.org/release/2.6.5/library/logging.html). You need Python 2.7. |
How much days left from today to given date | 7,628,036 | 2 | 2011-10-02T17:34:17Z | 7,628,046 | 9 | 2011-10-02T17:37:05Z | [
"python"
] | I have a date - 2015.05.20
What is the best way to calculate using python how much days left from today till this date?
```
from datetime import *
today = date.today()
future = date(2015,05,20)
???
``` | ```
diff = future - today
print diff.days
```
`diff` is a [timedelta](http://docs.python.org/library/datetime.html#timedelta-objects) object. |
Python: super and __init__() vs __init__( self ) | 7,629,556 | 14 | 2011-10-02T22:09:55Z | 7,629,620 | 23 | 2011-10-02T22:20:53Z | [
"python"
] | **A:**
```
super( BasicElement, self ).__init__()
```
**B:**
```
super( BasicElement, self ).__init__( self )
```
What is the difference between A and B? Most examples that I run across use A, but I am running into an issue where A is not calling the parent \_\_init\_\_ function, but B is. Why might this be? Which ... | You should not need to do that second form, unless somehow BasicElement class's `__init__` takes an argument.
```
class A(object):
def __init__(self):
print "Inside class A init"
class B(A):
def __init__(self):
super(B, self).__init__()
print "Inside class B init"
>>> b = B()
Inside c... |
How do I validate the format of a MAC address? | 7,629,643 | 11 | 2011-10-02T22:26:12Z | 7,629,690 | 30 | 2011-10-02T22:36:39Z | [
"python"
] | What's the best way to validate that an MAC address entered by the user?
The format is `HH:HH:HH:HH:HH:HH`, where each `H` is a hexadecimal character.
For instance, `00:29:15:80:4E:4A` is valid while `00:29:804E4A` is invalid. | If you mean just the syntax then this regexp should work for you
```
import re
...
if re.match("[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$", x.lower()):
...
```
it accepts 12 hex digits with either `:` or `-` as separators between pairs (but the separator must be uniform... either all separators are `:` or ... |
Is there Windows analog to supervisord? | 7,629,813 | 16 | 2011-10-02T23:02:47Z | 18,032,347 | 20 | 2013-08-03T11:25:55Z | [
"python",
"windows",
"supervisord"
] | I need to run python script and be sure that it will restart after it terminates. I know that there is UNIX solution called supervisord. But unfortunately server where my script has to be run is on Windows. Do you know what tool can be useful?
Thanks | Despite the big fat disclaimer [here](https://github.com/Supervisor/supervisor#supported-platforms), you can run Supervisor with [Cygwin](http://www.cygwin.com/) in Windows; it turns out that Cygwin goes a long way to simulate a Posix environment, so well that in fact supervisord runs unchanged. There is no need to lea... |
Convert Multiline into list | 7,630,273 | 4 | 2011-10-03T00:59:47Z | 7,630,286 | 8 | 2011-10-03T01:02:44Z | [
"python",
"list"
] | I have extracted a set of data from HTML page and copied to a variable. The variable looks like
```
names='''
Apple
Ball
Cat'''
```
Now I like to join each line into a list so that I can access any line I want. Is there any way to do that in Python | Using splitlines() to split by newline character and strip() to remove unnecessary white spaces.
```
>>> names='''
... Apple
... Ball
... Cat'''
>>> names
'\n Apple\n Ball\n Cat'
>>> names_list = [y for y in (x.strip() for x in names.splitlines()) if y]
>>> # if x.strip() is used to re... |
How can I install the Python library 'gevent' on Mac OS X Lion | 7,630,388 | 63 | 2011-10-03T01:33:34Z | 7,630,396 | 114 | 2011-10-03T01:38:09Z | [
"python",
"osx",
"osx-lion",
"gevent"
] | Python library `gevent`, version 0.13.6 (the current version on PyPI) will not `pip install` on OS X Lion, Python 2.7 (and probably others.) It works fine on Snow Leopard.
How can I get this library installed?
Bonus points if it can be done using `pip install`, rather than a manual or custom process, because then it ... | Don't post the entire thing! That's too much! 90% of the time, the first error is enough...
```
gevent/libevent.h:9:19: error: event.h: No such file or directory
```
This means that the library which provides the `event.h` header is not installed. The library is called libevent ([website](http://libevent.org/)).
In ... |
How can I install the Python library 'gevent' on Mac OS X Lion | 7,630,388 | 63 | 2011-10-03T01:33:34Z | 19,574,385 | 14 | 2013-10-24T19:02:51Z | [
"python",
"osx",
"osx-lion",
"gevent"
] | Python library `gevent`, version 0.13.6 (the current version on PyPI) will not `pip install` on OS X Lion, Python 2.7 (and probably others.) It works fine on Snow Leopard.
How can I get this library installed?
Bonus points if it can be done using `pip install`, rather than a manual or custom process, because then it ... | After a while, I realized that the paths for the CFLAGS variable mentioned above works when installing libevent from port, but not from brew. The following worked for me (on OSX Mavericks):
```
$ brew install libevent
$ export CFLAGS="-I /usr/local/Cellar/libevent/2.0.21/include -L /usr/local/Cellar/libevent/2.0.21/li... |
How can I install the Python library 'gevent' on Mac OS X Lion | 7,630,388 | 63 | 2011-10-03T01:33:34Z | 33,430,108 | 20 | 2015-10-30T06:38:06Z | [
"python",
"osx",
"osx-lion",
"gevent"
] | Python library `gevent`, version 0.13.6 (the current version on PyPI) will not `pip install` on OS X Lion, Python 2.7 (and probably others.) It works fine on Snow Leopard.
How can I get this library installed?
Bonus points if it can be done using `pip install`, rather than a manual or custom process, because then it ... | ```
CFLAGS='-std=c99' pip install gevent
```
See in: [Can't install gevent OSX 10.11](http://stackoverflow.com/questions/32417141/cant-install-gevent-osx-10-11)
on OS X 10.11, clang uses c11 as the default, so just turn it back to c99. |
Matplotlib: align origin of right axis with specific left axis value | 7,630,778 | 4 | 2011-10-03T03:22:41Z | 7,632,652 | 7 | 2011-10-03T08:28:54Z | [
"python",
"numpy",
"matplotlib",
"scipy"
] | When plotting several y axis in Matplotlib, is there a way to specify how to align the origin (and/or some ytick labels) of the right axis with a specific value of the left axis?
Here is my problem: I would like to plot two set of data as well as their difference (basically, I am trying to reproduce [this kind of grap... | You can make a little function that calculates the alignment of `ax2`:
```
def align_yaxis(ax1, v1, ax2, v2):
"""adjust ax2 ylimit so that v2 in ax2 is aligned to v1 in ax1"""
_, y1 = ax1.transData.transform((0, v1))
_, y2 = ax2.transData.transform((0, v2))
inv = ax2.transData.inverted()
_, dy = in... |
Python: Clicking a button with urllib or urllib2 | 7,630,795 | 8 | 2011-10-03T03:26:46Z | 7,630,845 | 8 | 2011-10-03T03:42:47Z | [
"python",
"urllib2",
"mechanize",
"urllib",
"twill"
] | I want to click a button with python, the info for the form is automatically filled by the webpage. the HTML code for sending a request to the button is:
```
INPUT type="submit" value="Place a Bid">
```
How would I go about doing this?
Is it possible to click the button with just urllib or urllib2? Or will I need to ... | Use the form target and send any input as post data like this:
```
<form target="http://mysite.com/blah.php" method="GET">
......
......
......
<input type="text" name="in1" value="abc">
<INPUT type="submit" value="Place a Bid">
</form>
```
Python:
```
# parse the page HTML with the form to get t... |
How to get the 'reactor' when the twisted application is started by twistd? | 7,631,353 | 5 | 2011-10-03T05:33:53Z | 7,631,821 | 10 | 2011-10-03T06:47:57Z | [
"python",
"service",
"twisted"
] | My application uses the 'twisted.web.client.Agent' to get web content. But the Agent class requires a 'reactor' instance to initiate. If I start my application using the 'twistd', there will be no 'reactor.run()' at all. So how can I get the 'reactor' instance? | I wish there were a [better answer](http://en.wikipedia.org/wiki/Singleton_pattern#Drawbacks), but the way to get the current, active reactor in a Twisted application is:
```
from twisted.internet import reactor
```
The important thing is to not do this all over the place, but once near the "top" of your application ... |
Python Dictionary DataStructure which method d[] or d.get()? | 7,631,929 | 11 | 2011-10-03T07:02:16Z | 7,631,951 | 16 | 2011-10-03T07:06:25Z | [
"python",
"data-structures"
] | While Using Python Dictionary DataStructure (which contains key-value pair) if i want to retrieve some value from my Dictionary i have two options **d[''] and g.get('key')** so i am confused now which is better and Why ?? I understand both some way but when it comes to memory consumption and evaluation in memory which ... | From the [Python Library Docs](http://docs.python.org/library/stdtypes.html)
> `d[key]`
> Return the item of *d* with key *key*. Raises a `KeyError` if *key* is not in the map.
>
> If a subclass of dict defines a method `__missing__()`, if the key *key* is not present, the `d[key]` operation calls that method with t... |
Getting realtime output from ffmpeg to be used in progress bar (PyQt4, stdout) | 7,632,589 | 14 | 2011-10-03T08:20:44Z | 7,641,175 | 11 | 2011-10-03T22:02:47Z | [
"python",
"ffmpeg",
"pyqt",
"subprocess",
"stdout"
] | I've looked at a number of questions but still can't quite figure this out. I'm using PyQt, and am hoping to run `ffmpeg -i file.mp4 file.avi` and get the output as it streams so I can create a progress bar.
I've looked at these questions:
[Can ffmpeg show a progress bar?](http://stackoverflow.com/questions/747982/can... | The only way I've found to get dynamic feedback/output from a child process is to use something like pexpect:
```
#! /usr/bin/python
import pexpect
cmd = "foo.sh"
thread = pexpect.spawn(cmd)
print "started %s" % cmd
cpl = thread.compile_pattern_list([pexpect.EOF,
'waited (\d+)'])
w... |
Numpy: find first index of value fast | 7,632,963 | 66 | 2011-10-03T09:03:57Z | 7,654,768 | 7 | 2011-10-04T22:31:37Z | [
"python",
"numpy",
"find"
] | How can I find the index of the first occurrence of a number in a Numpy array?
Speed is important to me. I am not interested in the following answers because they scan the whole array and don't stop when they find the first occurrence:
```
itemindex = numpy.where(array==item)[0][0]
nonzero(array == item)[0][0]
```
No... | I think you have hit a problem where a different method and some *a priori* knowledge of the array would really help. The kind of thing where you have a X probability of finding your answer in the first Y percent of the data. The splitting up the problem with the hope of getting lucky then doing this in python with a n... |
Numpy: find first index of value fast | 7,632,963 | 66 | 2011-10-03T09:03:57Z | 7,660,322 | 35 | 2011-10-05T11:05:47Z | [
"python",
"numpy",
"find"
] | How can I find the index of the first occurrence of a number in a Numpy array?
Speed is important to me. I am not interested in the following answers because they scan the whole array and don't stop when they find the first occurrence:
```
itemindex = numpy.where(array==item)[0][0]
nonzero(array == item)[0][0]
```
No... | There is a feature request for this scheduled for Numpy 2.0.0: <https://github.com/numpy/numpy/issues/2269> |
Numpy: find first index of value fast | 7,632,963 | 66 | 2011-10-03T09:03:57Z | 13,824,352 | 9 | 2012-12-11T16:30:43Z | [
"python",
"numpy",
"find"
] | How can I find the index of the first occurrence of a number in a Numpy array?
Speed is important to me. I am not interested in the following answers because they scan the whole array and don't stop when they find the first occurrence:
```
itemindex = numpy.where(array==item)[0][0]
nonzero(array == item)[0][0]
```
No... | You can convert a boolean array to a Python string using `array.tostring()` and then using the find() method:
```
(array==item).tostring().find('\x01')
```
This does involve copying the data, though, since Python strings need to be immutable. An advantage is that you can also search for e.g. a rising edge by finding ... |
Numpy: find first index of value fast | 7,632,963 | 66 | 2011-10-03T09:03:57Z | 29,799,815 | 10 | 2015-04-22T13:56:01Z | [
"python",
"numpy",
"find"
] | How can I find the index of the first occurrence of a number in a Numpy array?
Speed is important to me. I am not interested in the following answers because they scan the whole array and don't stop when they find the first occurrence:
```
itemindex = numpy.where(array==item)[0][0]
nonzero(array == item)[0][0]
```
No... | Although it is way too late for you, but for future reference:
Using numba ([1](http://numba.pydata.org/)) is the easiest way until numpy implements it. If you use anaconda python distribution it should already be installed.
The code will be compiled so it will be fast.
```
@jit(nopython=True)
def find_first(item, vec... |
Stripping characters from a Python string | 7,633,197 | 2 | 2011-10-03T09:29:31Z | 7,633,269 | 7 | 2011-10-03T09:35:34Z | [
"python",
"string"
] | I have a string:
```
v = "1 - 5 of 5"
```
I would like only the part after 'of' (5 in the above) and strip everything before 'of', including 'of'?
The problem is that the string is not fixed as in it could be '1-100 of 100', so I can't specify to strip everything off after the 10 or so characters. I need to search f... | Using the [partition](http://docs.python.org/library/stdtypes.html#str.partition) method is most readable for these cases.
```
string = "1 - 5 of 5"
first_part, middle, last_part = string.partition('of')
result = last_part.strip()
``` |
Extracting words from a string, removing punctuation and returning a list with separated words in Python | 7,633,274 | 3 | 2011-10-03T09:36:29Z | 7,633,435 | 12 | 2011-10-03T09:53:28Z | [
"python",
"string",
"list",
"methods"
] | I was wondering how to implement a function `get_words()` that returns the words in a string in a list, stripping away the punctuation.
How I would like to have it implemented is replace non `string.ascii_letters` with `''` and return a `.split()`.
```
def get_words(text):
'''The function should take one argumen... | This has nothing to do with splitting and punctuation; you just care about the letters (and numbers), and just want a regular expression:
```
import re
def getWords(text)
return re.compile('\w+').findall(text)
```
Demo:
```
>>> re.compile('\w+').findall('Hello world, my name is...James the 2nd!')
['Hello', 'worl... |
Insert string at the beginning of each line | 7,633,485 | 9 | 2011-10-03T09:59:36Z | 7,633,555 | 7 | 2011-10-03T10:05:11Z | [
"python",
"string",
"file"
] | How can i insert a string at the beginning of each line in a text file, i have the following code:
```
f = open('./ampo.txt', 'r+')
with open('./ampo.txt') as infile:
for line in infile:
f.insert(0, 'EDF ')
f.close
```
i get the following error:
"'file' object has no attribute 'insert'"
Please note that... | You can't modify a file inplace like that. Files do not support insertion. You have to read it all in and then write it all out again.
You can do this line by line if you wish. But in that case you need to write to a temporary file and then replace the original. So, for small enough files, it is just simpler to do it ... |
Insert string at the beginning of each line | 7,633,485 | 9 | 2011-10-03T09:59:36Z | 7,633,962 | 20 | 2011-10-03T10:45:17Z | [
"python",
"string",
"file"
] | How can i insert a string at the beginning of each line in a text file, i have the following code:
```
f = open('./ampo.txt', 'r+')
with open('./ampo.txt') as infile:
for line in infile:
f.insert(0, 'EDF ')
f.close
```
i get the following error:
"'file' object has no attribute 'insert'"
Please note that... | Python comes with [batteries included](http://docs.python.org/library/fileinput.html#module-fileinput):
```
import fileinput
import sys
for line in fileinput.input(['./ampo.txt'], inplace=True):
sys.stdout.write('EDF {l}'.format(l=line))
```
Unlike the solutions already posted, this also preserves file permissio... |
Python generators: correct code recursing a tree | 7,634,323 | 4 | 2011-10-03T11:24:55Z | 7,634,345 | 10 | 2011-10-03T11:27:45Z | [
"python",
"recursion",
"generator"
] | ```
class Node(object):
def __init__(self, lst):
if type(lst) == list:
self.value = lst[0]
self.children = lst[1:]
else:
self.value = lst
self.children = []
@property
def ChildElements(self):
return [Node(a) for a in self.children]
... | Simply calling `node_recurse_generator` recursively isn't enough - you have to `yield` its results:
```
def node_recurse_generator(node):
yield node.value
for n in node.ChildElements:
for rn in node_recurse_generator(n):
yield rn
``` |
Python decoding Unicode is not supported | 7,634,715 | 51 | 2011-10-03T12:04:05Z | 7,634,778 | 63 | 2011-10-03T12:09:04Z | [
"python",
"encoding",
"utf-8",
"character-encoding"
] | I am having a problem with my encoding in Python. I have tried different methods but I can't seem to find the best way to encode my output to UTF-8.
This is what I am trying to do:
```
result = unicode(google.searchGoogle(param), "utf-8").encode("utf-8")
```
`searchGoogle` returns the first Google result for `param`... | Looks like `google.searchGoogle(param)` already returns `unicode`:
```
>>> unicode(u'foo', 'utf-8')
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
unicode(u'foo', 'utf-8')
TypeError: decoding Unicode is not supported
```
So what you want is:
```
result = google.searchGoogle(param).... |
numpy: syntax/idiom to cast (n,) array to a (n, 1) array? | 7,635,237 | 5 | 2011-10-03T12:54:02Z | 7,635,363 | 7 | 2011-10-03T13:04:28Z | [
"python",
"arrays",
"vector",
"numpy",
"casting"
] | I'd like to cast a numpy `ndarray` object of shape (*n*,) into one having shape (*n*, 1). The best I've come up with is to roll my own \_to\_col function:
```
def _to_col(a):
return a.reshape((a.size, 1))
```
But it is hard for me to believe that such a ubiquitous operation is not already built into numpy's synta... | I'd use the following:
```
a[:,np.newaxis]
```
An alternative (but perhaps slightly less clear) way to write the same thing is:
```
a[:,None]
```
All of the above (including your version) are constant-time operations. |
Python split string in moving window | 7,636,004 | 9 | 2011-10-03T13:56:34Z | 7,636,054 | 10 | 2011-10-03T14:00:24Z | [
"python",
"string",
"split"
] | I have a string with digits like so - `digit = "7316717"`
Now I want to split the string in such a way that the output is a moving window of 3 digits at a time. So I get -
`["731", "316", "167", "671", "717"]`
How would the approach be? Straightforward way is to put in for-loop and iterate. But I feel some inbuilt p... | The [itertools examples](http://docs.python.org/release/2.3.5/lib/itertools-example.html) provides the `window` function that does just that:
```
from itertools import islice
def window(seq, n=2):
"Returns a sliding window (of width n) over data from the iterable"
" s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ..... |
Binary string in Python issues | 7,636,860 | 3 | 2011-10-03T15:07:15Z | 7,636,949 | 7 | 2011-10-03T15:14:09Z | [
"python",
"string",
"binary"
] | For some reason I'm having a heck of a time figuring out how to do this in Python.
I am trying to represent a binary string in a string variable, and all I want it to have is
```
0010111010
```
However, no matter how I try to format it as a string, Python always chops off the leading zeroes, which is giving me a head... | If I understood you right, you could do it this way:
```
a = 0b0010111010
'{:010b}'.format(a)
#The output is: '0010111010'
```
*Python 2.7*
It uses string [`format` method](http://docs.python.org/release/2.7/library/string.html#format-specification-mini-language).
This is the answer if you want to represent the bi... |
Linux Terminal Display and Python | 7,636,984 | 5 | 2011-10-03T15:17:22Z | 7,637,014 | 8 | 2011-10-03T15:19:54Z | [
"python",
"linux",
"terminal"
] | I am writing a Python script to print out displayable user interface. The problem is every Linux user would have their own unique terminal size. This will cause the hard-coded user interface to go out of format.
(If there is a lot of example below, the terminal looks Crazy!!!).
Example, in the script. I have print ou... | I'd highly suggest using something like the Python Standard Library's [`curses`](http://docs.python.org/library/curses.html) module to do this.
Don't reinvent the wheel - using an existing library will both help you avoid corner cases and also save you time. Plus, the curses interface is a familiar one to \*nix users,... |
HAML or Jade template syntax available for Python? | 7,637,789 | 18 | 2011-10-03T16:25:40Z | 8,323,639 | 29 | 2011-11-30T09:25:27Z | [
"python",
"haml",
"jade"
] | Are there any template engines for Python with a syntax similar to Jade or HAML? | Check the `pyjade` Python package [here at pypi](http://pypi.python.org/pypi/pyjade), and [here at github](http://github.com/syrusakbary/pyjade).
> Pyjade is a Jade syntax adapter for Django, Jinja2 and Mako templates
Disclaimer: I am the owner :) |
Reading Space separated input in python | 7,637,957 | 5 | 2011-10-03T16:39:36Z | 7,637,990 | 8 | 2011-10-03T16:41:12Z | [
"python",
"input"
] | Here is the Input Specification
The program has to read t lines of inputs. Each line consist of 2 space separated values first one is the name and second is the age. An Example of Input
```
Mike 18
Kevin 35
Angel 56
```
How to read this kind of input in python? If i use raw\_input(), both name and age are read in t... | If you have it in a string, you can use [`.split()`](http://docs.python.org/library/stdtypes.html#str.split) to separate them.
```
>>> for string in ('Mike 18', 'Kevin 35', 'Angel 56'):
... l = string.split()
... print repr(l[0]), repr(int(l[1]))
...
'Mike' 18
'Kevin' 35
'Angel' 56
>>>
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.