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 discard from the middle of a list using list comprehensions?
I could do this using an index but I thought there must be a cleaner way using list comprehensions. I'm a beginner. I hope it's not embarrassingly obvious. Thanks
for x in firstList:
firstFunc(x)
secondFunc(x)
x = process(x)
if x.d... | How to discard from the middle of a list using list comprehensions? | I could do this using an index but I thought there must be a cleaner way using list comprehensions. I'm a beginner. I hope it's not embarrassingly obvious. Thanks
for x in firstList:
firstFunc(x)
secondFunc(x)
x = process(x)
if x.discard == True:
(get rid of x)
secondList.append(firstList)
| [
"Just a thought, and it does little for documentation, but why not try:\ndef masterFunc(x):\n firstFunc(x)\n secondFunc(x)\n process(x)\n return x.discard\n\nsecondList = [ x for x in firstList if masterFunc(x) ]\n\nGood news: does what you asked, strictly speaking.\nBad news: it hides firstFunc, second... | [
2,
1,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0001405883_python.txt |
Q:
Why does "enable-shared failed" happen on libjpeg build for os X?
I'm trying to install libjpeg on os X to fix a problem with the Python Imaging Library JPEG setup.
I downloaded libjpeg from http://www.ijg.org/files/jpegsrc.v7.tar.gz
I then began to setup the config file
cp /usr/share/libtool/config.sub .
cp /usr/... | Why does "enable-shared failed" happen on libjpeg build for os X? | I'm trying to install libjpeg on os X to fix a problem with the Python Imaging Library JPEG setup.
I downloaded libjpeg from http://www.ijg.org/files/jpegsrc.v7.tar.gz
I then began to setup the config file
cp /usr/share/libtool/config.sub .
cp /usr/share/libtool/config.guess .
./configure –enable-shared
However, the e... | [
"I had copied the code from a blog. \nThe flag character there was not a hyphem , it just looked like one:\nord(\"–\")\n\nTypeError: ord() expected a character, but string of length 3 found\n\nI changed it to a proper hypen and it works fine.\n"
] | [
3
] | [] | [] | [
"build",
"macos",
"python"
] | stackoverflow_0001405920_build_macos_python.txt |
Q:
Consume a Web service thought an Active Directory
I have a project in which I have to consume a web service authenticating against Active Directory. I have my system written in python3, python-ldap module is not ported yet, so I want to know a way to acheive this consumption.
In the worst case, I will create a sta... | Consume a Web service thought an Active Directory | I have a project in which I have to consume a web service authenticating against Active Directory. I have my system written in python3, python-ldap module is not ported yet, so I want to know a way to acheive this consumption.
In the worst case, I will create a standalone consumer in python2.5, but I want to know how t... | [
"I've resolved it with python-ntlm a project in google that handles ntlm for www-authentication: negotiate, http://code.google.com/p/python-ntlm/ thanks!\n"
] | [
0
] | [] | [] | [
"ldap",
"python",
"web_services"
] | stackoverflow_0001405670_ldap_python_web_services.txt |
Q:
Python: How do I convert a NonType variable to a String?
I have the following function:
>>> def rule(x):
... rule = bin(x)[2:].zfill(8)
... rule = str(rule)
... print rule
I am trying to convert rule into a string, but when I run the following command, here is what I get:
>>> type(rule(20))
00010100... | Python: How do I convert a NonType variable to a String? | I have the following function:
>>> def rule(x):
... rule = bin(x)[2:].zfill(8)
... rule = str(rule)
... print rule
I am trying to convert rule into a string, but when I run the following command, here is what I get:
>>> type(rule(20))
00010100
<type 'NoneType'>
What is a NoneType variable and how can I ... | [
"you need to do:\ndef rule(x):\n return bin(x)[2:].zfill(8)\n\nAll functions return None implicitly if no return statement was encountered during execution of the function (as it is in your case).\n",
"Your rule function doesn't return anything -- it only prints. So, rule(20) returns None -- the python object ... | [
6,
1
] | [] | [] | [
"python"
] | stackoverflow_0001407557_python.txt |
Q:
How to generate basic CRUD functionality in python given a database tables
I want to develop a desktop application using python with basic crud operation. Is there any library in python that can generate a code for CRUD functionality and user interface given a database table.
A:
Hopefully, this won't be the best... | How to generate basic CRUD functionality in python given a database tables | I want to develop a desktop application using python with basic crud operation. Is there any library in python that can generate a code for CRUD functionality and user interface given a database table.
| [
"Hopefully, this won't be the best option you end up with, but, in the tradition of using web-interfaces for desktop applications, you could always try django. I would particularLY take a look at the inspectdb command, which will generate the ORM code for you.\nThe advantage is that it won't require that much cod... | [
3,
0,
0
] | [] | [] | [
"crud",
"database",
"desktop",
"python"
] | stackoverflow_0001407016_crud_database_desktop_python.txt |
Q:
Python urllib, minidom and parsing international characters
When I try to retrieve information from Google weather API with the following URL,
http://www.google.com/ig/api?weather=Munich,Germany&hl=de
and then try to parse it with minidom, I get error that the document is not well formed.
I use following code
soc... | Python urllib, minidom and parsing international characters | When I try to retrieve information from Google weather API with the following URL,
http://www.google.com/ig/api?weather=Munich,Germany&hl=de
and then try to parse it with minidom, I get error that the document is not well formed.
I use following code
sock = urllib.urlopen(url) # above mentioned url
doc = minidom.parse... | [
"This seems to work:\nsock = urllib.urlopen(url)\n# There is a nicer way for this, but I don't remember right now:\nencoding = sock.headers['Content-type'].split('charset=')[1]\ndata = sock.read()\ndom = minidom.parseString(data.decode(encoding).encode('ascii', 'xmlcharrefreplace'))\n\nI guess minidom doesn't handl... | [
2,
1
] | [] | [] | [
"internationalization",
"minidom",
"python",
"urllib"
] | stackoverflow_0001407874_internationalization_minidom_python_urllib.txt |
Q:
Create an executable process without using shell on Python 2.5 and below
Just what the title says:
The subprocess module cannot be used as this should work on 2.4 and 2.5
Shell process should not be spawned to pass arguments.
To explain (2), consider the following code:
>>> x=os.system('foo arg')
sh: foo: not fo... | Create an executable process without using shell on Python 2.5 and below | Just what the title says:
The subprocess module cannot be used as this should work on 2.4 and 2.5
Shell process should not be spawned to pass arguments.
To explain (2), consider the following code:
>>> x=os.system('foo arg')
sh: foo: not found
>>> x=os.popen('foo arg')
sh: foo: not found
>>>
As you can see os.syste... | [
"You probably need to use the subprocess module which is available in Python 2.4\nPopen(\"/home/user/foo\" + \" arg\")\n\n>>> Popen(\"foo arg\", shell=False)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"/usr/lib/python2.6/subprocess.py\", line 595, in __init__\n errread,... | [
3,
0
] | [] | [] | [
"fork",
"popen",
"process",
"python",
"subprocess"
] | stackoverflow_0001407992_fork_popen_process_python_subprocess.txt |
Q:
Nice Python Decorators
How do I nicely write a decorator?
In particular issues include: compatibility with other decorators, preserving of signatures, etc.
I would like to avoid dependency on the decorator module if possible, but if there were sufficient advantages, then I would consider it.
Related
Preserving si... | Nice Python Decorators | How do I nicely write a decorator?
In particular issues include: compatibility with other decorators, preserving of signatures, etc.
I would like to avoid dependency on the decorator module if possible, but if there were sufficient advantages, then I would consider it.
Related
Preserving signatures of decorated functi... | [
"Use functools to preserve the name and doc. The signature won't be preserved.\nDirectly from the doc. \n>>> from functools import wraps\n>>> def my_decorator(f):\n... @wraps(f)\n... def wrapper(*args, **kwds):\n... print 'Calling decorated function'\n... return f(*args, **kwds)\n... ret... | [
6,
5
] | [] | [] | [
"decorator",
"python"
] | stackoverflow_0001408253_decorator_python.txt |
Q:
NumPy array slice using None
This had me scratching my head for a while. I was unintentionally slicing an array with None and getting something other than an error (I expected an error). Instead, it returns an array with an extra dimension.
>>> import numpy
>>> a = numpy.arange(4).reshape(2,2)
>>> a
array([[0, 1... | NumPy array slice using None | This had me scratching my head for a while. I was unintentionally slicing an array with None and getting something other than an error (I expected an error). Instead, it returns an array with an extra dimension.
>>> import numpy
>>> a = numpy.arange(4).reshape(2,2)
>>> a
array([[0, 1],
[2, 3]])
>>> a[None]
arr... | [
"Using None is equivalent to using numpy.newaxis, so yes, it's intentional. In fact, they're the same thing, but, of course, newaxis spells it out better.\nThe docs:\n\nThe newaxis object can be used in all slicing operations to create an axis of length one. newaxis is an alias for ‘None’, and ‘None’ can be used i... | [
75
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0001408311_arrays_numpy_python.txt |
Q:
send an arbitrary number of inputs from python to a .exe
p = subprocess.Popen(args = "myprog.exe" + " " +
str(input1) + " " +
str(input2) + " " +
str(input3) + " " +
strpoints, stdout = subprocess.PIPE)
in the code above, input1, ... | send an arbitrary number of inputs from python to a .exe |
p = subprocess.Popen(args = "myprog.exe" + " " +
str(input1) + " " +
str(input2) + " " +
str(input3) + " " +
strpoints, stdout = subprocess.PIPE)
in the code above, input1, input2, and input3 are all integers that get converted to str... | [
"args can be a sequence:\np = subprocess.Popen(args = [\"myprog.exe\"] + \n [str(x) for x in [input1,input2,input3]] + \n strpoints,stdout = subprocess.PIPE)\n\nThis is more correct if your arguments contain shell metacharacters e.g. ' * and you don't want them ... | [
7,
4,
1,
0
] | [] | [] | [
"executable",
"python"
] | stackoverflow_0001408326_executable_python.txt |
Q:
Help with Python/Qt4 and QTableWidget column click
I'm trying to learn PyQt4 and GUI design with QtDesigner. I've got my basic GUI designed, and I now want to capture when the user clicks on a column header.
My thought is that I need to override QTableWidget, but I don't know how to attach to the signal. Here's ... | Help with Python/Qt4 and QTableWidget column click | I'm trying to learn PyQt4 and GUI design with QtDesigner. I've got my basic GUI designed, and I now want to capture when the user clicks on a column header.
My thought is that I need to override QTableWidget, but I don't know how to attach to the signal. Here's my class so far:
class MyTableWidget(QtGui.QTableWidget)... | [
"OK, the SIGNAL needed is:\nself.connect(self.horizontalHeader(), SIGNAL('sectionClicked(int)'), self.onClick)\n\n"
] | [
2
] | [] | [] | [
"pyqt4",
"python",
"qt4"
] | stackoverflow_0001408277_pyqt4_python_qt4.txt |
Q:
Python: NoneType errors.Do they look familiar
I've been looking for the NoneType for half a day. I've put 'print' and dir() all through the generation of the Object represented by t2. I've looked at the data structure after the crash using 'post mortem' and nowhere can I find a NoneType.
I was wondering if perhaps... | Python: NoneType errors.Do they look familiar | I've been looking for the NoneType for half a day. I've put 'print' and dir() all through the generation of the Object represented by t2. I've looked at the data structure after the crash using 'post mortem' and nowhere can I find a NoneType.
I was wondering if perhaps it's one of those errors that are initiated by som... | [
"NoneType is the type of the None object. So, in the first error, branch is None. The second error is tougher to diagnose without seeing the source code, but suggests that somewhere in t2, the data structure isn't exactly as you believe.\nWhen this comes up for me, I usually find that I've forgotten to end one of... | [
5,
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0001408286_python.txt |
Q:
How can you profile a parallelized Python script?
Suppose I have a python script called my_parallel_script.py that involves using multiprocessing to parallelize several things and I run it with the following command:
python -m cProfile my_parallel_script.py
This generates profiling output for the parent process o... | How can you profile a parallelized Python script? | Suppose I have a python script called my_parallel_script.py that involves using multiprocessing to parallelize several things and I run it with the following command:
python -m cProfile my_parallel_script.py
This generates profiling output for the parent process only. Calls made in child processes are not recorded at ... | [
"cProfile only works within a single process, so you will not automatically get the child process profiled.\nI would recommend that you tweak the child process code so that you can invoke it separately as a single process. Then run it under the profiler. You probably don't need to run your system multi-process wh... | [
10
] | [] | [] | [
"multiprocessing",
"parallel_processing",
"profile",
"python"
] | stackoverflow_0001408393_multiprocessing_parallel_processing_profile_python.txt |
Q:
Track process status with Python
I want to start a number of subprocesses in my Python script and then track when they complete or crash.
subprocess.Popen.poll() seems to return None when the process is still running, 0 on success, and non-zero on failure. Can that be expected on all OS's?
Unfortunately the standa... | Track process status with Python | I want to start a number of subprocesses in my Python script and then track when they complete or crash.
subprocess.Popen.poll() seems to return None when the process is still running, 0 on success, and non-zero on failure. Can that be expected on all OS's?
Unfortunately the standard library documentation is lacking fo... | [
"This may not be a very good answer to your question, but just in case you are at risk of reinventing a wheel, take a look at Supervisor \n\nSupervisor is a client/server system that allows its users to monitor and\n control a number of processes on\n UNIX-like operating systems.\n\nAnd it's all written in Python... | [
4,
1
] | [] | [] | [
"crash",
"process",
"python",
"subprocess"
] | stackoverflow_0001408627_crash_process_python_subprocess.txt |
Q:
Trimming Python Runtime
We've got a (Windows) application, with which we distribute an entire Python installation (including several 3rd-party modules that we use), so we have consistency and so we don't need to install everything separately. This works pretty well, but the application is pretty huge.
Obviously, ... | Trimming Python Runtime | We've got a (Windows) application, with which we distribute an entire Python installation (including several 3rd-party modules that we use), so we have consistency and so we don't need to install everything separately. This works pretty well, but the application is pretty huge.
Obviously, we don't use everything avail... | [
"One trick I've learned while trimming down .py files to ship: Delete all the .pyc files in the standard library, then run your application throughly (that is, enough to be sure all the Python modules it needs will be loaded). If you examine the standard library directories, there will be .pyc files for all the mo... | [
6,
5,
1
] | [] | [] | [
"python"
] | stackoverflow_0001408726_python.txt |
Q:
Getting another program's output as input on the fly
I've two programs I'm using in this way:
$ c_program | python_program.py
c_program prints something using printf() and python_program.py reads using sys.stdin.readline()
I'd like to make the python_program.py process c_program's output as it prints, immediatel... | Getting another program's output as input on the fly | I've two programs I'm using in this way:
$ c_program | python_program.py
c_program prints something using printf() and python_program.py reads using sys.stdin.readline()
I'd like to make the python_program.py process c_program's output as it prints, immediately, so that it can print its own current output. Unfortunat... | [
"Just set stdout to be line buffered at the beginning of your C program (before performing any output), like this:\n#include <stdio.h>\nsetvbuf(stdout, NULL, _IOLBF, 0);\n\nor\n#include <stdio.h>\nsetlinebuf(stdout);\n\nEither one will work on Linux, but setvbuf is part of the C standard so it will work on more sys... | [
18,
9,
7,
2,
1
] | [
"ok this maybe sound stupid but it might work:\noutput your pgm to a file\n$ c_program >> ./out.log\n\ndevelop a python program that read from tail command\nimport os\n\ntailoutput = os.popen(\"tail -n 0 -f ./out.log\")\n\ntry:\n while 1:\n line = tailoutput.readline()\n if len(line) == 0:\n ... | [
-1
] | [
"bash",
"c",
"linux",
"python",
"stdio"
] | stackoverflow_0001408678_bash_c_linux_python_stdio.txt |
Q:
Serving static files with Twisted and Django under non-root folders
I am in the process of migrating an application (Sage) from Twisted to Django.
Static documentation is currently served under /doc/static, while live (built on-the-fly) documentation are served under /doc/live.
Is it possible to use Twisted to ser... | Serving static files with Twisted and Django under non-root folders | I am in the process of migrating an application (Sage) from Twisted to Django.
Static documentation is currently served under /doc/static, while live (built on-the-fly) documentation are served under /doc/live.
Is it possible to use Twisted to serve /doc/static only, leaving Django to serve the rest of /doc/*?
| [
"Have a look at this link on how to run Django on top of Twisted: (instructions copied from the blog)\n\neasy_install Twisted\neasy_install Django\nProfit!\ndjango-admin.py startproject foo\nCreate a myapp.py with the following code:\nfrom django.core.handlers.wsgi import WSGIHandler\napplication = WSGIHandler()\ne... | [
3,
2
] | [
"Unless I misunderstood the question, why not simply rewrite the /doc/static url to Twisted before it even reaches Django (ie. at the Apache / proxy level)?\nhttp://httpd.apache.org/docs/2.0/mod/mod_rewrite.html\n"
] | [
-1
] | [
"django",
"python",
"twisted"
] | stackoverflow_0001405254_django_python_twisted.txt |
Q:
Inverse Dict in Python
I am trying to create a new dict using a list of values of an existing dict as individual keys.
So for example:
dict1 = dict({'a':[1,2,3], 'b':[1,2,3,4], 'c':[1,2]})
and I would like to obtain:
dict2 = dict({1:['a','b','c'], 2:['a','b','c'], 3:['a','b'], 4:['b']})
So far, I've not been abl... | Inverse Dict in Python | I am trying to create a new dict using a list of values of an existing dict as individual keys.
So for example:
dict1 = dict({'a':[1,2,3], 'b':[1,2,3,4], 'c':[1,2]})
and I would like to obtain:
dict2 = dict({1:['a','b','c'], 2:['a','b','c'], 3:['a','b'], 4:['b']})
So far, I've not been able to do this in a very clean... | [
"If you are using Python 2.5 or above, use the defaultdict class from the collections module; a defaultdict automatically creates values on the first access to a missing key, so you can use that here to create the lists for dict2, like this:\nfrom collections import defaultdict\ndict1 = dict({'a':[1,2,3], 'b':[1,2,... | [
8,
4
] | [
"Other way:\ndict2={}\n[[ (dict2.setdefault(i,[]) or 1) and (dict2[i].append(x)) for i in y ] for (x,y) in dict1.items()] \n\n"
] | [
-3
] | [
"data_structures",
"dictionary",
"python"
] | stackoverflow_0001410087_data_structures_dictionary_python.txt |
Q:
Python - IronPython dilemma
I'm starting to study Python, and for now I like it very much. But, if you could just answer a few questions for me, which have been troubling me, and I can't find any definite answers to them:
What is the relationship between Python's C implementation (main version from python.org) an... | Python - IronPython dilemma | I'm starting to study Python, and for now I like it very much. But, if you could just answer a few questions for me, which have been troubling me, and I can't find any definite answers to them:
What is the relationship between Python's C implementation (main version from python.org) and IronPython, in terms of languag... | [
"1) IronPython and CPython share nearly identical language syntax. There is very little difference between them. Transitioning should be trivial.\n2) The libraries in IronPython are very different than CPython. The Python libraries are a fair bit behind - quite a few of the CPython-accessible libraries will not ... | [
18,
11,
2,
1,
0
] | [] | [] | [
"excel",
"ironpython",
"python",
"python.net",
"vba"
] | stackoverflow_0001403103_excel_ironpython_python_python.net_vba.txt |
Q:
Auto-generate form fields for a Form in django
I have some models and I want to generate a multi-selection form from this data.
So the form would contain an entry for each category and the choices would be the skills in that category.
models.py
class SkillCategory(models.Model):
name = models.CharField(max_len... | Auto-generate form fields for a Form in django | I have some models and I want to generate a multi-selection form from this data.
So the form would contain an entry for each category and the choices would be the skills in that category.
models.py
class SkillCategory(models.Model):
name = models.CharField(max_length=50)
class Skill(models.Model):
name = model... | [
"Okay so you can't set fields like that on forms.Form, for reasons which will become apparent when you see DeclarativeFieldsMetaclass, the metaclass of forms.Form (but not of forms.BaseForm). A solution which may be overkill in your case but an example of how dynamic form construction can be done, is something like... | [
2,
1,
1
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0001409192_django_django_forms_python.txt |
Q:
Bypassing buffering of subprocess output with popen in C or Python
I have a general question about popen (and all related functions), applicable to all operating systems, when I write a python script or some c code and run the resulting executable from the console (win or linux), i can immediately see the output f... | Bypassing buffering of subprocess output with popen in C or Python | I have a general question about popen (and all related functions), applicable to all operating systems, when I write a python script or some c code and run the resulting executable from the console (win or linux), i can immediately see the output from the process. However, if I run the same executable as a forked proce... | [
"In general, the standard C runtime library (that's running on behalf of just about every program on every system, more or less;-) detects whether stdout is a terminal or not; if not, it buffers the output (which can be a huge efficiency win, compared to unbuffered output).\nIf you're in control of the program that... | [
16,
1
] | [] | [] | [
"buffer",
"c",
"pipe",
"python"
] | stackoverflow_0001410849_buffer_c_pipe_python.txt |
Q:
Is there something like Ruby's Machinist for Python
Copied from the site http://github.com/notahat/machinist/
Machinist makes it easy to create test data within your tests. It generates data for the fields you don't care about, and constructs any necessary associated objects, leaving you to only specify the field... | Is there something like Ruby's Machinist for Python | Copied from the site http://github.com/notahat/machinist/
Machinist makes it easy to create test data within your tests. It generates data for the fields you don't care about, and constructs any necessary associated objects, leaving you to only specify the fields you do care about in your tests
A simple blueprint migh... | [
"I looked through the whole Python Testing Tools Taxonomy page (which has lots of great stuff) but didn't find much of anything like Machinist.\nThere is one simply script (called Peckcheck) that's basically unit-testing-with-data-generation, but it doesn't have the Blueprinting and such... so you might say it's ju... | [
1
] | [] | [] | [
"python",
"ruby"
] | stackoverflow_0001404503_python_ruby.txt |
Q:
Locking in sqlalchemy
I'm confused about how to concurrently modify a table from several different processes. I've tried using Query.with_lockmode(), but it doesn't seem to be doing what I expect it to do, which would be to prevent two processes from simultaneously querying the same rows. Here's what I've tried:
i... | Locking in sqlalchemy | I'm confused about how to concurrently modify a table from several different processes. I've tried using Query.with_lockmode(), but it doesn't seem to be doing what I expect it to do, which would be to prevent two processes from simultaneously querying the same rows. Here's what I've tried:
import time
from sqlalchemy.... | [
"Are you by accident using MyISAM tables? This works fine with InnoDB tables, but would have the described behavior (silent failure to respect isolation) with MyISAM.\n"
] | [
5
] | [] | [] | [
"locking",
"python",
"sql",
"sqlalchemy"
] | stackoverflow_0001411350_locking_python_sql_sqlalchemy.txt |
Q:
Having problem with IronPython to instantiate a class in IronPython Console
I'm trying to learn IronPython. I created an extremely simple class like this one:
class Test:
def testMethod(self):
print "test"
Next I'm trying to use it in IronPython Console:
>>> import Test
>>> t = Test()
After the second lin... | Having problem with IronPython to instantiate a class in IronPython Console | I'm trying to learn IronPython. I created an extremely simple class like this one:
class Test:
def testMethod(self):
print "test"
Next I'm trying to use it in IronPython Console:
>>> import Test
>>> t = Test()
After the second line I get following error:
TypeError: Scope is not callable
What I'm doing wrong?... | [
"you need to from filename import Test where filename is a basename of file class Test is saved in.\ne.g.: class Test is saved in test.py\nthen:\nfrom test import Test\nt = Test()\n\nwill run as expected.\n",
"import Test loads the module named Test, defined in a file called Test.py(c|d). This module in turn con... | [
4,
2
] | [] | [] | [
"ironpython",
"python"
] | stackoverflow_0001411442_ironpython_python.txt |
Q:
Help with basic Python function
I have a function to connect to a database. This code works:
def connect():
return MySQLdb.connect("example.com", "username", "password", "database")
But this doesn't:
def connect():
host = "example.com"
user = "username"
pass = "password"
base = "database"
... | Help with basic Python function | I have a function to connect to a database. This code works:
def connect():
return MySQLdb.connect("example.com", "username", "password", "database")
But this doesn't:
def connect():
host = "example.com"
user = "username"
pass = "password"
base = "database"
return MySQLdb.connect(host, user, pa... | [
"pass is a reserved keyword. \nPick different variable names and your code should work fine.\nMaybe something like:\ndef connect():\n _host = \"example.com\"\n _user = \"username\"\n _pass = \"password\"\n _base = \"database\"\n return MySQLdb.connect(_host, _user, _pass, _base)\n\n"
] | [
8
] | [] | [] | [
"python"
] | stackoverflow_0001411553_python.txt |
Q:
Is there a way to reopen a socket?
I create many "short-term" sockets in some code that look like that :
nb=1000
for i in range(nb):
sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sck.connect((adr, prt)
sck.send('question %i'%i)
sck.shutdown(SHUT_WR)
answer=sck.recv(4096)
print 'an... | Is there a way to reopen a socket? | I create many "short-term" sockets in some code that look like that :
nb=1000
for i in range(nb):
sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sck.connect((adr, prt)
sck.send('question %i'%i)
sck.shutdown(SHUT_WR)
answer=sck.recv(4096)
print 'answer %i : %s' % (%i, answer)
sck.clo... | [
"No, this is a limitation of the underlying C sockets (and the TCP/IP protocol, for that matter). My question to you is: why are you shutting them down when you can architect your application to use them?\nThe problem with many short-term sockets is that shutting them down puts them in a state where they cannot be ... | [
18,
3,
1,
0
] | [] | [] | [
"python",
"sockets"
] | stackoverflow_0001410723_python_sockets.txt |
Q:
How to get '\x01' to 1
I am getting this:
_format_ = "7c7sc"
print struct.unpack(self._format_, data)
gives
('\x7f', 'E', 'L', 'F', '\x01', '\x01', '\x01', '\x00\x00\x00\x00\x00\x00\x00', '\x00')
I want to take '\x01' and get 1 from it, i.e., convert to ``int. Any ideas?
Thanks
A:
ord("\x01") will return 1.
A... | How to get '\x01' to 1 | I am getting this:
_format_ = "7c7sc"
print struct.unpack(self._format_, data)
gives
('\x7f', 'E', 'L', 'F', '\x01', '\x01', '\x01', '\x00\x00\x00\x00\x00\x00\x00', '\x00')
I want to take '\x01' and get 1 from it, i.e., convert to ``int. Any ideas?
Thanks
| [
"ord(\"\\x01\") will return 1.\n",
"Perhaps you are thinking of the ord function?\n>>> ord(\"\\x01\")\n1\n>>> ord(\"\\x02\")\n2\n>>> ord(\"\\x7f\")\n127\n\n"
] | [
26,
4
] | [] | [] | [
"python"
] | stackoverflow_0001411658_python.txt |
Q:
Python CGI returning an http status code, such as 403?
How can my python cgi return a specific http status code, such as 403 or 418?
I tried the obvious (print "Status:403 Forbidden") but it doesn't work.
A:
print 'Status: 403 Forbidden'
print
Works for me. You do need the second print though, as you need a do... | Python CGI returning an http status code, such as 403? | How can my python cgi return a specific http status code, such as 403 or 418?
I tried the obvious (print "Status:403 Forbidden") but it doesn't work.
| [
"print 'Status: 403 Forbidden'\nprint\n\nWorks for me. You do need the second print though, as you need a double-newline to end the HTTP response headers. Otherwise your web server may complain you aren't sending it a complete set of headers.\nsys.stdout('Status: 403 Forbidden\\r\\n\\r\\n')\n\nmay be technically mo... | [
21,
0
] | [] | [] | [
"cgi",
"http",
"http_status_codes",
"python"
] | stackoverflow_0001411867_cgi_http_http_status_codes_python.txt |
Q:
What difference it makes when I set python thread as a Daemon
What difference makes it when I set a python thread as a daemon, using thread.setDaemon(True)?
A:
A daemon thread will not prevent the application from exiting. The program ends when all non-daemon threads (main thread included) are complete.
So gene... | What difference it makes when I set python thread as a Daemon | What difference makes it when I set a python thread as a daemon, using thread.setDaemon(True)?
| [
"A daemon thread will not prevent the application from exiting. The program ends when all non-daemon threads (main thread included) are complete.\nSo generally, if you're doing something in the background, you might want to set the thread as daemon so you don't have to explicitly have that thread's function return... | [
24
] | [] | [] | [
"daemon",
"multithreading",
"python"
] | stackoverflow_0001411860_daemon_multithreading_python.txt |
Q:
Python Warning control
I would like some kind of warning to be raisen as errors, but only the first occurrence. How to do that?
I read http://docs.python.org/library/warnings.html and I dont know how to combine this two types of behaviour.
A:
Looking at the code to warnings.py, you can't assign more than one fil... | Python Warning control | I would like some kind of warning to be raisen as errors, but only the first occurrence. How to do that?
I read http://docs.python.org/library/warnings.html and I dont know how to combine this two types of behaviour.
| [
"Looking at the code to warnings.py, you can't assign more than one filter action to a warning, and you can't (easily) define your own actions, like 'raise_once'.\nHowever, if you want to raise a warning as an exception, but just once, that means that you are catching the exception. Why not put a line in your excep... | [
7
] | [] | [] | [
"python",
"warnings"
] | stackoverflow_0001412575_python_warnings.txt |
Q:
Python: what's the pythonic way to perform this loop?
What is the pythonic way to perform this loop. I'm trying to pick a random key that will return a subtree and not the root. Hence: 'parent == None' cannot be true. Nor can 'isRoot==True' be true.
thekey = random.choice(tree.thedict.keys())
while (tree.thedict[t... | Python: what's the pythonic way to perform this loop? | What is the pythonic way to perform this loop. I'm trying to pick a random key that will return a subtree and not the root. Hence: 'parent == None' cannot be true. Nor can 'isRoot==True' be true.
thekey = random.choice(tree.thedict.keys())
while (tree.thedict[thekey].parent == None)or(tree.thedict[thekey].isRoot == Tru... | [
"\nget a random subtree that is not the\n root\n\nnot_root_nodes = [key, node for key,node in tree.thedict.iteritems() if not ( node.parent is None or node.isRoot)]\nitem = random.choice( not_root_nodes )\n\n",
"key = random.choice([key for key, subtree in tree.thedict.items()\n if subtre... | [
3,
3,
1,
1,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0001411943_python.txt |
Q:
iTunes COM - How to acess Lyrics
I have been messing around with iTunes COM from python.
However, I haven't been able to access the Lyrics of any track.
I have been using python for this. Here is the code:
>>> import win32com.client
>>> itunes = win32com.client.Dispatch("iTunes.Application")
>>> lib = itunes.Libra... | iTunes COM - How to acess Lyrics | I have been messing around with iTunes COM from python.
However, I haven't been able to access the Lyrics of any track.
I have been using python for this. Here is the code:
>>> import win32com.client
>>> itunes = win32com.client.Dispatch("iTunes.Application")
>>> lib = itunes.LibraryPlaylist
>>> tracks = lib.Tracks
>>>... | [
"Try to convert it like this (not tested):\ntrack_converted = win32com.client.CastTo(tracks[1], \"IITFileOrCDTrack\")\n\n"
] | [
3
] | [] | [] | [
"com",
"itunes",
"python"
] | stackoverflow_0001412689_com_itunes_python.txt |
Q:
Django extends template
i have simple django/python app and i got 1 page - create.html. So i want to extend this page to use index.html. Everything work (no errors) and when the page is loaded all data from create.html and all text from index.html present but no formating is available - images and css that must be... | Django extends template | i have simple django/python app and i got 1 page - create.html. So i want to extend this page to use index.html. Everything work (no errors) and when the page is loaded all data from create.html and all text from index.html present but no formating is available - images and css that must be loaded from index.html is no... | [
"It looks like you are extending base.html and not index.html.\n",
"More specifically, look at the first line of your content.html:\n {% extends \"base.html\" %}\n\nChange this to\n {% extends \"index.html\" %}\n\n(or rename index.html to be base.html)\n",
"Ahaa find where is the problem!\nMEDIA_ROOT and MEDI... | [
1,
1,
1
] | [] | [] | [
"django",
"extends",
"python"
] | stackoverflow_0001412476_django_extends_python.txt |
Q:
python mysql fetch query
def dispcar ( self, reg ):
print ("The car information for '%s' is: "), (reg)
numrows = int(self.dbc.rowcount) #get the count of total rows
self.dbc.execute("select * from car where reg='%s'") %(reg)
for x in range(0, numrows)... | python mysql fetch query | def dispcar ( self, reg ):
print ("The car information for '%s' is: "), (reg)
numrows = int(self.dbc.rowcount) #get the count of total rows
self.dbc.execute("select * from car where reg='%s'") %(reg)
for x in range(0, numrows):
car_info... | [
"This confuses just about everyone who works with MySQLDB. You are passing arguments to the execute function, not doing python string substitution. The %s in the query string is used more like a prepared statement than a python string substitution. This also prevents SQL injection as MySQLDB will do the escaping fo... | [
4,
3,
1
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0001413057_mysql_python.txt |
Q:
Grant anonymous access to a specific url/action in Plone
I am running Plone 3.2.3 and I have installed HumaineMailman so that the users on the website can subscribe and unsubscribe themselves from our various mailinglists. HumaineMailman works very simple. There is a special URL/action that gives you a plain text ... | Grant anonymous access to a specific url/action in Plone | I am running Plone 3.2.3 and I have installed HumaineMailman so that the users on the website can subscribe and unsubscribe themselves from our various mailinglists. HumaineMailman works very simple. There is a special URL/action that gives you a plain text list of all e-mail addresses that are subscribed on a list. Fo... | [
"There are a couple ways to address this without apache or redeclaring security (which would make me nervous too)\nhttp://www.example.org:8080/mailman_autolist_update?list=mylist@example.org&password=secret&__ac_name=**USERNAME**&__ac_password=**PASSWORD**&pwd_empty=0&cookies_enabled=1&js_enabled=0&form.submitted=1... | [
2,
1,
0
] | [] | [] | [
"mailman",
"plone",
"python",
"zope"
] | stackoverflow_0001321828_mailman_plone_python_zope.txt |
Q:
Python Unicode and MIMEE
Can someone who is way smarter than I tell me what I'm doing wrong.. Shouldn't this simply process...
# encoding: utf-8
from email.MIMEText import MIMEText
msg = MIMEText("hi")
msg.set_charset('utf-8')
print msg.as_string()
a = 'Ho\xcc\x82tel Ste\xcc\x81phane '
b = unicode(a, "utf-8")
... | Python Unicode and MIMEE | Can someone who is way smarter than I tell me what I'm doing wrong.. Shouldn't this simply process...
# encoding: utf-8
from email.MIMEText import MIMEText
msg = MIMEText("hi")
msg.set_charset('utf-8')
print msg.as_string()
a = 'Ho\xcc\x82tel Ste\xcc\x81phane '
b = unicode(a, "utf-8")
print b
msg = MIMEText(b)
msg... | [
"Assuming Python 2.* (alas, you don't tell us whether you're on Python 3, but as you're using print as a statement it looks like you aren't): MIMEText\" takes a string -- a plain string, NOT a Unicode object. So, useb.encode('utf-8')as the argument if what you start with is a Unicode objectb`.\n"
] | [
2
] | [] | [] | [
"email",
"python",
"unicode"
] | stackoverflow_0001413735_email_python_unicode.txt |
Q:
Improving a Python Script that Updates Apache DocumentRoot
I'm tired of going through all the steps it takes (for me) to change the DocumentRoot in Apache. I'm trying to facilitate the process with the following Python script...
#!/usr/bin/python
import sys, re
if len(sys.argv) == 2:
f = open('/tmp/apachecdr', ... | Improving a Python Script that Updates Apache DocumentRoot | I'm tired of going through all the steps it takes (for me) to change the DocumentRoot in Apache. I'm trying to facilitate the process with the following Python script...
#!/usr/bin/python
import sys, re
if len(sys.argv) == 2:
f = open('/tmp/apachecdr', 'w')
f.write(open('/etc/apache2/httpd.conf').read())
f = open... | [
"You're doing a lot of file work for not much benefit. Why do you write /tmp/apachecdr and then immediately read it again? If you are copying httpd.conf to the tmp directory as a backup, the shutil module provides functions to copy files:\n#!/usr/bin/python\n\nimport shutil, sys, re\n\nHTTPD_CONF = '/etc/apache2/... | [
0,
0,
0
] | [] | [] | [
"apache",
"document",
"python",
"root"
] | stackoverflow_0001408424_apache_document_python_root.txt |
Q:
Python with matplotlib - reusing drawing functions
I have a follow up question to this question.
Is it possible to streamline the figure generation by having multiple python scripts that work on different parts of the figure?
For example, if I have the following functions:
FunctionA: Draw a histogram of somethi... | Python with matplotlib - reusing drawing functions | I have a follow up question to this question.
Is it possible to streamline the figure generation by having multiple python scripts that work on different parts of the figure?
For example, if I have the following functions:
FunctionA: Draw a histogram of something
FunctionB: Draw a box with a text in it
FunctionC... | [
"Here you want to use the Artist objects, and pass them as needed to the functions:\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef myhist(ax, color):\n ax.hist(np.log(np.arange(1, 10, .1)), facecolor=color)\n\ndef say_something(ax, words):\n t = ax.text(.2, 20., words)\n make_a_dim_yellow_bbox... | [
8,
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0001413681_matplotlib_python.txt |
Q:
Python decorate a class to change parent object type
Suppose you have two classes X & Y. You want to decorate those classes by adding attributes to the class to produce new classes X1 and Y1.
For example:
class X1(X):
new_attribute = 'something'
class Y1(Y):
new_attribute = 'something'
new_attribute will alw... | Python decorate a class to change parent object type | Suppose you have two classes X & Y. You want to decorate those classes by adding attributes to the class to produce new classes X1 and Y1.
For example:
class X1(X):
new_attribute = 'something'
class Y1(Y):
new_attribute = 'something'
new_attribute will always be the same for both X1 and Y1. X & Y are not related ... | [
"Use 3-arguments type:\ndef makeSomeNicelyDecoratedSubclass(someclass):\n return type('MyNiceName', (someclass,), {'new_attribute':'something'})\n\nThis is indeed, as you surmised, a reasonably popular idiom.\nEdit: in the general case if someclass has a custom metaclass you may need to extract and use it (with a ... | [
5,
3,
2
] | [] | [] | [
"decorator",
"multiple_inheritance",
"python"
] | stackoverflow_0001412210_decorator_multiple_inheritance_python.txt |
Q:
python serialize string
I am needing to unserialize a string into an array in python just like php and then serialize it back.
A:
If you mean PHP's explode, try this
>>> list("foobar")
['f', 'o', 'o', 'b', 'a', 'r']
>>> ''.join(['f', 'o', 'o', 'b', 'a', 'r'])
'foobar'
A:
Take a look at the pickle module. It i... | python serialize string | I am needing to unserialize a string into an array in python just like php and then serialize it back.
| [
"If you mean PHP's explode, try this\n>>> list(\"foobar\")\n['f', 'o', 'o', 'b', 'a', 'r']\n\n>>> ''.join(['f', 'o', 'o', 'b', 'a', 'r'])\n'foobar'\n\n",
"Take a look at the pickle module. It is probably what you're looking for. \nimport pickle\n\n# Unserialize the string to an array\nmy_array = pickle.loads(seri... | [
1,
0,
0,
0
] | [] | [] | [
"python",
"serialization"
] | stackoverflow_0001413763_python_serialization.txt |
Q:
help with python forking child server for doing ajax push, long polling
Alright, I only know some basic python but if I can get help with this then I am considering making it open source.
What I am trying to do:
- (Done) Ajax send for init content
- Python server recv command "init" to send most recent content
- (... | help with python forking child server for doing ajax push, long polling | Alright, I only know some basic python but if I can get help with this then I am considering making it open source.
What I am trying to do:
- (Done) Ajax send for init content
- Python server recv command "init" to send most recent content
- (Done) Ajax recv content and then immediately calls back to python server
- Py... | [
"Look at subprocess.\nRead all of these related questions on StackOverflow: https://stackoverflow.com/search?q=[python]+web+subprocess\n"
] | [
1
] | [] | [] | [
"fork",
"long_polling",
"python",
"sockets"
] | stackoverflow_0001414098_fork_long_polling_python_sockets.txt |
Q:
Expected LP_c_double instance instead of c_double_Array - python ctypes error
I have a function in a DLL that I have to wrap with python code. The function is expecting a pointer to an array of doubles. This is the error I'm getting:
Traceback (most recent call last):
File "C:\....\.FROGmoduleTEST.py", line 243,... | Expected LP_c_double instance instead of c_double_Array - python ctypes error | I have a function in a DLL that I have to wrap with python code. The function is expecting a pointer to an array of doubles. This is the error I'm getting:
Traceback (most recent call last):
File "C:\....\.FROGmoduleTEST.py", line 243, in <module>
FROGPCGPMonitorDLL.ReturnPulse(ptrpulse, ptrtdl, ptrtdP,ptrfdl,ptr... | [
"LP_c_double is created dynamically by ctypes when you create a pointer to a double. i.e.\nLP_c_double = POINTER(c_double)\n\nAt this point, you've created a C type. You can now create instances of these pointers.\nmy_pointer_one = LP_c_double()\n\nBut here's the kicker. Your function isn't expecting a pointer to ... | [
11,
2
] | [] | [] | [
"ctypes",
"python",
"types"
] | stackoverflow_0001413851_ctypes_python_types.txt |
Q:
Python code readability
I have a programming experience with statically typed languages. Now writing code in Python I feel difficulties with its readability. Lets say I have a class Host:
class Host(object):
def __init__(self, name, network_interface):
self.name = name
self.network_interface = network_in... | Python code readability | I have a programming experience with statically typed languages. Now writing code in Python I feel difficulties with its readability. Lets say I have a class Host:
class Host(object):
def __init__(self, name, network_interface):
self.name = name
self.network_interface = network_interface
I don't understand f... | [
"Using dynamic languages will teach you something about static languages: all the help you got from the static language that you now miss in the dynamic language, it wasn't all that helpful.\nTo use your example, in a static language, you'd know that the parameter was a string, and in Python you don't. So in Pytho... | [
22,
10,
9,
4,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0001409821_python.txt |
Q:
embedding plot within Qt gui
How do you embed a vpython plot (animated) within your Qt GUI? so that it has its own display area and would not need to created a new window anymore.
A:
vpython's FAQs claim that vpython's architecture make any embedding a problem...:
Q: Is there a way to embed VPython in another en... | embedding plot within Qt gui | How do you embed a vpython plot (animated) within your Qt GUI? so that it has its own display area and would not need to created a new window anymore.
| [
"vpython's FAQs claim that vpython's architecture make any embedding a problem...:\nQ: Is there a way to embed VPython in another environment?\n\nThis is difficult because VPython has\n two threads, your computational thread\n and a rendering thread which about 25\n times per second paints the scene\n using the... | [
3,
1
] | [] | [] | [
"python",
"qt",
"user_interface"
] | stackoverflow_0001397553_python_qt_user_interface.txt |
Q:
Profiling a python multiprocessing pool
I'm trying to run cProfile.runctx() on each process in a multiprocessing pool, to get an idea of what the multiprocessing bottlenecks are in my source. Here is a simplified example of what I'm trying to do:
from multiprocessing import Pool
import cProfile
def square(i):
... | Profiling a python multiprocessing pool | I'm trying to run cProfile.runctx() on each process in a multiprocessing pool, to get an idea of what the multiprocessing bottlenecks are in my source. Here is a simplified example of what I'm trying to do:
from multiprocessing import Pool
import cProfile
def square(i):
return i*i
def square_wrapper(i):
cProf... | [
"Try this:\ndef square_wrapper(i):\n result = [None]\n cProfile.runctx(\"result[0] = square(i)\", globals(), locals(), \"file_%d\" % i)\n return result[0]\n\n"
] | [
8
] | [] | [] | [
"multiprocessing",
"pool",
"profiling",
"python"
] | stackoverflow_0001414841_multiprocessing_pool_profiling_python.txt |
Q:
Prompt on exit in PyQt application
Is there any way to promt user to exit the gui-program written in Python?
Something like "Are you sure you want to exit the program?"
I'm using PyQt.
A:
Yes. You need to override the default close behaviour of the QWidget representing your application so that it doesn't immedia... | Prompt on exit in PyQt application | Is there any way to promt user to exit the gui-program written in Python?
Something like "Are you sure you want to exit the program?"
I'm using PyQt.
| [
"Yes. You need to override the default close behaviour of the QWidget representing your application so that it doesn't immediately accept the event. The basic structure you want is something like this:\ndef closeEvent(self, event):\n\n quit_msg = \"Are you sure you want to exit the program?\"\n reply = QtGui.... | [
61
] | [] | [] | [
"exit",
"pyqt",
"python"
] | stackoverflow_0001414781_exit_pyqt_python.txt |
Q:
sqlalchemy easy way to insert or update?
I have a sequence of new objects. They all look like similar to this:
Foo(pk_col1=x, pk_col2=y, val='bar')
Some of those are Foo that exist (i.e. only val differs from the row in the db)
and should generate update queries. The others should generate inserts.
I can think of ... | sqlalchemy easy way to insert or update? | I have a sequence of new objects. They all look like similar to this:
Foo(pk_col1=x, pk_col2=y, val='bar')
Some of those are Foo that exist (i.e. only val differs from the row in the db)
and should generate update queries. The others should generate inserts.
I can think of a few ways of doing this, the best being:
pk_c... | [
"I think you are after new_obj = session.merge(obj). This will merge an object in a detached state into the session if the primary keys match and will make a new one otherwise. So session.save(new_obj) will work for both insert and update.\n"
] | [
59
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0001382469_python_sqlalchemy.txt |
Q:
Does anybody use DjVu files in their production tools?
When it's about archiving and doc portability, it's all about PDF. I heard about DjVu somes years ago, and it seems to be now mature enough for serious usages. The benefits seems to be a small size format and a fast open / read experience.
But I have absolutel... | Does anybody use DjVu files in their production tools? | When it's about archiving and doc portability, it's all about PDF. I heard about DjVu somes years ago, and it seems to be now mature enough for serious usages. The benefits seems to be a small size format and a fast open / read experience.
But I have absolutely no feedback on how good / bad it is in the real world :
I... | [
"I've found DjVu to be ideal for image-intensive documents. I used to sell books of highly details maps, and those were always in DjVu. PDF however works really well; it's a standard, and -everybody- will be able to open it without installing additional software.\nThere's more info at:\nhttp://print-driver.com/news... | [
3
] | [] | [] | [
"djvu",
"pdf",
"python"
] | stackoverflow_0001415400_djvu_pdf_python.txt |
Q:
Read WordPerfect files with Python?
I really need to work with information contained in WordPerfect 12 files without using WordPerfect's sluggish visual interface, but I can't find any detailed documentation about the file format or any Python modules for reading/writing the files. I found a post on the web that s... | Read WordPerfect files with Python? | I really need to work with information contained in WordPerfect 12 files without using WordPerfect's sluggish visual interface, but I can't find any detailed documentation about the file format or any Python modules for reading/writing the files. I found a post on the web that seems to explain how to convert WordPerfec... | [
"The relevant part of your link is this:\nos.system( \"%s %s %s\" % ( WPD_TO_TEXT_CMD, \"/tmp/tmpfile\", \"/tmp/tmpfile.txt\" ) )\n\nWhich is making a system call to an outside program called \"wp2txt\". Googling for that program produces active hits.\n",
"OpenOffice.org should read WordPerfect files, I think.\n... | [
3,
2,
1
] | [] | [] | [
"python",
"wordperfect"
] | stackoverflow_0001297466_python_wordperfect.txt |
Q:
How can I obtain pattern string from compiled regexp pattern in python?
I have some code like this one:
>>> import re
>>> p = re.compile('my pattern')
>>> print p
_sre.SRE_Pattern object at 0x02274380
Is it possible to get string "my pattern" from p variable?
A:
p.pattern
Read more about re module here:
http:/... | How can I obtain pattern string from compiled regexp pattern in python? | I have some code like this one:
>>> import re
>>> p = re.compile('my pattern')
>>> print p
_sre.SRE_Pattern object at 0x02274380
Is it possible to get string "my pattern" from p variable?
| [
"p.pattern\n\nRead more about re module here:\nhttp://docs.python.org/library/re.html\n",
"From the \"Regular Expression Objects\" section of the re module documentation:\n\nRegexObject.pattern\nThe pattern string from which the RE object was compiled.\n\nFor example:\n>>> import re\n>>> p = re.compile('my patter... | [
126,
22,
9
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0001415924_python_regex.txt |
Q:
Installing Pinax on Windows
Can I install Pinax on Windows Environment?
Is there a easy way?
Which environment do you recommend?
A:
I have pinax 0.7rc1 installed and working on windows 7, with no problems.
Check out this video for a great example on how to do this. He uses pinax 0.7beta3 on windows XP.
http://... | Installing Pinax on Windows | Can I install Pinax on Windows Environment?
Is there a easy way?
Which environment do you recommend?
| [
"I have pinax 0.7rc1 installed and working on windows 7, with no problems.\nCheck out this video for a great example on how to do this. He uses pinax 0.7beta3 on windows XP.\nhttp://www.vimeo.com/6098872\nHere are the steps I followed.\n\ndownload and install python\ndownload and install python image library\ndownl... | [
7,
0,
0
] | [] | [] | [
"django",
"pinax",
"python",
"web_applications"
] | stackoverflow_0001233670_django_pinax_python_web_applications.txt |
Q:
How to improve speed of this readline loop in python?
i'm importing several parts of a Databasedump in text Format into MySQL, the problem is
that before the interesting Data there is very much non-interesting stuff infront.
I wrote this loop to get to the needed data:
def readloop(DBFILE):
txtdb=open(DBFILE, ... | How to improve speed of this readline loop in python? | i'm importing several parts of a Databasedump in text Format into MySQL, the problem is
that before the interesting Data there is very much non-interesting stuff infront.
I wrote this loop to get to the needed data:
def readloop(DBFILE):
txtdb=open(DBFILE, 'r')
sline = ""
# loop till 1st "customernum:" is found
w... | [
"Please do not write this code:\nwhile condition is False:\n\nBoolean conditions are boolean for cryin' out loud, so they can be tested (or negated and tested) directly:\nwhile not condition:\n\nYour second while loop isn't written as \"while condition is True:\", I'm curious why you felt the need to test \"is Fals... | [
5,
2,
1,
0,
0
] | [] | [] | [
"loops",
"python",
"readline"
] | stackoverflow_0001415369_loops_python_readline.txt |
Q:
How to create hover effect on StaticBitmap in wxpython?
I want to create hover effect on StaticBitmap - If the cursor of mouse is over the the bitmap, shows one image, if not, shows second image. It's trivial program (works perfectly with a button). However, StaticBitmap doesn't emit EVT_WINDOW_ENTER, EVT_WINDOW_L... | How to create hover effect on StaticBitmap in wxpython? | I want to create hover effect on StaticBitmap - If the cursor of mouse is over the the bitmap, shows one image, if not, shows second image. It's trivial program (works perfectly with a button). However, StaticBitmap doesn't emit EVT_WINDOW_ENTER, EVT_WINDOW_LEAVE events.
I can work with EVT_MOTION. If images are switch... | [
"It looks like this is a wxGTK bug, ENTER and LEAVE events work fine on windows. You should direct the attention of the core developers to the problem, a good place to do this is their bug tracker. This is an issue you should not have to work around IMHO.\nI have found that GenericButtons do not have this problem o... | [
1,
0
] | [] | [] | [
"hover",
"image",
"python",
"wxpython",
"wxwidgets"
] | stackoverflow_0001415727_hover_image_python_wxpython_wxwidgets.txt |
Q:
What is the least resource intense data structure to distribute with a Python Application
I am building an application to distribute to fellow academics. The application will take three parameters that the user submits and output a list of dates and codes related to those events. I have been building this using ... | What is the least resource intense data structure to distribute with a Python Application | I am building an application to distribute to fellow academics. The application will take three parameters that the user submits and output a list of dates and codes related to those events. I have been building this using a dictionary and intended to build the application so that the dictionary loaded from a pickle ... | [
"The standard shelve module will give you a persistent dictionary that is stored in a dbm style database. Providing that your keys are strings and your values are picklable (since you're using pickle already, this must be true), this could be a better solution that simply storing the entire dictionary in a single p... | [
6,
2,
2,
1,
0
] | [] | [] | [
"database",
"dictionary",
"python"
] | stackoverflow_0000885625_database_dictionary_python.txt |
Q:
Using SQLite in a Python program
I have created a Python module that creates and populates several SQLite tables. Now, I want to use it in a program but I don't really know how to call it properly. All the tutorials I've found are essentially "inline", i.e. they walk through using SQLite in a linear fashion rather... | Using SQLite in a Python program | I have created a Python module that creates and populates several SQLite tables. Now, I want to use it in a program but I don't really know how to call it properly. All the tutorials I've found are essentially "inline", i.e. they walk through using SQLite in a linear fashion rather than how to actually use it in produc... | [
"Don't make this more complex than it needs to be. The big, independent databases have complex setup and configuration requirements. SQLite is just a file you access with SQL, it's much simpler.\nDo the following.\n\nAdd a table to your database for \"Components\" or \"Versions\" or \"Configuration\" or \"Release... | [
29,
13,
7,
5,
4,
3,
2,
0
] | [] | [] | [
"exception",
"python",
"sqlite"
] | stackoverflow_0000211501_exception_python_sqlite.txt |
Q:
How to pickle numpy's Inf objects?
When trying to pickle the object Inf as defined in numpy (I think), the dumping goes Ok but the loading fails:
>>> cPickle.dump(Inf, file("c:/temp/a.pcl",'wb'))
>>> cPickle.load(file("c:/temp/a.pcl",'rb'))
Traceback (most recent call last):
File "<pyshell#257>", line 1, in <mod... | How to pickle numpy's Inf objects? | When trying to pickle the object Inf as defined in numpy (I think), the dumping goes Ok but the loading fails:
>>> cPickle.dump(Inf, file("c:/temp/a.pcl",'wb'))
>>> cPickle.load(file("c:/temp/a.pcl",'rb'))
Traceback (most recent call last):
File "<pyshell#257>", line 1, in <module>
cPickle.load(file("c:/temp/a.pc... | [
"If you specify a pickle protocol more than zero, it will work. Protocol is often specified as -1, meaning use the latest and greatest protocol:\n>>> cPickle.dump(Inf, file(\"c:/temp/a.pcl\",'wb'), -1)\n>>> cPickle.load(file(\"c:/temp/a.pcl\",'rb'))\n1.#INF -- may be platform dependent what print... | [
5
] | [
"Try this solution at SourceForge which will work for any arbitrary Python object:\ny_serial.py module :: warehouse Python objects with SQLite\n\"Serialization + persistance :: in a few lines of code, compress and annotate Python objects into SQLite; then later retrieve them chronologically by keywords without any ... | [
-1
] | [
"numpy",
"pickle",
"python"
] | stackoverflow_0001250367_numpy_pickle_python.txt |
Q:
pythonic way to convert variable to list
I have a function whose input argument can either be an element or a list of elements. If this argument is a single element then I put it in a list so I can iterate over the input in a consistent manner.
Currently I have this:
def my_func(input):
if not isinstance(inpu... | pythonic way to convert variable to list | I have a function whose input argument can either be an element or a list of elements. If this argument is a single element then I put it in a list so I can iterate over the input in a consistent manner.
Currently I have this:
def my_func(input):
if not isinstance(input, list): input = [input]
for e in input:
... | [
"Typically, strings (plain and unicode) are the only iterables that you want to nevertheless consider as \"single elements\" -- the basestring builtin exists SPECIFICALLY to let you test for either kind of strings with isinstance, so it's very UN-grotty for that special case;-).\nSo my suggested approach for the mo... | [
15,
10,
4,
2,
1,
0,
0
] | [
"This seems like a reasonable way to do it. You're wanting to test if the element is a list, and this accomplishes that directly. It gets more complicated if you want to support other 'list-like' data types, too, for example:\nisinstance(input, (list, tuple))\n\nor more generally, abstract away the question:\ndef i... | [
-1
] | [
"arguments",
"list",
"python"
] | stackoverflow_0001416646_arguments_list_python.txt |
Q:
Simple data storing in Python
I'm looking for a simple solution using Python to store data as a flat file, such that each line is a string representation of an array that can be easily parsed.
I'm sure python has library for doing such a task easily but so far all the approaches I have found seemed like it would h... | Simple data storing in Python | I'm looking for a simple solution using Python to store data as a flat file, such that each line is a string representation of an array that can be easily parsed.
I'm sure python has library for doing such a task easily but so far all the approaches I have found seemed like it would have been sloppy to get it to work a... | [
"In addition to pickle (mentioned above), there's json (built in to 2.6, available via simplejson before that), and marshal. Also, there's a reader in the same csv module the writer is in.\nUPDATE: As S. Lott pointed out in a comment, there's also YAML, available via PyYAML, among others.\n",
"http://docs.python.... | [
10,
6,
4,
2,
1
] | [] | [] | [
"csv",
"file_io",
"fileparsing",
"multidimensional_array",
"python"
] | stackoverflow_0000875228_csv_file_io_fileparsing_multidimensional_array_python.txt |
Q:
Why use **kwargs in python? What are some real world advantages over using named arguments?
I come from a background in static languages. Can someone explain (ideally through example) the real world advantages of using **kwargs over named arguments?
To me it only seems to make the function call more ambiguous. Tha... | Why use **kwargs in python? What are some real world advantages over using named arguments? | I come from a background in static languages. Can someone explain (ideally through example) the real world advantages of using **kwargs over named arguments?
To me it only seems to make the function call more ambiguous. Thanks.
| [
"You may want to accept nearly-arbitrary named arguments for a series of reasons -- and that's what the **kw form lets you do.\nThe most common reason is to pass the arguments right on to some other function you're wrapping (decorators are one case of this, but FAR from the only one!) -- in this case, **kw loosens ... | [
73,
46,
41,
15,
5,
3,
1,
0
] | [] | [] | [
"keyword_argument",
"python"
] | stackoverflow_0001415812_keyword_argument_python.txt |
Q:
What are the benefits of not using cPickle to create a persistent storage for data?
I'm considering the idea of creating a persistent storage like a dbms engine, what would be the benefits to create a custom binary format over directly cPickling the object and/or using the shelve module?
A:
Pickling is a two-fac... | What are the benefits of not using cPickle to create a persistent storage for data? | I'm considering the idea of creating a persistent storage like a dbms engine, what would be the benefits to create a custom binary format over directly cPickling the object and/or using the shelve module?
| [
"Pickling is a two-face coin.\nOn one side, you have a way to store your object in a very easy way. Just four lines of code and you pickle. You have the object exactly as it is.\nOn the other side, it can become a compatibility nightmare. You cannot unpickle objects if they are not defined in your code, exactly as ... | [
10,
3,
2,
1,
1,
1,
0
] | [] | [] | [
"data_structures",
"database",
"persistence",
"python"
] | stackoverflow_0001188585_data_structures_database_persistence_python.txt |
Q:
Google appengine string replacement in template file
I'm using google appengine (python, of course :) ) and I'd like to do a string.replace on a string from the template file.
{% for item in items %}
<p>{{ item.code.replace( '_', ' ' ) }}</p>
{% endfor %}
But that isn't working. So we cannot execute anything ... | Google appengine string replacement in template file | I'm using google appengine (python, of course :) ) and I'd like to do a string.replace on a string from the template file.
{% for item in items %}
<p>{{ item.code.replace( '_', ' ' ) }}</p>
{% endfor %}
But that isn't working. So we cannot execute anything other than basic checks in the app engine templates. Is t... | [
"Apart from the argument-less .fetch() call in your code, which I believe can't possibly work (you ALWAYS have to pass fetch an argument -- the max number of entities you're willing to fetch!), I can't reproduce your problem -- assigning a new attribute (including one obtained by processing existing ones) to each i... | [
1,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0001416921_google_app_engine_python.txt |
Q:
Riddle: The Square Puzzle
Last couple of days, I have refrained myself from master's studies and have been focusing on this (seemingly simple) puzzle:
There is this 10*10 grid which constitutes a square of 100 available places to go. The aim is to start from a corner and traverse through all the places with res... | Riddle: The Square Puzzle | Last couple of days, I have refrained myself from master's studies and have been focusing on this (seemingly simple) puzzle:
There is this 10*10 grid which constitutes a square of 100 available places to go. The aim is to start from a corner and traverse through all the places with respect to some simple "traverse r... | [
"This is very similar to the Knight's Tour problem which relates moving a knight around a chess board without revisiting the same square. Basically it's the same problem but with different \"Traverse Rules\".\nThe key optimisation I remember from tackling the Knights Tour recursively is take your next moves in inc... | [
15,
10,
8,
5,
1,
1,
0
] | [] | [] | [
"knights_tour",
"python"
] | stackoverflow_0000767912_knights_tour_python.txt |
Q:
Python code to Daemonize a process?
Can anyone share an efficient code snipper to daemonize a process in python?
A:
From http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/
(Wayback link)
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import sys, os, time, atexit
from signal import SIGTE... | Python code to Daemonize a process? | Can anyone share an efficient code snipper to daemonize a process in python?
| [
"From http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/\n(Wayback link)\n#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n\nimport sys, os, time, atexit\nfrom signal import SIGTERM \n\nclass Daemon:\n \"\"\"\n A generic daemon class.\n\n Usage: subclass the Daemon class and overrid... | [
4
] | [] | [] | [
"python"
] | stackoverflow_0001417631_python.txt |
Q:
Python: Warnings and logging verbose limit
I want to unify the whole logging facility of my app. Any warning is raise an exception, next I catch it and pass it to the logger. But the question: Is there in logging any mute facility? Sometimes logger becomes too verbose. Sometimes for the reason of too noisy warning... | Python: Warnings and logging verbose limit | I want to unify the whole logging facility of my app. Any warning is raise an exception, next I catch it and pass it to the logger. But the question: Is there in logging any mute facility? Sometimes logger becomes too verbose. Sometimes for the reason of too noisy warnings, is there are any verbose limit in warnings?
h... | [
"Not only are there log levels, but there is a really flexible way of configuring them. If you are using named logger objects (e.g., logger = logging.getLogger(...)) then you can configure them appropriately. That will let you configure verbosity on a subsystem-by-subsystem basis where a subsystem is defined by t... | [
3,
0,
0
] | [] | [] | [
"logging",
"python",
"warnings"
] | stackoverflow_0001417665_logging_python_warnings.txt |
Q:
Sending cookies in a SOAP request using Suds
I'm trying to access a SOAP API using Suds. The SOAP API documentation states that I have to provide three cookies with some login data. How can I accomplish this?
A:
Set a "Cookie" HTTP Request Header having the required name/value pairs. This is how Cookie values ar... | Sending cookies in a SOAP request using Suds | I'm trying to access a SOAP API using Suds. The SOAP API documentation states that I have to provide three cookies with some login data. How can I accomplish this?
| [
"Set a \"Cookie\" HTTP Request Header having the required name/value pairs. This is how Cookie values are usually transmitted in HTTP Based systems. You can add multiple key/value pairs in the same http header.\nSingle Cookie\n\nCookie: name1=value1\n\nMultiple Cookies (seperated by semicolons)\n\nCookie: name1=val... | [
4
] | [] | [] | [
"cookies",
"python",
"soap",
"suds"
] | stackoverflow_0001417902_cookies_python_soap_suds.txt |
Q:
Twisted - listen to multiple ports for multiple processes with one reactor
i need to run multiple instances of my server app each on it's own port. It's not a problem if i start these with os.system or subprocess.Popen, but i'd like to have some process communication with multiprocessing.
I'd like to somehow dyna... | Twisted - listen to multiple ports for multiple processes with one reactor | i need to run multiple instances of my server app each on it's own port. It's not a problem if i start these with os.system or subprocess.Popen, but i'd like to have some process communication with multiprocessing.
I'd like to somehow dynamically set up listening to different port from different processes. Just callin... | [
"I am not sure what error you are getting.\nThe following is an example from twisted site (modified)\nAnd as you can see, it listen on two ports, and can listen to many more.\nfrom twisted.internet.protocol import Protocol, Factory\nfrom twisted.internet import reactor\n\nclass QOTD(Protocol):\n\n def connection... | [
12
] | [] | [] | [
"process",
"python",
"twisted"
] | stackoverflow_0001411281_process_python_twisted.txt |
Q:
Time out error while creating cgi.FieldStorage object
Hey, any idea about what is the timeout error which I am getting here:
Error trace:
File "/array/purato/python2.6/lib/python2.6/site-packages/cherrypy/_cprequest.py", line 606, in respond
cherrypy.re... | Time out error while creating cgi.FieldStorage object | Hey, any idea about what is the timeout error which I am getting here:
Error trace:
File "/array/purato/python2.6/lib/python2.6/site-packages/cherrypy/_cprequest.py", line 606, in respond
cherrypy.response.body = self.handler() ... | [
"\nenviron={'REQUEST_METHOD':'POST'} \n\nThat seems a rather deficient environ. The CGI spec requires many more environment variables to be in there, some of which the cgi module is going to need.\nIn particular there is no CONTENT_LENGTH header. Without it, cgi is defaulting to reading the entire contents of the s... | [
0
] | [] | [] | [
"cgi",
"cherrypy",
"python"
] | stackoverflow_0001417918_cgi_cherrypy_python.txt |
Q:
django newbie. Having trouble with ModelForm
i'm trying to write a very simple django app. I cant get it to show my form inside my template.
<form ...>
{{form.as_p}}
</form>
it shows absolutely nothing. If I add a submit button, it only shows that.
Do I have to declare a form object that inherits from forms.Form ... | django newbie. Having trouble with ModelForm | i'm trying to write a very simple django app. I cant get it to show my form inside my template.
<form ...>
{{form.as_p}}
</form>
it shows absolutely nothing. If I add a submit button, it only shows that.
Do I have to declare a form object that inherits from forms.Form ? Cant it be done with ModelForms?
[UPDATE]Solved!... | [
"The problem is in your view. You will have no existing student object to retrieve from the database. The following code sample will help you implement an \"create\" view.\nAs a side note, you might like using the direct_to_template generic view function to make your life a bit easier.\ndef add_student(request):\n... | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001418149_django_python.txt |
Q:
Which is more pythonic for array removal?
I'm removing an item from an array if it exists.
Two ways I can think of to do this
Way #1
# x array, r item to remove
if r in x :
x.remove( r )
Way #2
try :
x.remove( r )
except :
pass
Timing it shows the try/except way can be faster
(some times i'm getting:)
1... | Which is more pythonic for array removal? | I'm removing an item from an array if it exists.
Two ways I can think of to do this
Way #1
# x array, r item to remove
if r in x :
x.remove( r )
Way #2
try :
x.remove( r )
except :
pass
Timing it shows the try/except way can be faster
(some times i'm getting:)
1.16225508968e-06
8.80804972547e-07
1.143141965... | [
"I've always gone with the first method. if in reads far more clearly than exception handling does.\n",
"that would be:\ntry:\n x.remove(r)\nexcept ValueError:\n pass\n\nbtw, you should have tried to remove an item that is not in the list, to have a comprehensive comparison.\n",
"Speed depends on the ratio o... | [
6,
5,
3,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0001418266_python.txt |
Q:
Access an instance from Terminal
Can't figure this out. In Terminal, I import a module which instantiates a class, which I haven't figured out how to access. Of course, I can always instantiate in Terminal:
Server=Data.ServerData()
Then I can get a result:
Server.Property().DefaultChart
However, I want to skip... | Access an instance from Terminal | Can't figure this out. In Terminal, I import a module which instantiates a class, which I haven't figured out how to access. Of course, I can always instantiate in Terminal:
Server=Data.ServerData()
Then I can get a result:
Server.Property().DefaultChart
However, I want to skip that step getting the result directly... | [
"If importing Data.py implicitly creates an instance of the Data.ServerData class (somewhat dubious, but OK in certain cases), that still tells us nothing about how that module chose to name that one instance. Do dir(Data) at the >>> prompt to see all the names defined in the Data module; if you want to see what n... | [
2
] | [] | [] | [
"class",
"instance",
"interactive",
"module",
"python"
] | stackoverflow_0001418262_class_instance_interactive_module_python.txt |
Q:
Python implementation question
Hey. I have a problem I'm trying to solve in Python and I can't think of a clever implementation. The input is a string of letters. Some of them represent variables, others represent operators, and I want to iterate over a large amount of values for the variables (different configura... | Python implementation question | Hey. I have a problem I'm trying to solve in Python and I can't think of a clever implementation. The input is a string of letters. Some of them represent variables, others represent operators, and I want to iterate over a large amount of values for the variables (different configurations).
I think an equivalent questi... | [
"as Ira said you need an expression evaluator like Lex/Yacc to do this job, you have plenty available here :\nhttp://wiki.python.org/moin/LanguageParsing\nI have been using pyparsing and works greats for that kind of things\n",
"What you want is obviously an expression evaluator.\nOther you use a built in facilit... | [
1,
0,
0,
0
] | [] | [] | [
"data_structures",
"formula",
"implementation",
"python"
] | stackoverflow_0001418255_data_structures_formula_implementation_python.txt |
Q:
Any experiences with Protocol Buffers?
I was just looking through some information about Google's protocol buffers data interchange format. Has anyone played around with the code or even created a project around it?
I'm currently using XML in a Python project for structured content created by hand in a text edito... | Any experiences with Protocol Buffers? | I was just looking through some information about Google's protocol buffers data interchange format. Has anyone played around with the code or even created a project around it?
I'm currently using XML in a Python project for structured content created by hand in a text editor, and I was wondering what the general opin... | [
"If you are looking for user facing interaction, stick with xml. It has more support, understanding, and general acceptance currently. If it's internal, I would say that protocol buffers are a great idea.\nMaybe in a few years as more tools come out to support protocol buffers, then start looking towards that for a... | [
13,
11,
4,
3
] | [] | [] | [
"database",
"protocol_buffers",
"python",
"xml"
] | stackoverflow_0000001734_database_protocol_buffers_python_xml.txt |
Q:
Call Python from C++
I'm trying to call a function in a Python script from my main C++ program. The python function takes a string as the argument and returns nothing (ok.. 'None').
It works perfectly well (never thought it would be that easy..) as long as the previous call is finished before the function is call... | Call Python from C++ | I'm trying to call a function in a Python script from my main C++ program. The python function takes a string as the argument and returns nothing (ok.. 'None').
It works perfectly well (never thought it would be that easy..) as long as the previous call is finished before the function is called again, otherwise there ... | [
"When you say \"as long as the previous call is finished before the function is called again\", I can only assume that you have multiple threads calling from C++ into Python. The python is not thread safe, so this is going to fail!\nRead up on the Global Interpreter Lock (GIL) in the Python manual. Perhaps the fo... | [
5,
1
] | [] | [] | [
"c",
"c++",
"python"
] | stackoverflow_0001417473_c_c++_python.txt |
Q:
Are Python list comprehensions the same thing as map/grep in Perl?
I was having some trouble grokking the list comprehension syntax in Python, so I started thinking about how to achieve the same thing in Perl, which I'm more familiar with. I realized that the basic examples (taken from this page) can all be done i... | Are Python list comprehensions the same thing as map/grep in Perl? | I was having some trouble grokking the list comprehension syntax in Python, so I started thinking about how to achieve the same thing in Perl, which I'm more familiar with. I realized that the basic examples (taken from this page) can all be done in Perl with map or grep.
E.g.
(python) (perl)... | [
"You are correct: a list comprehension is essentially just syntactic sugar for map and filter (terms from the functional programming world).\nHopefully this sample code demonstrates their equality:\n>>> # Python 2\n>>> [x**2 for x in range(10)] == map(lambda x: x**2, range(10))\nTrue\n>>> [2**i for i in range(13)] ... | [
15,
3,
3,
2,
0,
0
] | [] | [] | [
"list",
"perl",
"python"
] | stackoverflow_0001418912_list_perl_python.txt |
Q:
Python memory leaks?
I am writing a python extension that seems to be leaking memory. I am trying to figure out the soure of the problem using valgrind.
However, it seems that python itself is leaking memory according to valgrind. Using the following simple script:
hello.py
print "Hello World!"
and doing
> va... | Python memory leaks? | I am writing a python extension that seems to be leaking memory. I am trying to figure out the soure of the problem using valgrind.
However, it seems that python itself is leaking memory according to valgrind. Using the following simple script:
hello.py
print "Hello World!"
and doing
> valgrind --tool=memcheck pyt... | [
"There's a whole README.valgrind in the Python sources that explains the various caveats trying to use Valgrind with Python:\nhttp://svn.python.org/projects/python/trunk/Misc/README.valgrind\nPython uses its own small-object allocation scheme on top of malloc,\ncalled PyMalloc.\n\nValgrind may show some unexpected ... | [
12,
2
] | [] | [] | [
"memory",
"memory_management",
"python",
"valgrind"
] | stackoverflow_0001419065_memory_memory_management_python_valgrind.txt |
Q:
appengine select based on timestamp
I can't seem to select something based on timestamp. The behavior is a bit weird and the < and = symbols don't seem to mean what I expect them to.
""" A site message """
class Message( db.Model ) :
# from/to/ a few other fields
subject = db.StringProperty()
body = db.Tex... | appengine select based on timestamp | I can't seem to select something based on timestamp. The behavior is a bit weird and the < and = symbols don't seem to mean what I expect them to.
""" A site message """
class Message( db.Model ) :
# from/to/ a few other fields
subject = db.StringProperty()
body = db.Text()
# this is the field i'm trying to ... | [
"Do NOT use strings to \"stand in\" for datetimes! It just won't work...\nSee the docs: DateTimeProperty corresponds to a datetime.datetime value. import datetime, convert your beloved strings to datetime.datetime instances (e.g. by calling the strptime method thereof), use THOSE instances for comparisons -- and,... | [
5
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0001419354_google_app_engine_python.txt |
Q:
How to forward port to router using python
I am building python p2p application like p2p instant messenger. I am communicating with other peers using TCP/IP connection. I do not want client to do port forwarding.
When application starts it should check whether port is forwarded to router if not it should forward ... | How to forward port to router using python | I am building python p2p application like p2p instant messenger. I am communicating with other peers using TCP/IP connection. I do not want client to do port forwarding.
When application starts it should check whether port is forwarded to router if not it should forward it to router.
Is it possible to programaticaly f... | [
"You may find the post and files listed here helpful. This person implemented a Nat PMP library in Python.\nhttp://blog.yimingliu.com/2008/01/07/nat-pmp-client-library-for-python/\nIf you want to use port 80 for p2p communication, you will simply just need to write your own protocol in HTTP and connect over port 80... | [
1
] | [] | [] | [
"p2p",
"portforwarding",
"python"
] | stackoverflow_0001419590_p2p_portforwarding_python.txt |
Q:
How to extract and then refer to variables defined in a python module?
I'm trying to build a simple environment check script for my firm's test environment. My goal is to be able to ping each of the hosts defined for a given test environment instance. The hosts are defined in a file like this:
#!/usr/bin/env pyt... | How to extract and then refer to variables defined in a python module? | I'm trying to build a simple environment check script for my firm's test environment. My goal is to be able to ping each of the hosts defined for a given test environment instance. The hosts are defined in a file like this:
#!/usr/bin/env python
host_ip = '192.168.100.10'
router_ip = '192.168.100.254'
fs_ip = '192.16... | [
"First off, I strongly recommend not doing it that way. Instead, do:\nhosts = {\n \"host_ip\": '192.168.100.10',\n \"router_ip\": '192.168.100.254',\n \"fs_ip\": '192.168.200.10',\n}\n\nThen you can simply import the module and reference it normally--this gives an ordinary, standard way to access this dat... | [
8,
2,
1,
0,
-2
] | [] | [] | [
"import",
"python",
"variables"
] | stackoverflow_0001419620_import_python_variables.txt |
Q:
Parsing unstructured text in Python
I wanted to parse a text file that contains unstructured text. I need to get the address, date of birth, name, sex, and ID.
. 55 MORILLO ZONE VIII,
BARANGAY ZONE VIII
(POB.), LUISIANA, LAGROS
F
01/16/1952
ALOMO, TERESITA CABALLES
3412-00000-A1652TCA2
12
. 22 FABRICANTE ST. Z... | Parsing unstructured text in Python | I wanted to parse a text file that contains unstructured text. I need to get the address, date of birth, name, sex, and ID.
. 55 MORILLO ZONE VIII,
BARANGAY ZONE VIII
(POB.), LUISIANA, LAGROS
F
01/16/1952
ALOMO, TERESITA CABALLES
3412-00000-A1652TCA2
12
. 22 FABRICANTE ST. ZONE
VIII LUISIANA LAGROS,
BARANGAY ZONE V... | [
"Here is a first stab at a pyparsing solution (easy-to-copy code at the pyparsing pastebin). Walk through the separate parts, according to the interleaved comments.\ndata = \"\"\"\\\n. 55 MORILLO ZONE VIII,\nBARANGAY ZONE VIII\n(POB.), LUISIANA, LAGROS\nF\n01/16/1952\nALOMO, TERESITA CABALLES\n3412-00000-A1652TCA2... | [
16,
4,
3,
2,
1
] | [] | [] | [
"parsing",
"python",
"text"
] | stackoverflow_0001419653_parsing_python_text.txt |
Q:
Cannot import file in Python/Django
I'm not sure what's going on, but on my own laptop, everything works okay. When I upload to my host with Python 2.3.5, my views.py can't find anything in my models.py. I have:
from dtms.models import User
from dtms.item_list import *
where my models, item_list, and views files ... | Cannot import file in Python/Django | I'm not sure what's going on, but on my own laptop, everything works okay. When I upload to my host with Python 2.3.5, my views.py can't find anything in my models.py. I have:
from dtms.models import User
from dtms.item_list import *
where my models, item_list, and views files are in /mysite/dtms/
It ends up telling m... | [
"The fact that from X import * works does not guarantee that from X import Wowie will work too, you know (if you could wean yourself away from that import * addiction you'd be WAY happier on the long run, but, that's another issue;-).\nMy general advice in import problems is to bracket the problematic import with t... | [
4,
2,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001419224_django_python.txt |
Q:
convert the key in MIME encoded form in python
I need to convert the key in MIME encoded form which is presently comes in (ascii armored) radix 64 format. For that, I have to get this radix64 format in its binary form and also need to remove its header and checksum than coversion in MIME format, but I didnt find a... | convert the key in MIME encoded form in python | I need to convert the key in MIME encoded form which is presently comes in (ascii armored) radix 64 format. For that, I have to get this radix64 format in its binary form and also need to remove its header and checksum than coversion in MIME format, but I didnt find any method which can do this conversion.
f = urllib.u... | [
"For a start, when you do use a valid search value (\"jay\" returns an error stating \"too many values\"), you will receive an HTML page from which you need to extract the actual key. Trying a search value of \"jaysh\" I get the following response:\n>>> print urllib.urlopen('http://pool.sks-keyservers.net:11371/pks... | [
0
] | [] | [] | [
"encoding",
"python"
] | stackoverflow_0001419686_encoding_python.txt |
Q:
How can I generate a complete histogram with numpy?
I have a very long list in a numpy.array. I want to generate a histogram for it. However, Numpy's built in histogram requires a pre-defined number of bins. What's the best way to generate a full histogram with one bin for each value?
A:
If you have an array ... | How can I generate a complete histogram with numpy? | I have a very long list in a numpy.array. I want to generate a histogram for it. However, Numpy's built in histogram requires a pre-defined number of bins. What's the best way to generate a full histogram with one bin for each value?
| [
"If you have an array of integers and the max value isn't too large you can use numpy.bincount:\nhist = dict((key,val) for key, val in enumerate(numpy.bincount(data)) if val)\n\nEdit:\nIf you have float data, or data spread over a huge range you can convert it to integers by doing:\nbins = numpy.unique(data)\nbinco... | [
8,
0
] | [] | [] | [
"histogram",
"numpy",
"python"
] | stackoverflow_0001420235_histogram_numpy_python.txt |
Q:
How to install distutils packages using distutils api or setuptools api
I'm working on a buildout script that needs to install a distutils package on remote server.
On PyPi there are 2 recipes for doing this
collective.recipe.distutils 0.1 and zerokspot.recipe.distutils 0.1.1.
The later module a derivative of the ... | How to install distutils packages using distutils api or setuptools api | I'm working on a buildout script that needs to install a distutils package on remote server.
On PyPi there are 2 recipes for doing this
collective.recipe.distutils 0.1 and zerokspot.recipe.distutils 0.1.1.
The later module a derivative of the former, and is a little more convenient then the first, but the both suffer f... | [
"You can call a command line program within your Python program using the subprocess module:\nimport subprocess\nsubprocess.call('python setup.py install')\n\nHowever, how much control do you have over the environment that this install will be run? If it is a package that you are distributing, you will likely have ... | [
1,
1,
0
] | [] | [] | [
"buildout",
"distutils",
"python"
] | stackoverflow_0001419379_buildout_distutils_python.txt |
Q:
How do I loop through relationships in a list only once?
I have a list of users:
users = [1,2,3,4,5]
I want to compute a relationship between them:
score = compatibility( user[0], user[1] )
How do I loop over users so that a relationship between users are computed only once?
A:
If you care only about ordered r... | How do I loop through relationships in a list only once? | I have a list of users:
users = [1,2,3,4,5]
I want to compute a relationship between them:
score = compatibility( user[0], user[1] )
How do I loop over users so that a relationship between users are computed only once?
| [
"If you care only about ordered relationship, you could do the following:\n>>> for i, u in enumerate(users[1:]):\n print(users[i], u) # or do something else\n\n\n1 2\n2 3\n3 4\n4 5\n\nif you need all combinations you should use itertools.combinations:\n>>> import itertools\n>>> for i in itertools.combi... | [
11,
0,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0001420705_python.txt |
Q:
setuptools / dpkg-buildpackage: Refuse to build if nosetests fail
I have a very simple python package that I build into debian packages using setuptools, cdbs and pycentral:
setup.py:
from setuptools import setup
setup(name='PHPSerialize',
version='1.0',
py_modules=['PHPSerialize'],
test_suite = 'nose.collec... | setuptools / dpkg-buildpackage: Refuse to build if nosetests fail | I have a very simple python package that I build into debian packages using setuptools, cdbs and pycentral:
setup.py:
from setuptools import setup
setup(name='PHPSerialize',
version='1.0',
py_modules=['PHPSerialize'],
test_suite = 'nose.collector'
)
debian/rules:
#!/usr/bin/make -f
DEB_PYTHON_SYSTEM = pycentral... | [
"Try\nbuild/yourpackage::\n nosetests\n\n"
] | [
2
] | [] | [] | [
"cdbs",
"debian",
"nose",
"python",
"setuptools"
] | stackoverflow_0001231958_cdbs_debian_nose_python_setuptools.txt |
Q:
Detecting the http request type (GET, HEAD, etc) from a python cgi
How can I find out the http request my python cgi received? I need different behaviors for HEAD and GET.
Thanks!
A:
import os
if os.environ['REQUEST_METHOD'] == 'GET':
# blah
A:
Why do you need to distinguish between GET and HEAD?
Normally... | Detecting the http request type (GET, HEAD, etc) from a python cgi | How can I find out the http request my python cgi received? I need different behaviors for HEAD and GET.
Thanks!
| [
"import os\n\nif os.environ['REQUEST_METHOD'] == 'GET':\n # blah\n\n",
"Why do you need to distinguish between GET and HEAD?\nNormally you shouldn't distinguish and should treat a HEAD request just like a GET. This is because a HEAD request is meant to return the exact same headers as a GET. The only differenc... | [
17,
0
] | [
"This is not a direct answer to your question. But your question stems from doing things the wrong way.\nDo not write Python CGI scripts.\nWrite a mod_wsgi application. Better still, use a Python web framework. There are dozens. Choose one like Werkzeug.\nThe WSGI standard (described in PEP 333) makes it much, ... | [
-1
] | [
"cgi",
"http",
"httpwebrequest",
"python"
] | stackoverflow_0001417715_cgi_http_httpwebrequest_python.txt |
Q:
What variable name do you use for file descriptors?
A pretty silly trivial question. The canonical example is f = open('filename'), but
f is not very descriptive. After not looking at code in a while,
you can forget whether it means
"file" or "function f(x)" or "fourier
transform results" or something else. EI... | What variable name do you use for file descriptors? | A pretty silly trivial question. The canonical example is f = open('filename'), but
f is not very descriptive. After not looking at code in a while,
you can forget whether it means
"file" or "function f(x)" or "fourier
transform results" or something else. EIBTI.
In Python, file is already taken by a function.
Wha... | [
" data_file\n settings_file\n results_file\n .... etc\n\n",
"You can append it to the beginning, Hungarian-like \"file_fft\".\nHowever, I would try to close file descriptors as soon as possible, and I recommend using the with statement like this so you don't have to worry about closing it, and it makes it easier ... | [
8,
6,
4,
3,
2,
0
] | [] | [] | [
"explicit",
"file",
"naming_conventions",
"python",
"variable_names"
] | stackoverflow_0001419039_explicit_file_naming_conventions_python_variable_names.txt |
Q:
How can I add a decorator to an existing object method?
If I'm using a module/class I have no control over, how would I decorate one of the methods?
I understand I can: my_decorate_method(target_method)() but I'm looking to have this happen wherever target_method is called without having to do a search/replace.
I... | How can I add a decorator to an existing object method? | If I'm using a module/class I have no control over, how would I decorate one of the methods?
I understand I can: my_decorate_method(target_method)() but I'm looking to have this happen wherever target_method is called without having to do a search/replace.
Is it even possible?
| [
"Don't do this.\nUse inheritance.\nimport some_module\n\nclass MyVersionOfAClass( some_module.AClass ):\n def someMethod( self, *args, **kwargs ):\n # do your \"decoration\" here.\n super( MyVersionOfAClass, self ). someMethod( *args, **kwargs )\n # you can also do \"decoration\" here.\n\nNo... | [
7,
3
] | [] | [] | [
"decorator",
"python"
] | stackoverflow_0001420484_decorator_python.txt |
Q:
How do I pass a string into subprocess.Popen in Python 2?
I would like to run a process from Python (2.4/2.5/2.6) using Popen, and I
would like to give it a string as its standard input.
I'll write an example where the process does a "head -n 1" its input.
The following works, but I would like to solve it in a nic... | How do I pass a string into subprocess.Popen in Python 2? | I would like to run a process from Python (2.4/2.5/2.6) using Popen, and I
would like to give it a string as its standard input.
I'll write an example where the process does a "head -n 1" its input.
The following works, but I would like to solve it in a nicer way, without using
echo:
>>> from subprocess import *
>>> p1... | [
"Have you tried to feed your string to communicate as a string?\nPopen.communicate(input=my_input)\n\nIt works like this:\np = subprocess.Popen([\"head\", \"-n\", \"1\"], stdin=subprocess.PIPE)\np.communicate('first\\nsecond')\n\noutput:\nfirst\n\nI forgot to set stdin to subprocess.PIPE when I tried it at first.\n... | [
8,
5
] | [] | [] | [
"popen",
"python"
] | stackoverflow_0001421311_popen_python.txt |
Q:
Python regular expression for HTML parsing (BeautifulSoup)
I want to grab the value of a hidden input field in HTML.
<input type="hidden" name="fooId" value="12-3456789-1111111111" />
I want to write a regular expression in Python that will return the value of fooId, given that I know the line in the HTML follows... | Python regular expression for HTML parsing (BeautifulSoup) | I want to grab the value of a hidden input field in HTML.
<input type="hidden" name="fooId" value="12-3456789-1111111111" />
I want to write a regular expression in Python that will return the value of fooId, given that I know the line in the HTML follows the format
<input type="hidden" name="fooId" value="**[id is he... | [
"For this particular case, BeautifulSoup is harder to write than a regex, but it is much more robust... I'm just contributing with the BeautifulSoup example, given that you already know which regexp to use :-)\nfrom BeautifulSoup import BeautifulSoup\n\n#Or retrieve it from the web, etc. \nhtml_data = open('/yourwe... | [
27,
18,
8,
5,
1,
0,
0
] | [] | [] | [
"python",
"regex",
"screen_scraping"
] | stackoverflow_0000055391_python_regex_screen_scraping.txt |
Q:
Set files to ownership of current directory in Python
I'm working on a Python script that creates text files containing size/space information about the directories that the script is run on. The script needs to be run as root, and as a result, it sets the text files that it creates to root's ownership.
I know I c... | Set files to ownership of current directory in Python | I'm working on a Python script that creates text files containing size/space information about the directories that the script is run on. The script needs to be run as root, and as a result, it sets the text files that it creates to root's ownership.
I know I can change the ownership with os.fchown, but how do I pass f... | [
"Use\nimport os, stat\ninfo = os.stat(dirpath)\nuid, gid = info[stat.ST_UID], info[stat.ST_GID]\n\n"
] | [
0
] | [] | [] | [
"permissions",
"python"
] | stackoverflow_0001421807_permissions_python.txt |
Q:
Debugging Ruby/Python/Groovy
I'm rephrasing this question because it was either too uninteresting or too incomprehensible. :)
The original question came about because I'm making the transation from Java to Groovy, but the example could apply equally when transitioning to any of the higher-level languages (Ruby, Py... | Debugging Ruby/Python/Groovy | I'm rephrasing this question because it was either too uninteresting or too incomprehensible. :)
The original question came about because I'm making the transation from Java to Groovy, but the example could apply equally when transitioning to any of the higher-level languages (Ruby, Python, Groovy).
Java is easy to deb... | [
"If I were to debug your example, the first thing I would do is break it down into multiple steps. I don't care if it's \"pythonic\" or \"the ruby way\" or \"tclish\" or whatever, code like that can be difficult to debug. \nThat's not to say I don't write code like that. Once it's been debugged it is sometimes OK t... | [
3,
2,
0
] | [] | [] | [
"debugging",
"dynamic_languages",
"groovy",
"python",
"ruby"
] | stackoverflow_0001205343_debugging_dynamic_languages_groovy_python_ruby.txt |
Q:
Switching databases in TG2 during runtime
I am doing an application which will use multiple sqlite3 databases, prepopuldated with data from an external application. Each database will have the exact same tables, but with different data.
I want to be able to switch between these databases according to user input. W... | Switching databases in TG2 during runtime | I am doing an application which will use multiple sqlite3 databases, prepopuldated with data from an external application. Each database will have the exact same tables, but with different data.
I want to be able to switch between these databases according to user input. What is the most elegant way to do that in Turbo... | [
"If ALL databases have the same schema then you should be able to create several Sessions using the same model to the different DBs.\n",
"Dzhelil,\nI wrote a blog post a while back about using multiple databases in TG2. You could combine this method with Jorge's suggestion of multiple DBSessions and I think you c... | [
1,
1,
1
] | [] | [] | [
"python",
"sqlite",
"turbogears",
"turbogears2"
] | stackoverflow_0001093589_python_sqlite_turbogears_turbogears2.txt |
Q:
pytz: Why is normalize needed when converting between timezones?
I'm reading the not so complete pytz documentation and I'm stuck on understand one part of it.
Converting between timezones also needs special attention. This also needs to use the normalize method to ensure the conversion is correct.
>>> utc_dt = ... | pytz: Why is normalize needed when converting between timezones? | I'm reading the not so complete pytz documentation and I'm stuck on understand one part of it.
Converting between timezones also needs special attention. This also needs to use the normalize method to ensure the conversion is correct.
>>> utc_dt = utc.localize(datetime.utcfromtimestamp(1143408899))
>>> utc_dt.strftim... | [
"From the pytz documentation:\n\nIn addition, if you perform date arithmetic on local times that cross DST boundaries, the results may be in an incorrect timezone (ie. subtract 1 minute from 2002-10-27 1:00 EST and you get 2002-10-27 0:59 EST instead of the correct 2002-10-27 1:59 EDT). A normalize() method is prov... | [
12,
6
] | [] | [] | [
"python",
"pytz",
"timezone"
] | stackoverflow_0001422880_python_pytz_timezone.txt |
Q:
Python and the built-in heap
At the moment, I am trying to write a priority queue in Python using the built in heapq library. However, I am stuck trying to get a handle on what Python does with the tie-breaking, I want to have a specific condition where I can dictate what happens with the tie-breaking instead of t... | Python and the built-in heap | At the moment, I am trying to write a priority queue in Python using the built in heapq library. However, I am stuck trying to get a handle on what Python does with the tie-breaking, I want to have a specific condition where I can dictate what happens with the tie-breaking instead of the heapq library that seems to alm... | [
"heapq uses the intrinsic comparisons on queue items (__le__ and friends). The general way to work around this limit is the good old approach known as \"decorate/undecorate\" -- that's what we used to do in sorting, before the key= parameter was introduced there.\nTo put it simply, you enqueue and dequeue, not just... | [
10
] | [] | [] | [
"python"
] | stackoverflow_0001422969_python.txt |
Q:
Negative lookahead after newline?
I have a CSV-like text file that has about 1000 lines. Between each record in the file is a long series of dashes. The records generally end with a \n, but sometimes there is an extra \n before the end of the record. Simplified example:
"1x", "1y", "Hi there"
---------------------... | Negative lookahead after newline? | I have a CSV-like text file that has about 1000 lines. Between each record in the file is a long series of dashes. The records generally end with a \n, but sometimes there is an extra \n before the end of the record. Simplified example:
"1x", "1y", "Hi there"
-------------------------------
"2x", "2y", "Hello - I'm los... | [
"This is a good place to use a generator function to skip the lines of ----'s and yield something that the csv module can read.\ndef readCleanLines( someFile ):\n for line in someFile:\n if line.strip() == len(line.strip())*'-':\n continue\n yield line\n\nreader= csv.reader( readCleanLin... | [
7,
5,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0001423260_python_regex.txt |
Q:
Can I run a Python script as a service?
Is it possible to run a Python script as a background service on a webserver? I want to do this for socket communication.
A:
You can make it a daemon. There is a PEP for a more complete solution, but I have found that this works well.
import os, sys
def become_daemon(our... | Can I run a Python script as a service? | Is it possible to run a Python script as a background service on a webserver? I want to do this for socket communication.
| [
"You can make it a daemon. There is a PEP for a more complete solution, but I have found that this works well.\nimport os, sys\n\ndef become_daemon(our_home_dir='.', out_log='/dev/null', err_log='/dev/null', pidfile='/var/tmp/daemon.pid'):\n \"\"\" Make the current process a daemon. \"\"\"\n\n try:\n ... | [
10,
7,
2,
2,
0,
0
] | [] | [] | [
"python",
"sockets",
"web_services",
"webserver"
] | stackoverflow_0001423345_python_sockets_web_services_webserver.txt |
Q:
What is wrong with this python function from "Programming Collective Intelligence"?
This is the function in question. It calculates the Pearson correlation coefficient for p1 and p2, which is supposed to be a number between -1 and 1.
When I use this with real user data, it sometimes returns a number greater than 1... | What is wrong with this python function from "Programming Collective Intelligence"? | This is the function in question. It calculates the Pearson correlation coefficient for p1 and p2, which is supposed to be a number between -1 and 1.
When I use this with real user data, it sometimes returns a number greater than 1, like in this example:
def sim_pearson(prefs,p1,p2):
si={}
for item in prefs[p1]... | [
"It looks like you may be unexpectedly using integer division. I made the following change and your function returned 1.0:\nnum=pSum-(1.0*sum1*sum2/n)\nden=sqrt((sum1Sq-1.0*pow(sum1,2)/n)*(sum2Sq-1.0*pow(sum2,2)/n))\n\nSee PEP 238 for more information on the division operator in Python. An alternate way of fixing y... | [
8,
2,
2,
1
] | [] | [] | [
"algorithm",
"pearson",
"python"
] | stackoverflow_0001423525_algorithm_pearson_python.txt |
Q:
adding the same object twice to a ManyToManyField
I have two django model classes:
class A(models.Model):
name = models.CharField(max_length = 128) #irrelevant
class B(models.Model):
a = models.ManyToManyField(A)
name = models.CharField(max_length = 128) #irrelevant
What I want to do is the ... | adding the same object twice to a ManyToManyField | I have two django model classes:
class A(models.Model):
name = models.CharField(max_length = 128) #irrelevant
class B(models.Model):
a = models.ManyToManyField(A)
name = models.CharField(max_length = 128) #irrelevant
What I want to do is the following:
a1 = A()
a2 = A()
b = B()
b.a.add(a1)
b.a.a... | [
"I think what you want is to use an intermediary model to form the M2M relationship using the through keyword argument in the ManyToManyField. Sort of like the first answer above, but more \"Django-y\".\nclass A(models.Model):\n name = models.CharField(max_length=200)\n\nclass B(models.Model):\n a = models.Ma... | [
8,
4,
2
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0001417825_django_django_models_python.txt |
Q:
hashlib / md5. Compatibility with python 2.4
python 2.6 reports that the md5 module is obsolete and hashlib should be used. If I change import md5 to import hashlib I will solve for python 2.5 and python 2.6, but not for python 2.4, which has no hashlib module (leading to a ImportError, which I can catch).
Now, to... | hashlib / md5. Compatibility with python 2.4 | python 2.6 reports that the md5 module is obsolete and hashlib should be used. If I change import md5 to import hashlib I will solve for python 2.5 and python 2.6, but not for python 2.4, which has no hashlib module (leading to a ImportError, which I can catch).
Now, to fix it, I could do a try/catch, and define a getM... | [
"In general the following construct is just fine:\ntry:\n import module\nexcept ImportError: \n # Do something else.\n\nIn your particular case, perhaps:\ntry: \n from hashlib import md5\nexcept ImportError:\n from md5 import md5\n\n",
"In the case where the modules have the same interface, as they do h... | [
18,
2
] | [] | [] | [
"backwards_compatibility",
"hashlib",
"import",
"md5",
"python"
] | stackoverflow_0001423861_backwards_compatibility_hashlib_import_md5_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.