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 |
|---|---|---|---|---|---|---|---|---|---|
Call method from string | 1,855,558 | 17 | 2009-12-06T14:41:13Z | 1,855,575 | 50 | 2009-12-06T14:46:35Z | [
"python",
"oop"
] | If I have a Python class, and would like to call a function from it depending on a variable, how would I do so? I imagined following could do it:
```
class CallMe: # Class
def App(): # Method one
...
def Foo(): # Method two
...
variable = "App" # Method to call
CallMe.variable() # Calling App()... | You can do this:
```
getattr(CallMe, variable)()
```
[getattr](http://docs.python.org/library/functions.html#getattr) is a builtin method, it returns the value of the named attributed of object. The value in this case is a method object that you can call with () |
How to find/replace text in html while preserving html tags/structure | 1,856,014 | 6 | 2009-12-06T17:44:58Z | 1,856,019 | 9 | 2009-12-06T17:46:11Z | [
"python",
"html",
"html-parsing"
] | I use regexps to transform text as I want, but I want to preserve the HTML tags.
e.g. if I want to replace "stack overflow" with "stack underflow", this should work as
expected: if the input is `stack <sometag>overflow</sometag>`, I must obtain `stack <sometag>underflow</sometag>` (i.e. the string substitution is done,... | Use a DOM library, not regular expressions, when dealing with manipulating HTML:
* lxml: a parser, document, and HTML serializer. Also can use BeautifulSoup and html5lib for parsing.
* BeautifulSoup: a parser, document, and HTML serializer.
* html5lib: a parser. It has a serializer.
* ElementTree: a document object, a... |
SyntaxError inconsistency in Python? | 1,856,408 | 8 | 2009-12-06T19:54:43Z | 1,856,431 | 14 | 2009-12-06T20:02:04Z | [
"python",
"exception"
] | Consider these two snippets:
```
try:
a+a=a
except SyntaxError:
print "first exception caught"
```
.
```
try:
eval("a+a=a")
except SyntaxError:
print "second exception caught"
```
In the second case the "second exception .." statement is printed (exception caught), while in the first one isn't.
Is ... | In the first case, the exception is raised by the compiler, which is running *before* the `try/except` structure even *exists* (since it's the compiler itself that will set it up right after parsing). In the second case, the compiler is running twice -- and the exception is getting raised when the compiler runs as part... |
python can't remove a file after closing it, "being used by another process" | 1,856,718 | 13 | 2009-12-06T21:42:43Z | 1,856,787 | 8 | 2009-12-06T22:10:36Z | [
"python"
] | I am trying to remove a file after reading from it, but getting "WindowsError: [Error 32] The process cannot access the file because it is being used by another process"
```
file = open(self.filePath)
for line in file:
#do things
file.close()
os.remove(self.filePath) #throws error
os.rename(self.filePath, se... | Another *possibility* is that a virus checker still has the file open at the time you try to delete or rename it. This doesn't happen often but when it does, it's really annoying to track down. |
Intelligently launching the default editor from inside a Python CLI program? | 1,856,792 | 5 | 2009-12-06T22:11:37Z | 1,856,911 | 10 | 2009-12-06T22:46:19Z | [
"python",
"editor"
] | The answers in [this question](http://stackoverflow.com/questions/1442841) didn't get to the heart of the problem. In a CLI-based Python program, I want the user to be able to edit a file and then return to the program. Before returning, I want them to be able to cancel their edits. This should feel like the commit-not... | You could try looking through the sources to Mercurial, which is written in Python.
They use `os.environ` to read the value of environment variables `HGEDITOR`, `VISUAL`, and `EDITOR`, defaulting to vi. Then they use `os.system` to launch the editor on a temp file created with `tempfile.mkstemp`. When the editor is do... |
Python attribute error: type object '_socketobject' has no attribute 'gethostbyname' | 1,857,146 | 7 | 2009-12-07T00:31:55Z | 1,857,159 | 12 | 2009-12-07T00:36:44Z | [
"python",
"attributeerror",
"gethostbyname"
] | I am trying to do this in my program:
```
dest = socket.gethostbyname(host)
```
I have included the line:
```
from socket import *
```
in the beginning of the file.
I am getting this error:
> AttributeError: type object
> '\_socketobject' has no attribute
> 'gethostbyname'
I am running Vista 64bit. Could there b... | You shoulod either use
```
import socket
dest = socket.gethostbyname(host)
```
or use
```
from socket import *
dest = gethostbyname(host)
```
Note: the first option is by far the recommended one. |
python optparse, how to include additional info in usage output? | 1,857,346 | 23 | 2009-12-07T01:48:08Z | 1,857,374 | 38 | 2009-12-07T01:57:59Z | [
"python",
"optparse"
] | Using python's optparse module I would like to add extra example lines below the regular usage output. My current help\_print() output looks like this:
```
usage: check_dell.py [options]
options:
-h, --help show this help message and exit
-s, --storage checks virtual and physical disks
-c, --chassis checks spec... | ```
parser = optparse.OptionParser(epilog="otherstuff")
```
The default `format_epilog` strips the newlines (uses textwrap), so you would need to override `format_epilog` in your parser like this.
```
def main():
class MyParser(optparse.OptionParser):
def format_epilog(self, formatter):
retur... |
python optparse, how to include additional info in usage output? | 1,857,346 | 23 | 2009-12-07T01:48:08Z | 4,882,964 | 11 | 2011-02-03T05:54:44Z | [
"python",
"optparse"
] | Using python's optparse module I would like to add extra example lines below the regular usage output. My current help\_print() output looks like this:
```
usage: check_dell.py [options]
options:
-h, --help show this help message and exit
-s, --storage checks virtual and physical disks
-c, --chassis checks spec... | Elaborating on the winning answer (which helped me solve the same problem in my own code), one quick-and-dirty option is to directly override the class's method with an identity method:
```
optparse.OptionParser.format_epilog = lambda self, formatter: self.epilog
optparser = optparse.OptionParser(epilog=helptext)
```
... |
Django - Populating a database for test purposes | 1,857,527 | 4 | 2009-12-07T02:48:13Z | 1,858,008 | 7 | 2009-12-07T05:29:22Z | [
"python",
"database",
"django"
] | I need to populate my database with a bunch of dummy entries (around 200+) so that I can test the admin interface I've made and I was wondering if there was a better way to do it. I spent the better part of my day yesterday trying to fill it in by hand (i.e by wrapping stuff like this my\_model(title="asdfasdf", field2... | Check this app
[https://github.com/aerosol/django-dilla/](https://github.com/aerosol/django-dilla)
Let's say you wrote your blog application (oh yeah, your favorite!) in Django. Unit tests went fine, and everything runs extremely fast, even those ORM-generated ultra-long queries. You've added several categorized post... |
sparse assignment list in python | 1,857,780 | 8 | 2009-12-07T04:20:43Z | 1,857,860 | 16 | 2009-12-07T04:45:42Z | [
"python"
] | I need a list with the following behavior
```
>>> l = SparseList()
>>> l
[]
>>> l[2] = "hello"
>>> l
[ None, None, "hello"]
>>> l[5]
None
>>> l[4] = 22
>>> l
[ None, None, "hello", None, 22]
>>> len(l)
5
>>> for i in l: print i
None
None
"hello"
None
22
```
Although it can "emulated" via a dictionary, it's not exactl... | Here's minimal code to pass your given examples (with indispensable adjustments: you expect weird spacing and quoting, 'None' to be printed out at the prompt without a `print` statement, etc etc):
```
class SparseList(list):
def __setitem__(self, index, value):
missing = index - len(self) + 1
if missing > 0:... |
Creating portable Django apps - help needed | 1,858,749 | 8 | 2009-12-07T09:04:57Z | 1,859,033 | 7 | 2009-12-07T10:07:08Z | [
"python",
"linux",
"django",
"cherrypy",
"software-distribution"
] | I'm building a Django app, which I comfortably run (test :)) on a Ubuntu Linux host. I would like to package the app without source code and distribute it to another production machine. Ideally the app could be run by ./runapp command which starts a CherryPy server that runs the python/django code.
I've discovered sev... | I suggest you base your distro on [setuptools](http://ianbicking.org/docs/setuptools-presentation/) (a tool that enhances the standard Python distro mechanizm [distutils](http://docs.python.org/library/distutils.html)).
Using setuptools, you should be able to create a Python egg containing your application. The egg's ... |
Python: Continuing to next iteration in outer loop | 1,859,072 | 52 | 2009-12-07T10:14:11Z | 1,859,099 | 71 | 2009-12-07T10:20:35Z | [
"python",
"loops"
] | I wanted to know if there are any built-in ways to continue to next iteration in outer loop in python. For example, consider the code:
```
for ii in range(200):
for jj in range(200, 400):
...block0...
if something:
continue
...block1...
```
I want this continue statement to exit th... | ```
for ii in range(200):
for jj in range(200, 400):
...block0...
if something:
break
else:
...block1...
```
`Break` will break the inner loop, and block1 won't be executed (it will run only if the inner loop is exited normally). |
Python: Continuing to next iteration in outer loop | 1,859,072 | 52 | 2009-12-07T10:14:11Z | 1,859,147 | 18 | 2009-12-07T10:28:51Z | [
"python",
"loops"
] | I wanted to know if there are any built-in ways to continue to next iteration in outer loop in python. For example, consider the code:
```
for ii in range(200):
for jj in range(200, 400):
...block0...
if something:
continue
...block1...
```
I want this continue statement to exit th... | In other languages you can label the loop and break from the labelled loop. [Python Enhancement Proposal (PEP) 3136 suggested adding these to Python](http://www.python.org/dev/peps/pep-3136/) but [Guido rejected it](http://mail.python.org/pipermail/python-3000/2007-July/008663.html):
> However, I'm rejecting it on the... |
Python: Continuing to next iteration in outer loop | 1,859,072 | 52 | 2009-12-07T10:14:11Z | 3,409,911 | 7 | 2010-08-04T21:19:55Z | [
"python",
"loops"
] | I wanted to know if there are any built-in ways to continue to next iteration in outer loop in python. For example, consider the code:
```
for ii in range(200):
for jj in range(200, 400):
...block0...
if something:
continue
...block1...
```
I want this continue statement to exit th... | I think you could do something like this:
```
for ii in range(200):
restart = False
for jj in range(200, 400):
...block0...
if something:
restart = True
break
if restart:
continue
...block1...
``` |
How to create an integer array in Python? | 1,859,864 | 15 | 2009-12-07T13:08:31Z | 1,859,887 | 21 | 2009-12-07T13:12:31Z | [
"python",
"arrays"
] | It should not be so hard. I mean in C,
```
int a[10];
```
is all you need. How to create an array of all zeros for a random size. I know the zeros() function in NumPy but there must be an easy way built-in, not another module. | two ways:
```
x = [0] * 10
x = [0 for i in xrange(10)]
```
Edit: replaced `range` by `xrange` to avoid creating another list.
Also: as many others have noted including Pi and Ben James, this creates a `list`, not a Python array. While a list is in many cases sufficient and easy enough, for performance critical uses ... |
How to create an integer array in Python? | 1,859,864 | 15 | 2009-12-07T13:08:31Z | 1,859,889 | 13 | 2009-12-07T13:12:47Z | [
"python",
"arrays"
] | It should not be so hard. I mean in C,
```
int a[10];
```
is all you need. How to create an array of all zeros for a random size. I know the zeros() function in NumPy but there must be an easy way built-in, not another module. | If you are not satisfied with lists (because they can contain anything and take up too much memory) you can use efficient array of integers:
```
import array
array.array('i')
```
See [here](http://docs.python.org/library/array.html)
If you need to initialize it,
```
a = array.array('i',(0 for i in range(0,10)))
``` |
What is Jython and is it useful at all? | 1,859,865 | 11 | 2009-12-07T13:08:40Z | 1,859,872 | 18 | 2009-12-07T13:10:17Z | [
"java",
"python",
"jython"
] | I know Python. When will I need Jython? What are the drawbacks. I assume it is slow? Please detail it out! thanks. | Quoting [Wikipedia](http://en.wikipedia.org/wiki/Jython):
> Jython, successor of JPython, is an implementation of the Python programming language written in Java.
As for what uses it may have:
> Jython programs can seamlessly import and use any Java class. Except for some standard modules, Jython programs use Java c... |
Python static methods - how to call a method from another method | 1,859,959 | 22 | 2009-12-07T13:23:42Z | 1,859,975 | 27 | 2009-12-07T13:26:39Z | [
"python",
"static-methods"
] | When I have regular methods for calling another method in a class I have to do this
```
class test:
def __init__(self):
pass
def dosomething(self):
print "do something"
self.dosomethingelse()
def dosomethingelse(self):
print "do something else"
```
but when I have static me... | `class.method` should work.
```
class SomeClass:
@classmethod
def some_class_method(cls):
pass
@staticmethod
def some_static_method():
pass
SomeClass.some_class_method()
SomeClass.some_static_method()
``` |
Python static methods - how to call a method from another method | 1,859,959 | 22 | 2009-12-07T13:23:42Z | 4,104,303 | 28 | 2010-11-05T08:08:06Z | [
"python",
"static-methods"
] | When I have regular methods for calling another method in a class I have to do this
```
class test:
def __init__(self):
pass
def dosomething(self):
print "do something"
self.dosomethingelse()
def dosomethingelse(self):
print "do something else"
```
but when I have static me... | > How do I have to do in Python for calling an static method from another static method of the same class?
```
class Test() :
@staticmethod
def static_method_to_call()
pass
@staticmethod
def another_static_method() :
Test.static_method_to_call()
@classmethod
def another_class_... |
Need help understanding how this recursive function is working | 1,860,049 | 2 | 2009-12-07T13:40:47Z | 1,860,137 | 7 | 2009-12-07T13:57:23Z | [
"python",
"recursion"
] | Here's a function (credit to user Abbot, for providing it in another question)
```
def traverse(ftp):
level = {}
for entry in (path for path in ftp.nlst() if path not in ('.', '..')):
ftp.cwd(entry)
level[entry] = traverse(ftp)
ftp.cwd('..')
return level
```
Here's what I don't u... | No. Every "instance" of the function has its own copy of `level` and there are no side effects between the various copies of `level`.
Take this folder tree:
```
root
`-home
|- lyrae
| |- ftp.py
| `- http.py
`- badp
```
Here's the (simplified) execution flow when you call `ftp` on `root`:
* `ftp... |
Virtualenv: global site-packages vs the site-packages in the virtual environment | 1,860,348 | 7 | 2009-12-07T14:35:10Z | 1,861,734 | 9 | 2009-12-07T17:56:11Z | [
"python",
"virtualenv"
] | 1. If I have a certain package installed both in the global site-packages and in the local one, which package will get imported? Will that even work or will I get an error?
2. Which packages should I put in the global site-packages and which in the local one? | The previous answer wraps up question 1 but ignores question 2.
The general best practice I've seen for which packages to put globally:
First, the core Python packages, as these don't change with backwards-incompatible issues unless you're upgrading a major version, and you'll want whatever security fixes from a pyth... |
Why is this invalid syntax? | 1,861,555 | 2 | 2009-12-07T17:35:03Z | 1,861,576 | 11 | 2009-12-07T17:36:57Z | [
"python",
"printing",
"python-3.x",
"syntax-error"
] | Why is this complaining about an invalid syntax?
```
#! /usr/bin/python
recipients = []
recipients.append('chris@elserinteractive.com')
for recip in recipients:
print recip
```
I keep getting:
```
File "send_test_email.py", line 31
print recip
^
SyntaxError: invalid syntax
``` | If you are using Python 3 `print` is a function. Call it like this: `print(recip)`. |
Checking File Permissions in Linux with Python | 1,861,836 | 30 | 2009-12-07T18:10:31Z | 1,861,970 | 63 | 2009-12-07T18:31:31Z | [
"python"
] | I'm writing a script to check permissions of files in user's directories and if they're not acceptable I'll be warning them, but I want to check permissions of not just the logged in user, but also group and others. How can i do this? It seems to me that .access() in Python can only check the permissions for the user r... | You're right that [os.access](http://docs.python.org/library/os.html?highlight=os.access#os.access), like the underlying [access](http://linux.die.net/man/2/access) syscall, checks for a specific user (real rather than effective IDs, to help out with suid situations).
[os.stat](http://docs.python.org/library/os.html?h... |
grep -r in python | 1,863,236 | 3 | 2009-12-07T22:03:01Z | 1,863,274 | 7 | 2009-12-07T22:09:51Z | [
"python",
"grep"
] | i'd like to implement the unix command 'grep -r' in a python function. i know about commands.getstatusoutput(), but for now i don't want to use that. i came up with this:
```
def grep_r (str, dir):
files = [ o[0]+"/"+f for o in os.walk(dir) for f in o[2] if os.path.isfile(o[0]+"/"+f) ]
return [ l for f in file... | You might want to `search()` instead of `match()` to catch matches in the middle of lines, as noted in <http://docs.python.org/library/re.html#matching-vs-searching>
Also, the structure and intent of your code is quite hidden. I've pythonized it.
```
def grep_r (pattern, dir):
r = re.compile(pattern)
for pare... |
Python Selector (URL routing library), experience/opinions? | 1,864,393 | 8 | 2009-12-08T03:33:34Z | 1,867,590 | 8 | 2009-12-08T15:09:57Z | [
"python",
"url-routing",
"selector",
"wsgi"
] | Does anyone have opinions about or experience with [Python Selector](https://github.com/lukearno/selector)? It looks great, but I'm a bit put off by its "Alpha" status on pypi and lack of unit tests.
I mostly like that its simple, self contained, and pure WSGI. All other url routers I've found assume I'm using django,... | I've used Selector for the last couple years and found it perfectly stable. It's been at 0.8.11 for at least two years now.
I would draw two conclusions from that:
1. It could be basically unmaintained. If you find a bug in it or need a new feature, I wouldn't count on being able to get Luke Arno to jump up and fix i... |
Convert UTF-8 octets to unicode code points | 1,864,701 | 6 | 2009-12-08T04:59:12Z | 1,864,715 | 9 | 2009-12-08T05:03:15Z | [
"python",
"unicode",
"utf-8"
] | I have a set of UTF-8 octets and I need to convert them back to unicode code points. How can I do this in python.
e.g. UTF-8 octet ['0xc5','0x81'] should be converted to 0x141 codepoint. | I'm assuming pre-3.x...
Put them in a str, and either call unicode with the string and 'utf-8':
```
>>> unicode('\xc5\x81', 'utf-8')
u'\u0141'
```
Or call `.decode('utf-8')` on the str:
```
>>> '\xc5\x81'.decode('utf-8')
u'\u0141'
```
If by "octet" you really mean a string in the form '0xc5' (rather than '\xc5') y... |
How to design an application in a modular way? | 1,865,727 | 22 | 2009-12-08T09:17:22Z | 1,866,360 | 8 | 2009-12-08T11:25:18Z | [
"python",
"design-patterns",
"oop",
"modularity",
"software-design"
] | **I am looking for pointers, suggestions, links, warnings, ideas and even anecdotical accounts about *"how to design an application in a modular way"*. I am going to use python for this project, but advice does not need to necessarily refer to this language, although I am only willing to implement a design based on OOP... | As you will deliver some basic functionality with your app, make sure that you code the part that should be extendable/replaceable already as a plugin by yourself. Then you'll best get a feeling about how your API should look like.
And to prove that the API is good, you should write a second and third plugin, because ... |
How to design an application in a modular way? | 1,865,727 | 22 | 2009-12-08T09:17:22Z | 1,866,505 | 12 | 2009-12-08T11:57:54Z | [
"python",
"design-patterns",
"oop",
"modularity",
"software-design"
] | **I am looking for pointers, suggestions, links, warnings, ideas and even anecdotical accounts about *"how to design an application in a modular way"*. I am going to use python for this project, but advice does not need to necessarily refer to this language, although I am only willing to implement a design based on OOP... | Try to keep things loosely coupled, and use interfaces liberally to help.
I'd start the design with the *Separation of Concerns*. The major architectural layers are:
* Problem Domain (aka. Engine, Back-end): the domain classes, which do all the actual work, have domain knowledge implement domain behaviour
* Persisten... |
searching all fields in a table in django | 1,866,847 | 2 | 2009-12-08T13:04:17Z | 1,867,469 | 7 | 2009-12-08T14:51:21Z | [
"python",
"django"
] | How to search all fields in a table in django using filter clause
ex:table.object.filter(any field in the table="sumthing")
Thanks. | I agree with Alasdair, but the answer to your question is this though:
```
from django.db.models import CharField
from django.db.models import Q
fields = [f for f in table._meta.fields if isinstance(f, CharField)]
queries = [Q(**{f.name: SEARCH_TERM}) for f in fields]
qs = Q()
for query in queries:
qs = qs | qu... |
Python reference problem | 1,867,068 | 3 | 2009-12-08T13:44:19Z | 1,867,089 | 16 | 2009-12-08T13:48:31Z | [
"python",
"reference"
] | I'm experiencing a (for me) very weird problem in Python.
I have a class called Menu: (snippet)
```
class Menu:
"""Shows a menu with the defined items"""
menu_items = {}
characters = map(chr, range(97, 123))
def __init__(self, menu_items):
self.init_menu(menu_items)
def init_menu(self, m... | The `menu_items` dict is a class attribute that's shared between all `Menu` instances. Initialize it like this instead, and you should be fine:
```
class Menu:
"""Shows a menu with the defined items"""
characters = map(chr, range(97, 123))
def __init__(self, menu_items):
self.menu_items = {}
... |
Set an object's superclass at __init__? | 1,867,258 | 4 | 2009-12-08T14:18:59Z | 1,867,386 | 7 | 2009-12-08T14:39:44Z | [
"python",
"oop"
] | Is it possible, when instantiating an object, to pass-in a class which the object should derive from?
For instance:
```
class Red(object):
def x(self):
print '#F00'
class Blue(object):
def x(self):
print '#00F'
class Circle(object):
def __init__(self, parent):
# here, we set Bar'... | Perhaps what you are looking for is a class factory:
```
#!/usr/bin/env python
class Foo(object):
def x(self):
print('y')
def Bar(parent=Foo):
class Adoptee(parent):
def __init__(self):
self.x()
return Adoptee()
obj=Bar(parent=Foo)
``` |
How do I determine an open file's size in Python? | 1,867,357 | 9 | 2009-12-08T14:33:47Z | 1,867,382 | 15 | 2009-12-08T14:38:24Z | [
"python",
"linux",
"file",
"filesystems",
"ext2"
] | There's a file that I would like to make sure does not grow larger than 2 GB (as it must run on a system that uses ext 2). What's a good way to check a file's size bearing in mind that I will be writing to this file in between checks? In particular, do I need to worry about buffered, unflushed changes that haven't been... | Perhaps not what you want, but I'll suggest it anyway.
```
import os
a = os.path.getsize("C:/TestFolder/Input/1.avi")
```
Alternatively for an opened file you can use the [fstat](http://docs.python.org/library/os.html#os.fstat) function, which can be used on an opened file. It takes an integer file handle, not a file... |
Django TemplateSyntaxError: current transaction is aborted, what does this exception mean? Does postgresql 8.4 work fine with django? | 1,867,407 | 7 | 2009-12-08T14:42:44Z | 1,867,711 | 13 | 2009-12-08T15:30:50Z | [
"python",
"django",
"postgresql"
] | The full text of the error is:
> TemplateSyntaxError at /
>
> Caught an exception while rendering:
> current transaction is aborted,
> commands ignored until end of
> transaction block
I've recently reinstalled all the software on my computer. The code used to work no problem before. It also still works no problem on... | That exception means that there was an error in some SQL that is getting executed. Since Django runs all the SQL inside of a database transaction, all the SQL that is being executed after the error gets ignored. So:
```
BEGIN;
SELECT * FROM table;
SELECT missing_column FROM table WHERE id = 1; -- generates an error be... |
Python dictionary, how to keep keys/values in same order as declared? | 1,867,861 | 109 | 2009-12-08T15:53:35Z | 10,982,022 | 14 | 2012-06-11T14:25:10Z | [
"python",
"dictionary",
"order"
] | new to Python and had a question about dictionaries. I have a dictionary that I declared in a particular order and want to keep it in that order all the time. The keys/values can't really be kept in order based on their value, I just want it in the order that I declared it.
So if I have the dictionary:
```
d = {'ac':... | python dictionaries are unordered. If you want an ordered dictionary, try [collections.OrderedDict](http://docs.python.org/library/collections.html#collections.OrderedDict).
Note that OrderedDict was introduced into the standard library in python 2.7. If you have an older version of python, you can find recipes for or... |
Python dictionary, how to keep keys/values in same order as declared? | 1,867,861 | 109 | 2009-12-08T15:53:35Z | 10,982,037 | 73 | 2012-06-11T14:26:02Z | [
"python",
"dictionary",
"order"
] | new to Python and had a question about dictionaries. I have a dictionary that I declared in a particular order and want to keep it in that order all the time. The keys/values can't really be kept in order based on their value, I just want it in the order that I declared it.
So if I have the dictionary:
```
d = {'ac':... | ```
from collections import OrderedDict
OrderedDict((word, True) for word in words)
```
contains
```
OrderedDict([('He', True), ('will', True), ('be', True), ('the', True), ('winner', True)])
```
If the values are `True` (or any other immutable object), you can also use:
```
OrderedDict.fromkeys(words, True)
``` |
Python dictionary, how to keep keys/values in same order as declared? | 1,867,861 | 109 | 2009-12-08T15:53:35Z | 28,231,217 | 52 | 2015-01-30T07:29:33Z | [
"python",
"dictionary",
"order"
] | new to Python and had a question about dictionaries. I have a dictionary that I declared in a particular order and want to keep it in that order all the time. The keys/values can't really be kept in order based on their value, I just want it in the order that I declared it.
So if I have the dictionary:
```
d = {'ac':... | Rather than explaining the theoretical part, I'll give a simple example.
```
>>> from collections import OrderedDict
>>> my_dictionary=OrderedDict()
>>> my_dictionary['foo']=3
>>> my_dictionary['aol']=1
>>> my_dictionary
OrderedDict([('foo', 3), ('aol', 1)])
``` |
Why does my Python class claim that I have 2 arguments instead of 1? | 1,868,685 | 5 | 2009-12-08T17:52:50Z | 1,868,702 | 16 | 2009-12-08T17:54:37Z | [
"python",
"class-method"
] | ```
#! /usr/bin/env python
import os
import stat
import sys
class chkup:
def set(file):
filepermission = os.stat(file)
user_read()
user_write()
user_exec()
def user_read():
"""Return True if 'file' is readable by user
... | The first argument for a python class method is the `self` variable. If you call `classInstance.method(parameter)`, the method is invoked as `method(self, parameter)`.
So, when you're defining your class, do something like this:
```
class MyClass(Object):
def my_method(self, parameter):
print parameter
... |
How do I copy an entire directory of files into an existing directory using Python? | 1,868,714 | 43 | 2009-12-08T17:56:04Z | 12,514,470 | 58 | 2012-09-20T14:10:22Z | [
"python",
"shutil",
"copytree"
] | Run the following code from a directory that contains a directory named `bar` (containing one or more files) and a directory named `baz` (also containing one or more files). Make sure there is not a directory named `foo`.
```
import shutil
shutil.copytree('bar', 'foo')
shutil.copytree('baz', 'foo')
```
It will fail w... | This limitation of the standard `shutil.copytree` seems arbitrary and annoying. Workaround:
```
def copytree(src, dst, symlinks=False, ignore=None):
for item in os.listdir(src):
s = os.path.join(src, item)
d = os.path.join(dst, item)
if os.path.isdir(s):
shutil.copytree(s, d, sy... |
How do I copy an entire directory of files into an existing directory using Python? | 1,868,714 | 43 | 2009-12-08T17:56:04Z | 13,814,557 | 34 | 2012-12-11T06:04:54Z | [
"python",
"shutil",
"copytree"
] | Run the following code from a directory that contains a directory named `bar` (containing one or more files) and a directory named `baz` (also containing one or more files). Make sure there is not a directory named `foo`.
```
import shutil
shutil.copytree('bar', 'foo')
shutil.copytree('baz', 'foo')
```
It will fail w... | In slight improvement on atzz's answer to the function where the above function always tries to copy the files from source to destination.
```
def copytree(src, dst, symlinks=False, ignore=None):
if not os.path.exists(dst):
os.makedirs(dst)
for item in os.listdir(src):
s = os.path.join(src, ite... |
How do I copy an entire directory of files into an existing directory using Python? | 1,868,714 | 43 | 2009-12-08T17:56:04Z | 22,331,852 | 23 | 2014-03-11T17:14:16Z | [
"python",
"shutil",
"copytree"
] | Run the following code from a directory that contains a directory named `bar` (containing one or more files) and a directory named `baz` (also containing one or more files). Make sure there is not a directory named `foo`.
```
import shutil
shutil.copytree('bar', 'foo')
shutil.copytree('baz', 'foo')
```
It will fail w... | A merge one inspired by atzz and Mital Vora:
```
#!/usr/bin/python
import os
import shutil
import stat
def copytree(src, dst, symlinks = False, ignore = None):
if not os.path.exists(dst):
os.makedirs(dst)
shutil.copystat(src, dst)
lst = os.listdir(src)
if ignore:
excl = ignore(src, lst)
lst = [x ... |
How do I copy an entire directory of files into an existing directory using Python? | 1,868,714 | 43 | 2009-12-08T17:56:04Z | 31,039,095 | 18 | 2015-06-24T23:56:31Z | [
"python",
"shutil",
"copytree"
] | Run the following code from a directory that contains a directory named `bar` (containing one or more files) and a directory named `baz` (also containing one or more files). Make sure there is not a directory named `foo`.
```
import shutil
shutil.copytree('bar', 'foo')
shutil.copytree('baz', 'foo')
```
It will fail w... | Here's a solution that's part of the standard library.
```
from distutils.dir_util import copy_tree
copy_tree("/a/b/c", "/x/y/z")
```
See this similar question.
[Copy directory contents into a directory with python](http://stackoverflow.com/questions/15034151/copy-directory-contents-into-a-directory-with-python)
* ... |
Convert and merge strings into a list in Python | 1,868,857 | 4 | 2009-12-08T18:17:58Z | 1,868,881 | 11 | 2009-12-08T18:22:32Z | [
"python",
"string",
"list"
] | In Python I have four strings that include the formatting of a list:
```
line1 ="['a.b.c','b.c.a','c.d.e']"
line2 ="['def','efg']"
line3 ="['f']"
line4 ="['g']"
```
How do I merge them all so I get a valid Python list such as:
```
SumLine = ['a.b.c','b.c.a','c.d.e','def','efg','f','g']
``` | ```
import ast
line1 ="['a.b.c','b.c.a','c.d.e']"
line2 ="['def','efg']"
line3 ="['f']"
line4 ="['g']"
SumLine = []
for x in (line1, line2, line3, line4):
SumLine.extend(ast.literal_eval(x))
print SumLine
```
Don't use the built-in `eval` unless you have preternatural trust in the strings you're evaluating; `ast... |
Why doesn't my script work, but I can manualy INSERT into mysql? | 1,869,835 | 5 | 2009-12-08T21:05:46Z | 1,869,861 | 14 | 2009-12-08T21:10:02Z | [
"python",
"mysql",
"database"
] | ```
conn = MySQLdb.connect(host='db1', user='user', passwd='pass', db='db', port=3306)
cursor = conn.cursor()
count = int(sys.argv[1])
x = 0
while x < count:
x += 1
cursor.execute("INSERT INTO auth_group(name) VALUES(%s)", (str(x)))
#if I change %s to 'kkkk', it doesn't work either.
print str(x) + ' /... | If there's no particular error message (in other words, it seems to work, but the insert doesn't stick), make sure you commit() after the statement:
```
conn.commit()
``` |
Why is the Python calculated "hashlib.sha1" different from "git hash-object" for a file? | 1,869,885 | 44 | 2009-12-08T21:13:58Z | 1,869,911 | 48 | 2009-12-08T21:17:52Z | [
"python",
"git",
"hash"
] | I'm trying to calculate the SHA-1 value of a file.
I've fabricated this script:
```
def hashfile(filepath):
sha1 = hashlib.sha1()
f = open(filepath, 'rb')
try:
sha1.update(f.read())
finally:
f.close()
return sha1.hexdigest()
```
For a specific file I get this hash value:
`8c3e10... | git calculates hashes like this:
```
sha1("blob " + filesize + "\0" + data)
```
[Reference](http://stackoverflow.com/questions/552659/assigning-git-sha1s-without-git) |
Why is the Python calculated "hashlib.sha1" different from "git hash-object" for a file? | 1,869,885 | 44 | 2009-12-08T21:13:58Z | 19,711,609 | 31 | 2013-10-31T16:14:19Z | [
"python",
"git",
"hash"
] | I'm trying to calculate the SHA-1 value of a file.
I've fabricated this script:
```
def hashfile(filepath):
sha1 = hashlib.sha1()
f = open(filepath, 'rb')
try:
sha1.update(f.read())
finally:
f.close()
return sha1.hexdigest()
```
For a specific file I get this hash value:
`8c3e10... | For reference, here's a more concise version:
```
def sha1OfFile(filepath):
import hashlib
with open(filepath, 'rb') as f:
return hashlib.sha1(f.read()).hexdigest()
```
On second thought: although I've never seen it, I think there's potential for `f.read()` to return less than the full file, or for a ... |
Recreating Postgres COPY directly in Python? | 1,869,973 | 16 | 2009-12-08T21:30:04Z | 1,870,002 | 41 | 2009-12-08T21:34:56Z | [
"python",
"postgresql",
"psycopg2"
] | I have a block of data, currently as a list of n-tuples but the format is pretty flexible, that I'd like to append to a Postgres table - in this case, each n-tuple corresponds to a row in the DB.
What I had been doing up to this point is writing these all to a CSV file and then using postgres' COPY to bulk load all of... | If you're using the psycopg2 driver, the cursors provide a `copy_to` and `copy_from` function that can read from any file-like object (including a `StringIO` buffer).
There are examples in the files [examples/copy\_from.py](https://github.com/psycopg/psycopg2/blob/master/examples/copy_from.py) and [examples/copy\_to.p... |
Quickly alphabetize a large file via python | 1,870,541 | 5 | 2009-12-08T23:12:03Z | 1,870,548 | 8 | 2009-12-08T23:15:12Z | [
"python",
"file",
"order",
"alphabetical"
] | ```
#!/usr/bin/python
import random
import string
appendToFile = open("appendedFile", "a" )
# Generator
for i in range(1, 100000):
chars = "".join( [random.choice(string.letters) for i in xrange(15)] )
chars2 = "".join( [random.choice(string.letters) for i in xrange(15)] )
appendToFile.write(chars + "... | The obvious first approach is simply to use the built-in sort feature in Python. Is this not what you had in mind? If not, why? With only 100,000 lines of random text, the built-in sort would be very fast.
```
lst = open("appendedFile", "rt").readlines()
lst.sort(key=str.lower)
```
Done. We could do it as a one-liner... |
How can I convert JSON to CSV? | 1,871,524 | 62 | 2009-12-09T04:06:37Z | 1,871,557 | 17 | 2009-12-09T04:23:05Z | [
"python",
"json",
"csv"
] | I have a JSON file that I want to covert to a CSV file. How can I do this with Python?
I tried:
```
import json
import csv
f = open('data.json')
data = json.load(f)
f.close()
f = open('data.csv')
csv_file = csv.writer(f)
for item in data:
f.writerow(item)
f.close()
```
However, it did not work. I am using Djan... | This code should work for you, assuming that your JSON data is in a file called `data.json`.
```
import json
import csv
with open("data.json") as file:
data = json.load(file)
with open("data.csv", "w") as file:
csv_file = csv.writer(file)
for item in data:
csv_file.writerow([item['pk'], item['mod... |
How can I convert JSON to CSV? | 1,871,524 | 62 | 2009-12-09T04:06:37Z | 1,871,568 | 29 | 2009-12-09T04:27:25Z | [
"python",
"json",
"csv"
] | I have a JSON file that I want to covert to a CSV file. How can I do this with Python?
I tried:
```
import json
import csv
f = open('data.json')
data = json.load(f)
f.close()
f = open('data.csv')
csv_file = csv.writer(f)
for item in data:
f.writerow(item)
f.close()
```
However, it did not work. I am using Djan... | JSON can represent a wide variety of data structures -- a JS "object" is roughly like a Python dict (with string keys), a JS "array" roughly like a Python list, and you can nest them as long as the final "leaf" elements are numbers or strings.
CSV can essentially represent only a 2-D table -- optionally with a first r... |
How can I convert JSON to CSV? | 1,871,524 | 62 | 2009-12-09T04:06:37Z | 1,872,081 | 51 | 2009-12-09T06:56:38Z | [
"python",
"json",
"csv"
] | I have a JSON file that I want to covert to a CSV file. How can I do this with Python?
I tried:
```
import json
import csv
f = open('data.json')
data = json.load(f)
f.close()
f = open('data.csv')
csv_file = csv.writer(f)
for item in data:
f.writerow(item)
f.close()
```
However, it did not work. I am using Djan... | I am not sure this question is solved already or not, but let me paste what I have done for reference.
First, your JSON has nested objects, so it normally cannot be directly converted to CSV.
You need to change that to something like this:
```
{
"pk": 22,
"model": "auth.permission",
"codename": "add_logen... |
How can I convert JSON to CSV? | 1,871,524 | 62 | 2009-12-09T04:06:37Z | 12,738,863 | 16 | 2012-10-05T02:55:35Z | [
"python",
"json",
"csv"
] | I have a JSON file that I want to covert to a CSV file. How can I do this with Python?
I tried:
```
import json
import csv
f = open('data.json')
data = json.load(f)
f.close()
f = open('data.csv')
csv_file = csv.writer(f)
for item in data:
f.writerow(item)
f.close()
```
However, it did not work. I am using Djan... | A generic solution which translates any json list of *flat* objects to csv.
Pass the input.json file as first argument on command line.
```
import csv, json, sys
input = open(sys.argv[1])
data = json.load(input)
input.close()
output = csv.writer(sys.stdout)
output.writerow(data[0].keys()) # header row
for row in... |
How can I convert JSON to CSV? | 1,871,524 | 62 | 2009-12-09T04:06:37Z | 28,246,154 | 28 | 2015-01-30T23:11:27Z | [
"python",
"json",
"csv"
] | I have a JSON file that I want to covert to a CSV file. How can I do this with Python?
I tried:
```
import json
import csv
f = open('data.json')
data = json.load(f)
f.close()
f = open('data.csv')
csv_file = csv.writer(f)
for item in data:
f.writerow(item)
f.close()
```
However, it did not work. I am using Djan... | I am assuming that your JSON file will decode into a list of dictionaries. First we need a function which will flatten the JSON objects:
```
def flattenjson( b, delim ):
val = {}
for i in b.keys():
if isinstance( b[i], dict ):
get = flattenjson( b[i], delim )
for j in get.keys()... |
Euclidean distance between points in two different Numpy arrays, not within | 1,871,536 | 26 | 2009-12-09T04:11:16Z | 1,871,630 | 20 | 2009-12-09T04:44:54Z | [
"python",
"numpy",
"euclidean-distance"
] | I have two arrays of *x*-*y* coordinates, and I would like to find the minimum Euclidean distance between *each* point in one array with *all* the points in the other array. The arrays are not necessarily the same size. For example:
```
xy1=numpy.array(
[[ 243, 3173],
[ 525, 2997]])
xy2=numpy.array(
[[ 682, 2644]... | To compute the m by p matrix of distances, this should work:
```
>>> def distances(xy1, xy2):
... d0 = numpy.subtract.outer(xy1[:,0], xy2[:,0])
... d1 = numpy.subtract.outer(xy1[:,1], xy2[:,1])
... return numpy.hypot(d0, d1)
```
the `.outer` calls make two such matrices (of scalar differences along the two axes... |
Euclidean distance between points in two different Numpy arrays, not within | 1,871,536 | 26 | 2009-12-09T04:11:16Z | 3,127,955 | 31 | 2010-06-27T16:22:18Z | [
"python",
"numpy",
"euclidean-distance"
] | I have two arrays of *x*-*y* coordinates, and I would like to find the minimum Euclidean distance between *each* point in one array with *all* the points in the other array. The arrays are not necessarily the same size. For example:
```
xy1=numpy.array(
[[ 243, 3173],
[ 525, 2997]])
xy2=numpy.array(
[[ 682, 2644]... | (Months later)
`scipy.spatial.distance.cdist( X, Y )`
gives all pairs of distances,
for X and Y 2 dim, 3 dim ...
It also does 22 different norms, detailed
[here](http://docs.scipy.org/doc/scipy/reference/spatial.distance.html) .
```
# cdist example: (nx,dim) (ny,dim) -> (nx,ny)
from __future__ import division
impor... |
Python: Determine if running inside virtualenv | 1,871,549 | 84 | 2009-12-09T04:18:47Z | 1,883,251 | 97 | 2009-12-10T19:07:58Z | [
"python",
"virtualenv"
] | Is it possible to determine if the current script is running inside a virtualenv environment? | AFAIK the most reliable way to check for this (and the way that is used internally in virtualenv and in pip) is to check for the existence of `sys.real_prefix`:
```
import sys
if hasattr(sys, 'real_prefix'):
#...
```
Inside a virtualenv, `sys.prefix` points to the virtualenv directory, and `sys.real_prefix` poin... |
Python: Determine if running inside virtualenv | 1,871,549 | 84 | 2009-12-09T04:18:47Z | 10,743,097 | 12 | 2012-05-24T18:15:59Z | [
"python",
"virtualenv"
] | Is it possible to determine if the current script is running inside a virtualenv environment? | According to the virtualenv pep at <http://www.python.org/dev/peps/pep-0405/#specification> you can just use sys.prefix instead os.environ['VIRTUAL\_ENV'].
the sys.real\_prefix does not exist in my virtualenv and same with sys.base\_prefix. |
Python: Determine if running inside virtualenv | 1,871,549 | 84 | 2009-12-09T04:18:47Z | 28,388,115 | 8 | 2015-02-07T22:17:31Z | [
"python",
"virtualenv"
] | Is it possible to determine if the current script is running inside a virtualenv environment? | Using $VIRTUAL\_ENV variable indeed will check if we are inside virtual environment, but the issue might be with deactivate function that not clear this variable when we leave virtualenv. |
Level Design in Pygame | 1,871,672 | 3 | 2009-12-09T05:01:37Z | 1,873,480 | 8 | 2009-12-09T12:03:04Z | [
"python",
"design-patterns",
"oop",
"pygame"
] | Hey--I'm trying to design my first game using the Pygame library for Python, and I was wondering what the best practices are for level design in general. I would love to hear what you guys think are good object oriented design patterns for managing levels. Also, I'm fairly new to Python--thanks! | With this type of game your maps are in terms of tiles (I'm assuming that by level you mean an individual level, not managing all of your levels). Each tile has
* an associated picture (what it looks like on the display)
* a type (ie, a wall, the ground, a trap, etc.)
When I create tile-based games in Pygame, I usual... |
In python is there a way to check if a function is a "generator function" before calling it? | 1,871,685 | 37 | 2009-12-09T05:05:10Z | 1,871,702 | 7 | 2009-12-09T05:10:44Z | [
"python",
"function",
"generator",
"coroutine"
] | Lets say I have two functions:
```
def foo():
return 'foo'
def bar():
yield 'bar'
```
The first one is a normal function, and the second is a generator function. Now I want to write something like this:
```
def run(func):
if is_generator_function(func):
gen = func()
gen.next()
#... run the gene... | ```
>>> def foo():
... return 'foo'
...
>>> def bar():
... yield 'bar'
...
>>> import dis
>>> dis.dis(foo)
2 0 LOAD_CONST 1 ('foo')
3 RETURN_VALUE
>>> dis.dis(bar)
2 0 LOAD_CONST 1 ('bar')
3 YIELD_VALUE
... |
In python is there a way to check if a function is a "generator function" before calling it? | 1,871,685 | 37 | 2009-12-09T05:05:10Z | 1,871,759 | 13 | 2009-12-09T05:24:28Z | [
"python",
"function",
"generator",
"coroutine"
] | Lets say I have two functions:
```
def foo():
return 'foo'
def bar():
yield 'bar'
```
The first one is a normal function, and the second is a generator function. Now I want to write something like this:
```
def run(func):
if is_generator_function(func):
gen = func()
gen.next()
#... run the gene... | Actually, I'm wondering just how useful such a hypothetical `is_generator_function()` would be really. Consider:
```
def foo():
return 'foo'
def bar():
yield 'bar'
def baz():
return bar()
def quux(b):
if b:
return foo()
else:
return bar()
```
What should `is_generator_function()` r... |
In python is there a way to check if a function is a "generator function" before calling it? | 1,871,685 | 37 | 2009-12-09T05:05:10Z | 6,416,855 | 42 | 2011-06-20T20:09:14Z | [
"python",
"function",
"generator",
"coroutine"
] | Lets say I have two functions:
```
def foo():
return 'foo'
def bar():
yield 'bar'
```
The first one is a normal function, and the second is a generator function. Now I want to write something like this:
```
def run(func):
if is_generator_function(func):
gen = func()
gen.next()
#... run the gene... | ```
>>> import inspect
>>>
>>> def foo():
... return 'foo'
...
>>> def bar():
... yield 'bar'
...
>>> print inspect.isgeneratorfunction(foo)
False
>>> print inspect.isgeneratorfunction(bar)
True
```
* New in Python version 2.6 |
Not possible to do (a, b) += (1, 2) in python? | 1,871,786 | 3 | 2009-12-09T05:32:10Z | 1,871,814 | 10 | 2009-12-09T05:39:16Z | [
"python"
] | The following line doesn't seem to work:
```
(count, total) += self._GetNumberOfNonZeroActions((state[0] + x, state[1] - ring, state[2]))
```
I guess it is not possible to use the += operator in this case. I wonder why?
edit: Actually what I want is to add to variables count and total the values given by the tuple r... | Your observation is right: `a += b` for any a and b means the same as `a = a + b` (except that it may save one evaluation of a). So if `a` is a tuple, the only thing that can be `+=`'d to it is another tuple; if `a` is a temporary unnamed tuple, that `+=` will of course be unobservable -- Python helps you out by catchi... |
Storing Python dictionary entries in the order they are pushed | 1,872,329 | 16 | 2009-12-09T08:04:00Z | 1,872,350 | 25 | 2009-12-09T08:09:14Z | [
"python",
"sorting",
"dictionary",
"mapping",
"order"
] | Fellows:
A Python dictionary is stored in no particular order (mappings have no order), e.g.,
```
>>> myDict = {'first':'uno','second':'dos','third':'tres'}
myDict = {'first':'uno','second':'dos','third':'tres'}
>>> myDict
myDict
{'second': 'dos', 'third': 'tres', 'first': 'uno'}
```
While it is possible to retrieve... | Try python 2.7 and above, probably 3.1, there is OrderedDict
<http://www.python.org/>
<http://python.org/download/releases/2.7/>
```
>>> from collections import OrderedDict
>>> d = OrderedDict([('first', 1), ('second', 2),
... ('third', 3)])
>>> d.items()
[('first', 1), ('second', 2), ('third', 3)]
... |
Python to Javascript | 1,873,135 | 6 | 2009-12-09T11:02:13Z | 1,873,148 | 8 | 2009-12-09T11:04:27Z | [
"javascript",
"python"
] | are there any tools for Windows to convert python to javascript?
regards
Alberto | Check out [Pyjamas](http://pyjs.org/) |
Python to Javascript | 1,873,135 | 6 | 2009-12-09T11:02:13Z | 1,873,149 | 9 | 2009-12-09T11:04:31Z | [
"javascript",
"python"
] | are there any tools for Windows to convert python to javascript?
regards
Alberto | Pyjs (formerly Pyjamas)? <http://pyjs.org/>
There are a few howto pages for Pyjs with django, webpy, etc.: <https://github.com/pyjs/pyjs/wiki> |
How could I get a Frame with a scrollbar in Tkinter? | 1,873,575 | 7 | 2009-12-09T12:26:04Z | 1,877,862 | 7 | 2009-12-10T00:14:59Z | [
"python",
"scrollbar",
"tkinter",
"frame"
] | I'd like to have a `Frame`, where the user could add as many textfields as needed by the application.
The application starts with a textfield, and a button below that textfield. When the user presses the button, a new text entry will be added below the first one ( this may be repeated countless times ). In the middle ... | If you can use Tix, there is the ScrolledWindow widget which has a `window` Frame and one or two Scrollbar widgets:
```
import Tix as tk
r= tk.Tk()
r.title("test scrolled window")
sw= tk.ScrolledWindow(r, scrollbar=tk.Y) # just the vertical scrollbar
sw.pack(fill=tk.BOTH, expand=1)
for i in xrange(10):
e= tk.Entr... |
How to allow users to change their own passwords in Django? | 1,873,806 | 55 | 2009-12-09T13:15:50Z | 1,873,855 | 112 | 2009-12-09T13:21:32Z | [
"python",
"django"
] | Can any one point me to code where users can change their own passwords in Django? | > Django comes with a user
> authentication system. It handles user
> accounts, groups, permissions and
> cookie-based user sessions. This
> document explains how things work.
[How to change Django passwords](http://docs.djangoproject.com/en/dev/topics/auth/)
See the **Changing passwords** section
1. Navigation to y... |
How to allow users to change their own passwords in Django? | 1,873,806 | 55 | 2009-12-09T13:15:50Z | 1,873,933 | 21 | 2009-12-09T13:34:19Z | [
"python",
"django"
] | Can any one point me to code where users can change their own passwords in Django? | You can also just use the `django.contrib.auth.views.password_change` view in your URLconf. It uses a default form and template; supplying your own is optional. |
Checking if a postgresql table exists under python (and probably Psycopg2) | 1,874,113 | 26 | 2009-12-09T14:02:56Z | 1,874,147 | 18 | 2009-12-09T14:09:52Z | [
"python",
"postgresql",
"psycopg2"
] | How can I determine if a table exists using the Psycopg2 Python library? I want a true or false boolean. | I don't know the psycopg2 lib specifically, but the following query can be used to check for existence of a table:
```
SELECT EXISTS(SELECT 1 FROM information_schema.tables
WHERE table_catalog='DB_NAME' AND
table_schema='public' AND
table_name='TABLE_NAME');
```... |
Checking if a postgresql table exists under python (and probably Psycopg2) | 1,874,113 | 26 | 2009-12-09T14:02:56Z | 1,874,268 | 42 | 2009-12-09T14:28:57Z | [
"python",
"postgresql",
"psycopg2"
] | How can I determine if a table exists using the Psycopg2 Python library? I want a true or false boolean. | How about:
```
>>> import psycopg2
>>> conn = psycopg2.connect("dbname='mydb' user='username' host='localhost' password='foobar'")
>>> cur = conn.cursor()
>>> cur.execute("select * from information_schema.tables where table_name=%s", ('mytable',))
>>> bool(cur.rowcount)
True
```
An alternative using EXISTS is better ... |
Pythonic way to get the largest item in a list | 1,874,194 | 17 | 2009-12-09T14:19:45Z | 1,874,210 | 45 | 2009-12-09T14:21:16Z | [
"python"
] | Is there a better way of doing this? I don't really need the list to be sorted, just scanning through to get the item with the greatest specified attribute. I care most about readability but sorting a whole list to get one item seems a bit wasteful.
```
>>> import operator
>>>
>>> a_list = [('Tom', 23), ('Dick', 45),... | ```
max(a_list, key=operator.itemgetter(1))
``` |
Pythonic way to get the largest item in a list | 1,874,194 | 17 | 2009-12-09T14:19:45Z | 1,874,225 | 7 | 2009-12-09T14:23:06Z | [
"python"
] | Is there a better way of doing this? I don't really need the list to be sorted, just scanning through to get the item with the greatest specified attribute. I care most about readability but sorting a whole list to get one item seems a bit wasteful.
```
>>> import operator
>>>
>>> a_list = [('Tom', 23), ('Dick', 45),... | You could use the `max` function.
> Help on built-in function max in module \_\_builtin\_\_:
>
> max(...)
>
> max(iterable[, key=func]) -> value
>
> max(a, b, c, ...[, key=func]) -> value
>
> With a single iterable argument, return its largest item.
> With two or more arguments, return the largest argument.
```
max_i... |
PEP8 - 80 Characters - Big Strings | 1,874,592 | 80 | 2009-12-09T15:20:54Z | 1,874,623 | 10 | 2009-12-09T15:24:16Z | [
"python",
"string",
"pep8"
] | Due to the sheer annoyance of figuring out what to Google, I've decided to risk what any reputation I had to ask this rather simple question.
As PEP8 suggests keeping below the 80 column rule for your python program, how can I abide to that with long strings, i.e.
```
s = "this is my really, really, really, really, r... | You lost a space, and you probably need a line continuation character, ie. a `\`.
```
s = "this is my really, really, really, really, really, really" + \
" really long string that I'd like to shorten."
```
or even:
```
s = "this is my really, really, really, really, really, really" \
" really long string t... |
PEP8 - 80 Characters - Big Strings | 1,874,592 | 80 | 2009-12-09T15:20:54Z | 1,874,628 | 8 | 2009-12-09T15:24:55Z | [
"python",
"string",
"pep8"
] | Due to the sheer annoyance of figuring out what to Google, I've decided to risk what any reputation I had to ask this rather simple question.
As PEP8 suggests keeping below the 80 column rule for your python program, how can I abide to that with long strings, i.e.
```
s = "this is my really, really, really, really, r... | I think the most important word in your question was "suggests".
Coding standards are funny things. Often the guidance they provide has a really good basis when it was written (e.g. most terminals being unable to show > 80 characters on a line), but over time they become functionally obsolete, but still rigidly adhere... |
PEP8 - 80 Characters - Big Strings | 1,874,592 | 80 | 2009-12-09T15:20:54Z | 1,874,635 | 48 | 2009-12-09T15:25:52Z | [
"python",
"string",
"pep8"
] | Due to the sheer annoyance of figuring out what to Google, I've decided to risk what any reputation I had to ask this rather simple question.
As PEP8 suggests keeping below the 80 column rule for your python program, how can I abide to that with long strings, i.e.
```
s = "this is my really, really, really, really, r... | Implicit concatenation might be the cleanest solution:
```
s = "this is my really, really, really, really, really, really," \
" really long string that I'd like to shorten."
```
**Edit** Todd's answer below (using brackets rather than line continuation) is better for all the reasons he gives. The only hesitation ... |
PEP8 - 80 Characters - Big Strings | 1,874,592 | 80 | 2009-12-09T15:20:54Z | 1,874,679 | 112 | 2009-12-09T15:31:49Z | [
"python",
"string",
"pep8"
] | Due to the sheer annoyance of figuring out what to Google, I've decided to risk what any reputation I had to ask this rather simple question.
As PEP8 suggests keeping below the 80 column rule for your python program, how can I abide to that with long strings, i.e.
```
s = "this is my really, really, really, really, r... | Also, because neighboring string constants are automatically concatenated, you can code it like this too:
```
s = ("this is my really, really, really, really, really, really, "
"really long string that I'd like to shorten.")
```
Note no plus sign, and I added the extra comma and space that follows the formatti... |
How to use Matplotlib in Django? | 1,874,642 | 13 | 2009-12-09T15:26:50Z | 1,874,740 | 19 | 2009-12-09T15:40:58Z | [
"python",
"django",
"matplotlib"
] | From some examples from the Internet I made the test code below. It works!
... BUT if I reload the page, the pie will draw itself with the same image. Some parts get darker every time I reload the page. When I restart the the development server, it is reset. How do I draw properly with [Matplotlib](http://en.wikipedia... | You need to remove the `num` parameter from the [figure constructor](http://matplotlib.sourceforge.net/api/pyplot%5Fapi.html#matplotlib.pyplot.figure) and [close](http://matplotlib.sourceforge.net/api/pyplot%5Fapi.html#matplotlib.pyplot.close) the figure when you're done with it.
```
import matplotlib.pyplot
def test... |
Using paired certificates with urllib2 | 1,875,052 | 14 | 2009-12-09T16:27:21Z | 1,875,106 | 10 | 2009-12-09T16:34:40Z | [
"python",
"ssl",
"certificate",
"urllib2"
] | I need to create a secure channel between my server and a remote web service. I'll be using HTTPS with a client certificate. I'll also need to validate the certificate presented by the remote service.
1. How can I use my own client certificate with urllib2?
2. What will I need to do in my code to ensure that the remot... | Here's a [bug in the official Python bugtracker](http://bugs.python.org/issue3466) that looks relevant, and has a proposed patch. |
Using paired certificates with urllib2 | 1,875,052 | 14 | 2009-12-09T16:27:21Z | 4,464,435 | 26 | 2010-12-16T19:05:28Z | [
"python",
"ssl",
"certificate",
"urllib2"
] | I need to create a secure channel between my server and a remote web service. I'll be using HTTPS with a client certificate. I'll also need to validate the certificate presented by the remote service.
1. How can I use my own client certificate with urllib2?
2. What will I need to do in my code to ensure that the remot... | Because alex's answer is a link, and the code on that page is poorly formatted, I'm just going to put this here for posterity:
```
import urllib2, httplib
class HTTPSClientAuthHandler(urllib2.HTTPSHandler):
def __init__(self, key, cert):
urllib2.HTTPSHandler.__init__(self)
self.key = key
s... |
Importing a module based on installed python version? | 1,875,259 | 5 | 2009-12-09T16:55:26Z | 1,875,267 | 9 | 2009-12-09T16:56:30Z | [
"python",
"json"
] | My module currently imports the `json` module, which is only available in 2.6. I'd like to make a check against the python version to import `simplejson`, which can be built for 2.5 (and is the module adopted in 2.6 anyway). Something like:
```
if __version__ 2.5:
import simplejson as json
else:
import json
``... | ```
try:
import simplejson as json
except ImportError:
import json
```
of course, it doesn't work around cases when in python-2.5 you don't have `simplejson` installed, the same as your example. |
Validate image size in django admin | 1,875,316 | 13 | 2009-12-09T17:02:27Z | 1,875,453 | 36 | 2009-12-09T17:20:18Z | [
"python",
"django",
"image",
"django-forms",
"python-imaging-library"
] | I see a lot of people with Django apps that have image uploads are automatically resizing the images after they are uploaded. That is well and good for some cases, but I don't want to do this. Instead, I simply want to force the user to upload a file that is already the proper size.
I want to have an ImageField where ... | The right place to do this is during form validation.
A quick example (will edit/integrate with more info later):
```
from django.core.files.images import get_image_dimensions
class myForm(forms.ModelForm):
class Meta:
model = myModel
def clean_picture(self):
picture = self.cleaned_data.get("pict... |
Python 2.6+ str.format() and regular expressions | 1,875,676 | 9 | 2009-12-09T17:57:34Z | 1,875,706 | 15 | 2009-12-09T18:02:01Z | [
"python",
"regex",
"format",
"string-formatting"
] | Using `str.format()` is the new standard for formatting strings in Python 2.6, and Python 3. I've run into an issue when using `str.format()` with regular expressions.
I've written a regular expression to return all domains that are a single level below a specified domain or any domains that are 2 levels below the dom... | you first would need to format string and then use regex. It really doesn't worth it to put everything into a single line. Escaping is done by doubling the curly braces:
```
>>> pat= '^(w{{3}}\.)?([0-9A-Za-z-]+\.){{1}}{domainName}$'.format(domainName = 'delivery.com')
>>> pat
'^(w{3}\\.)?([0-9A-Za-z-]+\\.){1}delivery.... |
Execute sql query with Elixir | 1,875,885 | 5 | 2009-12-09T18:36:02Z | 2,096,497 | 10 | 2010-01-19T19:39:42Z | [
"python",
"postgresql",
"sqlalchemy",
"python-elixir"
] | I'm using Elixir in a project that connects to a postgres database. I want to run the following query on the database I'm connected to, but I'm not sure how to do it as I'm rather new to Elixir and SQLAlchemy. Anyone know how?
`VACUUM FULL ANALYZE table`
**Update**
The error is: "UnboundExecutionError: Could not loc... | Dammit. I knew the answer was going to be right under my nose. Assuming you setup your connection like I did.
```
metadata.bind = 'postgres://user:pw@host/db'
```
The solution to this was as simple as
```
conn = metadata.bind.engine.connect()
old_lvl = conn.connection.isolation_level
conn.connection.set_isolation_l... |
Deleting key/value from list of dictionaries using lambda and map | 1,875,932 | 6 | 2009-12-09T18:40:52Z | 1,875,946 | 12 | 2009-12-09T18:43:27Z | [
"python",
"dictionary",
"lambda"
] | I have a list of dictionaries that have the same keys within eg:
```
[{k1:'foo', k2:'bar', k3...k4....}, {k1:'foo2', k2:'bar2', k3...k4....}, ....]
```
I'm trying to delete k1 from all dictionaries within the list.
I tried
```
map(lambda x: del x['k1'], list)
```
but that gave me a syntax error. Where have I gone ... | lambda bodies are only expressions, not statements like `del`.
If you *have* to use map and lambda, then:
```
map(lambda d: d.pop('k1'), list_of_d)
```
A for loop is probably clearer:
```
for d in list_of_d:
del d['k1']
``` |
How can I access an uploaded file in universal-newline mode? | 1,875,956 | 14 | 2009-12-09T18:45:07Z | 1,979,878 | 12 | 2009-12-30T12:11:35Z | [
"python",
"django",
"django-forms"
] | I am working with a file uploaded using Django's `forms.FileField`. This returns an object of type `InMemoryUploadedFile`.
I need to access this file in universal-newline mode. Any ideas on how to do this without saving and then reopening the file?
Thanks | If you are using Python 2.6 or higher, you can use the `io.StringIO` class after having read your file into memory (using the read() method). Example:
```
>>> import io
>>> s = u"a\r\nb\nc\rd"
>>> sio = io.StringIO(s, newline=None)
>>> sio.readlines()
[u'a\n', u'b\n', u'c\n', u'd']
```
To actually use this in your dj... |
Explain Python .join() | 1,876,191 | 92 | 2009-12-09T19:22:04Z | 1,876,204 | 51 | 2009-12-09T19:24:45Z | [
"python",
"list",
"string"
] | I'm pretty new to Python and am completely confused by .join() which I have read is the preferred method for concatenating strings.
I try:
```
strid = repr(595)
print array.array('c', random.sample(string.ascii_letters, 20 - len(strid)))
.tostring().join(strid)
```
and get something like:
```
5wlfgALGbXOahekxSs... | `join` takes an iterable thing as an argument. Usually it's a list. The problem in your case is that a string is itself iterable, giving out each character in turn. Your code breaks down to this:
```
"wlfgALGbXOahekxSs".join("595")
```
which acts the same as this:
```
"wlfgALGbXOahekxSs".join(["5", "9", "5"])
```
a... |
Explain Python .join() | 1,876,191 | 92 | 2009-12-09T19:22:04Z | 1,876,206 | 162 | 2009-12-09T19:25:02Z | [
"python",
"list",
"string"
] | I'm pretty new to Python and am completely confused by .join() which I have read is the preferred method for concatenating strings.
I try:
```
strid = repr(595)
print array.array('c', random.sample(string.ascii_letters, 20 - len(strid)))
.tostring().join(strid)
```
and get something like:
```
5wlfgALGbXOahekxSs... | Look carefully at your output:
```
5wlfgALGbXOahekxSs9wlfgALGbXOahekxSs5
^ ^ ^
```
I've highlighted the "5", "9", "5" of your original string. The Python [`join()`](https://docs.python.org/3/library/stdtypes.html#str.join) method is a string method, and takes a *list* of things to join... |
Explain Python .join() | 1,876,191 | 92 | 2009-12-09T19:22:04Z | 1,876,211 | 19 | 2009-12-09T19:26:13Z | [
"python",
"list",
"string"
] | I'm pretty new to Python and am completely confused by .join() which I have read is the preferred method for concatenating strings.
I try:
```
strid = repr(595)
print array.array('c', random.sample(string.ascii_letters, 20 - len(strid)))
.tostring().join(strid)
```
and get something like:
```
5wlfgALGbXOahekxSs... | To append a string, just concatenate it with the `+` sign.
E.g.
```
>>> a = "Hello, "
>>> b = "world"
>>> str = a + b
>>> print str
Hello, world
```
`join` connects strings together with a separator. The separator is what you
place right before the `join`. E.g.
```
>>> "-".join([a,b])
'Hello, -world'
```
Join take... |
Proper help for arguments | 1,876,289 | 2 | 2009-12-09T19:37:25Z | 1,876,338 | 7 | 2009-12-09T19:45:39Z | [
"python",
"optparse"
] | Python optparse works very good when script usage is something like this
```
%prog [options] [args]
```
But I need to write help for script with 1 required argument, so usage will be like this
```
%prog action [options] [args]
```
You can see something similar when you use Subversion - its usage string is
```
svn ... | I think a good solution for you is [argparse](http://code.google.com/p/argparse/), which has been [proposed for inclusion in Python 2.7 and 3.2](http://www.python.org/dev/peps/pep-0389/). It handles subcommands, I believe as you want, and the linked page includes a link to a page on porting your code from optparse.
Se... |
how to auto-update a Django page only when required? | 1,876,625 | 2 | 2009-12-09T20:24:08Z | 1,877,367 | 7 | 2009-12-09T22:26:27Z | [
"javascript",
"python",
"ajax",
"django"
] | As described in <http://stackoverflow.com/questions/1836861/how-to-update-a-django-page-without-a-page-reload>, I send periodic XMLHTTPRequests from the browser to the server using JavaScript to get those pieces of the webpage that changes during the course of my application.
However, most of the time, nothing changes... | The difficulty in answering is in not knowing what the server-side resources are that are being returned to the user.
I'll make up something which may serve as an example. Let's say you were developing an application that allowed you to monitor in real-time comments being made by users on your site. We can do several ... |
why is python reusing a class instance inside in function | 1,876,905 | 6 | 2009-12-09T21:11:02Z | 1,877,006 | 11 | 2009-12-09T21:26:05Z | [
"python",
"namespaces",
"class"
] | I'm running a for loop inside a function which is creating instances of a class to test them. instead of making new classes it appears to be reusing the same two over and over.
Is there something I'm missing about how classes and variables are handled in python methods?
how can I generate a new object for each iterat... | All that shows is that the memory of the objects is being reused, not that new objects aren't being instantiated. In each iteration `collection` is being overwritten, hence the previous object's reference count drops and the Python interpreter is free to deallocate its memory and reuse it (for the next object).
```
>>... |
Implementing python exceptions | 1,877,686 | 3 | 2009-12-09T23:26:53Z | 1,877,720 | 10 | 2009-12-09T23:34:15Z | [
"python",
"exception"
] | I'm having some problems implementing an exception system in my program.
I found somewhere the following piece of code that I am trying to use for my program:
```
class InvalidProgramStateException(Exception):
def __init__(self, expr, msg):
self.expr = expr
self.msg = msg
```
I think msg must be a... | Your custom exceptions don't actually need to take parameters at all. If you haven't got any particular error message or state to encapsulate in the Exception, this will work just fine:
```
class MyException(Exception):
pass
```
This would allow your program to catch cases of this exception by type:
```
try:
... |
Delete final line in file via python | 1,877,999 | 14 | 2009-12-10T00:57:00Z | 1,878,056 | 7 | 2009-12-10T01:13:51Z | [
"python",
"text",
"line"
] | How can one delete the very last line of a file via python?
Example File:
```
hello
world
foo
bar
```
Resulatant File:
```
hello
world
foo
```
I've created the following code to find the number of lines in the file - but I do not know how to delete the specific line number. I'm new to python - so if there is an ea... | This doesn't use python, but python's the wrong tool for the job if this is the only task you want. You can use the standard \*nix utility `head`, and run
```
head -n-1 filename > newfile
```
which will copy all but the last line of filename to newfile. |
Delete final line in file via python | 1,877,999 | 14 | 2009-12-10T00:57:00Z | 10,289,740 | 32 | 2012-04-23T23:32:06Z | [
"python",
"text",
"line"
] | How can one delete the very last line of a file via python?
Example File:
```
hello
world
foo
bar
```
Resulatant File:
```
hello
world
foo
```
I've created the following code to find the number of lines in the file - but I do not know how to delete the specific line number. I'm new to python - so if there is an ea... | Because I routinely work with many-gigabyte files, looping through as mentioned in the answers didn't work for me. The solution I use:
```
file = open(sys.argv[1], "r+", encoding = "utf-8")
#Move the pointer (similar to a cursor in a text editor) to the end of the file.
file.seek(0, os.SEEK_END)
#This code means th... |
Add tuple to list of tuples in Python | 1,878,470 | 13 | 2009-12-10T03:29:54Z | 1,878,486 | 11 | 2009-12-10T03:35:49Z | [
"python",
"tuples"
] | I am new to python and don't know the best way to do this.
I have a list of tuples which represent points and another list which represents offsets. I need a set of all the combinations that this forms.
Here's some code:
```
offsets = [( 0, 0),( 0,-1),( 0, 1),( 1, 0),(-1, 0)]
points = [( 1, 5),( 3, 3),( 8, 7)]
```
S... | Pretty simple:
```
>>> rslt = []
>>> for x, y in points:
... for dx, dy in offsets:
... rslt.append( (x+dx, y+dy) )
...
>>> rslt
[(1, 5), (1, 4), (1, 6), (2, 5), (0, 5), (3, 3), (3, 2), (3, 4), (4, 3), (2, 3), (8, 7), (8, 6), (8, 8), (9, 7), (7, 7)]
```
Cycle through the points and the offsets, then buil... |
Add tuple to list of tuples in Python | 1,878,470 | 13 | 2009-12-10T03:29:54Z | 1,878,488 | 25 | 2009-12-10T03:37:00Z | [
"python",
"tuples"
] | I am new to python and don't know the best way to do this.
I have a list of tuples which represent points and another list which represents offsets. I need a set of all the combinations that this forms.
Here's some code:
```
offsets = [( 0, 0),( 0,-1),( 0, 1),( 1, 0),(-1, 0)]
points = [( 1, 5),( 3, 3),( 8, 7)]
```
S... | ```
result = [(x+dx, y+dy) for x,y in points for dx,dy in offsets]
```
For more, see [list comprehensions](http://docs.python.org/tutorial/datastructures.html#list-comprehensions). |
Add tuple to list of tuples in Python | 1,878,470 | 13 | 2009-12-10T03:29:54Z | 1,878,842 | 7 | 2009-12-10T05:42:35Z | [
"python",
"tuples"
] | I am new to python and don't know the best way to do this.
I have a list of tuples which represent points and another list which represents offsets. I need a set of all the combinations that this forms.
Here's some code:
```
offsets = [( 0, 0),( 0,-1),( 0, 1),( 1, 0),(-1, 0)]
points = [( 1, 5),( 3, 3),( 8, 7)]
```
S... | Personally, I like Alok's answer. However, for fans of [itertools](http://docs.python.org/library/itertools.html#itertools.product), the itertools-based equivalent (in Python 2.6 and later) is:
```
import itertools as it
ps = [(x+dx, y+dy) for (x, y), (dx, dy) in it.product(points, offsets)]
```
However, in this case... |
struct objects in python | 1,878,710 | 8 | 2009-12-10T04:55:04Z | 1,878,775 | 14 | 2009-12-10T05:21:33Z | [
"python"
] | I wanted to create a throwaway "struct" object to keep various status flags. My first approach was this (javascript style)
```
>>> status = object()
>>> status.foo = 3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'foo'
```
Definitely not w... | From the [Python Official Documentation](http://docs.python.org/tutorial/classes.html#odds-and-ends):
> 9.7. Odds and Ends
>
> Sometimes it is useful to have a data
> type similar to the Pascal ârecordâ or
> C âstructâ, bundling together a few
> named data items. An empty class
> definition will do nicely:
``... |
struct objects in python | 1,878,710 | 8 | 2009-12-10T04:55:04Z | 1,878,789 | 8 | 2009-12-10T05:26:03Z | [
"python"
] | I wanted to create a throwaway "struct" object to keep various status flags. My first approach was this (javascript style)
```
>>> status = object()
>>> status.foo = 3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'foo'
```
Definitely not w... | I had the same question once. I asked it in a mailing list, and Alex Martelli pointed out that `object` is the basis of all inheritance in Python; if `object()` created a class instance with its own dictionary, then every object in Python would have to have its own dictionary, and that would waste memory. For example, ... |
struct objects in python | 1,878,710 | 8 | 2009-12-10T04:55:04Z | 1,878,803 | 17 | 2009-12-10T05:31:21Z | [
"python"
] | I wanted to create a throwaway "struct" object to keep various status flags. My first approach was this (javascript style)
```
>>> status = object()
>>> status.foo = 3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'foo'
```
Definitely not w... | The most concise way to make "a generic object to which you can assign/fetch attributes" is probably:
```
b = lambda:0
```
As most other answers point out, there are many other ways, but it's hard to beat this one for conciseness (`lambda:0` is exactly the same number of characters as `object()`...;-). |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.