content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
How to convert a list of number to html in Python?
hey guys, my last problem ^^ say i have a string which contains html, like
html = '<td class="p11_666699"><strong>100</strong></td>'
and a list like
numbers = [100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112,
113, 114, 115, 116, 117, 1... | How to convert a list of number to html in Python? | hey guys, my last problem ^^ say i have a string which contains html, like
html = '<td class="p11_666699"><strong>100</strong></td>'
and a list like
numbers = [100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112,
113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125,
126, 1... | [
"As pointed out in the comments, it's really hard to understand your question... but if you want to generate a bunch of table cells, each containing one of the numbers, use something like this:\nhtml = ''.join('<td>%d</td>' % n for n in numbers)\n\nOf course you can add in a class or other attribute to be applied t... | [
4,
2,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0000520881_python.txt |
Q:
Further Processing of Output of Undefined Methods (Python)
How do I write a Python class that handles calls on undefined methods by first, getting the output of a function of the same name from a given module, and then, doing something further with that output?
For example, given add(x, y), doublerInstance.add(1, ... | Further Processing of Output of Undefined Methods (Python) | How do I write a Python class that handles calls on undefined methods by first, getting the output of a function of the same name from a given module, and then, doing something further with that output?
For example, given add(x, y), doublerInstance.add(1, 1) should return 4.
I know _ _ getattr _ _() intercepts calls on... | [
"__getattr__ has to return the function - not the result from calling it:\nclass Doubler:\n def __init__(self, source):\n self.source = source\n\n def __getattr__(self, attrname):\n fnc = getattr(self.source, attrname)\n return lambda x,y : fnc(x,y) * 2\n\nThis uses a lambda expression; it returns a new ... | [
2,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0000521111_python.txt |
Q:
How does one parse simple inline markup (i.e. *bold*), in Python?
How does one implement a parser (in Python) for a subset of wikitext that modifies text, namely:
*bold*, /italics/, _underline_
I'm converting it to LaTeX, so the conversion is from:
Hello, *world*! Let's /go/.
to:
Hello \textbf{world}! Let's \te... | How does one parse simple inline markup (i.e. *bold*), in Python? | How does one implement a parser (in Python) for a subset of wikitext that modifies text, namely:
*bold*, /italics/, _underline_
I'm converting it to LaTeX, so the conversion is from:
Hello, *world*! Let's /go/.
to:
Hello \textbf{world}! Let's \textit{go}.
Though there's nothing specific about it being a conversion ... | [
"If your language is small, regular expressions might be the least painful solution:\n>>> import re\n>>> str = \"Hello, *world*! Let's /go/.\"\n>>> str = re.sub(r\"\\*([^\\*]*)\\*\", r\"\\textbf{\\1}\", str)\n>>> str = re.sub(r\"/([^/]*)/\", r\"\\textit{\\1}\", str)\n>>> str\n\"Hello, \\textbf{world}! Let's \\tex... | [
7
] | [] | [] | [
"creole",
"parsing",
"python",
"wikitext"
] | stackoverflow_0000521326_creole_parsing_python_wikitext.txt |
Q:
How to get the concrete class name as a string?
I want to avoid calling a lot of isinstance() functions, so I'm looking for a way to get the concrete class name for an instance variable as a string.
Any ideas?
A:
instance.__class__.__name__
example:
>>> class A():
pass
>>> a = A()
>>> a.__class__.__name__
... | How to get the concrete class name as a string? | I want to avoid calling a lot of isinstance() functions, so I'm looking for a way to get the concrete class name for an instance variable as a string.
Any ideas?
| [
" instance.__class__.__name__\n\nexample:\n>>> class A():\n pass\n>>> a = A()\n>>> a.__class__.__name__\n'A'\n\n",
"<object>.__class__.__name__\n\n",
"you can also create a dict with the classes themselves as keys, not necessarily the classnames\ntypefunc={\n int:lambda x: x*2,\n str:lambda s:'(*(%s)*)... | [
309,
29,
9
] | [] | [] | [
"python"
] | stackoverflow_0000521502_python.txt |
Q:
How can I get only class variables?
I have this class definition:
class cols:
name = 'name'
size = 'size'
date = 'date'
@classmethod
def foo(cls):
print "This is a class method"
With __dict__ I get all class attributes (members and variables). Also there are the "Internal attributes" t... | How can I get only class variables? | I have this class definition:
class cols:
name = 'name'
size = 'size'
date = 'date'
@classmethod
def foo(cls):
print "This is a class method"
With __dict__ I get all class attributes (members and variables). Also there are the "Internal attributes" too (like __main__). How can I get only th... | [
"I wouldn't know a straightforward way, especially since from the interpreter's POV, there is not that much of a difference between a method of a class and any other variable (methods have descriptors, but that's it...).\nSo when you only want non-callable class members, you have to fiddle around a little:\n>>> cla... | [
5,
1
] | [] | [] | [
"python"
] | stackoverflow_0000521710_python.txt |
Q:
How can I generate multi-line build commands?
In SCons, my command generators create ridiculously long command lines. I'd
like to be able to split these commands across multiple lines for
readability in the build log.
e.g. I have a SConscipt like:
import os
# create dependency
def my_cmd_generator(source, targe... | How can I generate multi-line build commands? | In SCons, my command generators create ridiculously long command lines. I'd
like to be able to split these commands across multiple lines for
readability in the build log.
e.g. I have a SConscipt like:
import os
# create dependency
def my_cmd_generator(source, target, env, for_signature):
return r'''echo its a s... | [
"Thanks to cournape's tip about Actions versus Generators ( and eclipse pydev debugger), I've finally figured out what I need to do. You want to pass in your function to the 'Builder' class as an 'action' not a 'generator'. This will allow you to actually execute the os.system or os.popen call directly. Here's t... | [
3,
1
] | [] | [] | [
"build",
"build_automation",
"python",
"scons"
] | stackoverflow_0000466293_build_build_automation_python_scons.txt |
Q:
Execute a string as a command in python
I am developing my stuff in python. In this process I encountered a situation where I have a string called "import django". And I want to validate this string. Which means, I want to check whether the module mentioned('django' in this case) is in the python-path. How can I d... | Execute a string as a command in python | I am developing my stuff in python. In this process I encountered a situation where I have a string called "import django". And I want to validate this string. Which means, I want to check whether the module mentioned('django' in this case) is in the python-path. How can I do it?
| [
"My previous answer was wrong -- i didn't think to test my code. This actually works, though: look at the imp module.\nTo just check for the module's importability in the current sys.path: \ntry:\n imp.find_module('django', sys.path)\nexcept ImportError:\n print \"Boo! no django for you!\"\n\n",
"I doub't ... | [
14,
1,
1
] | [] | [] | [
"django",
"path",
"python"
] | stackoverflow_0000517491_django_path_python.txt |
Q:
Refactor this Python code to iterate over a container
Surely there is a better way to do this?
results = []
if not queryset is None:
for obj in queryset:
results.append((getattr(obj,field.attname),obj.pk))
The problem is that sometimes queryset is None which causes an exception when I try to iterate o... | Refactor this Python code to iterate over a container | Surely there is a better way to do this?
results = []
if not queryset is None:
for obj in queryset:
results.append((getattr(obj,field.attname),obj.pk))
The problem is that sometimes queryset is None which causes an exception when I try to iterate over it. In this case, I just want result to be set to an em... | [
"results = [(getattr(obj, field.attname), obj.pk) for obj in queryset or []]\n\n",
"How about\nfor obj in (queryset or []):\n # Do your stuff\n\nIt is the same as J.F Sebastians suggestion, only not implemented as a list comprehension.\n",
"For what it's worth, Django managers have a \"none\" queryset that y... | [
19,
8,
2,
1
] | [] | [] | [
"django",
"iterator",
"python",
"refactoring"
] | stackoverflow_0000495294_django_iterator_python_refactoring.txt |
Q:
What's the most pythonic way of access C libraries - for example, OpenSSL?
I need to access the crypto functions of OpenSSL to encode Blowfish data in a CBC streams. I've googled and found some Blowfish libraries (hand written) and some OpenSSL wrappers (none of the seem complete.)
In the end, I need to access the... | What's the most pythonic way of access C libraries - for example, OpenSSL? | I need to access the crypto functions of OpenSSL to encode Blowfish data in a CBC streams. I've googled and found some Blowfish libraries (hand written) and some OpenSSL wrappers (none of the seem complete.)
In the end, I need to access the certain OpenSSL functions, such as the full blowfish.h library of commands. Wha... | [
"ctypes is the place to start. It lets you call into DLLs, using C-declared types, etc. I don't know if there are limitations that will keep you from doing everything you need, but it's very capable, and it's included in the standard library.\n",
"There's lots of ways to interface with C (and C++) in Python. ct... | [
5,
5,
5,
0,
0,
0
] | [] | [] | [
"c",
"encryption",
"openssl",
"python"
] | stackoverflow_0000422903_c_encryption_openssl_python.txt |
Q:
Unicode vs UTF-8 confusion in Python / Django?
I stumbled over this passage in the Django tutorial:
Django models have a default str() method that calls unicode() and converts the result to a UTF-8 bytestring. This means that unicode(p) will return a Unicode string, and str(p) will return a normal string, with ch... | Unicode vs UTF-8 confusion in Python / Django? | I stumbled over this passage in the Django tutorial:
Django models have a default str() method that calls unicode() and converts the result to a UTF-8 bytestring. This means that unicode(p) will return a Unicode string, and str(p) will return a normal string, with characters encoded as UTF-8.
Now, I'm confused becaus... | [
"\nwhat is a \"Unicode string\" in Python? Does that mean UCS-2?\n\nUnicode strings in Python are stored internally either as UCS-2 (fixed-length 16-bit representation, almost the same as UTF-16) or UCS-4/UTF-32 (fixed-length 32-bit representation). It's a compile-time option; on Windows it's always UTF-16 whilst m... | [
54,
9,
0
] | [
"From Wikipedia on UTF-8: \n\nUTF-8 (8-bit UCS/Unicode Transformation Format) is a variable-length character encoding for Unicode. It is able to represent any character in the Unicode standard, yet the initial encoding of byte codes and character assignments for UTF-8 is backwards compatible with ASCII. For these r... | [
-1,
-2
] | [
"django",
"python",
"unicode"
] | stackoverflow_0000022149_django_python_unicode.txt |
Q:
Python cannot create instances
I am trying to create a simple Python extension using PyCXX. And I'm compiling against my Python 2.5 installation.
My goal is to be able to do the following in Python:
import Cats
kitty = Cats.Kitty()
if type(kitty) == Cats.Kitty:
kitty.Speak()
But every time I try, this is th... | Python cannot create instances | I am trying to create a simple Python extension using PyCXX. And I'm compiling against my Python 2.5 installation.
My goal is to be able to do the following in Python:
import Cats
kitty = Cats.Kitty()
if type(kitty) == Cats.Kitty:
kitty.Speak()
But every time I try, this is the error that I get:
TypeError: canno... | [
"I do'nt see it in the code, but sort of thing normally means it can't create an instance, which means it can't find a ctor. Are you sure you've got a ctor that exactly matches the expected signature?\n"
] | [
2
] | [] | [] | [
"pycxx",
"python"
] | stackoverflow_0000522921_pycxx_python.txt |
Q:
Event handling with Jython & Swing
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", actionPerform... | Event handling with Jython & Swing | 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)
or
JButton("Pu... | [
"JButton(\"Push me\", actionPerformed=self.nameOfMethodToCall)\n\nHere's a modified example from the article you cited:\nfrom javax.swing import JButton, JFrame\n\nclass MyFrame(JFrame):\n def __init__(self):\n JFrame.__init__(self, \"Hello Jython\")\n button = JButton(\"Hello\", actionPerformed=se... | [
11
] | [] | [] | [
"java",
"jython",
"python",
"swing",
"user_interface"
] | stackoverflow_0000520615_java_jython_python_swing_user_interface.txt |
Q:
Passing a list while retaining the original
So I'm teaching myself Python, and I'm having an issue with lists. I want to pass my function a list and pop items off it while retaining the original list. How do I make python "instance" the passed list rather that passing a pointer to the original one?
Example:
def bu... | Passing a list while retaining the original | So I'm teaching myself Python, and I'm having an issue with lists. I want to pass my function a list and pop items off it while retaining the original list. How do I make python "instance" the passed list rather that passing a pointer to the original one?
Example:
def burninate(b):
c = []
for i in range(3):
... | [
"As other answers have suggested, you can provide your function with a copy of the list.\nAs an alternative, your function could take a copy of the argument:\ndef burninate(b):\n c = []\n b = list(b)\n for i in range(3):\n c.append(b.pop())\n return c\n\nBasically, you need to be clear in your mi... | [
14,
10,
6,
5,
2,
1,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0000227790_list_python.txt |
Q:
Is there a way to loop through a sub section of a list in Python
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.
A:
for x in thousand[400:500]:
pass
If you are working with an iterable instead of a list... | Is there a way to loop through a sub section of a list in Python | 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]:\n pass\n\nIf you are working with an iterable instead of a list, you should use itertools:\nimport itertools\nfor x in itertools.islice(thousand, 400, 500):\n pass\n\nIf you need to loop over thousand[500], then use 501 as the latter index. This will work even if thousand[501] is ... | [
22,
7,
2
] | [] | [] | [
"list",
"loops",
"python"
] | stackoverflow_0000522430_list_loops_python.txt |
Q:
Google Apps HTTP Streaming with Python question
I got a little question here:
Some time ago I implemented HTTP Streaming using PHP code, something similar to what is on this page:
http://my.opera.com/WebApplications/blog/show.dml/438711#comments
And I get data with very similar solution. Now I tried to use second ... | Google Apps HTTP Streaming with Python question | I got a little question here:
Some time ago I implemented HTTP Streaming using PHP code, something similar to what is on this page:
http://my.opera.com/WebApplications/blog/show.dml/438711#comments
And I get data with very similar solution. Now I tried to use second code from this page (in Python), but no matter what I... | [
"Its highly likely App Engine buffers output. A quick search found this: http://code.google.com/appengine/docs/python/tools/webapp/buildingtheresponse.html\n\nThe out stream buffers all output in memory, then sends the final output when the handler exits. webapp does not support streaming data to the client.\n\n"... | [
3,
1
] | [] | [] | [
"javascript",
"python",
"streaming"
] | stackoverflow_0000523579_javascript_python_streaming.txt |
Q:
How to externally populate a Django model?
What is the best idea to fill up data into a Django model from an external source?
E.g. I have a model Run, and runs data in an XML file, which changes weekly.
Should I create a view and call that view URL from a curl cronjob (with the advantage that that data can be read... | How to externally populate a Django model? | What is the best idea to fill up data into a Django model from an external source?
E.g. I have a model Run, and runs data in an XML file, which changes weekly.
Should I create a view and call that view URL from a curl cronjob (with the advantage that that data can be read anytime, not only when the cronjob runs), or cr... | [
"There is excellent way to do some maintenance-like jobs in project environment- write a custom manage.py command. It takes all environment configuration and other stuff allows you to concentrate on concrete task.\nAnd of course call it directly by cron.\n",
"You don't need to create a view, you should just trigg... | [
11,
4,
2,
2
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0000524214_django_django_models_python.txt |
Q:
How to 'zoom' in on a section of the Mandelbrot set?
I have created a Python file to generate a Mandelbrot set image. The original maths code was not mine, so I do not understand it - I only heavily modified it to make it about 250x faster (Threads rule!).
Anyway, I was wondering how I could modify the maths part ... | How to 'zoom' in on a section of the Mandelbrot set? | I have created a Python file to generate a Mandelbrot set image. The original maths code was not mine, so I do not understand it - I only heavily modified it to make it about 250x faster (Threads rule!).
Anyway, I was wondering how I could modify the maths part of the code to make it render one specific bit. Here is th... | [
"The line:\nbox=((-2,1.25),(0.5,-1.25))\n\nis the bit that defines the area of coordinate space that is being rendered, so you just need to change this line. First coordinate pair is the top-left of the area, the second is the bottom right. \nTo get a new coordinate from the image should be quite straightforward. Y... | [
15,
4
] | [] | [] | [
"mandelbrot",
"math",
"python"
] | stackoverflow_0000524291_mandelbrot_math_python.txt |
Q:
Splitting arguments -- preserving quoted substrings -- in python
Exact duplicate: Split a string by spaces -- preserving quoted substrings -- in Python
I want to take in a string and return a list, dictionary or tuple of values as separated by spaces. However, I want to not match spaces that are somehow between q... | Splitting arguments -- preserving quoted substrings -- in python | Exact duplicate: Split a string by spaces -- preserving quoted substrings -- in Python
I want to take in a string and return a list, dictionary or tuple of values as separated by spaces. However, I want to not match spaces that are somehow between quote marks, i.e.
apple orange "banana tree" green
Should come back a... | [
"This problem sounds a lot like parsing tag input, you could take a look at django-tagging utils.py implementation which solves this kind of problem\n",
"def splitstring(string):\n \"\"\"\n >>> string = 'apple orange \"banana tree\" green'\n >>> splitstring(string)\n ['apple', 'orange', 'green', '\"ba... | [
1,
-2
] | [] | [] | [
"parsing",
"python"
] | stackoverflow_0000524541_parsing_python.txt |
Q:
python, how to tell what type of obj was returned
How can i find out if the obj returned by a func is a int or something else (like a sqlite cursor)
A:
Use isinstance(item, type) -- for instance:
if isinstance(foo, int):
pass # handle this case
However, explicit type checking is not considered a good practi... | python, how to tell what type of obj was returned | How can i find out if the obj returned by a func is a int or something else (like a sqlite cursor)
| [
"Use isinstance(item, type) -- for instance:\nif isinstance(foo, int):\n pass # handle this case\n\nHowever, explicit type checking is not considered a good practice in the Python world -- it means that much of the power of duck typing is lost: Something which walks and quacks like a duck should be allowed to be... | [
12
] | [
"Use the built-in \"type\" function, e.g. type(10) -> .\n"
] | [
-1
] | [
"python",
"types"
] | stackoverflow_0000524734_python_types.txt |
Q:
Python's equivalent of $this->$varName
In PHP I can do the following:
$myVar = 'name';
print $myClass->$myVar;
// Identical to $myClass->name
I wish to do this in Python but can't find out how
A:
In python, it's the getattr built-in function.
class Something( object ):
def __init__( self ):
self.a=... | Python's equivalent of $this->$varName | In PHP I can do the following:
$myVar = 'name';
print $myClass->$myVar;
// Identical to $myClass->name
I wish to do this in Python but can't find out how
| [
"In python, it's the getattr built-in function.\nclass Something( object ):\n def __init__( self ):\n self.a= 2\n self.b= 3\n\nx= Something()\ngetattr( x, 'a' )\ngetattr( x, 'b' )\n\n",
"You'll want to use the getattr builtin function.\nmyvar = 'name'\n\n//both should produce the same results\nva... | [
16,
5
] | [] | [] | [
"php",
"python"
] | stackoverflow_0000524831_php_python.txt |
Q:
python coding speed and cleanest
Python is pretty clean, and I can code neat apps quickly.
But I notice I have some minor error someplace and I dont find the error at compile but at run time. Then I need to change and run the script again. Is there a way to have it break and let me modify and run?
Also, I dislike ... | python coding speed and cleanest | Python is pretty clean, and I can code neat apps quickly.
But I notice I have some minor error someplace and I dont find the error at compile but at run time. Then I need to change and run the script again. Is there a way to have it break and let me modify and run?
Also, I dislike how python has no enums. If I were to ... | [
"\"I don't find the error at compile but at run time\"\nCorrect. True for all non-compiled interpreted languages.\n\"I need to change and run the script again\"\nAlso correct. True for all non-compiled interpreted languages.\n\"Is there a way to have it break and let me modify and run?\"\nWhat?\nIf it's a run-tim... | [
9,
3,
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0000525080_python.txt |
Q:
pythonic replacement for enums
In my python script i am parsing a user created file and typically there will be some errors and there are cases were i warn the user to be more clear. In c i would have an enum like eAssignBad, eAssignMismatch, eAssignmentSignMix (sign mixed with unsigned). Then i would look the val... | pythonic replacement for enums | In my python script i am parsing a user created file and typically there will be some errors and there are cases were i warn the user to be more clear. In c i would have an enum like eAssignBad, eAssignMismatch, eAssignmentSignMix (sign mixed with unsigned). Then i would look the value up to print an error or warning m... | [
"Here is one of the best enum implementations I've found so far:\nhttp://code.activestate.com/recipes/413486/\nBut, dare I ask, do you need an enum?\nYou could have a simple dict with your error messages and some integer constants with your error numbers.\neAssignBad = 0\neAssignMismatch = 1\neAssignmentSignMix = 2... | [
4,
3
] | [] | [] | [
"enums",
"python"
] | stackoverflow_0000525134_enums_python.txt |
Q:
BaseHTTPRequestHandler freezes while writing to self.wfile after installing Python 3.0
I'm starting to lose my head with this one.
I have a class that extends BaseHTTPRequestHandler. It works fine on
Python 2.5. And yesterday I was curious and decided to install Python
3.0 on my Mac (I followed this tutorial, to b... | BaseHTTPRequestHandler freezes while writing to self.wfile after installing Python 3.0 | I'm starting to lose my head with this one.
I have a class that extends BaseHTTPRequestHandler. It works fine on
Python 2.5. And yesterday I was curious and decided to install Python
3.0 on my Mac (I followed this tutorial, to be sure I wasn't messing
things up: http://farmdev.com/thoughts/66/python-3-0-on-mac-os-x-alo... | [
"I would suggest develop a simple page that would dump the version details of the perl environment and confirm that now you are back on 2.5. Mostly in such scenarios there are some environment entries or binaries that are left out.\n",
"I'm sorry, it seems to have been a weird setting between routers (mac <-> rou... | [
0,
0
] | [] | [] | [
"python",
"sockets"
] | stackoverflow_0000523885_python_sockets.txt |
Q:
Translating Python Regexp to Shell
I'm writing an Applescript playlist generator. Part of the process is to read the iTunes Library XML file to get a list of all of the genres in a user's library. This is the python implementation, which works as I'd like:
#!/usr/bin/env python
# script to get all of the ge... | Translating Python Regexp to Shell | I'm writing an Applescript playlist generator. Part of the process is to read the iTunes Library XML file to get a list of all of the genres in a user's library. This is the python implementation, which works as I'd like:
#!/usr/bin/env python
# script to get all of the genres from itunes
import re,sys,sets
#... | [
"Why are you using regex to parse XML? Why not use a proper XML library? Python has some great utilities like ElementTree that make walking the DOM a lot easier, and it yields nice, friendly objects rather than untyped strings.\nHere are some ways of parsing XML using Applescript:\nApplescript XML Parser (Availab... | [
3,
0,
0
] | [] | [] | [
"applescript",
"python"
] | stackoverflow_0000514767_applescript_python.txt |
Q:
return eats exception
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. ... | return eats exception | 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 bug? Is that docu... | [
"\nThe exception disappears when you use return inside a finally clause. .. Is that documented anywhere?\n\nIt is:\n\nIf finally is present, it specifies a ‘cleanup’ handler. The try clause is executed, including any except and else clauses. If an exception occurs in any of the clauses and is not handled, the excep... | [
53,
36,
5,
2
] | [] | [] | [
"exception",
"finally",
"python",
"return"
] | stackoverflow_0000517060_exception_finally_python_return.txt |
Q:
NumPy, PIL adding an image
I'm trying to add two images together using NumPy and PIL. The way I would do this in MATLAB would be something like:
>> M1 = imread('_1.jpg');
>> M2 = imread('_2.jpg');
>> resM = M1 + M2;
>> imwrite(resM, 'res.jpg');
I get something like this:
alt text http://www.deadlink.cc/matlab.jpg... | NumPy, PIL adding an image | I'm trying to add two images together using NumPy and PIL. The way I would do this in MATLAB would be something like:
>> M1 = imread('_1.jpg');
>> M2 = imread('_2.jpg');
>> resM = M1 + M2;
>> imwrite(resM, 'res.jpg');
I get something like this:
alt text http://www.deadlink.cc/matlab.jpg
Using a compositing program and... | [
"As everyone suggested already, the weird colors you're observing are overflow. And as you point out in the comment of schnaader's answer you still get overflow if you add your images like this:\naddition=(im1arr+im2arr)/2\n\nThe reason for this overflow is that your NumPy arrays (im1arr im2arr) are of the uint8 ty... | [
34,
20,
2,
2,
0
] | [] | [] | [
"image_processing",
"numpy",
"python",
"python_imaging_library"
] | stackoverflow_0000524930_image_processing_numpy_python_python_imaging_library.txt |
Q:
subprocess.Popen error
I am running an msi installer in silent mode and caching logs in the specific file. The following is the command i need to execute.
C:\Program Files\ My Installer\Setup.exe /s /v "/qn /lv %TEMP%\log_silent.log"
I used:
subprocess.Popen(['C:\Program Files\ My Installer\Setup.exe', '/s /v "/q... | subprocess.Popen error | I am running an msi installer in silent mode and caching logs in the specific file. The following is the command i need to execute.
C:\Program Files\ My Installer\Setup.exe /s /v "/qn /lv %TEMP%\log_silent.log"
I used:
subprocess.Popen(['C:\Program Files\ My Installer\Setup.exe', '/s /v "/qn /lv %TEMP%\log_silent.log"... | [
"The problem is very subtle.\nYou're executing the program directly. It gets:\nargv[0] = \"C:\\Program Files\\ My Installer\\Setup.exe\"\nargv[1] = /s /v \"/qn /lv %TEMP%\\log_silent.log\"\n\nWhereas it should be:\nargv[1] = \"/s\"\nargv[2] = \"/v\"\nargv[3] = \"/qn\"\nargv[4] = \"/lv %TEMP%\\log_silent.log\"\n\nIn... | [
9,
2,
0,
0
] | [] | [] | [
"popen",
"python",
"subprocess"
] | stackoverflow_0000526734_popen_python_subprocess.txt |
Q:
How to run included tests on deployed pylons application
I have installed pylons based application from egg, so it sits somewhere under /usr/lib/python2.5/site-packages. I see that the tests are packaged too and I would like to run them (to catch a problem that shows up on deployed application but not on developme... | How to run included tests on deployed pylons application | I have installed pylons based application from egg, so it sits somewhere under /usr/lib/python2.5/site-packages. I see that the tests are packaged too and I would like to run them (to catch a problem that shows up on deployed application but not on development version).
So how do I run them? Doing "nosetests" from dir... | [
"Straight from the horse's mouth:\nInstall nose: easy_install -W nose.\nRun nose: nosetests --with-pylons=test.ini OR python setup.py nosetests\nTo run \"python setup.py nosetests\" you need to have a [nosetests] block in your setup.cfg looking like this:\n\n[nosetests]\nverbose=True\nverbosity=2\nwith-pylons=test.... | [
1
] | [] | [] | [
"nose",
"paster",
"pylons",
"python",
"unit_testing"
] | stackoverflow_0000188417_nose_paster_pylons_python_unit_testing.txt |
Q:
Need instructions for Reversi game
I am trying to write Reversi game in Python. Can anyone give me some basic ideas and strategy which are simple, good and easy to use?
I would appreciate for any help because I've gone to a little far but is stucked between codes and it became more complex too. I think I overdid i... | Need instructions for Reversi game | I am trying to write Reversi game in Python. Can anyone give me some basic ideas and strategy which are simple, good and easy to use?
I would appreciate for any help because I've gone to a little far but is stucked between codes and it became more complex too. I think I overdid in some part that should be fairly simple... | [
"Reversi is an elegantly simple game. I'm going to use a psuedo C#/Java langauge to explain some concepts, but you can transpose them to Python.\nTo break it down into its most simple compnents, you have two basic things:\nA 2 dimensional array that represents the game board:\ngameBoard[10,10]\n\nAnd some form of e... | [
4,
1,
0,
0,
0,
0
] | [] | [] | [
"python",
"reversi"
] | stackoverflow_0000315435_python_reversi.txt |
Q:
python console intrupt? and cross platform threads
I want my app to loop in python but have a way to quit. Is there a way to get input from the console, scan it for letter q and quick when my app is ready to quit? in C i would just create a pthread that waits for cin, scans, locks a global quit var, change, unlock... | python console intrupt? and cross platform threads | I want my app to loop in python but have a way to quit. Is there a way to get input from the console, scan it for letter q and quick when my app is ready to quit? in C i would just create a pthread that waits for cin, scans, locks a global quit var, change, unlock and exit the thread allowing my app to quit when its do... | [
"use the threading module to make a thread class.\nimport threading;\n\nclass foo(threading.Thread):\n def __init__(self):\n #initialize anything\n def run(self):\n while True:\n str = raw_input(\"input something\");\n\nclass bar:\n def __init__(self)\n self.thread = foo(); ... | [
1,
1
] | [] | [] | [
"console",
"multithreading",
"python",
"quit"
] | stackoverflow_0000526955_console_multithreading_python_quit.txt |
Q:
Dynamic data in postgresql
I intend to have a python script do many UPDATEs per second on 2,433,000 rows. I am currently trying to keep the dynamic column in python as a value in a python dict. Yet to keep my python dict synchronized with changes in the other columns is becoming more and more difficult or nonviabl... | Dynamic data in postgresql | I intend to have a python script do many UPDATEs per second on 2,433,000 rows. I am currently trying to keep the dynamic column in python as a value in a python dict. Yet to keep my python dict synchronized with changes in the other columns is becoming more and more difficult or nonviable.
I know I could put the autova... | [
"PostgreSQL supports asynchronous notifications using the LISTEN and NOTIFY commands. An application (client) LISTENs for a notification using a notification name (e.g. \"table_updated\"). The database itself can be made to issue notifications either manually i.e. in the code that performs the insertions or modific... | [
3
] | [] | [] | [
"dynamic_data",
"performance",
"postgresql",
"python",
"vacuum"
] | stackoverflow_0000527013_dynamic_data_performance_postgresql_python_vacuum.txt |
Q:
Intercepting stdout of a subprocess while it is running
If this is my subprocess:
import time, sys
for i in range(200):
sys.stdout.write( 'reading %i\n'%i )
time.sleep(.02)
And this is the script controlling and modifying the output of the subprocess:
import subprocess, time, sys
print 'starting'
pr... | Intercepting stdout of a subprocess while it is running | If this is my subprocess:
import time, sys
for i in range(200):
sys.stdout.write( 'reading %i\n'%i )
time.sleep(.02)
And this is the script controlling and modifying the output of the subprocess:
import subprocess, time, sys
print 'starting'
proc = subprocess.Popen(
'c:/test_apps/testcr.py',
shel... | [
"As Charles already mentioned, the problem is buffering. I ran in to a similar problem when writing some modules for SNMPd, and solved it by replacing stdout with an auto-flushing version.\nI used the following code, inspired by some posts on ActiveState:\nclass FlushFile(object):\n \"\"\"Write-only flushing wra... | [
16,
8
] | [] | [] | [
"popen",
"process",
"python",
"stdout",
"subprocess"
] | stackoverflow_0000527197_popen_process_python_stdout_subprocess.txt |
Q:
How to debug deadlock with python?
I am developing a multi-threading application, which is deadlocking.
I am using Visual C++ Express 2008 to trace the program. Once the deadlock occurs, I just pause the program and trace. I found that when deadlock occurs, there will be two threads called python from my C++ exte... | How to debug deadlock with python? | I am developing a multi-threading application, which is deadlocking.
I am using Visual C++ Express 2008 to trace the program. Once the deadlock occurs, I just pause the program and trace. I found that when deadlock occurs, there will be two threads called python from my C++ extension.
All of them use Queue in python ... | [
"If you can compile your extension module with gcc (for example, by using Cygwin), you could use gdb and the pystack gdb macro to get Python stacks in that situation. I don't know if it would be possible to do something equivalent to pystack in Visual C++ Express, but you might get some ideas from the pystack macro... | [
6
] | [] | [] | [
"deadlock",
"debugging",
"multithreading",
"python"
] | stackoverflow_0000527296_deadlock_debugging_multithreading_python.txt |
Q:
How to embed p tag inside some text using Beautifulsoup?
I wanted to embed <p> tag where ever there is a \r\n\r\n.
u"Finally Sri Lanka showed up, prevented their first 5-0 series whitewash, and stopped India at nine ODI wins in a row. \r\n\r\nFor 62 balls Yuvraj Singh played a dream knock, keeping India in the ga... | How to embed p tag inside some text using Beautifulsoup? | I wanted to embed <p> tag where ever there is a \r\n\r\n.
u"Finally Sri Lanka showed up, prevented their first 5-0 series whitewash, and stopped India at nine ODI wins in a row. \r\n\r\nFor 62 balls Yuvraj Singh played a dream knock, keeping India in the game despite wickets falling around him. \r\n\r\nPerhaps the tos... | [
"''.join('<p>%s</p>' % line for line in text.split('\\r\\n\\r\\n'))\n# Results:\nu\"<p>Finally Sri Lanka showed up, prevented their first 5-0\nseries whitewash, and stopped India at nine ODI wins in a row. </p>\n<p>For 62 balls Yuvraj Singh played a dream knock, keeping India in the \ngame despite wickets falling a... | [
5
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0000527629_beautifulsoup_python.txt |
Q:
Can I instantiate a subclass object from the superclass
I have the following example code:
class A(object):
def __init__(self, id):
self.myid = id
def foo(self, x):
print 'foo', self.myid*x
class B(A):
def __init__(self, id):
self.myid = id
self.mybid = id*2
def bar... | Can I instantiate a subclass object from the superclass | I have the following example code:
class A(object):
def __init__(self, id):
self.myid = id
def foo(self, x):
print 'foo', self.myid*x
class B(A):
def __init__(self, id):
self.myid = id
self.mybid = id*2
def bar(self, x):
print 'bar', self.myid, self.mybid, x
Whe... | [
"You should rather implement Abstract Factory pattern, and your factory would then build any object you like, depending on provided parameters. That way your code will remain clean and extensible.\nAny hack you could use to make it directly can be removed when you upgrade your interpreter version, since no one exp... | [
6,
2,
2
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0000527757_oop_python.txt |
Q:
input and thread problem, python
I am doing something like this in python
class MyThread ( threading.Thread ):
def run (s):
try:
s.wantQuit = 0
while(not s.wantQuit):
button = raw_input()
if button == "q":
s.wantQuit=1
... | input and thread problem, python | I am doing something like this in python
class MyThread ( threading.Thread ):
def run (s):
try:
s.wantQuit = 0
while(not s.wantQuit):
button = raw_input()
if button == "q":
s.wantQuit=1
except KeyboardInterrupt:
... | [
"You mean the while loop runs before the thread? Well, you can't predict this unless you synchronize it. No one guarantees you that the thread will run before or after that while loop. But if it's being blocked for 5 seconds that's akward - the thread should have been pre-empted by then.\nAlso, since you're first u... | [
1,
1,
0,
0
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0000527420_multithreading_python.txt |
Q:
How to properly organize a package/module dependency tree?
Good morning,
I am currently writing a python library. At the moment, modules and classes are deployed in an unorganized way, with no reasoned design. As I approach a more official release, I would like to reorganize classes and modules so that they have a... | How to properly organize a package/module dependency tree? | Good morning,
I am currently writing a python library. At the moment, modules and classes are deployed in an unorganized way, with no reasoned design. As I approach a more official release, I would like to reorganize classes and modules so that they have a better overall design. I drew a diagram of the import dependenc... | [
"\"I drew a diagram of the import dependencies, and I was planning to aggregate classes by layer level.\"\nPython must read like English (or any other natural language.)\nAn import is a first-class statement that should have real meaning. Organizing things by \"layer level\" (whatever that is) should be clear, mea... | [
6,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0000527919_python.txt |
Q:
Python Script: Print new line each time to shell rather than update existing line
I am a noob when it comes to python. I have a python script which gives me output like this:
[last] ZVZX-W3vo9I: Downloading video webpage
[last] ZVZX-W3vo9I: Extracting video information
[download] Destination: myvideo.flv
[download... | Python Script: Print new line each time to shell rather than update existing line | I am a noob when it comes to python. I have a python script which gives me output like this:
[last] ZVZX-W3vo9I: Downloading video webpage
[last] ZVZX-W3vo9I: Extracting video information
[download] Destination: myvideo.flv
[download] 9.9% of 10.09M at 3.30M/s ETA 00:02
The last line keeps getting updated with ne... | [
"If I understand your request properly, you should be able to change that function to this:\ndef report_progress(self, percent_str, data_len_str, speed_str, eta_str):\n \"\"\"Report download progress.\"\"\"\n print u'[download] %s of %s at %s ETA %s' % (percent_str, data_len_str, speed_str, eta_str)\n\nThat w... | [
3,
3,
0,
0
] | [] | [] | [
"python",
"shell"
] | stackoverflow_0000529395_python_shell.txt |
Q:
Print method question Python
In python, what does the 2nd % signifies?
print "%s" % ( i )
A:
As others have said, this is the Python string formatting/interpolation operator. It's basically the equivalent of sprintf in C, for example:
a = "%d bottles of %s on the wall" % (10, "beer")
is equivalent to something ... | Print method question Python | In python, what does the 2nd % signifies?
print "%s" % ( i )
| [
"As others have said, this is the Python string formatting/interpolation operator. It's basically the equivalent of sprintf in C, for example:\na = \"%d bottles of %s on the wall\" % (10, \"beer\")\nis equivalent to something like\na = sprintf(\"%d bottles of %s on the wall\", 10, \"beer\");\nin C. Each of these ... | [
8,
5,
0,
0,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0000530114_python_string.txt |
Q:
Guide in organizing large Django projects
Anyone could recommend a good guide/tutorial/article with tips/guidelines in how to organize and partition a large Django project?
I'm looking for advices in what to do when you need to start factorizing the initial unique files (models.py, urls.py, views.py) and working ... | Guide in organizing large Django projects | Anyone could recommend a good guide/tutorial/article with tips/guidelines in how to organize and partition a large Django project?
I'm looking for advices in what to do when you need to start factorizing the initial unique files (models.py, urls.py, views.py) and working with more than a few dozens of entities.
| [
"Each \"application\" should be small -- a single reusable entity plus a few associated tables. We have about 5 plus/minus 2 tables per application model. Most of our half-dozen applications are smaller than 5 tables. One has zero tables in the model. \nEach application should be designed to be one reusable con... | [
38,
10
] | [] | [] | [
"django",
"projects",
"python"
] | stackoverflow_0000529921_django_projects_python.txt |
Q:
Why does concatenation work differently in these two samples?
I am raising exceptions in two different places in my Python code:
holeCards = input("Select a hand to play: ")
try:
if len(holeCards) != 4:
raise ValueError(holeCards + ' does not represent a valid hand.')
AND (edited to correct raising co... | Why does concatenation work differently in these two samples? | I am raising exceptions in two different places in my Python code:
holeCards = input("Select a hand to play: ")
try:
if len(holeCards) != 4:
raise ValueError(holeCards + ' does not represent a valid hand.')
AND (edited to correct raising code)
def __init__(self, card):
[...]
if self.cardFace == -1 or ... | [
"Um, am I missing something or are you comparing the output of\nraise ValueError(card, 'is not a known card.')\n\nwith\nraise ValueError(card + ' is not a known card.')\n\n???\nThe second uses \"+\", but the first uses \",\", which does and should give the output you show!\n(nb. the question was edited from a versi... | [
8,
5,
4,
1,
0
] | [] | [] | [
"concatenation",
"python"
] | stackoverflow_0000530329_concatenation_python.txt |
Q:
Deploying bluechannel with fastcgi
I am trying to get a basic blue-channel website running through fcgi, I have a django.fcgi file. How do I do this.
Thank you
A:
Read The Fabulous Manual
| Deploying bluechannel with fastcgi | I am trying to get a basic blue-channel website running through fcgi, I have a django.fcgi file. How do I do this.
Thank you
| [
"Read The Fabulous Manual\n"
] | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0000530480_django_python.txt |
Q:
Is there a single Python regex that can change all "foo" to "bar" on lines starting with "#"?
Is it possible to write a single Python regular expression that can be applied to a multi-line string and change all occurrences of "foo" to "bar", but only on lines beginning with "#"?
I was able to get this working in P... | Is there a single Python regex that can change all "foo" to "bar" on lines starting with "#"? | Is it possible to write a single Python regular expression that can be applied to a multi-line string and change all occurrences of "foo" to "bar", but only on lines beginning with "#"?
I was able to get this working in Perl, using Perl's \G regular expression sigil, which matches the end of the previous match. However... | [
"lines = mystring.split('\\n')\nfor line in lines:\n if line.startswith('#'):\n line = line.replace('foo', 'bar')\n\nNo need for a regex.\n",
"It looked pretty easy to do with a regular expression:\n>>> import re\n... text = \"\"\"line 1\n... line 2\n... Barney Rubble Cutherbert Dribble and foo\n... lin... | [
3,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0000530546_python_regex.txt |
Q:
Huge collections in Python
Basically I am storing millions of vector3 values in a list. But right now the vector3s are defined like so:
[5,6,7]
which I believe is a list. The values will not be modified nor I need any vector3 functionality.
Is this the most performant way to do this?
A:
If you are storing milli... | Huge collections in Python | Basically I am storing millions of vector3 values in a list. But right now the vector3s are defined like so:
[5,6,7]
which I believe is a list. The values will not be modified nor I need any vector3 functionality.
Is this the most performant way to do this?
| [
"If you are storing millions of them, the best way (both for speed and memory use) is to use numpy. \nIf you want to avoid numpy and use only built-in python modules, using tuples instead of lists will save you some overhead.\n",
"The best way is probably using tuples rather than a list. Tuples are faster than li... | [
13,
6,
4
] | [] | [] | [
"collections",
"performance",
"python"
] | stackoverflow_0000530601_collections_performance_python.txt |
Q:
Is there a way to determine if a subdirectory is in the same filesystem from python when using os.walk?
I'm writing a python script that uses os.walk() to walk a directory tree. I'd like to give it the ability to skip subdirectories that are mounted to a different file system, the way find -xdev does. Checking t... | Is there a way to determine if a subdirectory is in the same filesystem from python when using os.walk? | I'm writing a python script that uses os.walk() to walk a directory tree. I'd like to give it the ability to skip subdirectories that are mounted to a different file system, the way find -xdev does. Checking through the documentation on os.walk(), I didn't see any argument to pass in for it to do that automatically. ... | [
"os.path.ismount()\n",
"I think you can use a combination of the os.stat call and a filtering of the dirnames given by os.walk to do what you want. Something like this:\nimport os\nfor root, dirs, files in os.walk(somerootdir) :\n do_processing(root, dirs, files)\n dirs = [i for i in dirs if os.stat(os.path... | [
7,
1
] | [] | [] | [
"python",
"unix"
] | stackoverflow_0000530645_python_unix.txt |
Q:
How to deploy a Python application with libraries as source with no further dependencies?
Background: I have a small Python application that makes life for developers releasing software in our company a bit easier. I build an executable for Windows using py2exe. The application as well as the binary are checked in... | How to deploy a Python application with libraries as source with no further dependencies? | Background: I have a small Python application that makes life for developers releasing software in our company a bit easier. I build an executable for Windows using py2exe. The application as well as the binary are checked into Subversion. Distribution happens by people just checking out the directory from SVN. The pro... | [
"Just use virtualenv - it is a tool to create isolated Python environments. You can create a set-up script and distribute the whole bunch if you want.\n",
"\"I dislike the fact that developers (or me starting on a clean new machine) have to jump through the distutils hoops of having to install the libraries local... | [
9,
8,
8,
0,
0
] | [] | [] | [
"bootstrapping",
"deployment",
"layout",
"python"
] | stackoverflow_0000527510_bootstrapping_deployment_layout_python.txt |
Q:
Parsing datetime strings with microseconds in Python 2.5
I have a text file with a lot of datetime strings in isoformat. The strings are similar to this:
'2009-02-10 16:06:52.598800'
These strings were generated using str(datetime_object). The problem is that, for some reason, str(datetime_object) generates a dif... | Parsing datetime strings with microseconds in Python 2.5 | I have a text file with a lot of datetime strings in isoformat. The strings are similar to this:
'2009-02-10 16:06:52.598800'
These strings were generated using str(datetime_object). The problem is that, for some reason, str(datetime_object) generates a different format when the datetime object has microseconds set to... | [
"Alternatively:\nfrom datetime import datetime\n\ndef str2datetime(s):\n parts = s.split('.')\n dt = datetime.strptime(parts[0], \"%Y-%m-%d %H:%M:%S\")\n return dt.replace(microsecond=int(parts[1]))\n\nUsing strptime itself to parse the date/time string (so no need to think up corner cases for a regex).\n"... | [
21,
11,
5,
2
] | [] | [] | [
"datetime",
"parsing",
"python",
"python_2.5"
] | stackoverflow_0000531157_datetime_parsing_python_python_2.5.txt |
Q:
Adding a shebang causes No such file or directory error when running my python script
I'm trying to run a python script. It works fine when I run it:
python2.5 myscript.py inpt0
The problem starts when I add a shebang:
#!/usr/bin/env python2.5
Result in:
$ myscript.py inpt0
: No such file or directory
Try 2:
#!... | Adding a shebang causes No such file or directory error when running my python script | I'm trying to run a python script. It works fine when I run it:
python2.5 myscript.py inpt0
The problem starts when I add a shebang:
#!/usr/bin/env python2.5
Result in:
$ myscript.py inpt0
: No such file or directory
Try 2:
#!/usr/local/bin/python2.5
Result in:
$ myscript.py inpt0
: bad interpreter: No such file or... | [
"I had similar problems and it turned out to be problem with line-endings. You use windows/linux/mac line endings?\nEdit: forgot the script name, but as OP says, it's dos2unix <filename>\n"
] | [
71
] | [] | [] | [
"python",
"shell"
] | stackoverflow_0000531382_python_shell.txt |
Q:
Why is python ordering my dictionary like so?
Here is the dictionary I have
propertyList = {
"id": "int",
"name": "char(40)",
"team": "int",
"realOwner": "int",
"x": "int",
"y": "int",
"description": "char(255)",
"port": ... | Why is python ordering my dictionary like so? | Here is the dictionary I have
propertyList = {
"id": "int",
"name": "char(40)",
"team": "int",
"realOwner": "int",
"x": "int",
"y": "int",
"description": "char(255)",
"port": "bool",
"secret": "bool",
"dead": ... | [
"For older versions of Python, the real question should be “why not?” — An unordered dictionary is usually implemented as a hash table where the order of elements is well-defined but not immediately obvious (the Python documentation used to state this). Your observations match the rules of a hash table perfectly: a... | [
80,
10,
8
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0000526125_dictionary_python.txt |
Q:
Django - how to remove cached results from previous form posts?
I've got a django Form which contains a dictionary of strings. I've given the form a submit button and a preview button. When the preview button is pressed after entering some information, a POST is sent, and the strings in the dictionary are automa... | Django - how to remove cached results from previous form posts? | I've got a django Form which contains a dictionary of strings. I've given the form a submit button and a preview button. When the preview button is pressed after entering some information, a POST is sent, and the strings in the dictionary are automagically recovered (I assume that it's done using session state or som... | [
"This code is broken in concept; it will never do what you want it to. Your dictionaries are class attributes on the ListingImagesForm class. This class is a module-level global. So you're storing some state in a global variable in-memory in a webserver process. This state is global to all users of your applica... | [
3
] | [] | [] | [
"django",
"python"
] | stackoverflow_0000530715_django_python.txt |
Q:
How can I find memory leaks in my Python program?
Possible Duplicate:
Python memory profiler
I've got a fairly complex (about 20,000) line Python program which after some development has started consuming increasing amounts of memory when it runs. What are the best tools and techniques for finding out what all t... | How can I find memory leaks in my Python program? |
Possible Duplicate:
Python memory profiler
I've got a fairly complex (about 20,000) line Python program which after some development has started consuming increasing amounts of memory when it runs. What are the best tools and techniques for finding out what all the memory is being used for?
Usually this comes down t... | [
"Generally, failing to close cursors is one of the most common kinds of memory leaks. The garbage collector can't see the MySQL resources involved in the cursor. MySQL doesn't know that the Python side was released unless the close() method is called explicitly.\nRule of thumb. Open, use and close cursors in as ... | [
19
] | [
"Python's memory is managed by a garbage collector. In general, there shouldn't be a problem with memory leaking (definitely not for Python2.5 and above), unless you happen to be writing extension modules in C/C++. In that case, Valgrind (Blog post -http://bruynooghe.blogspot.com/2008/12/finding-memory-leaks-in-pyt... | [
-1
] | [
"debugging",
"memory_leaks",
"python",
"twisted"
] | stackoverflow_0000532346_debugging_memory_leaks_python_twisted.txt |
Q:
How do I layout a 3 pane window using wxPython?
I am trying to find a simple way to layout a 3 pane window using wxPython.
I want to have a tree list in the left pane, then have a right pane that is split into two - with an edit component in the top part and a grid component in the bottom part.
Something along the... | How do I layout a 3 pane window using wxPython? | I am trying to find a simple way to layout a 3 pane window using wxPython.
I want to have a tree list in the left pane, then have a right pane that is split into two - with an edit component in the top part and a grid component in the bottom part.
Something along the lines of:
--------------------------------------
| ... | [
"This is a very simple layout using wx.aui and three panels. I guess you can easily adapt it to suit your needs.\nOrjanp...\nimport wx\nimport wx.aui\n\nclass MyFrame(wx.Frame):\n def __init__(self, *args, **kwargs):\n wx.Frame.__init__(self, *args, **kwargs)\n\n self.mgr = wx.aui.AuiManager(self)\... | [
8,
7,
3,
2
] | [] | [] | [
"elasticlayout",
"layout",
"python",
"wxpython"
] | stackoverflow_0000523363_elasticlayout_layout_python_wxpython.txt |
Q:
In python 2.4, how can I execute external commands with csh instead of bash?
Without using the new 2.6 subprocess module, how can I get either os.popen or os.system to execute my commands using the tcsh instead of bash? I need to source some scripts which are written in tcsh before executing some other commands a... | In python 2.4, how can I execute external commands with csh instead of bash? | Without using the new 2.6 subprocess module, how can I get either os.popen or os.system to execute my commands using the tcsh instead of bash? I need to source some scripts which are written in tcsh before executing some other commands and I need to do this within python2.4.
EDIT
Thanks for answers using 'tcsh -c', bu... | [
"Just prefix the shell as part of your command. I don't have tcsh installed but with zsh:\n>>> os.system (\"zsh -c 'echo $0'\")\nzsh\n0\n\n",
"How about:\n>>> os.system(\"tcsh your_own_script\")\n\nOr just write the script and add\n#!/bin/tcsh\n\nat the beginning of the file and let the OS take care of that.\n"
] | [
11,
5
] | [
"Just set the shell to use to be tcsh:\n>>> os.environ['SHELL'] = 'tcsh'\n>>> os.environ['SHELL']\n'tcsh'\n>>> os.system(\"echo $SHELL\")\ntcsh\n\n"
] | [
-1
] | [
"csh",
"python",
"shell",
"tcsh"
] | stackoverflow_0000533398_csh_python_shell_tcsh.txt |
Q:
How do I use the Django ORM to query this many-to-many example?
I have the following models:
class Author(models.Model):
author_name = models.CharField()
class Book(models.Model):
book_name = models.CharField()
class AuthorBook(models.Model):
author_id = models.ForeignKeyField(Author)
book_id = models.Fo... | How do I use the Django ORM to query this many-to-many example? | I have the following models:
class Author(models.Model):
author_name = models.CharField()
class Book(models.Model):
book_name = models.CharField()
class AuthorBook(models.Model):
author_id = models.ForeignKeyField(Author)
book_id = models.ForeignKeyField(Book)
With that being said, I'm trying to emulate this... | [
"You should be able to do:\nbooks = Book.objects.filter(authorbook__author_id=1)\n\nto get a QuerySet of Book objects matching your author_id restriction.\nThe nice thing about Django is you can cook this up and play around with it in the shell. You may also find \nhttp://docs.djangoproject.com/en/dev/topics/db/qu... | [
14,
14
] | [] | [] | [
"django",
"django_orm",
"python"
] | stackoverflow_0000533726_django_django_orm_python.txt |
Q:
Disable pixmap background defined by GTK theme per application
For our (open source) fullscreen text editor we're changing background colors of gtk.Window, gtk.Fixed, etc. to custom colors. This works fine, but some GTK themes (e.g. Mac4Lin) define background pixmaps instead of background colors for some widgets. ... | Disable pixmap background defined by GTK theme per application | For our (open source) fullscreen text editor we're changing background colors of gtk.Window, gtk.Fixed, etc. to custom colors. This works fine, but some GTK themes (e.g. Mac4Lin) define background pixmaps instead of background colors for some widgets. Those background pixmaps won't go away when calling modify_bg() meth... | [
"Yes ofcourse Mac4Lin uses pixmaps for more granular appearance to match MAC look.\nWell to disable those backgroud you dont need to override it.\nif you want background pixmap as its parent's, set it as\nbg_pixmap[state] = \"<parent>\" \n\nand to disable set it as\nbg_pixmap[state] = \"<none>\"\n\n"
] | [
3
] | [] | [] | [
"gtk",
"pygtk",
"python"
] | stackoverflow_0000533321_gtk_pygtk_python.txt |
Q:
Python Applications: Can You Secure Your Code Somehow?
If there is truly a 'best' way, what is the best way to ship a python app and ensure people can't (easily) reverse engineer your algorithms/security/work in general?
If there isn't a 'best' way, what are the different options available?
Background:
I love codi... | Python Applications: Can You Secure Your Code Somehow? | If there is truly a 'best' way, what is the best way to ship a python app and ensure people can't (easily) reverse engineer your algorithms/security/work in general?
If there isn't a 'best' way, what are the different options available?
Background:
I love coding in Python and would love to release more apps with it. O... | [
"Security through obscurity never works. If you must use a proprietary license, enforce it through the law, not half-baked obfuscation attempts.\nIf you're worried about them learning your security (e.g. cryptography) algorithm, the same applies. Real, useful, security algorithms (like AES) are secure even though... | [
13,
8,
5,
3,
1
] | [] | [] | [
"python",
"reverse_engineering",
"security"
] | stackoverflow_0000475216_python_reverse_engineering_security.txt |
Q:
Is there an easy way to send SCSI passthrough on OSX using native python
On Windows I am able to sent SCSI passthrough to devices using win32file.DeviceIOControl(..), on UN*X I can do it using fnctl.ioctl(...).
I have been searching for something equivalent in OSX that would allow me to send the IOCTL commands usi... | Is there an easy way to send SCSI passthrough on OSX using native python | On Windows I am able to sent SCSI passthrough to devices using win32file.DeviceIOControl(..), on UN*X I can do it using fnctl.ioctl(...).
I have been searching for something equivalent in OSX that would allow me to send the IOCTL commands using only native python.
I would to send commands to hard drives specifically, n... | [
"I saw this blog post recently talking about using SCSI passthrough under OS X. Looks like it isn't as easy as Windows or Unix\n"
] | [
1
] | [] | [] | [
"macos",
"python"
] | stackoverflow_0000445980_macos_python.txt |
Q:
Outputting data a row at a time from mysql using sqlalchemy
I want to fetch data from a mysql database using sqlalchemy and use the data in a different class.. Basically I fetch a row at a time, use the data, fetch another row, use the data and so on.. I am running into some problem doing this..
Basically, how do... | Outputting data a row at a time from mysql using sqlalchemy | I want to fetch data from a mysql database using sqlalchemy and use the data in a different class.. Basically I fetch a row at a time, use the data, fetch another row, use the data and so on.. I am running into some problem doing this..
Basically, how do I output data a row at a time from mysql data?.. I have looked i... | [
"Exactly what problems are you running into?\nYou can simply iterate over the ResultProxy object:\n\nfor row in conn_or_sess_or_engine.execute(selectable_obj_or_SQLstring):\n do_something_with(row)\n\n",
"From what I understand, you're interested in something like this:\n# s is object returned by the .select() ... | [
1,
0
] | [] | [] | [
"mysql",
"python",
"sqlalchemy"
] | stackoverflow_0000536051_mysql_python_sqlalchemy.txt |
Q:
How can I create a tag in Jinja that contains values from later in the template?
I'm using Jinja2, and I'm trying to create a couple tags that work together, such that if I have a template that looks something like this:
{{ my_summary() }}
... arbitrary HTML ...
{{ my_values('Tom', 'Dick', 'Harry') }}
... arbitrar... | How can I create a tag in Jinja that contains values from later in the template? | I'm using Jinja2, and I'm trying to create a couple tags that work together, such that if I have a template that looks something like this:
{{ my_summary() }}
... arbitrary HTML ...
{{ my_values('Tom', 'Dick', 'Harry') }}
... arbitrary HTML ...
{{ my_values('Fred', 'Barney') }}
I'd end up with the following:
This page... | [
"Disclaimer: I do not know Jinja.\nMy guess is that you cannot (easily) accomplish this.\nI would suggest the following alternative:\n\nPass the Tom, Dick, etc. values as variables to the template from the outside.\nLet your custom tags take the values as arguments.\nI do not know what \"the outside\" would be in y... | [
4
] | [] | [] | [
"jinja2",
"python",
"templating"
] | stackoverflow_0000535743_jinja2_python_templating.txt |
Q:
python, funny business with threads and IDEs?
Maybe i cant do what i want? I want to have 1 thread do w/e it wants and a 2nd thread to recv user input to set the quit flag. using this code i want to enter q anytime to quit or have it timeout after printing hey 6 times
import sys
import threading
import time
class... | python, funny business with threads and IDEs? | Maybe i cant do what i want? I want to have 1 thread do w/e it wants and a 2nd thread to recv user input to set the quit flag. using this code i want to enter q anytime to quit or have it timeout after printing hey 6 times
import sys
import threading
import time
class MyThread ( threading.Thread ):
def run (s):
... | [
"The problem here is that raw_input waits for an enter to flush the input stream; check out its documentation. PyScripter is probably seeing that the program is waiting for an input and giving you an input box (don't know for sure, never used it.)\nThe program works exactly as I expect it to from the command line; ... | [
2
] | [] | [] | [
"ide",
"multithreading",
"python"
] | stackoverflow_0000537196_ide_multithreading_python.txt |
Q:
How would you set up a python web server with multiple vhosts?
I've been told wsgi is the way to go and not mod_python. But more specifically, how would you set up your multi website server environment? Choice of web server, etc?
A:
Apache+mod_wsgi is a common choice.
Here's a simple example vhost, setup up to m... | How would you set up a python web server with multiple vhosts? | I've been told wsgi is the way to go and not mod_python. But more specifically, how would you set up your multi website server environment? Choice of web server, etc?
| [
"Apache+mod_wsgi is a common choice.\nHere's a simple example vhost, setup up to map any requests for /wsgi/something to the application (which can then look at PATH_INFO to choose an action, or however you are doing your dispatching). The root URL '/' is also routed to the WSGI application.\nLoadModule wsgi_module... | [
4,
1,
0
] | [] | [] | [
"environment",
"python",
"webserver",
"wsgi"
] | stackoverflow_0000537399_environment_python_webserver_wsgi.txt |
Q:
How can I create multiple hashes of a file using only one pass?
How can I get a MD5, SHA and other hashes from a file but only doing one pass? I have 100mb files, so I'd hate to process those 100MB files multiple times.
A:
Something like this perhaps?
>>> import hashlib
>>> hashes = (hashlib.md5(), hashlib.sha1(... | How can I create multiple hashes of a file using only one pass? | How can I get a MD5, SHA and other hashes from a file but only doing one pass? I have 100mb files, so I'd hate to process those 100MB files multiple times.
| [
"Something like this perhaps?\n>>> import hashlib\n>>> hashes = (hashlib.md5(), hashlib.sha1())\n>>> f = open('some_file', 'r')\n>>> for line in f:\n... for hash in hashes:\n... hash.update(line)\n... \n>>> for hash in hashes:\n... print hash.name, hash.hexdigest()\n\nor loop over f.read(1024) or so... | [
15,
8,
3
] | [] | [] | [
"hash",
"python"
] | stackoverflow_0000537542_hash_python.txt |
Q:
How to scale an image without occasionally inverting it (with the Python Imaging Library)
When resizing images along the lines shown in this question occasionally the resulting image is inverted. About 1% of the images I resize are inverted, the rest is fine. So far I was unable to find out what is different about... | How to scale an image without occasionally inverting it (with the Python Imaging Library) | When resizing images along the lines shown in this question occasionally the resulting image is inverted. About 1% of the images I resize are inverted, the rest is fine. So far I was unable to find out what is different about these images.
See resized example and original image for examples.
Any suggestions on how to t... | [
"I was finally able to find someone experienced in JPEG and with some additional knowledge was able to find a solution.\n\nJPEG is a very underspecified\nFormat.\nThe second image is a valid JPEG but it is in CMYK color space, not in RGB color space.\nDesign minded tools (read: things from Apple) can process CMYK J... | [
3,
2
] | [] | [] | [
"image_processing",
"python",
"python_imaging_library"
] | stackoverflow_0000523503_image_processing_python_python_imaging_library.txt |
Q:
Background Image on Jython GUI
I am trying to create a GUI in Jython. I want to import a background image that I can place buttons and textfields on. I've already created the frame with the buttons and labels in their appropriate places, I just need to know how to import a background image. The GUI is implemented ... | Background Image on Jython GUI | I am trying to create a GUI in Jython. I want to import a background image that I can place buttons and textfields on. I've already created the frame with the buttons and labels in their appropriate places, I just need to know how to import a background image. The GUI is implemented in Jython.
| [
"Take a look at the Java swing material, essentially you are just using the same api in python syntax. This might help: http://forums.sun.com/thread.jspa?threadID=599393\n"
] | [
1
] | [] | [] | [
"jython",
"python"
] | stackoverflow_0000539313_jython_python.txt |
Q:
Namespace Specification In Absence of Ambuguity
Why do some languages, like C++ and Python, require the namespace of an object be specified even when no ambiguity exists? I understand that there are backdoors to this, like using namespace x in C++, or from x import * in Python. However, I can't understand the ra... | Namespace Specification In Absence of Ambuguity | Why do some languages, like C++ and Python, require the namespace of an object be specified even when no ambiguity exists? I understand that there are backdoors to this, like using namespace x in C++, or from x import * in Python. However, I can't understand the rationale behind not wanting the language to just "do t... | [
"One reason is to protect against accidentally introducing a conflict when you change the code (or for an external module/library, when someone else changes it) later on. For example, in Python you can write\nfrom foo import *\nfrom bar import *\n\nwithout conflicts if you know that modules foo and bar don't have a... | [
11,
11,
5,
4,
1,
1,
0,
0
] | [] | [] | [
"c++",
"language_design",
"namespaces",
"python"
] | stackoverflow_0000539578_c++_language_design_namespaces_python.txt |
Q:
adding scrollbars to pythoncard application
scrollingwindow as main frame for the application is not supported yet for pythoncard. how can i add scrollbars to main frame(background)?
A:
Ive never used pythoncard but in pure wxpython you can just put a ScrolledWindow inside the frame, then use a sizer to controll... | adding scrollbars to pythoncard application | scrollingwindow as main frame for the application is not supported yet for pythoncard. how can i add scrollbars to main frame(background)?
| [
"Ive never used pythoncard but in pure wxpython you can just put a ScrolledWindow inside the frame, then use a sizer to controll the scrollbars (asumming the contents of the sizer dont fit in the window). Eg this short code snipit will give you a window with a vertical scrollbar.\nclass Scrolled(wx.ScrolledWindow):... | [
2
] | [] | [] | [
"python",
"pythoncard",
"scroll",
"wxpython"
] | stackoverflow_0000469219_python_pythoncard_scroll_wxpython.txt |
Q:
Python Imaging Library and JPEGs on MacOsX
I've gotten a hold of Python Imaging Library (PIL) and installed the PNG support stuff just fine. I am however having issues with theJPEG Library.
The default setting for it is nothing but they suggest "/home/libraries/jpeg-6b". On the Mac that directory doesn't exist, th... | Python Imaging Library and JPEGs on MacOsX | I've gotten a hold of Python Imaging Library (PIL) and installed the PNG support stuff just fine. I am however having issues with theJPEG Library.
The default setting for it is nothing but they suggest "/home/libraries/jpeg-6b". On the Mac that directory doesn't exist, the library is however installed fine, here's the ... | [
"For me, the only way to have working Python + PIL on OS X was to install both from ports. I've never managed to get fully functional PIL under either system Python or installed manually from python.org. Maybe you could try this approach?\n"
] | [
5
] | [] | [] | [
"jpeg",
"macos",
"python",
"python_imaging_library"
] | stackoverflow_0000540991_jpeg_macos_python_python_imaging_library.txt |
Q:
Does anyone know of a python based web ui for snmp monitoring?
Comparable to cacti or mrtg.
A:
http://www.zenoss.com/
This is a lot more than just SNMP but it is based on Python.
A:
or you can start building your own solution (like me), you will be surprised how much can you do with few lines of code using for... | Does anyone know of a python based web ui for snmp monitoring? | Comparable to cacti or mrtg.
| [
"http://www.zenoss.com/\nThis is a lot more than just SNMP but it is based on Python.\n",
"or you can start building your own solution (like me), you will be surprised how much can you do with few lines of code using for instance cherryp for web server, pysnmp, and python rrd module.\n"
] | [
3,
0
] | [] | [] | [
"django",
"pylons",
"python",
"snmp",
"turbogears"
] | stackoverflow_0000310759_django_pylons_python_snmp_turbogears.txt |
Q:
C to Python via SWIG: can't get void** parameters to hold their value
I have a C interface that looks like this (simplified):
extern bool Operation(void ** ppData);
extern float GetFieldValue(void* pData);
extern void Cleanup(p);
which is used as follows:
void * p = NULL;
float theAnswer = 0.0f;
if (Operation(&p)... | C to Python via SWIG: can't get void** parameters to hold their value | I have a C interface that looks like this (simplified):
extern bool Operation(void ** ppData);
extern float GetFieldValue(void* pData);
extern void Cleanup(p);
which is used as follows:
void * p = NULL;
float theAnswer = 0.0f;
if (Operation(&p))
{
theAnswer = GetFieldValue(p);
Cleanup(p);
}
You'll note that Ope... | [
"I agree with theller, you should use ctypes instead. It's always easier than thinking about typemaps.\nBut, if you're dead set on using swig, what you need to do is make a typemap for void** that RETURNS the newly allocated void*:\n%typemap (in,numinputs=0) void** (void *temp)\n{\n $1 = &temp;\n}\n\n%typemap (a... | [
7,
4
] | [] | [] | [
"c",
"python",
"swig",
"word_wrap"
] | stackoverflow_0000540427_c_python_swig_word_wrap.txt |
Q:
SCons problem - dont understand Variables class
I'm working on an SConstruct build file for a project and I'm trying to update from Options to Variables, since Options is being deprecated. I don't understand how to use Variables though. I have 0 python experience which is probably contributing to this.
For example... | SCons problem - dont understand Variables class | I'm working on an SConstruct build file for a project and I'm trying to update from Options to Variables, since Options is being deprecated. I don't understand how to use Variables though. I have 0 python experience which is probably contributing to this.
For example, I have this:
opts = Variables()
opts.Add('fcgi',0)
... | [
"Typically you would store the variables in your environment for later testing.\nopts = Variables()\nopts.Add('fcgi',0)\nenv = Environment(variables=opts, ...)\n\nThen later you can test:\nif env['fcgi'] == 0:\n # do something\n\n",
"That specific error tells you that class Variables hasn't implemented python'... | [
5,
1
] | [] | [] | [
"python",
"scons",
"variables"
] | stackoverflow_0000456100_python_scons_variables.txt |
Q:
Custom django widget - decompress() arg not populated
As an exercise I am trying to create a custom django widget for a 24 hour clock. The widget will is a MultiWidget - a select box for each field.
I am trying to follow docs online (kinda sparse) and looking at the Pro Django book, but I can't seem to figure it o... | Custom django widget - decompress() arg not populated | As an exercise I am trying to create a custom django widget for a 24 hour clock. The widget will is a MultiWidget - a select box for each field.
I am trying to follow docs online (kinda sparse) and looking at the Pro Django book, but I can't seem to figure it out. Am I on the right track? I can save my data from the fo... | [
"Note this line in the docstring for MultiWidget:\n\nYou'll probably want to use this class with MultiValueField.\n\nThat's the root of your problem. You might be able to get the single-widget-only approach working (Marty says it's possible in Pro Django, but I've never tried it, and I think it's likely to be more... | [
4,
0
] | [] | [] | [
"django",
"field",
"forms",
"python",
"widget"
] | stackoverflow_0000539899_django_field_forms_python_widget.txt |
Q:
Invoking built-in operators indirectly in Python
Let's say you have a small calculator program that takes numbers and an operator to perform on those numbers as input, then prints out the result of applying the specified operation. So if you input "4 + 5" it will print out "9". Simple, right? Well what I want to b... | Invoking built-in operators indirectly in Python | Let's say you have a small calculator program that takes numbers and an operator to perform on those numbers as input, then prints out the result of applying the specified operation. So if you input "4 + 5" it will print out "9". Simple, right? Well what I want to be able to write is something this:
a, op, b = raw_inpu... | [
"Basically no, you will at least need to have a dictionary or function to map operator characters to their implementations. It's actually a little more complicated than that, since not all operators take the form a [op] b, so in general you'd need to do a bit of parsing; see https://docs.python.org/library/operator... | [
7,
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0000542987_python.txt |
Q:
Python string formatting
I see you guys using
url = '"%s"' % url # This part
>>> url = "http://www.site.com/info.xx"
>>> print url
http://www.site.com/info.xx
>>> url = '"%s"' % url
>>> print url
"http://www.site.com/info.xx"
Is it advanced Python? Is there a tutorial for it? How can I learn about it?
A:
It's ... | Python string formatting | I see you guys using
url = '"%s"' % url # This part
>>> url = "http://www.site.com/info.xx"
>>> print url
http://www.site.com/info.xx
>>> url = '"%s"' % url
>>> print url
"http://www.site.com/info.xx"
Is it advanced Python? Is there a tutorial for it? How can I learn about it?
| [
"It's common string formatting, and very useful. It's analogous to C-style printf formatting. See String Formatting Operations in the Python.org docs. You can use multiple arguments like this:\n\"%3d\\t%s\" % (42, \"the answer to ...\")\n\n",
"That line of code is using Python string formatting. You can read up ... | [
16,
8,
0
] | [] | [] | [
"python"
] | stackoverflow_0000543399_python.txt |
Q:
Struct with a pointer to its own type in ctypes
I'm trying to map a struct definition using ctypes:
struct attrl {
struct attrl *next;
char *name;
char *resource;
char *value;
};
I'm unsure what to do with the "next" fi... | Struct with a pointer to its own type in ctypes | I'm trying to map a struct definition using ctypes:
struct attrl {
struct attrl *next;
char *name;
char *resource;
char *value;
};
I'm unsure what to do with the "next" field of the struct in the ctypes mapping. A definition... | [
"You need the equivalent of a forward declaration, as described here.\n"
] | [
4
] | [] | [] | [
"ctypes",
"python"
] | stackoverflow_0000543483_ctypes_python.txt |
Q:
memory use in large data-structures manipulation/processing
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... | memory use in large data-structures manipulation/processing | 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(filename... | [
"I'd suggest looking at the presentation by David Beazley 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 efficiently as possible; the trick is... | [
7,
3,
3,
2,
1,
1
] | [] | [] | [
"data_structures",
"garbage_collection",
"memory_leaks",
"python"
] | stackoverflow_0000512893_data_structures_garbage_collection_memory_leaks_python.txt |
Q:
Programmatically stop execution of python script?
Is it possible to stop execution of a python script at any line with a command?
Like
some code
quit() # quit at this point
some more code (that's not executed)
A:
sys.exit() will do exactly what you want.
import sys
sys.exit("Error message")
A:
You could rais... | Programmatically stop execution of python script? | Is it possible to stop execution of a python script at any line with a command?
Like
some code
quit() # quit at this point
some more code (that's not executed)
| [
"sys.exit() will do exactly what you want.\nimport sys\nsys.exit(\"Error message\")\n\n",
"You could raise SystemExit(0) instead of going to all the trouble to import sys; sys.exit(0).\n",
"You want sys.exit(). From Python's docs:\n >>> import sys\n >>> print sys.exit.__doc__\n exit([status])\n\nExit t... | [
442,
173,
43,
24
] | [] | [] | [
"python"
] | stackoverflow_0000543309_python.txt |
Q:
How to Install Satchmo in Windows?
I'm working on a Django project that's slated to be using Satchmo for its e-commerce aspects. I'd like to install it on my Windows Vista machine but some of the cPython modules it needs can't be compiled or easy_installed.
Has anyone been able to get Satchmo working on Windows, ... | How to Install Satchmo in Windows? | I'm working on a Django project that's slated to be using Satchmo for its e-commerce aspects. I'd like to install it on my Windows Vista machine but some of the cPython modules it needs can't be compiled or easy_installed.
Has anyone been able to get Satchmo working on Windows, and if so, what additional steps does it... | [
"Which modules are you having trouble with? \nPycrypto binaries are here - http://www.voidspace.org.uk/python/modules.shtml#pycrypto\nPython Imaging binaries are here - http://www.pythonware.com/products/pil/\nI believe everything else is pure python so it should be pretty simple to install the rest.\n"
] | [
3
] | [] | [] | [
"django",
"python",
"satchmo",
"windows",
"windows_vista"
] | stackoverflow_0000540046_django_python_satchmo_windows_windows_vista.txt |
Q:
python sleep == IDE lock up
When my script sleeps for 50sec my IDE locks up which is very annoying. I cant switch tabs, look through my source, type code, etc. It happens in pylde and pyscripter, i havent tried other IDEs. What can i do to fix this? i'm actually doing
for i in range(0, timeInSeconds): time.sleep(... | python sleep == IDE lock up | When my script sleeps for 50sec my IDE locks up which is very annoying. I cant switch tabs, look through my source, type code, etc. It happens in pylde and pyscripter, i havent tried other IDEs. What can i do to fix this? i'm actually doing
for i in range(0, timeInSeconds): time.sleep(1)
hoping the IDE will update o... | [
"I'm assuming you are running your code from within the IDE?\nYour IDE is probably blocking while running your code. Look for a setting of some sort which might control that behaviour, otherwise I think your only choice would be to change IDE. (Or, run your code from outside the IDE)\n",
"Can you configure to run... | [
2,
0,
0,
0,
0
] | [] | [] | [
"ide",
"lockup",
"python"
] | stackoverflow_0000535973_ide_lockup_python.txt |
Q:
Kerberos authentication with python
I need to write a script in python to check a webpage, which is protected by kerberos. Is there any possibility to do this from within python and how? The script is going to be deployed on a linux environment with python 2.4.something installed.
dertoni
A:
I think that python-... | Kerberos authentication with python | I need to write a script in python to check a webpage, which is protected by kerberos. Is there any possibility to do this from within python and how? The script is going to be deployed on a linux environment with python 2.4.something installed.
dertoni
| [
"I think that python-krbV and most Linux distributions also have a python-kerberos package. For example, Debian has one of the same name. Here's the documentation on it\nExtract from link:\n\n\"This Python package is a high-level wrapper for Kerberos (GSSAPI)\n operations. The goal is to avoid having to build a mo... | [
15
] | [] | [] | [
"kerberos",
"python",
"security"
] | stackoverflow_0000545294_kerberos_python_security.txt |
Q:
Using different versions of python for different projects in Eclipse
So, I'm slowly working in some Python 3.0, but I still have a lot of things that rely on 2.5.
But, in Eclipse, every time I change projects between a 3.0 and a 2.5, I need to go through
Project -> Properties -> project type.
Issue 1: if I just ... | Using different versions of python for different projects in Eclipse | So, I'm slowly working in some Python 3.0, but I still have a lot of things that rely on 2.5.
But, in Eclipse, every time I change projects between a 3.0 and a 2.5, I need to go through
Project -> Properties -> project type.
Issue 1: if I just switch the interpreter in the drop down box, that doesn't seem to change a... | [
"You can set the interpreter version on a per-script basis through the Run Configurations menu.\nTo do this go to Run -> Run Configurations, and then make a new entry under Python Run. Fill in your project name and the main script, and then go to the Interpeter tab and you can pick which interpreter you want to use... | [
11,
1
] | [] | [] | [
"eclipse",
"python"
] | stackoverflow_0000543466_eclipse_python.txt |
Q:
practice with threads in python
I know that Python has a global lock and i've read Glyph's explaination of python multithreading. But I still want to try it out. What I decided to do as an easy (conceptually) task was to do horizontal and vertical edge detection on a picture.
Here's what's happening (pseudocode):... | practice with threads in python | I know that Python has a global lock and i've read Glyph's explaination of python multithreading. But I still want to try it out. What I decided to do as an easy (conceptually) task was to do horizontal and vertical edge detection on a picture.
Here's what's happening (pseudocode):
for pixels in picture:
apply sob... | [
"Python 2.6 now includes the mulitprocessing module (formerly processing module on older versions of Python). \nIt has essentially the same interface as the threading module, but launches the execution into separate processes rather than threads. This allows Python to take advantage of multiple cores/CPUs and scale... | [
7,
3,
2,
0,
0
] | [] | [] | [
"image_manipulation",
"multithreading",
"python"
] | stackoverflow_0000535331_image_manipulation_multithreading_python.txt |
Q:
Does python support multiprocessor/multicore programming?
What is the difference between multiprocessor programming and multicore programming?
Preferably show examples in python how to write a small program for multiprocessor programming & multicore programming
A:
There is no such thing as "multiprocessor" or "m... | Does python support multiprocessor/multicore programming? | What is the difference between multiprocessor programming and multicore programming?
Preferably show examples in python how to write a small program for multiprocessor programming & multicore programming
| [
"There is no such thing as \"multiprocessor\" or \"multicore\" programming. The distinction between \"multiprocessor\" and \"multicore\" computers is probably not relevant to you as an application programmer; it has to do with subtleties of how the cores share access to memory.\nIn order to take advantage of a mul... | [
97,
24,
5,
2,
2,
1,
0
] | [] | [] | [
"multicore",
"python"
] | stackoverflow_0000203912_multicore_python.txt |
Q:
Mapping a global variable from a shared library with ctypes
I'd like to map an int value pbs_errno declared as a global in the library libtorque.so using ctypes.
Currently I can load the library like so:
from ctypes import *
libtorque = CDLL("libtorque.so")
and have successfully mapped a bunch of the functions. H... | Mapping a global variable from a shared library with ctypes | I'd like to map an int value pbs_errno declared as a global in the library libtorque.so using ctypes.
Currently I can load the library like so:
from ctypes import *
libtorque = CDLL("libtorque.so")
and have successfully mapped a bunch of the functions. However, for error checking purposes many of them set the pbs_errn... | [
"There's a section in the ctypes docs about accessing values exported in dlls:\nhttp://docs.python.org/library/ctypes.html#accessing-values-exported-from-dlls\ne.g.\n\ndef pbs_errno():\n return c_int.in_dll(libtorque, \"pbs_errno\")\n\n"
] | [
20
] | [] | [] | [
"ctypes",
"python"
] | stackoverflow_0000544173_ctypes_python.txt |
Q:
two questions (RFC822, login info) about sending email via python
1 -
In my email-sending script, I store spaced-out emails in a string, then I use ", ".join(to.split()). However, it looks like the script only sends to the 1st email - is it something to do with RFC822 format? If so, how can I fix this?
2 -
I feel ... | two questions (RFC822, login info) about sending email via python | 1 -
In my email-sending script, I store spaced-out emails in a string, then I use ", ".join(to.split()). However, it looks like the script only sends to the 1st email - is it something to do with RFC822 format? If so, how can I fix this?
2 -
I feel a bit edgy having my password visable in my script. Is there a way to r... | [
"Use ', '.join() for the list in the To: or Cc: header, but the headers are only for show. What determines where the mail actually goes is the RCPT envelope. Assuming you're using smtplib, that's the second argument:\nconnection.sendmail(senderaddress, to.split(), mailtext)\n\n2: it's possible, but far from straigh... | [
3,
2
] | [] | [] | [
"passwords",
"python",
"rfc822",
"smtp"
] | stackoverflow_0000543096_passwords_python_rfc822_smtp.txt |
Q:
Is there a better way (besides COM) to remote-control Excel?
I'm working on a regression-testing tool that will validate a very large number of Excel spreadsheets. At the moment I control them via COM from a Python script using the latest version of the pywin32 product. Unfortunately COM seems to have a number of ... | Is there a better way (besides COM) to remote-control Excel? | I'm working on a regression-testing tool that will validate a very large number of Excel spreadsheets. At the moment I control them via COM from a Python script using the latest version of the pywin32 product. Unfortunately COM seems to have a number of annoying drawbacks:
For example, the slightest upset seems to be a... | [
"There is no way that completely bypasses COM. You can use VSTO (Visual Studio Tools for Office), which has nice .NET wrappers on the COM objects, but it is still COM underneath. \n",
"\nThe Excel COM interface will not allow me to safely remote-control two seperate instances of the Excel application operating ... | [
7,
2,
1,
1,
1
] | [] | [] | [
".net",
"com",
"excel",
"python"
] | stackoverflow_0000528817_.net_com_excel_python.txt |
Q:
How Do I Perform Introspection on an Object in Python 2.x?
I'm using Python 2.x and I have an object I'm summoning from the aether; the documentation on it is not particularly clear. I would like to be able to get a list of properties for that object and the type of each property.
Similarly, I'd like to get a l... | How Do I Perform Introspection on an Object in Python 2.x? | I'm using Python 2.x and I have an object I'm summoning from the aether; the documentation on it is not particularly clear. I would like to be able to get a list of properties for that object and the type of each property.
Similarly, I'd like to get a list of methods for that object, as well, plus any other informat... | [
"Well ... Your first stop will be a simple dir(object). This will show you all the object's members, both fields and methods. Try it in an interactive Python shell, and play around a little.\nFor instance:\n> class Foo:\n def __init__(self):\n self.a = \"bar\"\n self.b = 4711\n\n> a=Foo()\n> dir(a)\n['__doc... | [
25,
9,
5,
4,
0
] | [] | [] | [
"introspection",
"python",
"python_datamodel"
] | stackoverflow_0000546337_introspection_python_python_datamodel.txt |
Q:
Generating lists/reports with in-line summaries in Django
I am trying to write a view that will generate a report which displays all Items within my Inventory system, and provide summaries at a certain point. This report is purely just an HTML template by the way.
In my case, each Item is part of an Order. An Orde... | Generating lists/reports with in-line summaries in Django | I am trying to write a view that will generate a report which displays all Items within my Inventory system, and provide summaries at a certain point. This report is purely just an HTML template by the way.
In my case, each Item is part of an Order. An Order can have several items, and I want to be able to display SUM ... | [
"Subtotals are SELECT SUM(qty) GROUP BY order_number things.\nThey are entirely separate from a query to get details.\nThe results of the two queries need to be interleaved. A good way to do this is to create each order as a tuple ( list_of_details, appropriate summary ).\nThen the display is easy\n{% for order in... | [
3,
1,
1
] | [] | [] | [
"django",
"list",
"python",
"report"
] | stackoverflow_0000546385_django_list_python_report.txt |
Q:
Send Info from Script to Module Python
Hi I wonder how you can send info over to a module
An Example
main.py Looks like this
from module import *
print helloworld()
module.py looks like this
def helloworld():
print "Hello world!"
Anyway i want to send over info from main.py to module.py is it possible?
... | Send Info from Script to Module Python | Hi I wonder how you can send info over to a module
An Example
main.py Looks like this
from module import *
print helloworld()
module.py looks like this
def helloworld():
print "Hello world!"
Anyway i want to send over info from main.py to module.py is it possible?
| [
"It is not clear what you mean by \"send info\", but if you but the typical way of passing a value would be with a function parameter.\nmain.py:\nhelloworld(\"Hello world!\")\n\nmodule.py\ndef helloworld(message):\n print message\n\nIs that what your looking for? Also the two uses of print in your example are r... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0000547450_python.txt |
Q:
problem ordering by votes with django-voting
I have a model Post, and a model Vote. Vote (form django-voting) is essentially just a pointer to a Post and -1, 0, or 1.
There is also Tourn, which is a start date and an end date. A Post made between the start and end of a Tourn is submitted to that tournament.
For t... | problem ordering by votes with django-voting | I have a model Post, and a model Vote. Vote (form django-voting) is essentially just a pointer to a Post and -1, 0, or 1.
There is also Tourn, which is a start date and an end date. A Post made between the start and end of a Tourn is submitted to that tournament.
For the sake of rep calculation, I'm trying to find the... | [
"I think you need to assign posts to the return value of posts.extra():\nposts = posts.extra(select={'score': \"\"\"\n SELECT SUM(vote)\n FROM %s\n WHERE content_type_id = %s\n AND object_id = %s.id\n AND voted_at > DATE(... | [
3
] | [] | [] | [
"django",
"django_voting",
"python"
] | stackoverflow_0000544597_django_django_voting_python.txt |
Q:
Python using result of function for Regular Expression Substitution
I have a block of text, and for every regex match, I want to substitute that match with the return value from another function. The argument to this function is of course the matched text.
I have been having trouble trying to come up with a one p... | Python using result of function for Regular Expression Substitution | I have a block of text, and for every regex match, I want to substitute that match with the return value from another function. The argument to this function is of course the matched text.
I have been having trouble trying to come up with a one pass solution to this problem. It feels like it should be pretty simple.
| [
"Right from the documentation:\n>>> def dashrepl(matchobj):\n... if matchobj.group(0) == '-': return ' '\n... else: return '-'\n>>> re.sub('-{1,2}', dashrepl, 'pro----gram-files')\n'pro--gram files'\n\n",
"Python-agnostic: Match everything before and everything after your text to replace.\n/^(.*?)(your r... | [
14,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0000547798_python_regex.txt |
Q:
dead simple Django file uploading not working :-((
I am trying desperately to do a very simple file upload with Django, without (for now) bothering with templating & co.
My HTML is:
<form
id="uploader"
action="bytes/"
enctype="multipart/form-data"
method="post"
>
<input type="fi... | dead simple Django file uploading not working :-(( | I am trying desperately to do a very simple file upload with Django, without (for now) bothering with templating & co.
My HTML is:
<form
id="uploader"
action="bytes/"
enctype="multipart/form-data"
method="post"
>
<input type="file" name="uploaded"/>
<input type="submit" value="... | [
"Try changing \"if 'uploaded' in request.FILES:\" to \"if request.FILES\".\nYou might want to take a look at the documentation as well; there's an example-- http://docs.djangoproject.com/en/dev/topics/http/file-uploads/\n"
] | [
6
] | [] | [] | [
"django",
"python",
"upload"
] | stackoverflow_0000547743_django_python_upload.txt |
Q:
Obtaining all possible states of an object for a NP-Complete(?) problem in Python
Not sure that the example (nor the actual usecase) qualifies as NP-Complete, but I'm wondering about the most Pythonic way to do the below assuming that this was the algorithm available.
Say you have :
class Person:
def __init__(se... | Obtaining all possible states of an object for a NP-Complete(?) problem in Python | Not sure that the example (nor the actual usecase) qualifies as NP-Complete, but I'm wondering about the most Pythonic way to do the below assuming that this was the algorithm available.
Say you have :
class Person:
def __init__(self):
self.status='unknown'
def set(self,value):
if value:
self.status='... | [
"I think this could do it:\nl = list()\nfor i in xrange(2 ** n):\n # create the list of n people\n sublist = [None] * n\n for j in xrange(n):\n sublist[j] = Person()\n sublist[j].set(i & (1 << j))\n l.append(sublist)\n\nNote that if you wrote Person so that its constructor accepted the val... | [
2,
1,
1
] | [] | [] | [
"combinatorics",
"iteration",
"python"
] | stackoverflow_0000539676_combinatorics_iteration_python.txt |
Q:
How to adding middleware to Appengine's webapp framework?
I'm using the appengine webapp framework (link). Is it possible to add Django middleware? I can't find any examples. I'm currently trying to get the FirePython middleware to work (link).
A:
It's easy: You create the WSGI application as per normal, then ... | How to adding middleware to Appengine's webapp framework? | I'm using the appengine webapp framework (link). Is it possible to add Django middleware? I can't find any examples. I'm currently trying to get the FirePython middleware to work (link).
| [
"It's easy: You create the WSGI application as per normal, then wrap that application in your WSGI middleware before executing it.\nSee this code from Bloog to see how firepython is added as middleware.\n",
"The GAE webapp framework does not map one to one to the Django framework. It would be hard to do what you... | [
6,
0,
0
] | [] | [] | [
"django",
"django_middleware",
"google_app_engine",
"middleware",
"python"
] | stackoverflow_0000352079_django_django_middleware_google_app_engine_middleware_python.txt |
Q:
Should I use Django's contrib applications or build my own?
The Django apps come with their own features and design. If your requirements don't match 100% with the features of the contib app, you end up customizing and tweaking the app. I feel this involves more effort than just building your own app to fit your r... | Should I use Django's contrib applications or build my own? | The Django apps come with their own features and design. If your requirements don't match 100% with the features of the contib app, you end up customizing and tweaking the app. I feel this involves more effort than just building your own app to fit your requirements.
What do you think?
| [
"It all depends. We had a need for something that was 98% similar to contrib.flatpages. We could have monkeypatched it, but we decided that the code was so straightforward that we would just copy and fork it. It worked out fine.\nDoing this with contrib.auth, on the other hand, might be a bad move given its interac... | [
7,
6,
4
] | [] | [] | [
"django",
"django_contrib",
"python"
] | stackoverflow_0000542594_django_django_contrib_python.txt |
Q:
Delete Chars in Python
does anybody know how to delete all characters behind a specific character??
like this:
http://google.com/translate_t
into
http://google.com
A:
if you're asking about an abstract string and not url you could go with:
>>> astring ="http://google.com/translate_t"
>>> astring.rpartition('/'... | Delete Chars in Python | does anybody know how to delete all characters behind a specific character??
like this:
http://google.com/translate_t
into
http://google.com
| [
"if you're asking about an abstract string and not url you could go with:\n>>> astring =\"http://google.com/translate_t\"\n>>> astring.rpartition('/')[0]\nhttp://google.com\n\n",
"For urls, using urlparse:\n>>> import urlparse\n>>> parts = urlparse.urlsplit('http://google.com/path/to/resource?query=spam#anchor')\... | [
6,
5,
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0000549130_python.txt |
Q:
In the windows python console, how to make Tab = four spaces?
Hello I would like that when I am in the python
console tabbing will give me four spaces. Any ideas?
A:
Download and install AutoHotkey
Write this script:
SetTitleMatchMode 2
#IfWinActive python
tab::
Send, {SPACE}
Send, {SPACE}
Send, {SPACE}
Send, {... | In the windows python console, how to make Tab = four spaces? | Hello I would like that when I am in the python
console tabbing will give me four spaces. Any ideas?
| [
"\nDownload and install AutoHotkey\nWrite this script:\nSetTitleMatchMode 2\n#IfWinActive python\ntab::\nSend, {SPACE}\nSend, {SPACE}\nSend, {SPACE}\nSend, {SPACE}\n\n\nSave it as tab-to-space.ahk, and doubleclick on the file.\nNote: you might have to captalize \"Python\" to match your window tite. Or you can have ... | [
5
] | [] | [] | [
"python",
"windows"
] | stackoverflow_0000549340_python_windows.txt |
Q:
Python extend with an empty list bug?
Why does python 2.5.2 have the following behavior
>>>[2].extend([]) == [2]
False
>>> [2].extend([]) == None
True
$ python --version
Python 2.5.2
I assume I'm not understanding something here, but intuitively I'd think that [2].extend([]) should yield [2]
A:
Extend is a me... | Python extend with an empty list bug? | Why does python 2.5.2 have the following behavior
>>>[2].extend([]) == [2]
False
>>> [2].extend([]) == None
True
$ python --version
Python 2.5.2
I assume I'm not understanding something here, but intuitively I'd think that [2].extend([]) should yield [2]
| [
"Extend is a method of list, which modifies it but doesn't return self (returning None instead). If you need the modified value as the expression value, use +, as in [2]+[].\n",
"Exactly.\n>>> x = [2]\n>>> x.extend([]) # Nothing is printed because the return value is None\n>>> x == [2]\nTrue\n>>> x\n[2]\n\nThey d... | [
50,
14
] | [] | [] | [
"extend",
"list",
"python"
] | stackoverflow_0000549741_extend_list_python.txt |
Q:
Simple unique non-priority queue system
I'm working on a simple web crawler in python and I wan't to make a simple queue class, but I'm not quite sure the best way to start. I want something that holds only unique items to process, so that the crawler will only crawl each page once per script run (simply to avoid ... | Simple unique non-priority queue system | I'm working on a simple web crawler in python and I wan't to make a simple queue class, but I'm not quite sure the best way to start. I want something that holds only unique items to process, so that the crawler will only crawl each page once per script run (simply to avoid infinite looping). Can anyone give me or poin... | [
"I'd just use a set, it doesn't maintain order but it will help you maintain uniqueness:\n>>> q = set([9, 8, 7, 7, 8, 5, 4, 1])\n>>> q.pop()\n1\n>>> q.pop()\n4\n>>> q.pop()\n5\n>>> q.add(3)\n>>> q.add(3)\n>>> q.add(3)\n>>> q.add(3)\n>>> q\nset([3, 7, 8, 9]\n\n",
"A very simple example would be to stuff each item'... | [
4,
2,
2,
1,
0
] | [] | [] | [
"python",
"queue"
] | stackoverflow_0000549536_python_queue.txt |
Q:
Parsing "From" addresses from email text
I'm trying to extract email addresses from plain text transcripts of emails.
I've cobbled together a bit of code to find the addresses themselves, but I don't know how to make it discriminate between them; right now it just spits out all email addresses in the file. I'd li... | Parsing "From" addresses from email text | I'm trying to extract email addresses from plain text transcripts of emails.
I've cobbled together a bit of code to find the addresses themselves, but I don't know how to make it discriminate between them; right now it just spits out all email addresses in the file. I'd like to make it so it only spits out addresses t... | [
"Try this out:\n>>> from email.utils import parseaddr\n\n>>> parseaddr('From: vg@m.com')\n('', 'vg@m.com')\n\n>>> parseaddr('From: Van Gale <vg@m.com>')\n('Van Gale', 'vg@m.com')\n\n>>> parseaddr(' From: Van Gale <vg@m.com> ')\n('Van Gale', 'vg@m.com')\n\n>>> parseaddr('blah abdf From: Van Gale <vg@m.com> ... | [
40,
10,
3,
2,
2,
1,
0,
0
] | [] | [] | [
"email",
"parsing",
"python",
"string",
"text"
] | stackoverflow_0000550009_email_parsing_python_string_text.txt |
Q:
Django Model API reverse lookup of many to many relationship through intermediary table
I have a Resident and can not seem to get the set of SSA's the resident belongs to. I've tried res.ssa_set.all() .ssas_set.all() and .ssa_resident_set.all(). Can't seem to manage it. What's the syntax for a reverse m2m lookup t... | Django Model API reverse lookup of many to many relationship through intermediary table | I have a Resident and can not seem to get the set of SSA's the resident belongs to. I've tried res.ssa_set.all() .ssas_set.all() and .ssa_resident_set.all(). Can't seem to manage it. What's the syntax for a reverse m2m lookup through another table?
EDIT: I'm getting an 'QuerySet as no attribute' error. Erm?
class SSA(... | [
"I was trying to evaluate a query set object, not the object itself. Executing a get on the query set and then a lookup of the relation set worked fine. I'm changing to community wiki and leaving this here just incase someone else is as stupid as I was.\nA working example:\nresident = Resident.objects.filter(name='... | [
1
] | [] | [] | [
"django",
"django_models",
"many_to_many",
"python"
] | stackoverflow_0000550300_django_django_models_many_to_many_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.