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 |
|---|---|---|---|---|---|---|---|---|---|
Python read a single character from the user | 510,357 | 157 | 2009-02-04T07:08:03Z | 510,364 | 105 | 2009-02-04T07:11:04Z | [
"python",
"input"
] | Is there a way of reading one single character from the user input? For instance, they press one key at the terminal and it is returned (sort of like `getch()`). I know there's a function in Windows for it, but I'd like something that is cross-platform. | Here's a link to a site that says how you can read a single character in Windows, Linux and OSX: <http://code.activestate.com/recipes/134892/>
```
class _Getch:
"""Gets a single character from standard input. Does not echo to the
screen."""
def __init__(self):
try:
self.impl = _GetchWindow... |
Python read a single character from the user | 510,357 | 157 | 2009-02-04T07:08:03Z | 510,404 | 54 | 2009-02-04T07:30:51Z | [
"python",
"input"
] | Is there a way of reading one single character from the user input? For instance, they press one key at the terminal and it is returned (sort of like `getch()`). I know there's a function in Windows for it, but I'd like something that is cross-platform. | ```
sys.stdin.read(1)
```
will basically read 1 byte from STDIN.
If you must use the method which does not wait for the `\n` you can use this code as suggested in previous answer:
```
class _Getch:
"""Gets a single character from standard input. Does not echo to the screen."""
def __init__(self):
tr... |
Python read a single character from the user | 510,357 | 157 | 2009-02-04T07:08:03Z | 510,897 | 12 | 2009-02-04T11:04:26Z | [
"python",
"input"
] | Is there a way of reading one single character from the user input? For instance, they press one key at the terminal and it is returned (sort of like `getch()`). I know there's a function in Windows for it, but I'd like something that is cross-platform. | I think it gets extremely clunky at this point, and debugging on the different platforms is a big mess.
You'd be better off using something like pyglet, pygame, cocos2d - if you are doing something more elaborate than this and will need visuals, OR **curses** if you are going to work with the terminal.
Curses is stan... |
Python read a single character from the user | 510,357 | 157 | 2009-02-04T07:08:03Z | 7,259,460 | 14 | 2011-08-31T15:30:40Z | [
"python",
"input"
] | Is there a way of reading one single character from the user input? For instance, they press one key at the terminal and it is returned (sort of like `getch()`). I know there's a function in Windows for it, but I'd like something that is cross-platform. | An alternative method:
```
import os
import sys
import termios
import fcntl
def getch():
fd = sys.stdin.fileno()
oldterm = termios.tcgetattr(fd)
newattr = termios.tcgetattr(fd)
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, newattr)
oldflags = fcntl.... |
Python read a single character from the user | 510,357 | 157 | 2009-02-04T07:08:03Z | 20,865,751 | 9 | 2014-01-01T05:13:33Z | [
"python",
"input"
] | Is there a way of reading one single character from the user input? For instance, they press one key at the terminal and it is returned (sort of like `getch()`). I know there's a function in Windows for it, but I'd like something that is cross-platform. | This code, based off [here](http://code.activestate.com/recipes/134892/), will correctly raise KeyboardInterrupt and EOFError if `Ctrl`+`C` or `Ctrl`+`D` are pressed.
Should work on Windows and Linux. An OS X version is available from the original source.
```
class _Getch:
"""Gets a single character from standard... |
Python read a single character from the user | 510,357 | 157 | 2009-02-04T07:08:03Z | 21,659,588 | 31 | 2014-02-09T13:27:42Z | [
"python",
"input"
] | Is there a way of reading one single character from the user input? For instance, they press one key at the terminal and it is returned (sort of like `getch()`). I know there's a function in Windows for it, but I'd like something that is cross-platform. | The ActiveState [recipe](http://code.activestate.com/recipes/134892/) quoted verbatim in two answers is over-engineered. It can be boiled down to this:
```
def _find_getch():
try:
import termios
except ImportError:
# Non-POSIX. Return msvcrt's (Windows') getch.
import msvcrt
ret... |
Python read a single character from the user | 510,357 | 157 | 2009-02-04T07:08:03Z | 25,342,814 | 21 | 2014-08-16T18:47:41Z | [
"python",
"input"
] | Is there a way of reading one single character from the user input? For instance, they press one key at the terminal and it is returned (sort of like `getch()`). I know there's a function in Windows for it, but I'd like something that is cross-platform. | Also worth trying is the [readchar](https://github.com/magmax/python-readchar) library, which is in part based on the ActiveState recipe mentioned in other answers.
Installation:
```
pip install readchar
```
Usage:
```
import readchar
print("Reading a char:")
print(repr(readchar.readchar()))
print("Reading a key:")... |
Is there a way to get the current ref count of an object in Python? | 510,406 | 34 | 2009-02-04T07:32:51Z | 510,411 | 36 | 2009-02-04T07:36:25Z | [
"python",
"refcounting"
] | Is there a way to get the current ref count of an object in Python? | Using the `gc` module, the interface to the garbage collector guts, you can call `gc.get_referrers(foo)` to get a list of everything referring to `foo`.
Hence, `len(gc.get_referrers(foo))` will give you the length of that list: the number of referrers, which is what you're after.
See also the [`gc` module documentati... |
Is there a way to get the current ref count of an object in Python? | 510,406 | 34 | 2009-02-04T07:32:51Z | 510,417 | 41 | 2009-02-04T07:39:03Z | [
"python",
"refcounting"
] | Is there a way to get the current ref count of an object in Python? | According to some Python 2.0 reference (<http://www.brunningonline.net/simon/python/quick-ref2_0.html>), the sys module contains a function:
```
import sys
sys.getrefcount(object) #-- Returns the reference count of the object.
```
Generally 1 higher than you might expect, because of object arg temp reference. |
Getting the class name of an instance in Python | 510,972 | 689 | 2009-02-04T11:37:48Z | 510,988 | 52 | 2009-02-04T11:42:31Z | [
"python",
"introspection",
"instanceof",
"python-datamodel"
] | How do I find out a name of class that created an instance of an object in Python if the function I am doing this from is the base class of which the class of the instance has been derived?
Was thinking maybe [the inspect module](https://docs.python.org/2/library/inspect.html) might have helped me out here, but it doe... | type() ?
```
>>> class A(object):
... def whoami(self):
... print type(self).__name__
...
>>>
>>> class B(A):
... pass
...
>>>
>>>
>>> o = B()
>>> o.whoami()
'B'
>>>
``` |
Getting the class name of an instance in Python | 510,972 | 689 | 2009-02-04T11:37:48Z | 511,059 | 948 | 2009-02-04T12:02:12Z | [
"python",
"introspection",
"instanceof",
"python-datamodel"
] | How do I find out a name of class that created an instance of an object in Python if the function I am doing this from is the base class of which the class of the instance has been derived?
Was thinking maybe [the inspect module](https://docs.python.org/2/library/inspect.html) might have helped me out here, but it doe... | Have you tried the `__name__` attribute of the class? ie `type(x).__name__` will give you the name of the class, which I think is what you want.
```
>>> import itertools
>>> x = itertools.count(0)
>>> type(x).__name__
'count'
```
This method works with [new-style classes](https://wiki.python.org/moin/NewClassVsClassi... |
Getting the class name of an instance in Python | 510,972 | 689 | 2009-02-04T11:37:48Z | 511,060 | 177 | 2009-02-04T12:02:16Z | [
"python",
"introspection",
"instanceof",
"python-datamodel"
] | How do I find out a name of class that created an instance of an object in Python if the function I am doing this from is the base class of which the class of the instance has been derived?
Was thinking maybe [the inspect module](https://docs.python.org/2/library/inspect.html) might have helped me out here, but it doe... | Do you want the name of the class as a string?
```
instance.__class__.__name__
``` |
Getting the class name of an instance in Python | 510,972 | 689 | 2009-02-04T11:37:48Z | 9,383,568 | 9 | 2012-02-21T19:07:40Z | [
"python",
"introspection",
"instanceof",
"python-datamodel"
] | How do I find out a name of class that created an instance of an object in Python if the function I am doing this from is the base class of which the class of the instance has been derived?
Was thinking maybe [the inspect module](https://docs.python.org/2/library/inspect.html) might have helped me out here, but it doe... | Good question.
Here's a simple example based on GHZ's which might help someone:
```
>>> class person(object):
def init(self,name):
self.name=name
def info(self)
print "My name is {0}, I am a {1}".format(self.name,self.__class__.__name__)
>>> bob = person(name='Robert')
>>> bob.... |
Getting the class name of an instance in Python | 510,972 | 689 | 2009-02-04T11:37:48Z | 16,293,038 | 16 | 2013-04-30T05:50:38Z | [
"python",
"introspection",
"instanceof",
"python-datamodel"
] | How do I find out a name of class that created an instance of an object in Python if the function I am doing this from is the base class of which the class of the instance has been derived?
Was thinking maybe [the inspect module](https://docs.python.org/2/library/inspect.html) might have helped me out here, but it doe... | ```
type(instance).__name__ != instance.__class__.__name #if class A is defined like
class A():
...
type(instance) == instance.__class__ #if class A is defined like
class A(object):
...
```
Example:
```
>>> class aclass(object):
... pass
...
>>> a = aclass()
>>> type(a)
<class '__main__.acla... |
Getting the class name of an instance in Python | 510,972 | 689 | 2009-02-04T11:37:48Z | 24,130,402 | 12 | 2014-06-09T23:04:17Z | [
"python",
"introspection",
"instanceof",
"python-datamodel"
] | How do I find out a name of class that created an instance of an object in Python if the function I am doing this from is the base class of which the class of the instance has been derived?
Was thinking maybe [the inspect module](https://docs.python.org/2/library/inspect.html) might have helped me out here, but it doe... | ```
class A:
pass
a = A()
str(a.__class__)
```
The sample code above (when input in the interactive interpreter) will produce `'__main__.A'` as opposed to `'A'` which is produced if the `__name__` attribute is invoked. By simply passing the result of `A.__class__` to the `str` constructor the parsing is handled for... |
How to print a string without including '\n' in Python | 511,204 | 15 | 2009-02-04T12:52:14Z | 511,208 | 19 | 2009-02-04T12:53:50Z | [
"python",
"string"
] | Suppose my string is:
```
' Hai Hello\nGood eve\n'
```
How do I eliminate the `'\n'` in between and make a string print like :
```
Hai Hello Good eve
```
? | You can use the `replace` method:
```
>>> a = "1\n2"
>>> print a
1
2
>>> a = a.replace("\n", " ")
>>> print a
1 2
``` |
How to print a string without including '\n' in Python | 511,204 | 15 | 2009-02-04T12:52:14Z | 511,216 | 22 | 2009-02-04T12:55:43Z | [
"python",
"string"
] | Suppose my string is:
```
' Hai Hello\nGood eve\n'
```
How do I eliminate the `'\n'` in between and make a string print like :
```
Hai Hello Good eve
```
? | If you don't want the newline at the end of the print statement:
```
import sys
sys.stdout.write("text")
``` |
How to print a string without including '\n' in Python | 511,204 | 15 | 2009-02-04T12:52:14Z | 1,038,910 | 11 | 2009-06-24T15:00:05Z | [
"python",
"string"
] | Suppose my string is:
```
' Hai Hello\nGood eve\n'
```
How do I eliminate the `'\n'` in between and make a string print like :
```
Hai Hello Good eve
```
? | In Python 2.6:
```
print "Hello.",
print "This is on the same line"
```
In Python 3.0
```
print("Hello", end = " ")
print("This is on the same line")
``` |
Django Installed Apps Location | 511,291 | 13 | 2009-02-04T13:15:59Z | 511,408 | 35 | 2009-02-04T13:41:41Z | [
"python",
"django"
] | I am an experienced PHP programmer using Django for the first time, and I think it is incredible!
I have a project that has a lot of apps, so I wanted to group them in an apps folder.
So the structure of the project is:
```
/project/
/project/apps/
/project/apps/app1/
/project/apps/app2
```
Then in Django settings ... | Make sure that the '\_\_init\_\_.py' file is in your apps directory, if it's not there it won't be recognized as part of the package.
So each of the folders here should have '\_\_init\_\_.py' file in it. (empty is fine).
```
/project/
/project/apps/
/project/apps/app1/
/project/apps/app2
```
Then as long as your roo... |
How to copy a directory and its contents to an existing location using Python? | 512,173 | 32 | 2009-02-04T16:41:12Z | 512,273 | 41 | 2009-02-04T17:03:21Z | [
"python",
"operating-system",
"filesystems",
"copy"
] | I'm trying to copy a directory and all its contents to a path that already exists. The problem is, between the os module and the shutil module, there doesn't seem to be a way to do this. the `shutil.copytree()` function expects that the destination path not exist beforehand.
The exact result I'm looking for is to copy... | [`distutils.dir_util.copy_tree`](http://docs.python.org/distutils/apiref.html#distutils.dir_util.copy_tree) does what you want.
> Copy an entire directory tree src to a
> new location dst. Both src and dst
> must be directory names. If src is not
> a directory, raise DistutilsFileError.
> If dst does not exist, it is ... |
gedit plugin development in python | 512,600 | 10 | 2009-02-04T18:15:16Z | 536,198 | 7 | 2009-02-11T10:08:36Z | [
"python",
"plugins",
"gedit"
] | Does anyone know where information about writing gedit plugins can be found ? I'm interested in writing them in Python. I know of [Gedit/PythonPluginHowTo](http://live.gnome.org/Gedit/PythonPluginHowTo)
, but it isn't very good . Besides the code of writing a plugin that does nothing , I can't seem to find more informa... | When I started working on my gedit plugin, I used the howto you gave a link to, also startign with [this URL](http://www.russellbeattie.com/blog/my-first-gedit-plugin). Then it was looking at other plugins code... I'm sorry to say that, but for me this topic is poorly documented and best and fastest way is to get a plu... |
memory use in large data-structures manipulation/processing | 512,893 | 4 | 2009-02-04T19:25:03Z | 515,820 | 7 | 2009-02-05T13:09:36Z | [
"python",
"data-structures",
"memory-leaks",
"garbage-collection"
] | I have a number of large (~100 Mb) files which I'm regularly processing. While I'm trying to delete unneeded data structures during processing, memory consumption is a bit too high. I was wondering if there is a way to efficiently manipulate large data, e.g.:
```
def read(self, filename):
fc = read_100_mb_file(fil... | I'd suggest looking at the [presentation by David Beazley](http://www.dabeaz.com/generators/) on using generators in Python. This technique allows you to handle a lot of data, and do complex processing, quickly and without blowing up your memory use. IMO, the trick isn't holding a huge amount of data in memory as effic... |
pure web based versioning system | 513,173 | 3 | 2009-02-04T20:34:13Z | 513,231 | 7 | 2009-02-04T20:45:06Z | [
"php",
"python",
"version-control",
"web-applications"
] | My hosting service does not currently run/allow svn, git, cvs on their server. I would really like to be able to 'sync' my current source on my development machine with my production server.
I am looking for a **pure php/python/ruby version control system** (not just a *client* for a version control system) that does ... | Get a better hosting service. Seriously. Even if you found something that worked in PHP/Ruby/Perl/Whatever, it would still be a sub-par solution. It most likely wouldn't integrate with any IDE you have, and wouldn't have a good tool set available for working with it. It would be really clunky to do correctly.
The othe... |
Delete file from zipfile with the ZipFile Module | 513,788 | 22 | 2009-02-04T23:00:26Z | 513,889 | 28 | 2009-02-04T23:31:37Z | [
"python",
"zip"
] | The only way i came up for deleting a file from a zipfile was to create a temporary zipfile without the file to be deleted and then rename it to the original filename.
In python 2.4 the ZipInfo class had an attribute `file_offset`, so it was possible to create a second zip file and copy the data to other file without ... | The following snippet worked for me (deletes all \*.exe files from a Zip archive):
```
zin = zipfile.ZipFile ('archive.zip', 'r')
zout = zipfile.ZipFile ('archve_new.zip', 'w')
for item in zin.infolist():
buffer = zin.read(item.filename)
if (item.filename[-4:] != '.exe'):
zout.writestr(item, buffer)
zo... |
Python: List vs Dict for look up table | 513,882 | 79 | 2009-02-04T23:28:41Z | 513,890 | 28 | 2009-02-04T23:31:41Z | [
"python",
"performance"
] | I have about 10million values that I need to put in some type of look up table, so I was wondering which would be more efficient a *list* or *dict*?
I know you can do something like this for both:
```
if something in dict_of_stuff:
pass
```
and
```
if something in list_of_stuff:
pass
```
My thought is the ... | A dict is a hash table, so it is really fast to find the keys. So between dict and list, dict would be faster. But if you don't have a value to associate, it is even better to use a set. It is a hash table, without the "table" part.
---
EDIT: for your new question, YES, a set would be better. Just create 2 sets, one ... |
Python: List vs Dict for look up table | 513,882 | 79 | 2009-02-04T23:28:41Z | 513,906 | 109 | 2009-02-04T23:38:36Z | [
"python",
"performance"
] | I have about 10million values that I need to put in some type of look up table, so I was wondering which would be more efficient a *list* or *dict*?
I know you can do something like this for both:
```
if something in dict_of_stuff:
pass
```
and
```
if something in list_of_stuff:
pass
```
My thought is the ... | # Speed
Lookups in lists are O(n), lookups in dictionaries are amortized O(1), with regard to the number of items in the data structure. If you don't need to associate values, use sets.
# Memory
Both dictionaries and sets use hashing and they use much more memory than only for object storage. According to A.M. Kuchl... |
Python: List vs Dict for look up table | 513,882 | 79 | 2009-02-04T23:28:41Z | 578,968 | 17 | 2009-02-23T19:24:39Z | [
"python",
"performance"
] | I have about 10million values that I need to put in some type of look up table, so I was wondering which would be more efficient a *list* or *dict*?
I know you can do something like this for both:
```
if something in dict_of_stuff:
pass
```
and
```
if something in list_of_stuff:
pass
```
My thought is the ... | [`set()`](http://docs.python.org/library/sets.html) is exactly what you want. O(1) lookups, and smaller than a dict. |
Python: List vs Dict for look up table | 513,882 | 79 | 2009-02-04T23:28:41Z | 11,241,481 | 12 | 2012-06-28T09:16:06Z | [
"python",
"performance"
] | I have about 10million values that I need to put in some type of look up table, so I was wondering which would be more efficient a *list* or *dict*?
I know you can do something like this for both:
```
if something in dict_of_stuff:
pass
```
and
```
if something in list_of_stuff:
pass
```
My thought is the ... | I did some benchmarking and it turns out that dict is faster than both list and set for large data sets, running python 2.7.3 on an i7 CPU on linux:
* `python -mtimeit -s 'd=range(10**7)' '5*10**6 in d'`
10 loops, best of 3: 64.2 msec per loop
* `python -mtimeit -s 'd=dict.fromkeys(range(10**7))' '5*10**6 in d'`
... |
How to split a string by using [] in Python | 514,029 | 2 | 2009-02-05T00:37:27Z | 514,045 | 13 | 2009-02-05T00:42:05Z | [
"python",
"string"
] | So from this string:
"name[id]"
I need this:
"id"
I used str.split ('[]'), but it didn't work. Does it only take a single delimiter? | Use a regular expression:
```
import re
s = "name[id]"
re.find(r"\[(.*?)\]", s).group(1) # = 'id'
```
`str.split()` takes a string on which to split input. For instance:
```
"i,split,on commas".split(',') # = ['i', 'split', 'on commas']
```
The `re` module also allows you to split by regular expression, which can ... |
How to split a string by using [] in Python | 514,029 | 2 | 2009-02-05T00:37:27Z | 514,047 | 7 | 2009-02-05T00:42:15Z | [
"python",
"string"
] | So from this string:
"name[id]"
I need this:
"id"
I used str.split ('[]'), but it didn't work. Does it only take a single delimiter? | Either
```
"name[id]".split('[')[1][:-1] == "id"
```
or
```
"name[id]".split('[')[1].split(']')[0] == "id"
```
or
```
re.search(r'\[(.*?)\]',"name[id]").group(1) == "id"
```
or
```
re.split(r'[\[\]]',"name[id]")[1] == "id"
``` |
Elegant ways to return multiple values from a function | 514,038 | 27 | 2009-02-05T00:39:48Z | 514,071 | 24 | 2009-02-05T00:48:27Z | [
"python",
"function",
"language-agnostic",
"language-design",
"syntactic-sugar"
] | It seems like in most mainstream programming languages, **returning multiple values from a function** is an extremely awkward thing.
The typical solutions are to make either a **struct** or a plain old data **class** and return that, or to pass at least some of the parameters by reference or pointer instead of returni... | Pretty much all ML-influenced functional langues (which is most of them) also have great tuple support that makes this sort of thing trivial.
For C++ I like boost::tuple plus boost::tie (or std::tr1 if you have it)
```
typedef boost::tuple<double,double,double> XYZ;
XYZ foo();
double x,y,z;
boost::tie(x,y,z) = foo(... |
Elegant ways to return multiple values from a function | 514,038 | 27 | 2009-02-05T00:39:48Z | 514,114 | 9 | 2009-02-05T01:05:05Z | [
"python",
"function",
"language-agnostic",
"language-design",
"syntactic-sugar"
] | It seems like in most mainstream programming languages, **returning multiple values from a function** is an extremely awkward thing.
The typical solutions are to make either a **struct** or a plain old data **class** and return that, or to pass at least some of the parameters by reference or pointer instead of returni... | A few languages, notably Lisp and JavaScript, have a feature called destructuring assignment or destructuring bind. This is essentially tuple unpacking on steroids: rather than being limited to sequences like tuples, lists, or generators, you can unpack more complex object structures in an assignment statement. For mor... |
Elegant ways to return multiple values from a function | 514,038 | 27 | 2009-02-05T00:39:48Z | 514,300 | 7 | 2009-02-05T02:31:32Z | [
"python",
"function",
"language-agnostic",
"language-design",
"syntactic-sugar"
] | It seems like in most mainstream programming languages, **returning multiple values from a function** is an extremely awkward thing.
The typical solutions are to make either a **struct** or a plain old data **class** and return that, or to pass at least some of the parameters by reference or pointer instead of returni... | PHP example:
```
function my_funct() {
$x = "hello";
$y = "world";
return array($x, $y);
}
```
Then, when run:
```
list($x, $y) = my_funct();
echo $x.' '.$y; // "hello world"
``` |
Extension methods in Python | 514,068 | 23 | 2009-02-05T00:47:37Z | 514,081 | 7 | 2009-02-05T00:53:57Z | [
"python",
"function",
"extension-methods"
] | Does Python have extension methods like C#? Is it possible to call a method like:
```
MyRandomMethod()
```
on existing types like `int`?
```
myInt.MyRandomMethod()
``` | not sure if that what you're asking but you can extend existing types and then call whatever you like on the new thing:
```
class int(int):
def random_method(self):
return 4 # guaranteed to be random
v = int(5) # you'll have to instantiate all you varia... |
Extension methods in Python | 514,068 | 23 | 2009-02-05T00:47:37Z | 514,101 | 32 | 2009-02-05T00:59:31Z | [
"python",
"function",
"extension-methods"
] | Does Python have extension methods like C#? Is it possible to call a method like:
```
MyRandomMethod()
```
on existing types like `int`?
```
myInt.MyRandomMethod()
``` | You can add whatever methods you like on class objects defined in Python code (AKA monkey patching):
```
>>> class A(object):
>>> pass
>>> def stuff(self):
>>> print self
>>> A.test = stuff
>>> A().test()
```
This does not work on builtin types, because their `__dict__` is not writable (it's a `dictproxy`)... |
What's the bad magic number error? | 514,371 | 140 | 2009-02-05T02:59:47Z | 514,395 | 174 | 2009-02-05T03:09:40Z | [
"python"
] | What's the "Bad magic number" ImportError in python, and how do I fix it?
The only thing I can find online suggests this is caused by compiling a .py -> .pyc file and then trying to use it with the wrong version of python. In my case, however, the file seems to import fine some times but not others, and I'm not sure w... | The magic number comes from UNIX-type systems where the first few bytes of a file held a marker indicating the file type.
Python puts a similar marker into its `pyc` files when it creates them.
Then the python interpreter makes sure this number is correct when loading it.
Anything that damages this magic number will... |
What's the bad magic number error? | 514,371 | 140 | 2009-02-05T02:59:47Z | 2,905,435 | 28 | 2010-05-25T14:12:02Z | [
"python"
] | What's the "Bad magic number" ImportError in python, and how do I fix it?
The only thing I can find online suggests this is caused by compiling a .py -> .pyc file and then trying to use it with the wrong version of python. In my case, however, the file seems to import fine some times but not others, and I'm not sure w... | Deleting all .pyc files will fix "Bad Magic Number" error.
```
find . -name "*.pyc" -delete
``` |
What's the bad magic number error? | 514,371 | 140 | 2009-02-05T02:59:47Z | 4,854,784 | 10 | 2011-01-31T18:52:09Z | [
"python"
] | What's the "Bad magic number" ImportError in python, and how do I fix it?
The only thing I can find online suggests this is caused by compiling a .py -> .pyc file and then trying to use it with the wrong version of python. In my case, however, the file seems to import fine some times but not others, and I'm not sure w... | Loading a python3 generated \*.pyc file with python2 also causes this error |
Python: loop over consecutive characters? | 514,448 | 8 | 2009-02-05T03:41:31Z | 514,466 | 31 | 2009-02-05T03:47:46Z | [
"python",
"algorithm",
"python-3.x",
"character"
] | In Python (specifically Python 3.0 but I don't think it matters), how do I easily write a loop over a sequence of characters having consecutive character codes? I want to do something like this pseudocode:
```
for Ch from 'a' to 'z' inclusive: #
f(Ch)
```
Example: how about a nice "pythonic" version of the follow... | You have a constant in the string module called `ascii_lowercase`, try that out:
```
>>> from string import ascii_lowercase
```
Then you can iterate over the characters in that string.
```
>>> for i in ascii_lowercase :
... f(i)
```
For your pangram question, there is a very simple way to find out if a string c... |
Python: loop over consecutive characters? | 514,448 | 8 | 2009-02-05T03:41:31Z | 514,517 | 8 | 2009-02-05T04:04:39Z | [
"python",
"algorithm",
"python-3.x",
"character"
] | In Python (specifically Python 3.0 but I don't think it matters), how do I easily write a loop over a sequence of characters having consecutive character codes? I want to do something like this pseudocode:
```
for Ch from 'a' to 'z' inclusive: #
f(Ch)
```
Example: how about a nice "pythonic" version of the follow... | Iterating a constant with all the characters you need is very Pythonic. However if you don't want to import anything and are only working in Unicode, use the built-ins ord() and its inverse chr().
```
for code in range(ord('a'), ord('z') + 1):
print chr(code)
``` |
Most pythonic way to extend a potentially incomplete list | 516,039 | 6 | 2009-02-05T14:11:32Z | 516,129 | 7 | 2009-02-05T14:31:59Z | [
"python"
] | What I'm looking for is the best way to say, 'If this list is too short, lengthen it to 9 elements and add 'Choice 4', 'Choice 5', etc, as the additional elements. Also, replace any 'None' elements with 'Choice x'.' It is ok to replace "" and 0 too.
An example transformation would be
```
['a','b',None,'c']
```
to
`... | My initial reaction was to split the list extension and "filling in the blanks" into separate parts as so:
```
for i, v in enumerate(my_list):
my_list[i] = v or "Choice %s" % (i+1)
for j in range(len(my_list)+1, 10):
my_list.append("Choice %s" % (j))
# maybe this is nicer for the extension?
while len(my_list... |
Most pythonic way to extend a potentially incomplete list | 516,039 | 6 | 2009-02-05T14:11:32Z | 516,491 | 8 | 2009-02-05T15:54:23Z | [
"python"
] | What I'm looking for is the best way to say, 'If this list is too short, lengthen it to 9 elements and add 'Choice 4', 'Choice 5', etc, as the additional elements. Also, replace any 'None' elements with 'Choice x'.' It is ok to replace "" and 0 too.
An example transformation would be
```
['a','b',None,'c']
```
to
`... | Unlike `zip`, Python's `map` automatically extends shorter sequences with `None`.
```
map(lambda a, b: b if a is None else a,
choicesTxt,
['Choice %i' % n for n in range(1, 10)])
```
You could simplify the lambda to
```
map(lambda a, b: a or b,
choicesTxt,
['Choice %i' % n for n in range(1, 10)])
```... |
Python regex: Turn "ThisFileName.txt" into "This File Name.txt" | 516,451 | 2 | 2009-02-05T15:46:33Z | 516,486 | 9 | 2009-02-05T15:53:24Z | [
"python",
"regex"
] | I'm trying to add a space before every capital letter, except the first one.
Here's what I have so far, and the output I'm getting:
```
>>> tex = "ThisFileName.txt"
>>> re.sub('[A-Z].', ' ', tex)
' his ile ame.txt'
```
I want:
'This File Name.txt'
(It'd be nice if I could also get rid of .txt, but I can do that in ... | Key concept here is backreferences in regular expressions:
```
import re
text = "ThisFileName.txt"
print re.sub('([a-z])([A-Z])', r'\1 \2', text)
# Prints: "This File Name.txt"
```
For pulling off the '.txt' in a reliable way, I recommend `os.path.splitext()`
```
import os
filename = "ThisFileName.txt"
print os.path... |
Is there a Vim equivalent to the Linux/Unix "fold" command? | 516,501 | 6 | 2009-02-05T15:56:00Z | 516,536 | 11 | 2009-02-05T16:02:09Z | [
"python",
"vim",
"formatting",
"comments",
"textwrapping"
] | I realize there's a way in Vim to hide/fold lines, but what I'm looking for is a way to select a block of text and have Vim wrap lines at or near column 80.
Mostly I want to use this on comments in situations where I'm adding some text to an existing comment that pushes it over 80 characters. It would also be nice if ... | ```
gq
```
It's controlled by the textwidth option, see `":help gq"` for more info.
`gq` will work on the current line by default, but you can highlight a visual block with `Ctrl`+`V` and format multiple lines / paragraphs like that.
`gqap` does the current "paragraph" of text. |
return eats exception | 517,060 | 13 | 2009-02-05T17:59:35Z | 517,082 | 40 | 2009-02-05T18:03:39Z | [
"python",
"exception",
"return",
"finally"
] | I found the following behavior at least *weird*:
```
def errors():
try:
ErrorErrorError
finally:
return 10
print errors()
# prints: 10
# It should raise: NameError: name 'ErrorErrorError' is not defined
```
The exception disappears when you use `return` inside a `finally` clause. Is that a bu... | > The exception disappears when you use `return` inside a `finally` clause. .. Is that documented anywhere?
[It is:](http://docs.python.org/reference/compound_stmts.html#the-try-statement)
> If finally is present, it specifies a âcleanupâ handler. The try clause is executed, including any except and else clauses.... |
return eats exception | 517,060 | 13 | 2009-02-05T17:59:35Z | 525,967 | 23 | 2009-02-08T16:15:35Z | [
"python",
"exception",
"return",
"finally"
] | I found the following behavior at least *weird*:
```
def errors():
try:
ErrorErrorError
finally:
return 10
print errors()
# prints: 10
# It should raise: NameError: name 'ErrorErrorError' is not defined
```
The exception disappears when you use `return` inside a `finally` clause. Is that a bu... | You asked about the Python developers' reasoning. I can't speak for them, but no other behavior makes sense. A function can either return a value, or it can raise an exception; it can't do both. The purpose of a "finally" clause is to provide cleanup code that is "guaranteed" to be run, regardless of exceptions. By put... |
How do I write output in same place on the console? | 517,127 | 82 | 2009-02-05T18:11:47Z | 517,148 | 10 | 2009-02-05T18:14:06Z | [
"python",
"console-output"
] | I am new to python and am writing some scripts to automate downloading files from FTP servers, etc. I want to show the progress of the download, but I want it to stay in the same position, such as:
output:
> Downloading File FooFile.txt [47%]
I'm trying to avoid something like this:
```
Downloading File FooFil... | Print the backspace character `\b` several times, and then overwrite the old number with the new number. |
How do I write output in same place on the console? | 517,127 | 82 | 2009-02-05T18:11:47Z | 517,179 | 19 | 2009-02-05T18:19:09Z | [
"python",
"console-output"
] | I am new to python and am writing some scripts to automate downloading files from FTP servers, etc. I want to show the progress of the download, but I want it to stay in the same position, such as:
output:
> Downloading File FooFile.txt [47%]
I'm trying to avoid something like this:
```
Downloading File FooFil... | Use a terminal-handling library like the [curses module](http://docs.python.org/library/curses.html):
> The curses module provides an interface to the curses library, the de-facto standard for portable advanced terminal handling. |
How do I write output in same place on the console? | 517,127 | 82 | 2009-02-05T18:11:47Z | 517,207 | 142 | 2009-02-05T18:22:47Z | [
"python",
"console-output"
] | I am new to python and am writing some scripts to automate downloading files from FTP servers, etc. I want to show the progress of the download, but I want it to stay in the same position, such as:
output:
> Downloading File FooFile.txt [47%]
I'm trying to avoid something like this:
```
Downloading File FooFil... | You can also use the carriage return:
```
sys.stdout.write("Download progress: %d%% \r" % (progress) )
sys.stdout.flush()
``` |
How do I write output in same place on the console? | 517,127 | 82 | 2009-02-05T18:11:47Z | 517,523 | 8 | 2009-02-05T19:29:23Z | [
"python",
"console-output"
] | I am new to python and am writing some scripts to automate downloading files from FTP servers, etc. I want to show the progress of the download, but I want it to stay in the same position, such as:
output:
> Downloading File FooFile.txt [47%]
I'm trying to avoid something like this:
```
Downloading File FooFil... | I like the following:
```
print 'Downloading File FooFile.txt [%d%%]\r'%i,
```
Demo:
```
import time
for i in range(100):
time.sleep(0.1)
print 'Downloading File FooFile.txt [%d%%]\r'%i,
``` |
How do I write output in same place on the console? | 517,127 | 82 | 2009-02-05T18:11:47Z | 7,975,759 | 7 | 2011-11-02T04:14:27Z | [
"python",
"console-output"
] | I am new to python and am writing some scripts to automate downloading files from FTP servers, etc. I want to show the progress of the download, but I want it to stay in the same position, such as:
output:
> Downloading File FooFile.txt [47%]
I'm trying to avoid something like this:
```
Downloading File FooFil... | ```
#kinda like the one above but better :P
from __future__ import print_function
from time import sleep
for i in range(101):
str1="Downloading File FooFile.txt [{}%]".format(i)
back="\b"*len(str1)
print(str1, end="")
sleep(0.1)
print(back, end="")
``` |
String formatting in Python | 517,355 | 21 | 2009-02-05T18:53:29Z | 517,372 | 16 | 2009-02-05T18:59:07Z | [
"python",
"string",
"formatting"
] | I want to do something like String.Format ("[{0}, {1}, {2}]", 1, 2, 3) which returns:
```
[1, 2, 3]
```
How do I do this in Python? | You're looking for string formatting, which in python is based on the sprintf function in C.
```
print "[%s, %s, %s]" % (1, 2, 3)
```
For a complete reference look here:
<http://docs.python.org/library/stdtypes.html#string-formatting> |
String formatting in Python | 517,355 | 21 | 2009-02-05T18:53:29Z | 517,471 | 53 | 2009-02-05T19:16:29Z | [
"python",
"string",
"formatting"
] | I want to do something like String.Format ("[{0}, {1}, {2}]", 1, 2, 3) which returns:
```
[1, 2, 3]
```
How do I do this in Python? | The previous answers have used % formatting, which is being phased out in Python 3.0+. Assuming you're using Python 2.6+, a more future-proof formatting system is described here:
<http://docs.python.org/library/string.html#formatstrings>
Although there are more advanced features as well, the simplest form ends up loo... |
String formatting in Python | 517,355 | 21 | 2009-02-05T18:53:29Z | 628,974 | 25 | 2009-03-10T04:54:35Z | [
"python",
"string",
"formatting"
] | I want to do something like String.Format ("[{0}, {1}, {2}]", 1, 2, 3) which returns:
```
[1, 2, 3]
```
How do I do this in Python? | You can do it three ways:
---
Use Python's automatic pretty printing:
```
print [1, 2, 3] # Prints [1, 2, 3]
```
Showing the same thing with a variable:
```
numberList = [1, 2]
numberList.append(3)
print numberList # Prints [1, 2, 3]
```
---
Use 'classic' string substitutions (ala C's printf). Note the diffe... |
What is the best way to remove accents in a Python unicode string? | 517,923 | 230 | 2009-02-05T21:10:40Z | 517,974 | 83 | 2009-02-05T21:19:34Z | [
"python",
"python-3.x",
"unicode",
"python-2.x",
"diacritics"
] | I have a Unicode string in Python, and I would like to remove all the accents (diacritics).
I found on the Web an elegant way to do this in Java:
1. convert the Unicode string to its long normalized form (with a separate character for letters and diacritics)
2. remove all the characters whose Unicode type is "diacrit... | I just found this answer on the Web:
```
import unicodedata
def remove_accents(input_str):
nfkd_form = unicodedata.normalize('NFKD', input_str)
only_ascii = nfkd_form.encode('ASCII', 'ignore')
return only_ascii
```
It works fine (for French, for example), but I think the second step (removing the accents... |
What is the best way to remove accents in a Python unicode string? | 517,923 | 230 | 2009-02-05T21:10:40Z | 518,232 | 164 | 2009-02-05T22:17:22Z | [
"python",
"python-3.x",
"unicode",
"python-2.x",
"diacritics"
] | I have a Unicode string in Python, and I would like to remove all the accents (diacritics).
I found on the Web an elegant way to do this in Java:
1. convert the Unicode string to its long normalized form (with a separate character for letters and diacritics)
2. remove all the characters whose Unicode type is "diacrit... | How about this:
```
import unicodedata
def strip_accents(s):
return ''.join(c for c in unicodedata.normalize('NFD', s)
if unicodedata.category(c) != 'Mn')
```
This works on greek letters, too:
```
>>> strip_accents(u"A \u00c0 \u0394 \u038E")
u'A A \u0394 \u03a5'
>>>
```
The [character category]... |
What is the best way to remove accents in a Python unicode string? | 517,923 | 230 | 2009-02-05T21:10:40Z | 2,633,310 | 155 | 2010-04-13T21:21:14Z | [
"python",
"python-3.x",
"unicode",
"python-2.x",
"diacritics"
] | I have a Unicode string in Python, and I would like to remove all the accents (diacritics).
I found on the Web an elegant way to do this in Java:
1. convert the Unicode string to its long normalized form (with a separate character for letters and diacritics)
2. remove all the characters whose Unicode type is "diacrit... | [Unidecode](https://pypi.python.org/pypi/Unidecode) is the correct answer for this. It transliterates any unicode string into the closest possible representation in ascii text. |
What is the best way to remove accents in a Python unicode string? | 517,923 | 230 | 2009-02-05T21:10:40Z | 15,547,803 | 9 | 2013-03-21T12:39:18Z | [
"python",
"python-3.x",
"unicode",
"python-2.x",
"diacritics"
] | I have a Unicode string in Python, and I would like to remove all the accents (diacritics).
I found on the Web an elegant way to do this in Java:
1. convert the Unicode string to its long normalized form (with a separate character for letters and diacritics)
2. remove all the characters whose Unicode type is "diacrit... | This handles not only accents, but also "strokes" (as in ø etc.):
```
import unicodedata as ud
def rmdiacritics(char):
'''
Return the base character of char, by "removing" any
diacritics like accents or curls and strokes and the like.
'''
desc = ud.name(unicode(char))
cutoff = desc.find(' WIT... |
What is the best way to remove accents in a Python unicode string? | 517,923 | 230 | 2009-02-05T21:10:40Z | 17,069,876 | 8 | 2013-06-12T15:48:48Z | [
"python",
"python-3.x",
"unicode",
"python-2.x",
"diacritics"
] | I have a Unicode string in Python, and I would like to remove all the accents (diacritics).
I found on the Web an elegant way to do this in Java:
1. convert the Unicode string to its long normalized form (with a separate character for letters and diacritics)
2. remove all the characters whose Unicode type is "diacrit... | In response to @MiniQuark's answer:
I was trying to read in a csv file that was half-French (containing accents) and also some strings which would eventually become integers and floats.
As a test, I created a `test.txt` file that looked like this:
> Montréal, über, 12.89, Mère, Françoise, noël, 889
I had to inc... |
How to clear python interpreter console? | 517,970 | 169 | 2009-02-05T21:19:20Z | 517,992 | 56 | 2009-02-05T21:22:43Z | [
"windows",
"console",
"clear",
"python"
] | Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc.
Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command severa... | Well, here's a quick hack:
```
>>> clear = "\n" * 100
>>> print clear
>>> ...do some other stuff...
>>> print clear
```
Or to save some typing, put this file in your python search path:
```
# wiper.py
class Wipe(object):
def __repr__(self):
return '\n'*1000
wipe = Wipe()
```
Then you can do this from t... |
How to clear python interpreter console? | 517,970 | 169 | 2009-02-05T21:19:20Z | 518,007 | 218 | 2009-02-05T21:25:08Z | [
"windows",
"console",
"clear",
"python"
] | Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc.
Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command severa... | As you mentioned, you can do a system call:
```
>>> import os
>>> clear = lambda: os.system('cls')
>>> clear()
```
I am not sure of any other way in Windows. |
How to clear python interpreter console? | 517,970 | 169 | 2009-02-05T21:19:20Z | 684,344 | 111 | 2009-03-26T02:42:42Z | [
"windows",
"console",
"clear",
"python"
] | Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc.
Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command severa... | here something handy that is a little more cross-platform
```
import os
def cls():
os.system('cls' if os.name=='nt' else 'clear')
# now, to clear the screen
cls()
``` |
How to clear python interpreter console? | 517,970 | 169 | 2009-02-05T21:19:20Z | 3,917,856 | 22 | 2010-10-12T18:36:11Z | [
"windows",
"console",
"clear",
"python"
] | Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc.
Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command severa... | Although this is an older question, I thought I'd contribute something summing up what I think were the best of the other answers and add a wrinkle of my own by suggesting that you put these command(s) into a file and set your PYTHONSTARTUP environment variable to point to it. Since I'm on Windows at the moment, it's s... |
Getting the length of an array in Python | 518,021 | 400 | 2009-02-05T21:26:47Z | 518,038 | 718 | 2009-02-05T21:29:48Z | [
"python",
"arrays"
] | In [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29), is the following the only way to get the number of elements?
```
arr.__len__()
```
If so, why the strange syntax? | ```
my_list = [1,2,3,4,5]
len(my_list)
```
The same works for tuples:
```
my_tuple = (1,2,3,4,5)
len(my_tuple)
```
And strings, which are really just arrays of characters:
```
my_string = 'hello world'
len(my_string)
```
It was [intentionally done this way](http://effbot.org/pyfaq/why-does-python-use-methods-for-s... |
Getting the length of an array in Python | 518,021 | 400 | 2009-02-05T21:26:47Z | 518,039 | 13 | 2009-02-05T21:30:05Z | [
"python",
"arrays"
] | In [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29), is the following the only way to get the number of elements?
```
arr.__len__()
```
If so, why the strange syntax? | Just use len(arr):
```
>>> import array
>>> arr = array.array('i')
>>> arr.append('2')
>>> arr.__len__()
1
>>> len(arr)
1
``` |
Getting the length of an array in Python | 518,021 | 400 | 2009-02-05T21:26:47Z | 518,053 | 19 | 2009-02-05T21:32:43Z | [
"python",
"arrays"
] | In [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29), is the following the only way to get the number of elements?
```
arr.__len__()
```
If so, why the strange syntax? | The preferred way to get the length of any python object is to pass it as an argument to the `len` function. Internally, python will then try to call the special `__len__` method of the object that was passed. |
Getting the length of an array in Python | 518,021 | 400 | 2009-02-05T21:26:47Z | 518,061 | 32 | 2009-02-05T21:34:00Z | [
"python",
"arrays"
] | In [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29), is the following the only way to get the number of elements?
```
arr.__len__()
```
If so, why the strange syntax? | The way you take a length of anything for which that makes sense (a list, dictionary, tuple, string, ...) is to call `len` on it.
```
l = [1,2,3,4]
s = 'abcde'
len(l) #returns 4
len(s) #returns 5
```
The reason for the "strange" syntax is that internally python translates `len(object)` into `object.__len__()`. This a... |
Getting the length of an array in Python | 518,021 | 400 | 2009-02-05T21:26:47Z | 519,644 | 18 | 2009-02-06T09:15:37Z | [
"python",
"arrays"
] | In [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29), is the following the only way to get the number of elements?
```
arr.__len__()
```
If so, why the strange syntax? | Python uses [duck typing](http://en.wikipedia.org/wiki/Duck_typing): it doesn't care about what an object *is*, as long as it has the appropriate interface for the situation at hand. When you call the built-in function len() on an object, you are actually calling its internal \_\_len\_\_ method. A custom object can imp... |
Lazy Method for Reading Big File in Python? | 519,633 | 156 | 2009-02-06T09:11:13Z | 519,653 | 231 | 2009-02-06T09:20:08Z | [
"python",
"file-io",
"generator"
] | I have a very big file 4GB and when I try to read it my computer hangs.
So I want to read it piece by piece and after processing each piece store the processed piece into another file and read next piece.
Is there any method to `yield` these pieces ?
I would love to have a **lazy method**. | To write a lazy function, just use [`yield`](http://docs.python.org/tutorial/classes.html#generators):
```
def read_in_chunks(file_object, chunk_size=1024):
"""Lazy function (generator) to read a file piece by piece.
Default chunk size: 1k."""
while True:
data = file_object.read(chunk_size)
... |
Lazy Method for Reading Big File in Python? | 519,633 | 156 | 2009-02-06T09:11:13Z | 519,667 | 18 | 2009-02-06T09:28:12Z | [
"python",
"file-io",
"generator"
] | I have a very big file 4GB and when I try to read it my computer hangs.
So I want to read it piece by piece and after processing each piece store the processed piece into another file and read next piece.
Is there any method to `yield` these pieces ?
I would love to have a **lazy method**. | Take a look at [this post on Neopythonic](http://neopythonic.blogspot.com/2008/10/sorting-million-32-bit-integers-in-2mb.html): "Sorting a million 32-bit integers in 2MB of RAM using Python" |
Lazy Method for Reading Big File in Python? | 519,633 | 156 | 2009-02-06T09:11:13Z | 519,693 | 20 | 2009-02-06T09:41:29Z | [
"python",
"file-io",
"generator"
] | I have a very big file 4GB and when I try to read it my computer hangs.
So I want to read it piece by piece and after processing each piece store the processed piece into another file and read next piece.
Is there any method to `yield` these pieces ?
I would love to have a **lazy method**. | You can use the [mmap module](http://docs.python.org/library/mmap.html) to map the contents of the file into memory and access it with indices and slices. Here an example from the documentation:
```
import mmap
with open("hello.txt", "r+") as f:
# memory-map the file, size 0 means whole file
map = mmap.mmap(f.... |
Lazy Method for Reading Big File in Python? | 519,633 | 156 | 2009-02-06T09:11:13Z | 2,111,801 | 18 | 2010-01-21T18:27:59Z | [
"python",
"file-io",
"generator"
] | I have a very big file 4GB and when I try to read it my computer hangs.
So I want to read it piece by piece and after processing each piece store the processed piece into another file and read next piece.
Is there any method to `yield` these pieces ?
I would love to have a **lazy method**. | file.readlines() takes in an optional size argument which approximates the number of lines read in the lines returned.
```
bigfile = open('bigfilename','r')
tmp_lines = bigfile.readlines(BUF_SIZE)
while tmp_lines:
process([line for line in tmp_lines])
tmp_lines = bigfile.readlines(BUF_SIZE)
``` |
Is there a HAML implementation for use with Python and Django | 519,671 | 68 | 2009-02-06T09:30:01Z | 519,679 | 21 | 2009-02-06T09:36:46Z | [
"python",
"django",
"django-templates",
"haml"
] | I happened to stumble across [HAML](http://haml-lang.com/), an interesting and beautiful way to mark up contents and write templates for HTML.
Since I use Python and Django for my web developing need, I would like to see if there is a Python implementation of HAML (or some similar concepts -- need not be exactly ident... | I'd check out [GHRML](https://github.com/derdon/ghrml), Haml for Genshi. The author admits that it's basically Haml for Python and that most of the syntax is the same (and that it works in Django). Here's some GHRML just to show you how close they are:
```
%html
%head
%title Hello World
%style{'type': 'text/... |
Is there a HAML implementation for use with Python and Django | 519,671 | 68 | 2009-02-06T09:30:01Z | 1,934,207 | 35 | 2009-12-19T21:33:50Z | [
"python",
"django",
"django-templates",
"haml"
] | I happened to stumble across [HAML](http://haml-lang.com/), an interesting and beautiful way to mark up contents and write templates for HTML.
Since I use Python and Django for my web developing need, I would like to see if there is a Python implementation of HAML (or some similar concepts -- need not be exactly ident... | You might be interested in SHPAML:
<http://shpaml.com/>
I am actively maintaining it. It is a simple preprocessor, so it is not tied to any other tools like Genshi. I happen to use it with Django, so there is a little bit of Django support, but it should not interfere with most other use cases. |
Is there a HAML implementation for use with Python and Django | 519,671 | 68 | 2009-02-06T09:30:01Z | 3,324,983 | 18 | 2010-07-24T11:56:45Z | [
"python",
"django",
"django-templates",
"haml"
] | I happened to stumble across [HAML](http://haml-lang.com/), an interesting and beautiful way to mark up contents and write templates for HTML.
Since I use Python and Django for my web developing need, I would like to see if there is a Python implementation of HAML (or some similar concepts -- need not be exactly ident... | i'm looking for the same. I haven't tried it, but found this:
<http://github.com/jessemiller/HamlPy> |
Cross-platform gui toolkit for deploying Python applications | 520,015 | 45 | 2009-02-06T11:43:30Z | 520,055 | 42 | 2009-02-06T12:06:10Z | [
"python",
"user-interface",
"cross-platform"
] | Building on:
<http://www.reddit.com/r/Python/comments/7v5ra/whats_your_favorite_gui_toolkit_and_why/>
# Merits:
1 - ease of design / integration - learning curve
2 - support / availability for \*nix, Windows, Mac, extra points for native l&f, support for mobile or web
3 - pythonic API
4 - quality of documentation ... | Please don't hesitate to expand this answer.
# [Tkinter](http://wiki.python.org/moin/TkInter)
Tkinter is the toolkit that comes with python. That means you already have everything you need to write a GUI. What that also means is that if you choose to distribute your program, most likely everyone else already has what... |
What's the cleanest way to extract URLs from a string using Python? | 520,031 | 18 | 2009-02-06T11:51:57Z | 520,036 | 8 | 2009-02-06T11:54:44Z | [
"python",
"regex",
"url"
] | Although I know I could use some hugeass regex such as the one posted [here](http://geekswithblogs.net/casualjim/archive/2005/12/01/61722.aspx) I'm wondering if there is some tweaky as hell way to do this either with a standard module or perhaps some third-party add-on?
Simple question, but nothing jumped out on Googl... | Use a regular expression.
Reply to comment from the OP: I know this is not helpful. I am telling you the correct way to solve the problem as you stated it is to use a regular expression. |
What's the cleanest way to extract URLs from a string using Python? | 520,031 | 18 | 2009-02-06T11:51:57Z | 1,855,891 | 10 | 2009-12-06T17:03:32Z | [
"python",
"regex",
"url"
] | Although I know I could use some hugeass regex such as the one posted [here](http://geekswithblogs.net/casualjim/archive/2005/12/01/61722.aspx) I'm wondering if there is some tweaky as hell way to do this either with a standard module or perhaps some third-party add-on?
Simple question, but nothing jumped out on Googl... | Look at Django's approach here: [`django.utils.urlize()`](https://github.com/django/django/blob/98c5370ef673bc83deaf24c197e0bb22a75071e3/django/utils/html.py#L257). Regexps are too limited for the job and you have to use heuristics to get results that are mostly right. |
Where is Python used? I read about it a lot on Reddit | 520,210 | 8 | 2009-02-06T13:08:13Z | 520,230 | 17 | 2009-02-06T13:12:56Z | [
"python"
] | I have downloaded the Pyscripter and learning Python. But I have no Idea if it has any job value , especially in India. I am learning Python as a Hobby. But it would be comforting to know if Python programmers are in demand in India. | Everywhere. It's used [extensively by google](http://panela.blog-city.com/python_at_google_greg_stein__sdforum.htm) for one.
See [list of python software](http://en.wikipedia.org/wiki/Python_software) for more info, and also [who uses python on the web?](http://www.python.org/doc/essays/ppt/www8-py-www/sld010.htm) |
Where is Python used? I read about it a lot on Reddit | 520,210 | 8 | 2009-02-06T13:08:13Z | 520,247 | 10 | 2009-02-06T13:16:37Z | [
"python"
] | I have downloaded the Pyscripter and learning Python. But I have no Idea if it has any job value , especially in India. I am learning Python as a Hobby. But it would be comforting to know if Python programmers are in demand in India. | In many large companies it is a primary scripting language.
Google is using it along with Java and C++ and almost nothing else.
Also many web pages are built on top of python and Django.
Another place is game development. Many games have their engines written in C++ but all the logic in Python.
In other words it is on... |
Event handling with Jython & Swing | 520,615 | 8 | 2009-02-06T15:09:13Z | 523,456 | 11 | 2009-02-07T08:35:51Z | [
"java",
"python",
"user-interface",
"swing",
"jython"
] | I'm making a GUI by using Swing from Jython. Event handling seems to be particularly elegant from Jython, just set
```
JButton("Push me", actionPerformed = nameOfFunctionToCall)
```
However, trying same thing inside a class gets difficult. Naively trying
```
JButton("Push me", actionPerformed = nameOfMethodToCall)
`... | ```
JButton("Push me", actionPerformed=self.nameOfMethodToCall)
```
Here's a modified example from the article you cited:
```
from javax.swing import JButton, JFrame
class MyFrame(JFrame):
def __init__(self):
JFrame.__init__(self, "Hello Jython")
button = JButton("Hello", actionPerformed=self.hel... |
Python loops with multiple lists? | 521,321 | 15 | 2009-02-06T17:42:27Z | 521,345 | 10 | 2009-02-06T17:46:38Z | [
"python",
"arrays",
"loops",
"list"
] | **<edit>**
Thanks to everyone who has answered so far. The zip and os.path.join are really helpful. Any suggestions on ways to list the counter in front, without doing something like this:
```
zip(range(len(files)), files, directories)
```
**</edit>**
Hi,
I'm in the process of learning Python, but I come from a bac... | Try this:
```
directories = ['directory_0', 'directory_1', 'directory_2']
files = ['file_a', 'file_b', 'file_c']
for file, dir in zip(files, directories):
print dir + '/' + file
```
To explain, the `zip()` function takes lists as input and returns a list of "zipped" tuples. so `zip([1,2,3,4,5],[a,b,c,d,e])` woul... |
Python loops with multiple lists? | 521,321 | 15 | 2009-02-06T17:42:27Z | 521,361 | 35 | 2009-02-06T17:49:07Z | [
"python",
"arrays",
"loops",
"list"
] | **<edit>**
Thanks to everyone who has answered so far. The zip and os.path.join are really helpful. Any suggestions on ways to list the counter in front, without doing something like this:
```
zip(range(len(files)), files, directories)
```
**</edit>**
Hi,
I'm in the process of learning Python, but I come from a bac... | ```
import os.path
for dir, file in zip(directories, files):
print(os.path.join(dir, file)) # for directories, files
```
you can have it as a list comprehension as well, creating list of string with print going after that]
with counter:
```
for i, (dir, file) in enumerate(zip(directories, fi... |
Why True/False is capitalized in Python? | 521,476 | 34 | 2009-02-06T18:13:04Z | 521,508 | 49 | 2009-02-06T18:20:10Z | [
"python",
"camelcasing"
] | All members are camel case, right? Why True/False but not true/false, which is more relaxed? | From [Pep 285](http://www.python.org/dev/peps/pep-0285/):
> Should the constants be called 'True'
> and 'False' (similar to
> None) or 'true' and 'false' (as in C++, Java and C99)?
>
> => True and False.
>
> Most reviewers agree that consistency within Python is more
> important than consistency with other languages.
... |
Why True/False is capitalized in Python? | 521,476 | 34 | 2009-02-06T18:13:04Z | 521,515 | 10 | 2009-02-06T18:21:40Z | [
"python",
"camelcasing"
] | All members are camel case, right? Why True/False but not true/false, which is more relaxed? | All of python's [built-in constants](http://docs.python.org/library/constants.html) are capitalized or [upper] CamelCase: |
How do i get python's pprint to return a string instead of printing? | 521,532 | 76 | 2009-02-06T18:25:53Z | 521,545 | 123 | 2009-02-06T18:28:30Z | [
"python"
] | In other words, what's the sprintf equivalent to pprint? | The [pprint](http://docs.python.org/library/pprint.html) module has a command named [pformat](http://docs.python.org/library/pprint.html#pprint.pformat), for just that purpose.
From the documentation:
> Return the formatted representation of object as a string. indent,
> width and depth will be passed to the PrettyPr... |
How do i get python's pprint to return a string instead of printing? | 521,532 | 76 | 2009-02-06T18:25:53Z | 521,546 | 7 | 2009-02-06T18:29:14Z | [
"python"
] | In other words, what's the sprintf equivalent to pprint? | Are you looking for `pprint.pformat`? |
How do i get python's pprint to return a string instead of printing? | 521,532 | 76 | 2009-02-06T18:25:53Z | 521,550 | 10 | 2009-02-06T18:29:47Z | [
"python"
] | In other words, what's the sprintf equivalent to pprint? | Assuming you really do mean `pprint` from the [pretty-print library](http://docs.python.org/library/pprint.html), then you want
the `pprint.pformat` method.
If you just mean `print`, then you want `str()` |
How do i get python's pprint to return a string instead of printing? | 521,532 | 76 | 2009-02-06T18:25:53Z | 6,472,848 | 8 | 2011-06-24T19:30:38Z | [
"python"
] | In other words, what's the sprintf equivalent to pprint? | ```
>>> import pprint
>>> pprint.pformat({'key1':'val1', 'key2':[1,2]})
"{'key1': 'val1', 'key2': [1, 2]}"
>>>
``` |
Is there a way to decode numerical COM error-codes in pywin32 | 521,759 | 24 | 2009-02-06T19:18:01Z | 531,105 | 33 | 2009-02-10T05:01:04Z | [
"python",
"windows",
"excel",
"com",
"pywin32"
] | Here is part of a stack-trace from a recent run of an unreliable application written in Python which controls another application written in Excel:
```
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2146788248), None)
```
Obviously something has gone wrong ... but what?[1] These ... | You are not doing anything wrong. The first item in your stack trace (the number) is the error code returned by the COM object. The second item is the description associated with the error code which in this case is "Exception Occurred". pywintypes.com\_error already called the equivalent of win32api.FormatMessage(errC... |
Finding first and last index of some value in a list in Python | 522,372 | 23 | 2009-02-06T22:00:00Z | 522,401 | 39 | 2009-02-06T22:05:06Z | [
"python",
"list",
"search"
] | Is there any built-in methods that are part of lists that would give me the first and last index of some value, like:
```
verts.IndexOf(12.345)
verts.LastIndexOf(12.345)
``` | Sequences have a method `index(value)` which returns index of first occurrence.
You can run it on `verts[::-1]` to find out the last index. |
Finding first and last index of some value in a list in Python | 522,372 | 23 | 2009-02-06T22:00:00Z | 6,194,807 | 10 | 2011-05-31T23:48:50Z | [
"python",
"list",
"search"
] | Is there any built-in methods that are part of lists that would give me the first and last index of some value, like:
```
verts.IndexOf(12.345)
verts.LastIndexOf(12.345)
``` | Use `i1 = yourlist.index(yourvalue)` and `i2 = yourlist.rindex(yourvalue).` |
Finding first and last index of some value in a list in Python | 522,372 | 23 | 2009-02-06T22:00:00Z | 18,157,104 | 7 | 2013-08-09T23:23:39Z | [
"python",
"list",
"search"
] | Is there any built-in methods that are part of lists that would give me the first and last index of some value, like:
```
verts.IndexOf(12.345)
verts.LastIndexOf(12.345)
``` | if you are searching for the index of the last occurance of myvalue in mylist:
```
len(mylist) - mylist[::-1].index(myvalue) - 1
``` |
Is there a way to loop through a sub section of a list in Python | 522,430 | 3 | 2009-02-06T22:15:20Z | 522,439 | 7 | 2009-02-06T22:16:58Z | [
"python",
"loops",
"list"
] | So for a list that has 1000 elements, I want to loop from 400 to 500. How do you do it?
I don't see a way by using the for each and for range techniques. | ```
for element in allElements[400:501]:
# do something
```
These are [slices](http://docs.python.org/reference/expressions.html#id8) and generate a sublist of the whole list. They are one of the main elements of Python. |
Is there a way to loop through a sub section of a list in Python | 522,430 | 3 | 2009-02-06T22:15:20Z | 522,442 | 22 | 2009-02-06T22:17:21Z | [
"python",
"loops",
"list"
] | So for a list that has 1000 elements, I want to loop from 400 to 500. How do you do it?
I don't see a way by using the for each and for range techniques. | ```
for x in thousand[400:500]:
pass
```
If you are working with an iterable instead of a list, you should use [itertools](http://docs.python.org/library/itertools):
```
import itertools
for x in itertools.islice(thousand, 400, 500):
pass
```
If you need to loop over `thousand[500]`, then use 501 as the latt... |
Accessing the index in Python 'for' loops | 522,563 | 1,512 | 2009-02-06T22:47:54Z | 522,569 | 37 | 2009-02-06T22:49:23Z | [
"python",
"loops",
"list"
] | How do I access the index itself for a list like the following?
```
ints = [8, 23, 45, 12, 78]
```
When I loop through it using a `for` loop, how do I access the loop index, from 1 to 5 in this case? | ```
for i in range(len(ints)):
print i, ints[i]
``` |
Accessing the index in Python 'for' loops | 522,563 | 1,512 | 2009-02-06T22:47:54Z | 522,578 | 2,666 | 2009-02-06T22:52:36Z | [
"python",
"loops",
"list"
] | How do I access the index itself for a list like the following?
```
ints = [8, 23, 45, 12, 78]
```
When I loop through it using a `for` loop, how do I access the loop index, from 1 to 5 in this case? | Using an additional state variable, such as an index variable (which you would normally use in languages such as C or PHP), is considered non-pythonic.
The better option is to use the built-in function [`enumerate()`](https://docs.python.org/3/library/functions.html#enumerate), available in both Python 2 and 3:
```
f... |
Accessing the index in Python 'for' loops | 522,563 | 1,512 | 2009-02-06T22:47:54Z | 23,886,515 | 64 | 2014-05-27T10:04:52Z | [
"python",
"loops",
"list"
] | How do I access the index itself for a list like the following?
```
ints = [8, 23, 45, 12, 78]
```
When I loop through it using a `for` loop, how do I access the loop index, from 1 to 5 in this case? | It's pretty simple to start it from `1` other than `0`:
```
for index in enumerate(iterable, start=1):
print index
```
## Note
Important hint, though a little misleading, since `index` will be a `tuple` `(idx, item)` here.
Good to go. |
Accessing the index in Python 'for' loops | 522,563 | 1,512 | 2009-02-06T22:47:54Z | 28,072,982 | 155 | 2015-01-21T17:11:49Z | [
"python",
"loops",
"list"
] | How do I access the index itself for a list like the following?
```
ints = [8, 23, 45, 12, 78]
```
When I loop through it using a `for` loop, how do I access the loop index, from 1 to 5 in this case? | > # Using a for loop, how do I access the loop index, from 1 to 5 in this case?
Use `enumerate`:
```
for index, item in enumerate(items):
print(index, item)
```
And note that indexes start at zero, so you would get 0 to 4 with this. If you want the count, I explain that below.
# Unidiomatic control flow
What y... |
How can I strip Python logging calls without commenting them out? | 522,730 | 25 | 2009-02-07T00:08:11Z | 526,078 | 19 | 2009-02-08T17:33:41Z | [
"python",
"optimization",
"logging",
"bytecode"
] | Today I was thinking about a Python project I wrote about a year back where I used `logging` pretty extensively. I remember having to comment out a lot of logging calls in inner-loop-like scenarios (the 90% code) because of the overhead (`hotshot` indicated it was one of my biggest bottlenecks).
I wonder now if there'... | What about using [logging.disable](http://docs.python.org/library/logging.html?highlight=logging#logging.disable)?
I've also found I had to use [logging.isEnabledFor](http://docs.python.org/library/logging.html?highlight=logging#logging.Logger.isEnabledFor) if the logging message is expensive to create. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.