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:
Mapping URL Pattern to a Single RequestHandler in a WSGIApplication
Is it possible to map a URL pattern (regular expression or some other mapping) to a single RequestHandler? If so how can I accomplish this?
Ideally I'd like to do something like this:
application=WSGIApplication([('/*',MyRequestHandler),])
So th... | Mapping URL Pattern to a Single RequestHandler in a WSGIApplication | Is it possible to map a URL pattern (regular expression or some other mapping) to a single RequestHandler? If so how can I accomplish this?
Ideally I'd like to do something like this:
application=WSGIApplication([('/*',MyRequestHandler),])
So that MyRequestHandler handles all requests made. Note that I'm working on a... | [
"The pattern you describe will work fine. Also, any groups in the regular expression you specify will be passed as arguments to the handler methods (get, post, etc). For example:\nclass MyRequestHandler(webapp.RequestHandler):\n def get(self, date, id):\n # Do stuff. Note that date and id are both strings, even... | [
8,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0001010427_google_app_engine_python.txt |
Q:
Will Dict Return Keys and Values in Same Order?
Possible Duplicate:
Python dictionary: are keys() and values() always the same order?
If i have a dictonary in python, will .keys and .values return the corresponding elements in the same order?
E.g.
foo = {'foobar' : 1, 'foobar2' : 4, 'kittty' : 34743}
For the ke... | Will Dict Return Keys and Values in Same Order? |
Possible Duplicate:
Python dictionary: are keys() and values() always the same order?
If i have a dictonary in python, will .keys and .values return the corresponding elements in the same order?
E.g.
foo = {'foobar' : 1, 'foobar2' : 4, 'kittty' : 34743}
For the keys it returns:
>>> foo.keys()
['foobar2', 'foobar', ... | [
"It's hard to improve on the Python documentation:\n\nKeys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions. If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called wi... | [
18,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0001012354_python.txt |
Q:
What is the purpose of the two colons in this Python string-slicing statement?
For example,
str = "hello"
str[1::3]
And where can I find this in Python documentation?
A:
in sequences' description:
s[i:j:k] slice of s from i to j with step k
The slice of s from i to j with step k is defined as the sequence o... | What is the purpose of the two colons in this Python string-slicing statement? | For example,
str = "hello"
str[1::3]
And where can I find this in Python documentation?
| [
"in sequences' description:\ns[i:j:k] slice of s from i to j with step k\n\n\nThe slice of s from i to j with step k is defined as the sequence of items with index x = i + n*k such that 0 <= n < (j-i)/k. In other words, the indices are i, i+k, i+2*k, i+3*k and so on, stopping when j is reached (but never includi... | [
20
] | [] | [] | [
"python",
"slice"
] | stackoverflow_0001013272_python_slice.txt |
Q:
Why does this python code hang on import/compile but work in the shell?
I'm trying to use python to sftp a file, and the code works great in the interactive shell -- even pasting it in all at once.
When I try to import the file (just to compile it), the code hangs with no exceptions or obvious errors.
How do I ... | Why does this python code hang on import/compile but work in the shell? | I'm trying to use python to sftp a file, and the code works great in the interactive shell -- even pasting it in all at once.
When I try to import the file (just to compile it), the code hangs with no exceptions or obvious errors.
How do I get the code to compile, or does someone have working code that accomplishes ... | [
"That's indeed a bad idea to execute this kind of code at import time, although I am not sure why it hangs - it may be that import mechanism does something strange which interacts badly with paramiko (thread related issues maybe ?). Anyway, the usual solution is to implement the functionality into a function:\ndef ... | [
5,
1,
0
] | [] | [] | [
"compilation",
"python",
"sftp",
"shell"
] | stackoverflow_0001013064_compilation_python_sftp_shell.txt |
Q:
Windows error and python
I'm working on a bit of code that is supposed to run an exe file inside a folder on my system and getting an error saying...
WindowsError: [Error 3] The system cannot find the path specified.
Here's a bit of the code:
exepath = os.path.join(EXE file localtion)
exepath = '"' + os.path.norm... | Windows error and python | I'm working on a bit of code that is supposed to run an exe file inside a folder on my system and getting an error saying...
WindowsError: [Error 3] The system cannot find the path specified.
Here's a bit of the code:
exepath = os.path.join(EXE file localtion)
exepath = '"' + os.path.normpath(exepath) + '"'
cmd = [exe... | [
"You need to properly escape the space in the executable path\n",
"Besides properly escaping spaces and other characters that could cause problems (such as /), you can also use the 8 character old DOS paths. \nFor example, Program Files would be:\nProgra~1 , making sure to append ~1 for the last two characters.\n... | [
3,
1,
0,
0
] | [] | [] | [
"popen",
"python"
] | stackoverflow_0001013311_popen_python.txt |
Q:
Swig bindings for python/lua do not initialize member data properly
I'm trying to build a set of Lua bindings for a collection of C++ classes, but have been toying with Python to see if I get better results. In either language the bindings seem to work, however, when I initialize an instance of a class that contai... | Swig bindings for python/lua do not initialize member data properly | I'm trying to build a set of Lua bindings for a collection of C++ classes, but have been toying with Python to see if I get better results. In either language the bindings seem to work, however, when I initialize an instance of a class that contains members of other classes, those data members do not seem to be guarant... | [
"Turns out this problem was related to another problem I was having. See this thread for the resolution.\n"
] | [
0
] | [] | [] | [
"initialization",
"lua",
"python",
"swig"
] | stackoverflow_0000916555_initialization_lua_python_swig.txt |
Q:
Creating a logging handler to connect to Oracle?
So right now i need to create and implement an extension of the Python logging module that will be used to log to our database. Basically we have several python applications(that all run in the background) that currently log to a random mishmash of text files. Which... | Creating a logging handler to connect to Oracle? | So right now i need to create and implement an extension of the Python logging module that will be used to log to our database. Basically we have several python applications(that all run in the background) that currently log to a random mishmash of text files. Which makes it almost impossible to find out if a certain a... | [
"\nIf errors occur with cx_Oracle, it's probably best to log these to a text file.\nYou could try redirecting sys.stdout and sys.stderr to file-like objects which log whatever's written to them to a logger.\nI would guess you do want to commit after each event, unless you have strong reasons for not doing this. Alt... | [
20
] | [] | [] | [
"logging",
"oracle",
"python"
] | stackoverflow_0000935930_logging_oracle_python.txt |
Q:
Traversing foreign key related tables in django templates
View
categories = Category.objects.all()
t = loader.get_template('index.html')
v = Context({
'categories': categories
})
return HttpResponse(t.render(v))
Template
{% for category in categories %}
<h1>{{ category.name }}</h1>
{% endfor %}
this work... | Traversing foreign key related tables in django templates | View
categories = Category.objects.all()
t = loader.get_template('index.html')
v = Context({
'categories': categories
})
return HttpResponse(t.render(v))
Template
{% for category in categories %}
<h1>{{ category.name }}</h1>
{% endfor %}
this works great. now im trying to print each company in that category. ... | [
"Just get rid of the parentheses:\n{% for company in category.company_set.all %}\n\nHere's the appropriate documentation. You can call methods that take 0 parameters this way.\n"
] | [
52
] | [] | [] | [
"django",
"django_models",
"django_templates",
"python"
] | stackoverflow_0001014591_django_django_models_django_templates_python.txt |
Q:
Python Authentication with urllib2
So I'm trying to download a file from a site called vsearch.cisco.com with python
[python]
#Connects to the Cisco Server and Downloads files at the URL specified
import urllib2
#Define Useful Variables
url = 'http://vsearch.cisco.com'
username = 'xxxxxxxx'
password = 'xxxxxxxx... | Python Authentication with urllib2 | So I'm trying to download a file from a site called vsearch.cisco.com with python
[python]
#Connects to the Cisco Server and Downloads files at the URL specified
import urllib2
#Define Useful Variables
url = 'http://vsearch.cisco.com'
username = 'xxxxxxxx'
password = 'xxxxxxxx'
realm = 'CEC'
# Begin Making connecti... | [
"A \"password manager\" might help:\n mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()\n mgr.add_password(None, url, user, password) \n urllib2.build_opener(urllib2.HTTPBasicAuthHandler(mgr),\n urllib2.HTTPDigestAuthHandler(mgr))\n\n",
"As for what I tried in my tests (http:... | [
8,
0
] | [] | [] | [
"python"
] | stackoverflow_0001014570_python.txt |
Q:
Running Python code contained in a string
I'm writing a game engine using pygame and box2d, and in the character builder, I want to be able to write the code that will be executed on keydown events.
My plan was to have a text editor in the character builder that let you write code similar to:
if key == K_a:
##... | Running Python code contained in a string | I'm writing a game engine using pygame and box2d, and in the character builder, I want to be able to write the code that will be executed on keydown events.
My plan was to have a text editor in the character builder that let you write code similar to:
if key == K_a:
## Move left
pass
elif key == K_d:
## Mov... | [
"You can use the eval(string) method to do this. \nDefinition\neval(code, globals=None, locals=None)\nThe code is just standard Python code - this means that it still needs to be properly indented. \nThe globals can have a custom __builtins__ defined, which could be useful for security purposes.\nExample\neval(\"p... | [
25,
2,
0,
0
] | [] | [] | [
"eval",
"exec",
"pygame",
"python"
] | stackoverflow_0001015142_eval_exec_pygame_python.txt |
Q:
Logging All Exceptions in a pyqt4 app
What's the best way to log all of the exceptions in a pyqt4 application using the standard python logging api?
I've tried wrapping exec_() in a try, except block, and logging the exceptions from that, but it only logs exceptions from the initialization of the app.
As a tempora... | Logging All Exceptions in a pyqt4 app | What's the best way to log all of the exceptions in a pyqt4 application using the standard python logging api?
I've tried wrapping exec_() in a try, except block, and logging the exceptions from that, but it only logs exceptions from the initialization of the app.
As a temporary solution, I wrapped the most important m... | [
"You need to override sys.excepthook\ndef my_excepthook(type, value, tback):\n # log the exception here\n\n # then call the default handler\n sys.__excepthook__(type, value, tback) \n\nsys.excepthook = my_excepthook\n\n"
] | [
16
] | [] | [] | [
"logging",
"pyqt",
"python"
] | stackoverflow_0001015047_logging_pyqt_python.txt |
Q:
How do I compile Python C extensions using MinGW inside a virtualenv?
When using virtualenv in combination with the MinGW compiler on Windows, compiling a C extension results in the following error:
C:\MinGW\bin\..\lib\gcc\mingw32\3.4.5\..\..\..\..\mingw32\bin\ld.exe: cannot find -lpython25
collect2: ld returned... | How do I compile Python C extensions using MinGW inside a virtualenv? | When using virtualenv in combination with the MinGW compiler on Windows, compiling a C extension results in the following error:
C:\MinGW\bin\..\lib\gcc\mingw32\3.4.5\..\..\..\..\mingw32\bin\ld.exe: cannot find -lpython25
collect2: ld returned 1 exit status
error: Setup script exited with error: command 'gcc' failed... | [
"Set the LIBRARY_PATH environment variable so MinGW knows where to find the system-wide Python libpython25.a.\nPlace a line in your virtualenv's activate.bat:\nset LIBRARY_PATH=c:\\python25\\libs\n\nOr set a global environment variable in Windows.\nBe sure to change 25 to correspond to your version of Python if you... | [
6
] | [] | [] | [
"mingw",
"python",
"virtualenv"
] | stackoverflow_0001015605_mingw_python_virtualenv.txt |
Q:
Why is `self` in Python objects immutable?
Why can't I perform an action like the following:
class Test(object):
def __init__(self):
self = 5
t = Test()
print t
I would expect it to print 5 since we're overwriting the instance with it, but instead it doesn't do anything at all. Doesn't even throw an ... | Why is `self` in Python objects immutable? | Why can't I perform an action like the following:
class Test(object):
def __init__(self):
self = 5
t = Test()
print t
I would expect it to print 5 since we're overwriting the instance with it, but instead it doesn't do anything at all. Doesn't even throw an error. Just ignores the assignment.
I understand... | [
"Any simple assignment to any argument of any function behaves exactly the same way in Python: binds that name to a different value, and does nothing else whatsoever. \"No special case is special enough to break the rules\", as the Zen of Python says!-)\nSo, far from it being odd (that simply=assigning to a specifi... | [
63,
10,
3,
1,
1
] | [
"class Test(object):\n def __init__(self):\n self = 5\n\nt = Test()\nprint t\n\nis like having this PHP (only other lang i know, sorry)\nclass Test {\n function __construct() {\n $this = 5;\n }\n}\n\nI don't see how it makes sense. replacing the instance with a value?\n"
] | [
-3
] | [
"object",
"python"
] | stackoverflow_0001015592_object_python.txt |
Q:
How can I accurately program an automated "click" on Windows?
I wrote a program to click on an application automatically at scheduled time using Win32, using MOUSE_DOWN and MOUSE_UP. It usually works well, except I found that I need to put in a
sleep 0.1
between the MOUSE_DOWN and MOUSE_UP. (using Ruby, which ... | How can I accurately program an automated "click" on Windows? | I wrote a program to click on an application automatically at scheduled time using Win32, using MOUSE_DOWN and MOUSE_UP. It usually works well, except I found that I need to put in a
sleep 0.1
between the MOUSE_DOWN and MOUSE_UP. (using Ruby, which allows sleeping a fraction of a second).
Without the sleep, sometim... | [
"If you're not bound to a specific language you could have a look at AutoIt which is made especially for things like this.\nI had good experiences with it for automating things like mouseclicks or keystrokes.\n",
"You do not decide what delay setting between mouse down and mouse up results in a valid single click... | [
3,
3,
1,
1,
1,
1
] | [] | [] | [
"perl",
"python",
"ruby",
"winapi",
"windows"
] | stackoverflow_0001011799_perl_python_ruby_winapi_windows.txt |
Q:
What does : TypeError: cannot concatenate 'str' and 'list' objects mean?
What does this error mean?
TypeError: cannot concatenate 'str' and 'list' objects
Here's part of the code:
for j in ('90.','52.62263.','26.5651.','10.8123.'):
if j == '90.':
z = ('0.')
elif j == '52.62263.':
z = ('0.... | What does : TypeError: cannot concatenate 'str' and 'list' objects mean? | What does this error mean?
TypeError: cannot concatenate 'str' and 'list' objects
Here's part of the code:
for j in ('90.','52.62263.','26.5651.','10.8123.'):
if j == '90.':
z = ('0.')
elif j == '52.62263.':
z = ('0.', '72.', '144.', '216.', '288.')
for k in z:
exepath = os.path.j... | [
"I'm not sure you're aware that cmd is a one-element list, and not a string.\nChanging that line to the below would construct a string, and the rest of your code will work:\n# Just removing the square brackets\ncmd = exepath + '-j' + str(j) + '-n' + str(z)\n\nI assume you used brackets just to group the operations.... | [
11,
4,
2
] | [] | [] | [
"python",
"string"
] | stackoverflow_0001014503_python_string.txt |
Q:
Combining C and Python functions in a module
I have a C extension module, to which I would like to add some Python utility functions. Is there a recommended way of doing this?
For example:
import my_module
my_module.super_fast_written_in_C()
my_module.written_in_Python__easy_to_maintain()
I'm primarily intereste... | Combining C and Python functions in a module | I have a C extension module, to which I would like to add some Python utility functions. Is there a recommended way of doing this?
For example:
import my_module
my_module.super_fast_written_in_C()
my_module.written_in_Python__easy_to_maintain()
I'm primarily interested in Python 2.x.
| [
"The usual way of doing this is: mymod.py contains the utility functions written in Python, and imports the goodies in the _mymod module which is written in C and is imported from _mymod.so or _mymod.pyd. For example, look at .../Lib/csv.py in your Python distribution.\n",
"Prefix your native extension with an un... | [
8,
5,
1
] | [] | [] | [
"cpython",
"python"
] | stackoverflow_0001013449_cpython_python.txt |
Q:
python ORM allowing for table creation and bulk inserting?
I'm looking for an ORM that allows me to do bulk inserts, as well as create code based on python classes. I tried sqlobject, it worked fine for creating the tables but inserting was unacceptibly slow for the amount of data I wanted to insert. If such an OR... | python ORM allowing for table creation and bulk inserting? | I'm looking for an ORM that allows me to do bulk inserts, as well as create code based on python classes. I tried sqlobject, it worked fine for creating the tables but inserting was unacceptibly slow for the amount of data I wanted to insert. If such an ORM doesn't exist any pointers on classes that can help with thing... | [
"You might want to try SQLAlchemy.\n",
"I believe sqlalchemy has bulk inserts, but I haven't ever used it. However, it stacks up favorably in benchmark tests according to this this reviewer.\nEDIT: It doesn't seem clear how he's using SQLAlchemy...whether it's the actual ORM or just query code. Reading the blo... | [
5,
0,
0
] | [] | [] | [
"database",
"orm",
"python"
] | stackoverflow_0001013282_database_orm_python.txt |
Q:
Processing pairs of values from two sequences in Clojure
I'm trying to get into the Clojure community. I've been working a lot with Python, and one of the features I make extensive use of is the zip() method, for iterating over pairs of values. Is there a (clever and short) way of achieving the same in Clojure?
A... | Processing pairs of values from two sequences in Clojure | I'm trying to get into the Clojure community. I've been working a lot with Python, and one of the features I make extensive use of is the zip() method, for iterating over pairs of values. Is there a (clever and short) way of achieving the same in Clojure?
| [
"Another way is to simply use map together with some function that collects its arguments in a sequence, like this:\nuser=> (map vector '(1 2 3) \"abc\")\n([1 \\a] [2 \\b] [3 \\c])\n\n",
"(zipmap [:a :b :c] (range 3))\n-> {:c 2, :b 1, :a 0}\n\nIterating over maps happens pairwise, e.g. like this:\n(doseq [[k v] (... | [
12,
4,
3
] | [] | [] | [
"clojure",
"python",
"zip"
] | stackoverflow_0001009037_clojure_python_zip.txt |
Q:
Passing Formatted Text Through XSLT
I have formatted text (with newlines, tabs, etc.) coming in from a Telnet connection. I have a python script that manages the Telnet connection and embeds the Telnet response in XML that then gets passed through an XSLT transform. How do I pass that XML through the transform w... | Passing Formatted Text Through XSLT | I have formatted text (with newlines, tabs, etc.) coming in from a Telnet connection. I have a python script that manages the Telnet connection and embeds the Telnet response in XML that then gets passed through an XSLT transform. How do I pass that XML through the transform without losing the original formatting? I... | [
"You could embed the text you want to be untouched in a CDATA section.\n",
"Data stored in XML comes out the same way it goes in. So if you store the text in an element, no whitespace and newlines are lost unless you tamper with the data in the XSLT. \nEnclosing the text in CDATA is unnecessary unless there is so... | [
0,
0
] | [] | [] | [
"python",
"xslt"
] | stackoverflow_0001015816_python_xslt.txt |
Q:
Generate from generators
I have a generator that takes a number as an argument and yields other numbers.
I want to use the numbers yielded by this generator and pass them as arguments to the same generator, creating a chain of some length.
For example, mygenerator(2) yields 5, 4 and 6. Apply mygenerator to each of... | Generate from generators | I have a generator that takes a number as an argument and yields other numbers.
I want to use the numbers yielded by this generator and pass them as arguments to the same generator, creating a chain of some length.
For example, mygenerator(2) yields 5, 4 and 6. Apply mygenerator to each of these numbers, over and over ... | [
"Suppose our generator yields square and cube of given number that way it will output unique\nso if we want to get numbers at dist D in simplest case we can recursively get numbers at dist D-1 and then apply generator to them\ndef mygen(N):\n yield N**2\n yield N**3\n\ndef getSet(N, dist):\n if dist == 0:\... | [
3,
2,
0
] | [] | [] | [
"generator",
"python"
] | stackoverflow_0001016997_generator_python.txt |
Q:
How to link C lib against python for embedding under Windows?
I am working on an application written in C. One part of the application should embed python and there is my current problem. I try to link my source to the Python library but it does not work.
As I use MinGW I have created the python26.a file from pyth... | How to link C lib against python for embedding under Windows? | I am working on an application written in C. One part of the application should embed python and there is my current problem. I try to link my source to the Python library but it does not work.
As I use MinGW I have created the python26.a file from python26.lib with dlltool and put the *.a file in C:/Program Files (x86... | [
"Well on Windows the python distribution comes already with a libpython26.a in the libs subdir so there is no need to generate .a files using dll tools.\nI did try a little example with a single C file toto.c:\ngcc -shared -o ./toto.dll ./toto.c -I/Python26/include/ -L/Python26/libs -lpython26\n\nAnd it works like ... | [
3,
1,
1
] | [] | [] | [
"c",
"gcc",
"linker",
"python",
"windows"
] | stackoverflow_0001013441_c_gcc_linker_python_windows.txt |
Q:
wxProgressDialog like behaviour for a wxDialog
I want to create modal dialog but which shouldn't behave in a modal way i.e. control flow should continue
if i do
dlg = wx.Dialog(parent)
dlg.ShowModal()
print "xxx"
dlg.Destroy()
"xxx" will not get printed, but in case of progress dialog
dlg = wx.ProgressDialo... | wxProgressDialog like behaviour for a wxDialog | I want to create modal dialog but which shouldn't behave in a modal way i.e. control flow should continue
if i do
dlg = wx.Dialog(parent)
dlg.ShowModal()
print "xxx"
dlg.Destroy()
"xxx" will not get printed, but in case of progress dialog
dlg = wx.ProgressDialog.__init__(self,title, title, parent=parent, style=w... | [
"Just use Show instead of ShowModal.\nIf your function (the print \"xxx\" part) runs for a long time you will either have to manually call wx.SafeYield every so often or move your work to a separate thread and send custom events to your dialog from it.\nOne more tip. As I understand, you want to execute some code a... | [
1,
0
] | [] | [] | [
"modal_dialog",
"python",
"wxpython"
] | stackoverflow_0001006598_modal_dialog_python_wxpython.txt |
Q:
Bash or Python to go backwards?
I have a text file which a lot of random occurrences of the string @STRING_A, and I would be interested in writing a short script which removes only some of them. Particularly one that scans the file and once it finds a line which starts with this string like
@STRING_A
then checks ... | Bash or Python to go backwards? | I have a text file which a lot of random occurrences of the string @STRING_A, and I would be interested in writing a short script which removes only some of them. Particularly one that scans the file and once it finds a line which starts with this string like
@STRING_A
then checks if 3 lines backwards there is another... | [
"Funny that after all these hours nobody's yet given a solution to the problem as actually phrased (as @John Machin points out in a comment) -- remove just the leading marker (if followed by another such marker 3 lines down), not the whole line containing it. It's not hard, of course -- here's a tiny mod as needed ... | [
4,
2,
2,
1,
1,
1,
0,
0
] | [
"In bash you can use sort -r filename and tail -n filename to read the file backwards.\n$LINES=`tail -n filename | sort -r`\n# now iterate through the lines and do your checking\n\n",
"This may be what you're looking for?\nlines = open('sample.txt').readlines()\n\nneedle = \"@string \"\n\nfor i,line in enumerate(... | [
-1,
-1,
-2
] | [
"bash",
"python"
] | stackoverflow_0001012490_bash_python.txt |
Q:
Python cgi performance
I own a legacy python application written as CGI. Until now this works OK, but the number of concurrent users will increment largely in the very near future.
Here on SO I read: "CGI is great for low-traffic websites, but it has some performance problems for anything else". I know it would ha... | Python cgi performance | I own a legacy python application written as CGI. Until now this works OK, but the number of concurrent users will increment largely in the very near future.
Here on SO I read: "CGI is great for low-traffic websites, but it has some performance problems for anything else". I know it would have been better to start in a... | [
"CGI doesn't scale because each request forks a brand new server process. It's a lot of overhead. mod_wsgi avoid the overhead by forking one process and handing requests to that one running process.\nLet's assume the application is the worst kind of cgi.\nThe worst case is that it has files like this.\nmy_cgi.py\... | [
6,
3
] | [] | [] | [
"cgi",
"performance",
"python"
] | stackoverflow_0001017087_cgi_performance_python.txt |
Q:
UnicodeDecodeError when reading dictionary words file with simple Python script
First time doing Python in a while, and I'm having trouble doing a simple scan of a file when I run the following script with Python 3.0.1,
with open("/usr/share/dict/words", 'r') as f:
for line in f:
pass
I get this excepti... | UnicodeDecodeError when reading dictionary words file with simple Python script | First time doing Python in a while, and I'm having trouble doing a simple scan of a file when I run the following script with Python 3.0.1,
with open("/usr/share/dict/words", 'r') as f:
for line in f:
pass
I get this exception:
Traceback (most recent call last):
File "/home/matt/install/test.py", line 2, i... | [
"Can you check to make sure it is valid UTF-8? A way to do that is given at this SO question:\niconv -f UTF-8 /usr/share/dict/words -o /dev/null\n\nThere are other ways to do the same thing.\n",
"How have you determined from \"position 1689-1692\" what line in the file it has blown up on? Those numbers would be ... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0001017334_python.txt |
Q:
simple update in sqlalchemy
UserTable is:
id (INT)
name (STR)
last_login (DATETIME)
Serving a web page request i have a user id in hand and I only wish to update the last_login field to 'now'.
It seems to me that there are 2 ways:
issue a direct SQL using db_engine (losing the mapper)
OR query the user first an... | simple update in sqlalchemy | UserTable is:
id (INT)
name (STR)
last_login (DATETIME)
Serving a web page request i have a user id in hand and I only wish to update the last_login field to 'now'.
It seems to me that there are 2 ways:
issue a direct SQL using db_engine (losing the mapper)
OR query the user first and then update the object
Both wo... | [
"Assuming you have a mapper UserTable in place:\nDBSession.query(UserTable).filter_by(id = user_id).\\\n update({\"last_login\":datetime.datetime.now()}, synchronize_session=False)\n\nAdditional parameters in the docs.\n"
] | [
23
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0001017388_python_sqlalchemy.txt |
Q:
NameError: global name 'has_no_changeset' is not defined
OK - Python newbie here - I assume I am doing something really stupid, could you please tell me what it is so we can all get on with our lives?
I get the error NameError: global name 'has_no_changeset' is not defined in the line 55 (where I try calling the f... | NameError: global name 'has_no_changeset' is not defined | OK - Python newbie here - I assume I am doing something really stupid, could you please tell me what it is so we can all get on with our lives?
I get the error NameError: global name 'has_no_changeset' is not defined in the line 55 (where I try calling the function has_no_changeset).
from genshi.builder import tag
fro... | [
"You need to explicitly specify self (or in your case, me) when referring to a method of the current class:\nif me.has_no_changeset(ticket):\n\nYou're using me instead of self - that's legal but strongly discouraged. The first parameter of member functions should be called self:\ndef validate_ticket(self, req, tic... | [
4
] | [] | [] | [
"python",
"syntax"
] | stackoverflow_0001017467_python_syntax.txt |
Q:
backend for python
which is the best back end for python applications and what is the advantage of using sqlite ,how it can be connected to python applications
A:
What do you mean with back end? Python apps connect to SQLite just like any other database, you just have to import the correct module and check how t... | backend for python | which is the best back end for python applications and what is the advantage of using sqlite ,how it can be connected to python applications
| [
"What do you mean with back end? Python apps connect to SQLite just like any other database, you just have to import the correct module and check how to use it.\nThe advantages of using SQLite are:\n\nYou don't need to setup a database server, it's just a file\nNo configurations needed\nCross platform\n\nMainly, de... | [
3,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0001017399_python.txt |
Q:
Is there an API to access a Google Group data?
I'm trying to build some statistics for an email group I participate. Is there any Python API to access the email data on a GoogleGroup?
Also, I know some statistics are available on the group's main page. I'm looking for something more complex than what is shown ther... | Is there an API to access a Google Group data? | I'm trying to build some statistics for an email group I participate. Is there any Python API to access the email data on a GoogleGroup?
Also, I know some statistics are available on the group's main page. I'm looking for something more complex than what is shown there.
| [
"There isn't an API that I know of, however you can access the XML feed and manipulate it as required.\n"
] | [
3
] | [] | [] | [
"google_groups",
"python"
] | stackoverflow_0001017794_google_groups_python.txt |
Q:
Help me understand the difference between CLOBs and BLOBs in Oracle
This is mainly just a "check my understanding" type of question. Here's my understanding of CLOBs and BLOBs as they work in Oracle:
CLOBs are for text like XML, JSON, etc. You should not assume what encoding the database will store it as (at le... | Help me understand the difference between CLOBs and BLOBs in Oracle | This is mainly just a "check my understanding" type of question. Here's my understanding of CLOBs and BLOBs as they work in Oracle:
CLOBs are for text like XML, JSON, etc. You should not assume what encoding the database will store it as (at least in an application) as it will be converted to whatever encoding the d... | [
"CLOB is encoding and collation sensitive, BLOB is not.\nWhen you write into a CLOB using, say, CL8WIN1251, you write a 0xC0 (which is Cyrillic letter А).\nWhen you read data back using AL16UTF16, you get back 0x0410, which is a UTF16 represenation of this letter.\nIf you were reading from a BLOB, you would get sam... | [
56,
10
] | [] | [] | [
"oracle",
"python"
] | stackoverflow_0001018073_oracle_python.txt |
Q:
One django installation different users per site
How can I have different users for different sites with django.
My application should look like this:
a.mydomain.com
b.otherdomain.com
Users should be bound to the domain, so that a.mydomain.com and b.otherdomain.com have different users.
A:
In the auth setup, yo... | One django installation different users per site | How can I have different users for different sites with django.
My application should look like this:
a.mydomain.com
b.otherdomain.com
Users should be bound to the domain, so that a.mydomain.com and b.otherdomain.com have different users.
| [
"In the auth setup, you could create separate custom permissions, one per domain, and check if the current user has the permission for the current domain -- see the \"custom permissions\" section in the auth doc in question.\n"
] | [
1
] | [] | [] | [
"authentication",
"django",
"django_models",
"python"
] | stackoverflow_0001018111_authentication_django_django_models_python.txt |
Q:
Formatting csv file data with html template
I have an csv file, the data, and an HTML file, the template.
I want a script that will create an individual html file per record from the csv file, using the html file as a template.
Which is the best way to do this in Ruby? Python?
Is there a tool/library I can use for... | Formatting csv file data with html template | I have an csv file, the data, and an HTML file, the template.
I want a script that will create an individual html file per record from the csv file, using the html file as a template.
Which is the best way to do this in Ruby? Python?
Is there a tool/library I can use for this in either language?
| [
"Python with Jinja2.\nimport jinja\nimport csv\n\nenv= jinja.Environment()\nenv.loader= jinja.FileSystemLoader(\"some/directory\")\ntemplate= env.get_template( \"name\" )\n\nrdr= csv.reader( open(\"some.csv\", \"r\" ) )\ncsv_data = [ row for row in rdr ]\n\nprint template.render( data=csv_data )\n\nIt turns out tha... | [
6,
5
] | [] | [] | [
"csv",
"formatting",
"html",
"python",
"ruby"
] | stackoverflow_0001017898_csv_formatting_html_python_ruby.txt |
Q:
Pass-through keyword arguments
I've got a class function that needs to "pass through" a particular keyword argument:
def createOrOpenTable(self, tableName, schema, asType=Table):
if self.tableExists(tableName):
return self.openTable(tableName, asType=asType)
else:
return self.createTable(se... | Pass-through keyword arguments | I've got a class function that needs to "pass through" a particular keyword argument:
def createOrOpenTable(self, tableName, schema, asType=Table):
if self.tableExists(tableName):
return self.openTable(tableName, asType=asType)
else:
return self.createTable(self, tableName, schema, asType=asType... | [
"You're doing it right... Just take out the self in the second function call :)\n return self.createTable(self, tableName, schema, asType=asType)\n\nshould be:\n return self.createTable(tableName, schema, asType=asType)\n\n",
"I have to say, that I first thought of a more complicated problem. But the answer of ... | [
9,
5,
5
] | [] | [] | [
"python"
] | stackoverflow_0001018359_python.txt |
Q:
Python and if statement
I'm running a script to feed an exe file a statement like below:
for j in ('90.','52.62263.','26.5651.','10.8123.'):
if j == '90.':
z = ('0.')
elif j == '52.62263.':
z = ('0.', '72.', '144.', '216.', '288.')
elif j == '26.5651':
z = ('324.', '36.', '108.'... | Python and if statement | I'm running a script to feed an exe file a statement like below:
for j in ('90.','52.62263.','26.5651.','10.8123.'):
if j == '90.':
z = ('0.')
elif j == '52.62263.':
z = ('0.', '72.', '144.', '216.', '288.')
elif j == '26.5651':
z = ('324.', '36.', '108.', '180.', '252.')
else:
... | [
"z = ('0.') is not a tuple, therefore your for k in z loop will iterate over the characters \"0\" and \".\". Add a comma to tell python you want it to be a tuple:\nz = ('0.',)\n\n",
"I think what's happening right now is that you are not waiting for those processes to finish before they're printed. Try something... | [
8,
6,
5,
2
] | [] | [] | [
"if_statement",
"python"
] | stackoverflow_0001018415_if_statement_python.txt |
Q:
Difference between using __init__ and setting a class variable
I'm trying to learn descriptors, and I'm confused by objects behaviour - in the two examples below, as I understood __init__ they should work the same. Can someone unconfuse me, or point me to a resource that explains this?
import math
class poweroftwo... | Difference between using __init__ and setting a class variable | I'm trying to learn descriptors, and I'm confused by objects behaviour - in the two examples below, as I understood __init__ they should work the same. Can someone unconfuse me, or point me to a resource that explains this?
import math
class poweroftwo(object):
"""any time this is set with an int, turns it's value ... | [
"First, please name all classes with LeadingUpperCaseNames.\n>>> a.x\nGET\n(10, 100.0)\n>>> b.x\n<__main__.poweroftwo object at 0x00C57D10>\n>>> type(a.x)\nGET\n<type 'tuple'>\n>>> type(b.x)\n<class '__main__.poweroftwo'>\n\na.x is instance-level access, which supports descriptors. This is what is meant in section... | [
3
] | [] | [] | [
"descriptor",
"python"
] | stackoverflow_0001018977_descriptor_python.txt |
Q:
Python logging incompatibilty between 2.5 and 2.6
Could you help me solve the following incompatibility issue between Python 2.5 and 2.6?
logger.conf:
[loggers]
keys=root,aLogger,bLogger
[handlers]
keys=consoleHandler
[formatters]
keys=
[logger_root]
level=NOTSET
handlers=consoleHandler
[logger_aLogger]
level=... | Python logging incompatibilty between 2.5 and 2.6 | Could you help me solve the following incompatibility issue between Python 2.5 and 2.6?
logger.conf:
[loggers]
keys=root,aLogger,bLogger
[handlers]
keys=consoleHandler
[formatters]
keys=
[logger_root]
level=NOTSET
handlers=consoleHandler
[logger_aLogger]
level=DEBUG
handlers=consoleHandler
propagate=0
qualname=a
[... | [
"This is a bug which was fixed between 2.5 and 2.6. The fileConfig() function is intended for one-off configuration and so should not be called more than once - however you choose to arrange this. The intended behaviour of fileConfig is to disable any loggers which are not explicitly mentioned in the configuration,... | [
8,
1,
0,
0
] | [] | [] | [
"incompatibility",
"logging",
"python"
] | stackoverflow_0001018527_incompatibility_logging_python.txt |
Q:
Algorithm for updating a list from a list
I've got a data source that provides a list of objects and their properties (a CSV file, but that doesn't matter). Each time my program runs, it needs to pull a new copy of the list of objects, compare it to the list of objects (and their properties) stored in the database... | Algorithm for updating a list from a list | I've got a data source that provides a list of objects and their properties (a CSV file, but that doesn't matter). Each time my program runs, it needs to pull a new copy of the list of objects, compare it to the list of objects (and their properties) stored in the database, and update the database as needed.
Dealing wi... | [
"Is there no way to maintain a \"last time modified\" field? That's what it sounds like you're really looking for: an incremental backup, based on last time backup was run, compared to last time an object was changed/deleted(/added).\n",
"You need to have timestamps in both your database and your CSV file. Time... | [
1,
1,
1,
0
] | [] | [] | [
"google_app_engine",
"python",
"set"
] | stackoverflow_0001019302_google_app_engine_python_set.txt |
Q:
Using data from django queries in the same view
I might have missed somthing while searching through the documentation - I can't seem to find a way to use data from one query to form another query.
My query is:
sites_list = Site.objects.filter(worker=worker)
I'm trying to do something like this:
for site in sites... | Using data from django queries in the same view | I might have missed somthing while searching through the documentation - I can't seem to find a way to use data from one query to form another query.
My query is:
sites_list = Site.objects.filter(worker=worker)
I'm trying to do something like this:
for site in sites_list:
[Insert Query Here]
Edit: I saw the awnse... | [
"You could easily do something like this:\nsites_list = Site.objects.filter(worker=worker)\n\nfor site in sites_list:\n new_sites_list = Site.objects.filter(name=site.name).filter(something else)\n\n",
"You can also use the __in lookup type. For example, if you had an Entry model with a relation to Site, you c... | [
2,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0000995970_django_python.txt |
Q:
Python - configuration options, how to input/handle?
When your application takes a few (~ 5) configuration parameters, and the application is going
to be used by non-technology users (i.e. KISS), how do you usually handle reading
configuration options, and then passing around the parameters between objects/functio... | Python - configuration options, how to input/handle? | When your application takes a few (~ 5) configuration parameters, and the application is going
to be used by non-technology users (i.e. KISS), how do you usually handle reading
configuration options, and then passing around the parameters between objects/functions
(multiple modules)?
Options examples: input and output... | [
"Do you usually read config options via:\n- command-line/gui options\n- a config text file \nBoth. We use Django's settings.py and logging.ini. We also use command-line options and arguments for the options that change most frequently.\nHow do multiple modules/objects have access to these options?\n\nsettin... | [
2,
0
] | [] | [] | [
"command_line_arguments",
"configuration_files",
"python"
] | stackoverflow_0001019850_command_line_arguments_configuration_files_python.txt |
Q:
Subclassing in Python
Is it possible to subclass dynamically? I know there's ____bases____ but I don't want to effect all instances of the class. I want the object cf to polymorph into a mixin of the DrvCrystalfontz class. Further into the hierarchy is a subclass of gobject that needs to be available at this level... | Subclassing in Python | Is it possible to subclass dynamically? I know there's ____bases____ but I don't want to effect all instances of the class. I want the object cf to polymorph into a mixin of the DrvCrystalfontz class. Further into the hierarchy is a subclass of gobject that needs to be available at this level for connecting signals, an... | [
"I'm not sure I'm clear on your desired use here, but it is possible to subclass dynamically. You can use the type object to dynamically construct a class given a name, tuple of base classes and dict of methods / class attributes, eg:\n>>> MySub = type(\"MySub\", (DrvCrystalfontz, some_other_class), \n {'s... | [
2
] | [] | [] | [
"python",
"subclassing"
] | stackoverflow_0001019834_python_subclassing.txt |
Q:
Optimizing Jinja2 Environment creation
My application is running on Google App Engine and most of requests constantly gets yellow flag due to high CPU usage. Using profiler I tracked the issue down to the routine of creating jinja2.Environment instance.
I'm creating the instance at module level:
from jinja2 import... | Optimizing Jinja2 Environment creation | My application is running on Google App Engine and most of requests constantly gets yellow flag due to high CPU usage. Using profiler I tracked the issue down to the routine of creating jinja2.Environment instance.
I'm creating the instance at module level:
from jinja2 import Environment, FileSystemLoader
jinja_env = E... | [
"Armin suggested to pre-compile Jinja2 templates to python code, and use the compiled templates in production. So I've made a compiler/loader for that, and it now renders some complex templates 13 times faster, throwing away all the parsing overhead. The related discussion with link to the repository is here.\n",
... | [
10,
4,
1
] | [] | [] | [
"google_app_engine",
"jinja2",
"python"
] | stackoverflow_0000618827_google_app_engine_jinja2_python.txt |
Q:
Is there an easy way to convert an std::list to a Python list?
I'm writing a little Python extension in C/C++, and I've got a function like this:
void set_parameters(int first_param, std::list<double> param_list)
{
//do stuff
}
I'd like to be able to call it from Python like this:
set_parameters(f_param, [1.0,... | Is there an easy way to convert an std::list to a Python list? | I'm writing a little Python extension in C/C++, and I've got a function like this:
void set_parameters(int first_param, std::list<double> param_list)
{
//do stuff
}
I'd like to be able to call it from Python like this:
set_parameters(f_param, [1.0, 0.5, 2.1])
Is there a reasonably easy way to make that conversion?... | [
"Take a look at Boost.Python. Question you've asked is covered in Iterators chapter of the tutorial\nThe point is, Boost.Python provides stl_input_iterator template that converts Python's iterable to stl's input_iterator, which can be used to fill your std::list.\n",
"It turned out to be less pain than I thought,... | [
0,
0
] | [] | [] | [
"c",
"python",
"stl"
] | stackoverflow_0001019457_c_python_stl.txt |
Q:
How to walk up a linked-list using a list comprehension?
I've been trying to think of a way to traverse a hierarchical structure, like a linked list, using a list expression, but haven't come up with anything that seems to work.
Basically, I want to convert this code:
p = self.parent
names = []
while p:
names.ap... | How to walk up a linked-list using a list comprehension? | I've been trying to think of a way to traverse a hierarchical structure, like a linked list, using a list expression, but haven't come up with anything that seems to work.
Basically, I want to convert this code:
p = self.parent
names = []
while p:
names.append(p.name)
p = p.parent
print ".".join(names)
into a one-... | [
"The closest thing I can think of is to create a parent generator:\n# Generate a node's parents, heading towards ancestors\ndef gen_parents(node):\n node = node.parent\n while node:\n yield node\n node = node.parent\n\n# Now you can do this\nparents = [x.name for x in gen_parents(node)]\nprint '.'.joi... | [
6,
2,
1,
1
] | [] | [] | [
"list_comprehension",
"python"
] | stackoverflow_0001020037_list_comprehension_python.txt |
Q:
Can client side python use threads?
I have never programed in Python before, so excuse my code. I have this script that will run in a terminal but I can't get it to run client side. I am running this in Appcelerator's Titanium application. Anyway, I have been troubleshooting it and it seems that it isn't running t... | Can client side python use threads? | I have never programed in Python before, so excuse my code. I have this script that will run in a terminal but I can't get it to run client side. I am running this in Appcelerator's Titanium application. Anyway, I have been troubleshooting it and it seems that it isn't running the threads at all. Is this a limitation? ... | [
"The answer, currently (Friday, June 19th, 2009) is yes, it can run threads, but the nothing but the main thread can access JavaScript objects, this includes the DOM. so if you are planning on updating the UI with a threading app, this is not possible... YET. Until the Appcelerator team creates some sort of queue t... | [
2
] | [] | [] | [
"appcelerator",
"client_side",
"multithreading",
"python",
"titanium"
] | stackoverflow_0000992008_appcelerator_client_side_multithreading_python_titanium.txt |
Q:
Interacting with another command line program in Python
I need to write a Python script that can run another command line program and interact with it's stdin and stdout streams. Essentially, the Python script will read from the target command line program, intelligently respond by writing to its stdin, and then r... | Interacting with another command line program in Python | I need to write a Python script that can run another command line program and interact with it's stdin and stdout streams. Essentially, the Python script will read from the target command line program, intelligently respond by writing to its stdin, and then read the results from the program again. (It would do this rep... | [
"To perform such detailed interaction (when, outside of your control, the other program may be buffering its output unless it thinks it's talking to a terminal) needs something like pexpect -- which in turns requires pty, a Python standard library module that (on operating systems that allow it, such as Linux and M... | [
7,
4
] | [] | [] | [
"command_line",
"python",
"subprocess"
] | stackoverflow_0001020980_command_line_python_subprocess.txt |
Q:
bug in "django-admin.py makemessages" or xgettext call? -> "warning: unterminated string"
django-admin.py makemessages dies with errors "warning: unterminated string" on cases where really long strings are wrapped:
string = "some text \
more text\
and even more"
These strings don't even need ... | bug in "django-admin.py makemessages" or xgettext call? -> "warning: unterminated string" | django-admin.py makemessages dies with errors "warning: unterminated string" on cases where really long strings are wrapped:
string = "some text \
more text\
and even more"
These strings don't even need to be translated - e.g. sql query strings.
The problem goes away when I concatenate the string,... | [
"I can think of two possibilities: you might have an extra space after your backslash at the end of the line; or you might be somehow ending up with the wrong line-ending characters in your source (e.g. Windows-style when your Python is expecting Unix-style, thus disabling the backslashes).\nEither way, I would tak... | [
2
] | [] | [] | [
"django",
"internationalization",
"python",
"xgettext"
] | stackoverflow_0001020432_django_internationalization_python_xgettext.txt |
Q:
Is there a better way to convert a list to a dictionary in Python with keys but no values?
I was sure that there would be a one liner to convert a list to a dictionary where the items in the list were keys and the dictionary had no values.
The only way I could find to do it was argued against.
"Using list comprehe... | Is there a better way to convert a list to a dictionary in Python with keys but no values? | I was sure that there would be a one liner to convert a list to a dictionary where the items in the list were keys and the dictionary had no values.
The only way I could find to do it was argued against.
"Using list comprehensions when the result is ignored is misleading and inefficient. A for loop is better"
myList = ... | [
"Use dict.fromkeys:\n>>> my_list = [1, 2, 3]\n>>> dict.fromkeys(my_list)\n{1: None, 2: None, 3: None}\n\nValues default to None, but you can specify them as an optional argument:\n>>> my_list = [1, 2, 3]\n>>> dict.fromkeys(my_list, 0)\n{1: 0, 2: 0, 3: 0}\n\nFrom the docs:\n\na.fromkeys(seq[, value]) Creates a new\n... | [
23,
15,
5,
1,
1,
1
] | [] | [] | [
"dictionary",
"list",
"list_comprehension",
"python"
] | stackoverflow_0001020722_dictionary_list_list_comprehension_python.txt |
Q:
Package for creating and validating HTML forms in Python? - to be used in Google Appengine
Is there a well maintained package available in Python for creating and validating HTML forms? I will deploying it finally on Google Appengine.
A:
For client-side validation, check http://plugins.jquery.com/search/node/for... | Package for creating and validating HTML forms in Python? - to be used in Google Appengine | Is there a well maintained package available in Python for creating and validating HTML forms? I will deploying it finally on Google Appengine.
| [
"For client-side validation, check http://plugins.jquery.com/search/node/form+validate;\nfor server-side, actually ALMOST every web framework (web.py, django, etc.) has its own form generation as well as validation lib for you to use.\n",
"You can use Django form validation on GAE storage via db.djangoforms.Model... | [
2,
2,
0
] | [] | [] | [
"forms",
"google_app_engine",
"html",
"python"
] | stackoverflow_0001021411_forms_google_app_engine_html_python.txt |
Q:
split a string by a delimiter in a context sensitive way
For example, I want to split
str = '"a,b,c",d,e,f'
into
["a,b,c",'d','e','f']
(i.e. don't split the quoted part) In this case, this can be done with
re.findall('".*?"|[^,]+',str)
However, if
str = '"a,,b,c",d,,f'
I want
["a,,b,c",'d','','f']
i.e. I w... | split a string by a delimiter in a context sensitive way | For example, I want to split
str = '"a,b,c",d,e,f'
into
["a,b,c",'d','e','f']
(i.e. don't split the quoted part) In this case, this can be done with
re.findall('".*?"|[^,]+',str)
However, if
str = '"a,,b,c",d,,f'
I want
["a,,b,c",'d','','f']
i.e. I want a behavior that is like python's split function. Is there... | [
"Use the csv module as it is a real parser. Regular expressions are nonoptimal (or completely unsuited) for most things involving matching delimiters in which the rules change (I'm unsure as to whether this particular grammar is regular or not). You might be able to create a regex that would work in this case, bu... | [
2,
2,
1,
1,
0,
0,
0
] | [] | [] | [
"python",
"regex",
"split"
] | stackoverflow_0001019756_python_regex_split.txt |
Q:
Exporting a zope folder with python
We have two zope servers running our company's internal site. One is the live site and one is the dev site. I'm working on writing a python script that moves everything from the dev server to the live server. Right now the process involves a bunch of steps that are done in th... | Exporting a zope folder with python | We have two zope servers running our company's internal site. One is the live site and one is the dev site. I'm working on writing a python script that moves everything from the dev server to the live server. Right now the process involves a bunch of steps that are done in the zope management interface. I need to m... | [
"You can try to use the functions manage_exportObject and manage_importObject located in the file $ZOPE_HOME/lib/python/OFS/ObjectManager.py\nLet say we install two Zope 2.8 instances located at:\n\n/tmp/instance/dev for the development server (port 8080)\n/tmp/instance/prod for the production server (port 9090)\n\... | [
4,
3,
0
] | [] | [] | [
"python",
"zope"
] | stackoverflow_0000922319_python_zope.txt |
Q:
Generating a 3D CAPTCHA [pic]
I would like to write a Python script that would generate a 3D CAPTCHA like this one:
Which graphics libraries can I use?
Source: ocr-research.org.ua
A:
There are many approaches. I would personally create the image in Python Imaging Library using ImageDraw's draw.text, convert to... | Generating a 3D CAPTCHA [pic] | I would like to write a Python script that would generate a 3D CAPTCHA like this one:
Which graphics libraries can I use?
Source: ocr-research.org.ua
| [
"There are many approaches. I would personally create the image in Python Imaging Library using ImageDraw's draw.text, convert to a NumPy array (usint NumPy's asarray) then render with Matplotlib. (Requires Matplotlib maintenance package).\nFull code (in 2.5):\nimport numpy, pylab\nfrom PIL import Image, ImageDraw... | [
33,
4,
2,
1
] | [] | [] | [
"captcha",
"graphics",
"python"
] | stackoverflow_0001021721_captcha_graphics_python.txt |
Q:
Probability time series, observed data probabilities (deja vu)
okay folks...thanks for looking at this question. I remember doing the following below in college however I forgotten the exact solution. Any takers to steer in the right direction.
I have a time series of data (we'll use three) of N. The data serie... | Probability time series, observed data probabilities (deja vu) | okay folks...thanks for looking at this question. I remember doing the following below in college however I forgotten the exact solution. Any takers to steer in the right direction.
I have a time series of data (we'll use three) of N. The data series is sequential in order of time (e.g. obsOne[1] occurred along with... | [
"Are you talking about something like this?\nfrom __future__ import division\nfrom collections import defaultdict\n\nobsOne= [47, 136, -108, -15, 22, ]\nobsTwo= [448, 321, 122, -207, 269, ]\nobsThree= [381, 283, 429, -393, 242, ]\n\nclass BinParams( object ):\n def __init__( self, timeSeries, X ):\n self.... | [
1
] | [] | [] | [
"data_analysis",
"probability",
"python",
"time_series"
] | stackoverflow_0001021704_data_analysis_probability_python_time_series.txt |
Q:
Python behavior of string in loop
In trying to capitalize a string at separators I encountered behavior I do not understand. Can someone please explain why the string s in reverted during the loop? Thanks.
s = 'these-three_words'
seperators = ('-','_')
for sep in seperators:
s = sep.join([i.capitalize(... | Python behavior of string in loop | In trying to capitalize a string at separators I encountered behavior I do not understand. Can someone please explain why the string s in reverted during the loop? Thanks.
s = 'these-three_words'
seperators = ('-','_')
for sep in seperators:
s = sep.join([i.capitalize() for i in s.split(sep)])
print s... | [
"capitalize turns the first character uppercase and the rest of the string lowercase.\nIn the first iteration, it looks like this:\n>>> [i.capitalize() for i in s.split('-')]\n['These', 'Three_words']\n\nIn the second iteration, the strings are the separated into:\n>>> [i for i in s.split('_')]\n['These-Three', 'wo... | [
6,
5,
2,
2
] | [] | [] | [
"loops",
"python",
"string"
] | stackoverflow_0001022264_loops_python_string.txt |
Q:
StringListProperty in GAE
Is there any way to edit StringListProperty fields via Google's Data Viewer, or some other clever approach?
The last I want to do is to modify my application in such way that it provides special throwaway page for just that reason - I don't feel like it's the optimal solution.
Cheers,
MH
... | StringListProperty in GAE | Is there any way to edit StringListProperty fields via Google's Data Viewer, or some other clever approach?
The last I want to do is to modify my application in such way that it provides special throwaway page for just that reason - I don't feel like it's the optimal solution.
Cheers,
MH
| [
"I would recommend using the Remote API; you can edit anything in your datastore with a minimum of fuss and no special pages needed.\n"
] | [
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0001022382_google_app_engine_python.txt |
Q:
Emulating membership-test in Python: delegating __contains__ to contained-object correctly
I am used to that Python allows some neat tricks to delegate functionality to other objects. One example is delegation to contained objects.
But it seams, that I don't have luck, when I want to delegate __contains __:
class ... | Emulating membership-test in Python: delegating __contains__ to contained-object correctly | I am used to that Python allows some neat tricks to delegate functionality to other objects. One example is delegation to contained objects.
But it seams, that I don't have luck, when I want to delegate __contains __:
class A(object):
def __init__(self):
self.mydict = {}
self.__contains__ = self.mydic... | [
"Special methods such as __contains__ are only special when defined on the class, not on the instance (except in legacy classes in Python 2, which you should not use anyway).\nSo, do your delegation at class level:\nclass A(object):\n def __init__(self):\n self.mydict = {}\n\n def __contains__(self, oth... | [
18
] | [] | [] | [
"containers",
"delegation",
"emulation",
"iterable",
"python"
] | stackoverflow_0001022499_containers_delegation_emulation_iterable_python.txt |
Q:
Problem getting date with Universal Feed Parser
It looks like http://portland.beerandblog.com/feed/atom/ is messed up (as are the 0.92 and 2.0 RSS feeds).
Universal Feed Parser (latest version from http://code.google.com/p/feedparser/source/browse/trunk/feedparser/feedparser.py?spec=svn295&r=295 ) doesn't see an... | Problem getting date with Universal Feed Parser | It looks like http://portland.beerandblog.com/feed/atom/ is messed up (as are the 0.92 and 2.0 RSS feeds).
Universal Feed Parser (latest version from http://code.google.com/p/feedparser/source/browse/trunk/feedparser/feedparser.py?spec=svn295&r=295 ) doesn't see any dates.
<title>Beer and Blog Portland</title>
... | [
"Works for me:\n>>> e = feedparser.parse('http://portland.beerandblog.com/feed/atom/')\n>>> e.feed.date\nu'2009-06-19T22:54:57Z'\n>>> e.feed.date_parsed\n(2009, 6, 19, 22, 54, 57, 4, 170, 0)\n>>> e.feed.updated_parsed\n(2009, 6, 19, 22, 54, 57, 4, 170, 0)\n\nMaybe you're looking for e.updated_parsed where you shoul... | [
3,
1
] | [] | [] | [
"feed",
"parsing",
"python"
] | stackoverflow_0001022504_feed_parsing_python.txt |
Q:
How can I pass the environment from my Python web application to a Perl program?
How do I set Perl's %ENV to introduce a Perl script into the context of my web application?
I have a website, written in a language different from Perl (Python). However I need to use a Perl application, which consists of a .pl file:
... | How can I pass the environment from my Python web application to a Perl program? | How do I set Perl's %ENV to introduce a Perl script into the context of my web application?
I have a website, written in a language different from Perl (Python). However I need to use a Perl application, which consists of a .pl file:
#!/usr/bin/env perl
"$ENV{DOCUMENT_ROOT}/foo/bar.pm" =~ /^(.+)$/;
require ... | [
"If you're spawning that Perl process from your Python code (as opposed to \"directly from the webserver\"), there are several ways to set the child process environment from the Python parent process environment, depending on what you're using for the \"spawning\".\nFor example, if you're using subprocess.Popen, yo... | [
4,
2
] | [] | [] | [
"environment",
"perl",
"python"
] | stackoverflow_0001022694_environment_perl_python.txt |
Q:
How to make a simple command-line chat in Python?
I study network programming and would like to write a simple command-line chat in Python.
I'm wondering how make receving constant along with inputing available for sending at any time.
As you see, this client can do only one job at a time:
from socket import *
H... | How to make a simple command-line chat in Python? | I study network programming and would like to write a simple command-line chat in Python.
I'm wondering how make receving constant along with inputing available for sending at any time.
As you see, this client can do only one job at a time:
from socket import *
HOST = 'localhost'
PORT = 21567
BUFSIZE = 1024
ADDR = (H... | [
"Your question was not very coherent. However, your program does not need to be asynchronous at all to attain what you are asking for.\nThis is a working chat script you originally wanted with minimal changes. It uses 1 thread for receiving and 1 for sending, both using blocking sockets. It is far simpler than usin... | [
8,
5,
2,
2,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0001020839_python.txt |
Q:
How to pickle a CookieJar?
I have an object with a CookieJar that I want to pickle.
However as you all probably know, pickle chokes on objects that contain lock objects. And for some horrible reason, a CookieJar has a lock object.
from cPickle import dumps
from cookielib import CookieJar
class Person(object):
... | How to pickle a CookieJar? | I have an object with a CookieJar that I want to pickle.
However as you all probably know, pickle chokes on objects that contain lock objects. And for some horrible reason, a CookieJar has a lock object.
from cPickle import dumps
from cookielib import CookieJar
class Person(object):
def __init__(self, name):
... | [
"Here is an attempt, by deriving a class from CookieJar, which override getstate/setstate used by pickle. I haven't used cookieJar, so don't know if it is usable but you can dump derived class\nfrom cPickle import dumps\nfrom cookielib import CookieJar\nimport threading\n\nclass MyCookieJar(CookieJar):\n def __g... | [
9,
7
] | [] | [] | [
"cookiejar",
"cookielib",
"persistence",
"pickle",
"python"
] | stackoverflow_0001023224_cookiejar_cookielib_persistence_pickle_python.txt |
Q:
Is there any pywin32 odbc connector documentation available?
What is a good pywin32 odbc connector documentation and tutorial on the web?
A:
Alternatives:
mxODBC by egenix.com (if you need ODBC)
pyODBC
sqlalchemy and DB-API 2.0 modules (which isn't ODBC) but it's maybe better alternative
A:
The answer is: 't... | Is there any pywin32 odbc connector documentation available? | What is a good pywin32 odbc connector documentation and tutorial on the web?
| [
"Alternatives:\n\nmxODBC by egenix.com (if you need ODBC)\npyODBC\nsqlalchemy and DB-API 2.0 modules (which isn't ODBC) but it's maybe better alternative \n\n",
"The answer is: 'there isn't one'. However, here is an example that shows how to open a connection and issue a query, and how to get column metadata fr... | [
3,
2,
1
] | [] | [] | [
"odbc",
"pyodbc",
"python",
"windows"
] | stackoverflow_0000768250_odbc_pyodbc_python_windows.txt |
Q:
Working with django and sqlalchemy but backend mysql
I am working with python's django framework. My models are sqlalchemy and my back-end database is mysql. How will I configure them?
A:
Some links that might help you:
http://lethain.com/entry/2008/jul/23/replacing-django-s-orm-with-sqlalchemy/
http://code.goo... | Working with django and sqlalchemy but backend mysql | I am working with python's django framework. My models are sqlalchemy and my back-end database is mysql. How will I configure them?
| [
"Some links that might help you:\n\nhttp://lethain.com/entry/2008/jul/23/replacing-django-s-orm-with-sqlalchemy/\nhttp://code.google.com/p/django-sqlalchemy/\nhttp://adam.gomaa.us/blog/2007/aug/26/the-django-orm-problem/\nhttp://gitorious.org/django-sqlalchemy\n\n",
"See Django database installation,\n\nIf you’re... | [
1,
0
] | [] | [] | [
"django",
"mysql",
"python",
"sqlalchemy"
] | stackoverflow_0001023417_django_mysql_python_sqlalchemy.txt |
Q:
Why does mass importing not work but importing definition individually works?
So I just met a strange so-called bug. Because this work on my other .py files, but just on this file it suddenly stopped working.
from tuttobelo.management.models import *
The above used to work, but it stopped working all of a sudden,... | Why does mass importing not work but importing definition individually works? | So I just met a strange so-called bug. Because this work on my other .py files, but just on this file it suddenly stopped working.
from tuttobelo.management.models import *
The above used to work, but it stopped working all of a sudden, and I had to replace it with the bottom.
from tuttobelo.management.models import P... | [
"Maybe the models module has an __all__ which does not include what you're looking for. Anyway, from ... import * is never a good idea in production code -- we always meant the import * feature for interactive exploratory use, not production use. Specifically import the module you need -- use that name to qualify n... | [
4,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001023326_django_python.txt |
Q:
It is possible to match a character repetition with regex? How?
Question:
Is is possible, with regex, to match a word that contains the same character in different positions?
Condition:
All words have the same length, you know the character positions (example the 1st, the 2nd and the 4th) of the repeated char, but... | It is possible to match a character repetition with regex? How? | Question:
Is is possible, with regex, to match a word that contains the same character in different positions?
Condition:
All words have the same length, you know the character positions (example the 1st, the 2nd and the 4th) of the repeated char, but you don't know what is it.
Examples:
using lowercase 6char words I'... | [
"You can use a backreference to do this:\n(.)\\1\n\nThis will match consecutive occurrences of any character.\n\nEdit Here’s some Python example:\nimport re\n\nregexp = re.compile(r\"(.)\\1\")\ndata = [\"parrot\",\"follia\",\"carrot\",\"mattia\",\"rettoo\",\"melone\"]\n\nfor str in data:\n match = re.search(re... | [
50,
8,
2,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0001023902_python_regex.txt |
Q:
What's a good beginner setup for C++/Python on OSX?
I'm looking for a good setup for learning C++ and eventually Python on Mac OSX. As I'm going use C++ I don't want to use XCode, as (I understand) this is primarily used with Objective-C. I have a small bit of experience in Java and MATLAB programming, and math is... | What's a good beginner setup for C++/Python on OSX? | I'm looking for a good setup for learning C++ and eventually Python on Mac OSX. As I'm going use C++ I don't want to use XCode, as (I understand) this is primarily used with Objective-C. I have a small bit of experience in Java and MATLAB programming, and math is probably not going to be my main problem. I was thinking... | [
"\nAs I'm going use C++ I don't\n want to use XCode, as (I understand)\n this is primarily used with\n Objective-C.\n\nXCode is a fine choice, even for pure C++ solutions.\n\nWork through Accelerated C++.\n\nThat's the book that got me started! It's an excellent choice, but not a walk in the park. It took me a m... | [
3,
2,
2,
0,
0,
0,
0
] | [] | [] | [
"c++",
"ide",
"macos",
"python"
] | stackoverflow_0001024062_c++_ide_macos_python.txt |
Q:
What causes this Genshi's Template Syntax Error?
A Genshi template raises the following error:
TemplateSyntaxError: invalid syntax in expression "${item.error}" of "choose" directive
The part of the template code that the error specifies is the following ('feed' is a list of dictionary which is passed to the tem... | What causes this Genshi's Template Syntax Error? | A Genshi template raises the following error:
TemplateSyntaxError: invalid syntax in expression "${item.error}" of "choose" directive
The part of the template code that the error specifies is the following ('feed' is a list of dictionary which is passed to the template):
<item py:for="item in feed">
<py:choose error=... | [
"The docs perhaps don't make this clear, but the attribute needs to be called test (as it is in their examples) instead of error.\n<item py:for=\"item in feed\">\n<py:choose test=\"item.error\">\n <py:when test=\"0\">\n <title>${item.something}</title>\n </py:when>\n <py:otherwise>\n <title>$... | [
4,
0
] | [] | [] | [
"genshi",
"python",
"syntax_error"
] | stackoverflow_0000811737_genshi_python_syntax_error.txt |
Q:
Python newbie: What does this code do?
This is a snippet from Google AppEngine tutorial.
application = webapp.WSGIApplication([('/', MainPage)], debug=True)
I'm not quite sure what debug=True does inside the constructor call.
Does it create a local variable with name debug, assign True to it, and pass it to cons... | Python newbie: What does this code do? | This is a snippet from Google AppEngine tutorial.
application = webapp.WSGIApplication([('/', MainPage)], debug=True)
I'm not quite sure what debug=True does inside the constructor call.
Does it create a local variable with name debug, assign True to it, and pass it to constructor, or is this a way to set a class ins... | [
"Python functions accept keyword arguments. If you define a function like so:\ndef my_func(a, b='abc', c='def'):\n print a, b, c\n\nYou can call it like this:\nmy_func('hello', c='world')\n\nAnd the result will be:\nhello abc world\n\nYou can also support dynamic keyword arguments, using special syntax:\ndef my_... | [
11,
4,
3
] | [] | [] | [
"python"
] | stackoverflow_0001024437_python.txt |
Q:
Looping Fget with fsockopen in PHP 5.x
I have a Python Server finally working and responding to multiple command's with the output's, however I'm now having problem's with PHP receiving the full output. I have tried commands such as fgets, fread, the only command that seems to work is "fgets".
However this only re... | Looping Fget with fsockopen in PHP 5.x | I have a Python Server finally working and responding to multiple command's with the output's, however I'm now having problem's with PHP receiving the full output. I have tried commands such as fgets, fread, the only command that seems to work is "fgets".
However this only recieve's on line of data, I then created a wh... | [
"I believe you need to fix your server code a bit. I have removed the inner while loop. The problem with your code was that the server never closed the connection, so feof never returned true.\nI also removed the + \" &\" bit. To get the output, you need to wait until the process ends anyway. And I am not sure how ... | [
1
] | [] | [] | [
"fgets",
"php",
"python",
"sockets",
"tcp"
] | stackoverflow_0001024370_fgets_php_python_sockets_tcp.txt |
Q:
How to test a Python script with an input file filled with testcases?
I'm participating in online judge contests and I want to test my code with a .in file full of testcases to time my algorithm. How can I get my script to take input from this .in file?
A:
So the script normally takes test cases from stdin, and ... | How to test a Python script with an input file filled with testcases? | I'm participating in online judge contests and I want to test my code with a .in file full of testcases to time my algorithm. How can I get my script to take input from this .in file?
| [
"So the script normally takes test cases from stdin, and now you want to test using test cases from a file?\nIf that is the case, use the < redirection operation on the cmd line:\nmy_script < testcases.in\n\n",
"Read from file(s) and/or stdin:\nimport fileinput\nfor line in fileinput.input():\n process(line)\n... | [
7,
2,
1,
1
] | [] | [] | [
"input",
"python"
] | stackoverflow_0001024529_input_python.txt |
Q:
Django - alternative to subclassing User?
I am using the standard User model (django.contrib.auth) which comes with Django. I have made some of my own models in a Django application and created a relationship between like this:
from django.db import models
from django.contrib.auth.models import User
class GroupMe... | Django - alternative to subclassing User? | I am using the standard User model (django.contrib.auth) which comes with Django. I have made some of my own models in a Django application and created a relationship between like this:
from django.db import models
from django.contrib.auth.models import User
class GroupMembership(models.Model):
user = models.Forei... | [
"First, calling select_related and passing arguments, doesn't do anything. It's a hint that cache should be populated.\nYou would never call select_related in a template, only a view function. And only when you knew you needed all those related objects for other processing.\n\"Is the best to create a method insid... | [
3
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001024684_django_python.txt |
Q:
finding firefox version
How to find Firefox version using python?
A:
I tried Alan's code snippet and it didn't work for me. One problem with it is that in order for the "-v or -version" flags to work, you must have a debug version firefox. See here under "Miscellaneous" for details.
Try the following, which uses... | finding firefox version | How to find Firefox version using python?
| [
"I tried Alan's code snippet and it didn't work for me. One problem with it is that in order for the \"-v or -version\" flags to work, you must have a debug version firefox. See here under \"Miscellaneous\" for details.\nTry the following, which uses the win32 library to read the Product Version string directly fro... | [
3,
2
] | [] | [] | [
"firefox",
"python"
] | stackoverflow_0001016609_firefox_python.txt |
Q:
Finding the parent tag of a text string with ElementTree/lxml
I'm trying to take a string of text, and "extract" the rest of the text in the paragraph/document from the html.
My current is approach is trying to find the "parent tag" of the string in the html that has been parsed with lxml. (if you know of a better... | Finding the parent tag of a text string with ElementTree/lxml | I'm trying to take a string of text, and "extract" the rest of the text in the paragraph/document from the html.
My current is approach is trying to find the "parent tag" of the string in the html that has been parsed with lxml. (if you know of a better way to tackle this problem, I'm all ears!)
For example, search the... | [
"This is a simple way to do it with ElementTree. It does require that your HTML input is valid XML (so I have added the appropriate end tags to your HTML):\nimport elementtree.ElementTree as ET\n\nhtml = \"\"\"<html>\n<head>\n</head>\n<body>\n<div>\n<p>TEXT STRING HERE ......</p> \n</div>\n</body>\n</html>\"\"\"\n\... | [
3
] | [] | [] | [
"elementtree",
"lxml",
"python"
] | stackoverflow_0001025129_elementtree_lxml_python.txt |
Q:
Django Context Processor Trouble
So I am just starting out on learning Django, and I'm attempting to complete one of the sample applications from the book. I'm getting stuck now on creating DRY URL's. More specifically, I cannot get my context processor to work. I create my context processor as so:
from django.con... | Django Context Processor Trouble | So I am just starting out on learning Django, and I'm attempting to complete one of the sample applications from the book. I'm getting stuck now on creating DRY URL's. More specifically, I cannot get my context processor to work. I create my context processor as so:
from django.conf import settings
#from mysite.setting... | [
"TEMPLATE_CONTEXT_PROCESSORS should contain a list of callable objects, not modules. List the actual functions that will transform the template contexts. Link to docs. \n"
] | [
4
] | [] | [] | [
"django",
"django_urls",
"python"
] | stackoverflow_0001025025_django_django_urls_python.txt |
Q:
What's the best way to implement web service for ajax autocomplete
I'm implementing a "Google Suggest" like autocomplete feature for tag searching using jQuery's autocomplete.
I need to provide a web service to jQuery giving it a list of suggestions based on what the user has typed. I see 2 ways of implementing t... | What's the best way to implement web service for ajax autocomplete | I'm implementing a "Google Suggest" like autocomplete feature for tag searching using jQuery's autocomplete.
I need to provide a web service to jQuery giving it a list of suggestions based on what the user has typed. I see 2 ways of implementing the web service:
1) just store all the tags in a database and search the ... | [
"Don't be concerned about latency before you measure things -- make up a bunch of pseudo-tags, stick them in the DB, and measure latencies for typical queries. Depending on your DB setup, your latency may be just fine and you're spared wasted worries.\nDo always worry about threading, though - the GIL doesn't make ... | [
4,
1
] | [] | [] | [
"ajax",
"autocomplete",
"python",
"trie"
] | stackoverflow_0001025018_ajax_autocomplete_python_trie.txt |
Q:
Disable GNOME's automount with Python
I need to stop GNOME/Nautilus from automagically mounting new devices and partitions as they appear to the system. How can I accomplish this in python?
A:
Why would do it in Python? You can just use the commandline, as in:
gconftool-2 --type bool --set /apps/nautilus/prefere... | Disable GNOME's automount with Python | I need to stop GNOME/Nautilus from automagically mounting new devices and partitions as they appear to the system. How can I accomplish this in python?
| [
"Why would do it in Python? You can just use the commandline, as in:\ngconftool-2 --type bool --set /apps/nautilus/preferences/media_automount false\n\nIf you really need it to be in Python, then you can use the subprocess module:\nimport subprocess\n\ndef setAutomount(value):\n \"\"\"\n @type value: boolean\... | [
3
] | [] | [] | [
"automount",
"gnome",
"hal",
"python"
] | stackoverflow_0001025244_automount_gnome_hal_python.txt |
Q:
dual iterator in one python object
In python, I am trying to write a class that support two different kind of iterator. Roughly speaking, this object contains a matrix of data and I want to have two different kind of iterator to support row iteration and column iteration.
A:
dict has several iterator-producing ... | dual iterator in one python object | In python, I am trying to write a class that support two different kind of iterator. Roughly speaking, this object contains a matrix of data and I want to have two different kind of iterator to support row iteration and column iteration.
| [
"dict has several iterator-producing methods -- iterkeys, itervalues, iteritems -- and so should your class. If there's one \"most natural\" way of iterating, you should also alias it to __iter__ for convenience and readability (that's probably going to be iterrows; of course there is always going to be some doubt,... | [
5,
4,
2
] | [] | [] | [
"iterator",
"python"
] | stackoverflow_0001025348_iterator_python.txt |
Q:
mercurial + OSX == fail? hg log abort: Is a directory
$ mkdir foo
$ cd foo
$ hg init .
$ hg log
abort: Is a directory
$ hg history
abort: Is a directory
Darwin Host.local 9.6.1 Darwin Kernel Version 9.6.1: Wed Dec 10 10:38:33 PST 2008; root:xnu-1228.9.75~3/RELEASE_I386 i386
$ hg --version
Mercurial Distributed SC... | mercurial + OSX == fail? hg log abort: Is a directory | $ mkdir foo
$ cd foo
$ hg init .
$ hg log
abort: Is a directory
$ hg history
abort: Is a directory
Darwin Host.local 9.6.1 Darwin Kernel Version 9.6.1: Wed Dec 10 10:38:33 PST 2008; root:xnu-1228.9.75~3/RELEASE_I386 i386
$ hg --version
Mercurial Distributed SCM (version 1.2.1)
$ python --version
Python 2.5.4
(all ins... | [
"Not a direct answer to your question, but I've successfully been using the Mercurial pre-packaged binaries from here with the standard Python 2.5.1 install on OSX 10.5 without issue.\n$ mkdir foo\n$ cd foo\n$ hg init .\n$ hg log\n$ hg history\n\n$ hg --version\nMercurial Distributed SCM (version 1.2.1)\n\n$ python... | [
1,
1,
0,
0
] | [] | [] | [
"macos",
"mercurial",
"python"
] | stackoverflow_0000730319_macos_mercurial_python.txt |
Q:
Decimal alignment formatting in Python
This should be easy.
Here's my array (rather, a method of generating representative test arrays):
>>> ri = numpy.random.randint
>>> ri2 = lambda x: ''.join(ri(0,9,x).astype('S'))
>>> a = array([float(ri2(x)+ '.' + ri2(y)) for x,y in ri(1,10,(10,2))])
>>> a
array([ 7.99914000... | Decimal alignment formatting in Python | This should be easy.
Here's my array (rather, a method of generating representative test arrays):
>>> ri = numpy.random.randint
>>> ri2 = lambda x: ''.join(ri(0,9,x).astype('S'))
>>> a = array([float(ri2(x)+ '.' + ri2(y)) for x,y in ri(1,10,(10,2))])
>>> a
array([ 7.99914000e+01, 2.08000000e+01, 3.94000000e+02,
... | [
"Sorry, but after thorough investigation I can't find any way to perform the task you require without a minimum of post-processing (to strip off the trailing zeros you don't want to see); something like:\nimport re\nut0 = re.compile(r'(\\d)0+$')\n\nthelist = [ut0.sub(r'\\1', \"%12f\" % x) for x in a]\n\nprint '\\n'... | [
10,
2
] | [] | [] | [
"code_golf",
"formatting",
"numpy",
"python"
] | stackoverflow_0001025379_code_golf_formatting_numpy_python.txt |
Q:
How do I build a custom "list-type" entry to request.POST
Basically I have a model with a ManyToMany field, and then a modelform derived from that model where that field is rendered as a "multiple choice" selectbox. In my template I'm having that field omitted, electing instead to prepare the values for that fiel... | How do I build a custom "list-type" entry to request.POST | Basically I have a model with a ManyToMany field, and then a modelform derived from that model where that field is rendered as a "multiple choice" selectbox. In my template I'm having that field omitted, electing instead to prepare the values for that field in the view, then pass those prepared values into request.POS... | [
"It's really not clear what you're trying to do here, but I doubt that hacking the QueryDict is the right way to achieve it.\nIf you are trying to customise the display of the not_bases field, you can simply override the definition in your modelform declaration:\nclass MyModelForm(forms.ModelForm):\n not_bases =... | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001025216_django_python.txt |
Q:
Call program from within a browser without using a webserver
Is there a way to call a program (Python script) from a local HTML page?
I have a YUI-colorpicker on that page and need to send its value to a microcontroller via rs232. (There is other stuff than the picker, so I can't code an application instead of an ... | Call program from within a browser without using a webserver | Is there a way to call a program (Python script) from a local HTML page?
I have a YUI-colorpicker on that page and need to send its value to a microcontroller via rs232. (There is other stuff than the picker, so I can't code an application instead of an HTML page.)
Later, this will migrate to a server, but I need a fas... | [
"I see now that Daff mentioned the simple HTTP server, but I made an example on how you'd solve your problem (using BaseHTTPServer):\nimport BaseHTTPServer\n\nHOST_NAME = 'localhost'\nPORT_NUMBER = 1337\n\nclass MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):\n def do_GET(s):\n s.send_response(200)\n ... | [
6,
3,
1,
1,
0,
0,
0
] | [] | [] | [
"browser",
"html",
"python"
] | stackoverflow_0001025817_browser_html_python.txt |
Q:
Django model query with custom select fields
I'm using the row-level permission model known as django-granular-permissions (http://code.google.com/p/django-granular-permissions/). The permission model simply has just two more fields which are content-type and object id.
I've used the following query:
User.objects... | Django model query with custom select fields | I'm using the row-level permission model known as django-granular-permissions (http://code.google.com/p/django-granular-permissions/). The permission model simply has just two more fields which are content-type and object id.
I've used the following query:
User.objects.filter(Q(row_permission_set__name='staff') | \
... | [
".extra(select={'is_staff': \"%s.name='staff'\" % Permission._meta.db_table, 'is_student': \"%s.name='student'\" % Permission._meta.db_table, }) \n\n",
"Normally you'd use select_related() for things like this, but unfortunately it doesn't work on reverse relationships. What you could do is turn the query around:... | [
5,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0001026204_django_django_models_python.txt |
Q:
How can you add a camera to a robot in the Breve Simulator?
I've created a two wheeled robot based on the braitenberg vehicle. Our robots have two wheels and a PolygonDisk body(Much like kepera and e-puck robots). I would like to add a camera to the front of the robot. The problem then becomes how to control the c... | How can you add a camera to a robot in the Breve Simulator? | I've created a two wheeled robot based on the braitenberg vehicle. Our robots have two wheels and a PolygonDisk body(Much like kepera and e-puck robots). I would like to add a camera to the front of the robot. The problem then becomes how to control the camera and how to keep pointing it in the right direction(same dir... | [
"After much trying and failing I finally made it work.\nSo here is how I did it:\nThe general idea is to have an link or object linked to the vehicle and then measuring \nits rotation and location in order to find out in which direction the camera should be aimed.\n1) Add an object that is linked to the robot:\ndef... | [
1
] | [] | [] | [
"python",
"robotics",
"simulation"
] | stackoverflow_0001011602_python_robotics_simulation.txt |
Q:
MySQLdb through proxy
I'm using the above mentioned Python lib to connect to a MySQL server. So far I've worked locally and all worked fine, until i realized I'll have to use my program in a network where all access goes through a proxy.
Does anyone now how I can set the connections managed by that lib to use a pr... | MySQLdb through proxy | I'm using the above mentioned Python lib to connect to a MySQL server. So far I've worked locally and all worked fine, until i realized I'll have to use my program in a network where all access goes through a proxy.
Does anyone now how I can set the connections managed by that lib to use a proxy?
Alternatively: do you ... | [
"I use ssh tunneling for that kind of issues.\nFor example I am developing an application that connects to an oracle db.\nIn my code I write to connect to localhost and then from a shell I do:\nssh -L1521:localhost:1521 user@server.com\n\nIf you are in windows you can use PuTTY\n",
"there are a lot of different p... | [
2,
1,
0
] | [] | [] | [
"mysql",
"proxy",
"python"
] | stackoverflow_0001027751_mysql_proxy_python.txt |
Q:
Detect if X11 is available (python)
Firstly, what is the best/simplest way to detect if X11 is running and available for a python script.
parent process?
session leader?
X environment variables?
other?
Secondly, I would like to have a utility (python script) to present a gui if available, otherwise use a command... | Detect if X11 is available (python) | Firstly, what is the best/simplest way to detect if X11 is running and available for a python script.
parent process?
session leader?
X environment variables?
other?
Secondly, I would like to have a utility (python script) to present a gui if available, otherwise use a command line backed tool.
Off the top of my head... | [
"Check the return code of xset -q:\ndef X_is_running():\n from subprocess import Popen, PIPE\n p = Popen([\"xset\", \"-q\"], stdout=PIPE, stderr=PIPE)\n p.communicate()\n return p.returncode == 0\n\nAs for the second part of your question, I suggest the following main.py structure:\nimport common_lib\n\... | [
14,
10,
5
] | [] | [] | [
"python",
"user_interface"
] | stackoverflow_0001027894_python_user_interface.txt |
Q:
Writing with Python's built-in .csv module
[Please note that this is a different question from the already answered How to replace a column using Python’s built-in .csv writer module?]
I need to do a find and replace (specific to one column of URLs) in a huge Excel .csv file. Since I'm in the beginning stages of t... | Writing with Python's built-in .csv module | [Please note that this is a different question from the already answered How to replace a column using Python’s built-in .csv writer module?]
I need to do a find and replace (specific to one column of URLs) in a huge Excel .csv file. Since I'm in the beginning stages of trying to teach myself a scripting language, I fi... | [
"You cannot read and write the same file.\nsource = open(\"PALTemplateData.csv\",\"rb\")\nreader = csv.reader(source , dialect)\n\ntarget = open(\"AnotherFile.csv\",\"wb\")\nwriter = csv.writer(target , dialect)\n\nThe normal approach to ALL file manipulation is to create a modified COPY of the original file. Don'... | [
10,
4,
2
] | [] | [] | [
"csv",
"file_io",
"python",
"python_3.x"
] | stackoverflow_0001020053_csv_file_io_python_python_3.x.txt |
Q:
sqlite version for python26
which versions of sqlite may best suite for python 2.6.2?
A:
If your Python distribution already comes with a copy of sqlite (such as the Windows distribution, or Debian), this is the version you should use.
If you compile sqlite yourself, you should use the version that is recommende... | sqlite version for python26 | which versions of sqlite may best suite for python 2.6.2?
| [
"If your Python distribution already comes with a copy of sqlite (such as the Windows distribution, or Debian), this is the version you should use.\nIf you compile sqlite yourself, you should use the version that is recommended by the sqlite authors (currently 3.6.15).\n",
"I'm using 3.4.0 out of inertia (it's wh... | [
9,
0
] | [] | [] | [
"python",
"python_2.6",
"sqlite"
] | stackoverflow_0001025493_python_python_2.6_sqlite.txt |
Q:
Python - when is 'import' required?
mod1.py
import mod2
class Universe:
def __init__(self):
pass
def answer(self):
return 42
u = Universe()
mod2.show_answer(u)
mod2.py
#import mod1 -- not necessary
def show_answer(thing):
print thing.answer()
Coming from a C++ background I had the f... | Python - when is 'import' required? | mod1.py
import mod2
class Universe:
def __init__(self):
pass
def answer(self):
return 42
u = Universe()
mod2.show_answer(u)
mod2.py
#import mod1 -- not necessary
def show_answer(thing):
print thing.answer()
Coming from a C++ background I had the feeling it was necessary to import the mod... | [
"In this case you're right: show_answer() is given an object, of which it calls the method \"answer\". As long as the object given to show_answer() has such a method, it doesn't matter where the object comes from.\nIf, however, you wanted to create an instance of Universe inside mod2, you'd have to import mod1, bec... | [
6,
4,
1,
1,
1,
1,
1
] | [] | [] | [
"import",
"module",
"python"
] | stackoverflow_0001027557_import_module_python.txt |
Q:
Python MySQLdb update query fails
Okay. I've built here a mysql query browser, like navicat. Using MySQLdb to perform queries.
Here's the weird part. When i run the query through the program(using MySQLdb), it gives me success, affected rows = 1, but when i look at it in phpmyadmin, the value hasn't changed.
so be... | Python MySQLdb update query fails | Okay. I've built here a mysql query browser, like navicat. Using MySQLdb to perform queries.
Here's the weird part. When i run the query through the program(using MySQLdb), it gives me success, affected rows = 1, but when i look at it in phpmyadmin, the value hasn't changed.
so before i perform the query, i print it o... | [
"I believe @Jason Creighton and @S.Lott are correct.\nAt least if the table that you're updating is on a transactional storage engine. InnoDB is transactional, ISAM is not.\nYou either have to call commit() on your connection object before closing it, or you must set the connection to autocommit mode. I am not sure... | [
20,
16
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0001028671_mysql_python.txt |
Q:
Is there a Python interface to the Apache scoreboard (for server statistics)?
In short: Is there an existing open-source Python interface for the Apache scoreboard IPC facility? I need to collect statistics from a running server WITHOUT using the "mod_status" HTTP interface, and I'd like to avoid Perl if possibl... | Is there a Python interface to the Apache scoreboard (for server statistics)? | In short: Is there an existing open-source Python interface for the Apache scoreboard IPC facility? I need to collect statistics from a running server WITHOUT using the "mod_status" HTTP interface, and I'd like to avoid Perl if possible.
Some background: As I understand it, the Apache web server uses a functionality... | [
"Apache::Scoreboard can both fetch the scoreboard over HTTP, or, if it is loaded into the same server, access the scoreboard memory directly. This is done via a XS extension (i.e. native C). See httpd/include/scoreboard.h for how to access the in-memory scoreboard from C.\nIf you're running in mod_python, you sho... | [
3
] | [] | [] | [
"apache",
"http",
"perl",
"python"
] | stackoverflow_0001028408_apache_http_perl_python.txt |
Q:
Stop execution of a script called with execfile
Is it possible to break the execution of a Python script called with the execfile function without using an if/else statement? I've tried exit(), but it doesn't allow main.py to finish.
# main.py
print "Main starting"
execfile("script.py")
print "This should print"
... | Stop execution of a script called with execfile | Is it possible to break the execution of a Python script called with the execfile function without using an if/else statement? I've tried exit(), but it doesn't allow main.py to finish.
# main.py
print "Main starting"
execfile("script.py")
print "This should print"
# script.py
print "Script starting"
a = False
if a ... | [
"main can wrap the execfile into a try/except block: sys.exit raises a SystemExit exception which main can catch in the except clause in order to continue its execution normally, if desired. I.e., in main.py:\ntry:\n execfile('whatever.py')\nexcept SystemExit:\n print \"sys.exit was called but I'm proceeding anyw... | [
22,
4,
1
] | [] | [] | [
"control_flow",
"execfile",
"python"
] | stackoverflow_0001028609_control_flow_execfile_python.txt |
Q:
Can I avoid handling a file twice if I need the number of lines and I need to append to the file?
I am writing a file to disk in stages. As I write it I need to know the line numbers that I am writing to use to build an index. The file now has 12 million lines so I need to build the index on the fly. I am doing... | Can I avoid handling a file twice if I need the number of lines and I need to append to the file? | I am writing a file to disk in stages. As I write it I need to know the line numbers that I am writing to use to build an index. The file now has 12 million lines so I need to build the index on the fly. I am doing this in four steps, with four groupings of the value that I am indexing on. Based on some examples I ... | [
"You can open a file for reading AND writing:\nmyFile=open(r'C:\\NEWMASTERLIST\\FULLLIST.txt','r+')\n\nTry that.\nUPDATE: Ah, my mistake since the file might not exist. Use 'a+' instead of 'r+'.\n",
"Open the file for updates ('u' or 'rw', I forget). Now you can read it until EOF and then start writing to append.... | [
4,
0,
0,
0
] | [] | [] | [
"file",
"python"
] | stackoverflow_0001028122_file_python.txt |
Q:
Formatting cells in Excel with Python
How do I format cells in Excel with python?
In particular I need to change the font of several subsequent rows
to be regular instead of bold.
A:
Using xlwt:
from xlwt import *
font0 = Font()
font0.bold = False
style0 = XFStyle()
style0.font = font0
wb = Workbook()
ws0 = ... | Formatting cells in Excel with Python | How do I format cells in Excel with python?
In particular I need to change the font of several subsequent rows
to be regular instead of bold.
| [
"Using xlwt:\nfrom xlwt import *\n\nfont0 = Font()\nfont0.bold = False\n\nstyle0 = XFStyle()\nstyle0.font = font0\n\nwb = Workbook()\nws0 = wb.add_sheet('0')\n\nws0.write(0, 0, 'myNormalText', style0)\n\nfont1 = Font()\nfont1.bold = True\n\nstyle1 = XFStyle()\nstyle1.font = font1\n\nws0.write(0, 1, 'myBoldText', st... | [
3,
3,
1,
1
] | [] | [] | [
"excel",
"formatting",
"python"
] | stackoverflow_0001029500_excel_formatting_python.txt |
Q:
Formatting with mako
Anyone know how to format the length of a string with Mako?
The equivalent of print "%20s%10s" % ("string 1", "string 2")?
A:
you can use python's string formatting fairly easily in mako
${"%20s%10s" % ("string 1", "string 2")}
giving:
>>> from mako.template import Template
>>> Template('${... | Formatting with mako | Anyone know how to format the length of a string with Mako?
The equivalent of print "%20s%10s" % ("string 1", "string 2")?
| [
"you can use python's string formatting fairly easily in mako\n${\"%20s%10s\" % (\"string 1\", \"string 2\")}\n\ngiving:\n>>> from mako.template import Template\n>>> Template('${\"%20s%10s\" % (\"string 1\", \"string 2\")}').render()\n' string 1 string 2'\n\n"
] | [
7
] | [] | [] | [
"mako",
"python",
"template_engine"
] | stackoverflow_0001029965_mako_python_template_engine.txt |
Q:
Calling a hook function every time an Exception is raised
Let's say I want to be able to log to file every time any exception is raised, anywhere in my program. I don't want to modify any existing code.
Of course, this could be generalized to being able to insert a hook every time an exception is raised.
Would th... | Calling a hook function every time an Exception is raised | Let's say I want to be able to log to file every time any exception is raised, anywhere in my program. I don't want to modify any existing code.
Of course, this could be generalized to being able to insert a hook every time an exception is raised.
Would the following code be considered safe for doing such a thing?
cla... | [
"If you want to log uncaught exceptions, just use sys.excepthook.\nI'm not sure I see the value of logging all raised exceptions, since lots of libraries will raise/catch exceptions internally for things you probably won't care about.\n",
"Your code as far as I can tell would not work. \n\n__init__ has to return ... | [
19,
10,
7
] | [
"Download pypy and instrument it.\n"
] | [
-8
] | [
"exception",
"python"
] | stackoverflow_0001029318_exception_python.txt |
Q:
smoothing irregularly sampled time data
Given a table where the first column is seconds past a certain reference point and the second one is an arbitrary measurement:
6 0.738158581
21 0.801697222
39 1.797224596
49 2.77920469
54 2.839757536
79 3.832232283
91 4.676794376
97 5.18244704
100 5.521878863
118 6.... | smoothing irregularly sampled time data | Given a table where the first column is seconds past a certain reference point and the second one is an arbitrary measurement:
6 0.738158581
21 0.801697222
39 1.797224596
49 2.77920469
54 2.839757536
79 3.832232283
91 4.676794376
97 5.18244704
100 5.521878863
118 6.316630137
131 6.778507504
147 7.020395216
157... | [
"I'm using a sum result to which I'm adding the new members and subtracting the old ones. However in this way one may suffer accumulating floating point inaccuracies.\nTherefore I implement a \"Deque\" with a list. And whenever my Deque reallocates to a smaller size. I recalculate the sum at the same occasion.\nI'm... | [
3,
2,
0,
0,
0,
0
] | [
"what about something like this, keep storing values till time difference with last time is > 100, average and yield such values\ne.g.\ndef getAvgValues(data):\n lastTime = 0\n prevValues = []\n avgSampleTime=100\n\n for t, v in data:\n if t - lastTime < avgSampleTime:\n prevValues.app... | [
-1,
-2
] | [
"data_mining",
"datetime",
"python",
"smoothing"
] | stackoverflow_0001023719_data_mining_datetime_python_smoothing.txt |
Q:
Does python have a "causes_exception()" function?
I have the following code:
def causes_exception(lamb):
try:
lamb()
return False
except:
return True
I was wondering if it came already in any built-in library?
/YGA
Edit: Thx for all the commentary. It's actually impossible to detect ... | Does python have a "causes_exception()" function? | I have the following code:
def causes_exception(lamb):
try:
lamb()
return False
except:
return True
I was wondering if it came already in any built-in library?
/YGA
Edit: Thx for all the commentary. It's actually impossible to detect whether code causes an exception without running it -- ... | [
"No, as far as I know there is no such function in the standard library. How would it be useful? I mean, presumably you would use it like this:\nif causes_exception(func):\n # do something\nelse:\n # do something else\n\nBut instead, you could just do \ntry:\n func()\nexcept SomeException:\n # do someth... | [
8,
4,
2
] | [] | [] | [
"python"
] | stackoverflow_0001030070_python.txt |
Q:
Calling an external program from python
So I have this shell script:
echo "Enter text to be classified, hit return to run classification."
read text
if [ `echo "$text" | sed -r 's/ +/ /g' | bin/stupidfilter data/c_rbf` = "1.000000" ]
then
echo "Text is not likely to be stupid."
fi
if [ `echo "$text" | sed -r ... | Calling an external program from python | So I have this shell script:
echo "Enter text to be classified, hit return to run classification."
read text
if [ `echo "$text" | sed -r 's/ +/ /g' | bin/stupidfilter data/c_rbf` = "1.000000" ]
then
echo "Text is not likely to be stupid."
fi
if [ `echo "$text" | sed -r 's/ +/ /g' | bin/stupidfilter data/c_rbf` = "... | [
"To do it just like the shell script does:\nimport subprocess\n\ntext = raw_input(\"Enter text to be classified: \")\np1 = subprocess.Popen('bin/stupidfilter', 'data/c_trbf')\nstupid = float(p1.communicate(text)[0])\n\nif stupid:\n print \"Text is likely to be stupid\"\nelse:\n print \"Text is not likely to b... | [
8,
1
] | [] | [] | [
"c",
"python"
] | stackoverflow_0001030114_c_python.txt |
Q:
How to Make a PyMe (Python library) Run in Python 2.4 on Windows?
I want to run this library on Python 2.4 in Windows XP.
I installed the pygpgme-0.8.1.win32.exe file but got this:
>>> from pyme import core
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "C:\Python24\Lib\site-packages\pyme... | How to Make a PyMe (Python library) Run in Python 2.4 on Windows? | I want to run this library on Python 2.4 in Windows XP.
I installed the pygpgme-0.8.1.win32.exe file but got this:
>>> from pyme import core
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "C:\Python24\Lib\site-packages\pyme\core.py", line 22, in ?
import pygpgme
File "C:\Python24\Lib\sit... | [
"While the pygpgme project does not clearly document it, it's clear from the error message you got that their .win32.exe was indeed compiled for Python 2.5.\nTo compile their code for Python 2.4 (assuming they support that release!), download their sources, unpack them, open a command window, cd to the directory yo... | [
2
] | [] | [] | [
"c",
"distutils",
"installation",
"python"
] | stackoverflow_0001030297_c_distutils_installation_python.txt |
Q:
Background process in GAE
I am developing a website using Google App Engine and Django 1.0 (app-engine-patch)
A major part of my program has to run in the background and change local data and also post to a remote URL
Can someone suggest an effective way of doing this?
A:
Check out The Task Queue Python API.
A:... | Background process in GAE | I am developing a website using Google App Engine and Django 1.0 (app-engine-patch)
A major part of my program has to run in the background and change local data and also post to a remote URL
Can someone suggest an effective way of doing this?
| [
"Check out The Task Queue Python API.\n",
"Without using a third-party system, I think currently your only option is to use the cron functionality.\nYou'd still be bound by the usual GAE script-execution-time limitations, but it wouldn't happen on a page load.\nThere is plans for background processing, see this A... | [
5,
2,
2
] | [] | [] | [
"backgroundworker",
"django",
"google_app_engine",
"python"
] | stackoverflow_0000845620_backgroundworker_django_google_app_engine_python.txt |
Q:
Unescape _xHHHH_ XML escape sequences using Python
I'm using Python 2.x [not negotiable] to read XML documents [created by others] that allow the content of many elements to contain characters that are not valid XML characters by escaping them using the _xHHHH_ convention e.g. ASCII BEL aka U+0007 is represented b... | Unescape _xHHHH_ XML escape sequences using Python | I'm using Python 2.x [not negotiable] to read XML documents [created by others] that allow the content of many elements to contain characters that are not valid XML characters by escaping them using the _xHHHH_ convention e.g. ASCII BEL aka U+0007 is represented by the 7-character sequence u"_x0007_". Neither the funct... | [
"You might as well check for '_x' rather than just _, that won't matter much but surely the two-character sequence's even rarer than the single underscore. Apart from such details, you do seem to be making the best of a bad situation!\n"
] | [
1
] | [] | [] | [
"escaping",
"python",
"xml"
] | stackoverflow_0001030522_escaping_python_xml.txt |
Q:
When to use a Templating Engine in Python?
As a "newbie" to Python, and mainly having a background of writing scripts for automating system administration related tasks, I don't have a lot of sense for where to use certain tools.
But I am very interested in developing instincts on where to use specific tools/techn... | When to use a Templating Engine in Python? | As a "newbie" to Python, and mainly having a background of writing scripts for automating system administration related tasks, I don't have a lot of sense for where to use certain tools.
But I am very interested in developing instincts on where to use specific tools/techniques.
I've seen a lot mentioned about templatin... | [
"As @mikem says, templates help generating whatever form of output you like, in the right conditions. Essentially the first meaningful thing I ever wrote in Python was a templating system -- YAPTU, for Yet Another Python Templating Utility -- and that was 8+ years ago, before other good such systems existed... soon... | [
9,
3,
0
] | [] | [] | [
"python",
"template_engine",
"templates"
] | stackoverflow_0001030622_python_template_engine_templates.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.