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:
Learning Python: simple functions to write
I'm starting to learn Python, and I would love to "test" myself with a series of simple challenges. Things like "write a function that sorts a list alphabetically", "write a function to convert underscore-separated strings into camel-case", etc. I'm basically looking for... | Learning Python: simple functions to write | I'm starting to learn Python, and I would love to "test" myself with a series of simple challenges. Things like "write a function that sorts a list alphabetically", "write a function to convert underscore-separated strings into camel-case", etc. I'm basically looking for a series of problems to work my way through as ... | [
"Beginner-level:\nhttp://codingbat.com/python\nAll other levels:\nhttp://projecteuler.net/\n",
"http://projecteuler.net/ and with http://www.pythonchallenge.com/, off you go! :)\nOh, I forgot my favourite: https://github.com/gregmalcolm/python_koans\n",
"Write a function to reverse the key-value relationship in... | [
8,
6,
1
] | [] | [] | [
"python"
] | stackoverflow_0004661532_python.txt |
Q:
how to specify default values for model with user FK in django
I have looked at the questions for extending user fields in django and thought of using the FK to user method:
class Parent(models.Model):
user = models.ForeignKey(User)
contact_means = models.IntegerField()
parent_id = models.AutoField(pri... | how to specify default values for model with user FK in django | I have looked at the questions for extending user fields in django and thought of using the FK to user method:
class Parent(models.Model):
user = models.ForeignKey(User)
contact_means = models.IntegerField()
parent_id = models.AutoField(primary_key = True)
I have a question here. With this method (compared... | [
"Can you clarify what you mean by specifying default attributes for user after registering Parent?\nAre you creating the user object from your Parent object? I could help better if I understood the flow between your User object creation and Parent object creation.\nTo hide your user field: specify the fields attrib... | [
0
] | [] | [] | [
"django",
"django_admin",
"django_models",
"python"
] | stackoverflow_0004658299_django_django_admin_django_models_python.txt |
Q:
Alternatives to PHP Cron Job for Long Running Jobs
We have a website that lists links to blogs in realtime. The problem is that the pages are slow to load because they are reading data from the various source sites.
I wrote a PHP script that creates an HTML version of each page. This runs once each hour. The probl... | Alternatives to PHP Cron Job for Long Running Jobs | We have a website that lists links to blogs in realtime. The problem is that the pages are slow to load because they are reading data from the various source sites.
I wrote a PHP script that creates an HTML version of each page. This runs once each hour. The problem is that the PHP script is timing out before it finish... | [
"Python with urllib2 will probably do a good job. Also, do I understand this right: you have a site that aggregates data from other sites, and it's all generated static HTML? It sounds like you're kind of using HTML as a database, so maybe consider using a proper one.\n",
"Given the fact that your original proble... | [
2,
1,
0
] | [] | [] | [
"cron",
"php",
"python",
"web_hosting"
] | stackoverflow_0004661377_cron_php_python_web_hosting.txt |
Q:
When is the output of repr useful?
I have been reading about repr in Python. I was wondering what the application of the output of repr is. e.g.
class A:
pass
repr(A) ='<class __main__.A at 0x6f570>'
b=A()
repr(b) = '<__main__.A instance at 0x74d78>'
When would one be interested in '<class __main__.A at 0x6f57... | When is the output of repr useful? | I have been reading about repr in Python. I was wondering what the application of the output of repr is. e.g.
class A:
pass
repr(A) ='<class __main__.A at 0x6f570>'
b=A()
repr(b) = '<__main__.A instance at 0x74d78>'
When would one be interested in '<class __main__.A at 0x6f570>' or'<__main__.A instance at 0x74d78>'... | [
"Theoretically, repr(obj) should spit out a string such that it can be fed into eval to recreate the object. In other words,\nobj2 = eval(repr(obj1))\n\nshould reproduce the object.\nIn practice, repr is often a \"lite\" version of str. str might print a human-readable form of the object, whereas repr prints out in... | [
5,
4,
1
] | [] | [] | [
"python",
"repr"
] | stackoverflow_0004661851_python_repr.txt |
Q:
Tracing interconnected Python executables on OS X
I have a rather long setup, then three questions at the end.
On OS X, the System Python framework contains three executables (let me give them short names):
> F=/System/Library/Frameworks/Python.framework/Versions/2.6
> A=$F/bin/python2.6
> B=$F/Resources/Python.ap... | Tracing interconnected Python executables on OS X | I have a rather long setup, then three questions at the end.
On OS X, the System Python framework contains three executables (let me give them short names):
> F=/System/Library/Frameworks/Python.framework/Versions/2.6
> A=$F/bin/python2.6
> B=$F/Resources/Python.app/Contents/MacOS/Python
> C=$F/Python
$A and $B are cl... | [
"The Apple-supplied Pythons in OS X 10.6 are built and installed using the standard Python framework build option, with a few customization tweaks. It is not in Apple's documentation because the specific layout is not an Apple invention; it has evolved over the years by the Python project using other OS X framewor... | [
3,
2
] | [] | [] | [
"frameworks",
"macos",
"python"
] | stackoverflow_0004658008_frameworks_macos_python.txt |
Q:
Vectors and matrices in Python 3.x
Is there a good Python 3 library for vectors and matrices?
Here's some of the functionality I expect to find in such a library:
matrix multiplication
matrix determinant
euclidean distance between two vectors
cosine similarity between two vectors
convolution
A:
The 1.5 version ... | Vectors and matrices in Python 3.x | Is there a good Python 3 library for vectors and matrices?
Here's some of the functionality I expect to find in such a library:
matrix multiplication
matrix determinant
euclidean distance between two vectors
cosine similarity between two vectors
convolution
| [
"The 1.5 version of numpy is compatible with Python 3.\n",
"U can download numpy for python 3: http://sourceforge.net/projects/numpy/files/NumPy/1.5.1/numpy-1.5.1-win32-superpack-python3.1.exe/download\nIts the best tool in the python for world for what u need\n"
] | [
9,
1
] | [] | [] | [
"matrix",
"python",
"python_3.x",
"vector"
] | stackoverflow_0004662210_matrix_python_python_3.x_vector.txt |
Q:
Problem with star code
I have a problem getting my a star implementation to work. Can you point the way? Thank you.
#!/usr/bin/env python
import sys, re, math
grid = []
g = []
h = []
width = int(sys.argv[1])
height = int(sys.argv[2])
open = []
close = []
startpos = (0,0) #(height,width)
endpos = (6,5) #... | Problem with star code | I have a problem getting my a star implementation to work. Can you point the way? Thank you.
#!/usr/bin/env python
import sys, re, math
grid = []
g = []
h = []
width = int(sys.argv[1])
height = int(sys.argv[2])
open = []
close = []
startpos = (0,0) #(height,width)
endpos = (6,5) #(height,width)
#Functions
... | [
"Some problems:\n\nYou do this for comments:\n'''some text'''\n\nThat is in fact not a comment, but a string. You just don't assign it to anything. se a comment instead:\n# some text\n\nThis code is very hard to read:\n if q==0:\n if w==-1 or w==1:\n nodecost = parentgcost+10\n elif q... | [
4,
0
] | [] | [] | [
"algorithm",
"graph",
"python"
] | stackoverflow_0004656315_algorithm_graph_python.txt |
Q:
Matplotlib: simultaneous plotting in multiple threads
I am trying to do some plotting in parallel to finish large batch jobs quicker. To this end, I start a thread for each plot I plan on making.
I had hoped that each thread would finish its plotting and close itself (as I understand it, Python closes threads when... | Matplotlib: simultaneous plotting in multiple threads | I am trying to do some plotting in parallel to finish large batch jobs quicker. To this end, I start a thread for each plot I plan on making.
I had hoped that each thread would finish its plotting and close itself (as I understand it, Python closes threads when they get through all the statements in run()). Below is so... | [
"Why not just use multiprocessing? As far as I can tell from your description, threading won't help you much, anyway... \nMatplotlib already threads so that you can display and interact with multiple figures at once. If you want to speed up batch processing on a multicore machine, you're going to need multiprocessi... | [
31,
6
] | [] | [] | [
"matplotlib",
"multithreading",
"python",
"python_multithreading"
] | stackoverflow_0004659680_matplotlib_multithreading_python_python_multithreading.txt |
Q:
How to display QLineEdit on the window?
I created a small window using PyQt4 and Pydev. The code is below:
import sys
from PyQt4 import QtGui
from PyQt4 import QtCore
# Create GUI object
app = QtGui.QApplication(sys.argv)
widget = QtGui.QWidget()
widget.setGeometry(400,300,800,800) # Position window
widget.resiz... | How to display QLineEdit on the window? | I created a small window using PyQt4 and Pydev. The code is below:
import sys
from PyQt4 import QtGui
from PyQt4 import QtCore
# Create GUI object
app = QtGui.QApplication(sys.argv)
widget = QtGui.QWidget()
widget.setGeometry(400,300,800,800) # Position window
widget.resize(450,250) # Resize window
widget.setWindow... | [
"Just use\nPassword = QtGui.QLineEdit(widget)\n\nThis tells Qt that you want widget to be the parent of the QLineEdit. If you leave out the widget, then the QLineEdit has no parent, so it's not shown.\nUpdate: To position child items in parent windows, you'll have to read up about layouts (I assume you want to do i... | [
1
] | [] | [] | [
"pyqt4",
"python"
] | stackoverflow_0004662500_pyqt4_python.txt |
Q:
Switching from web to desktop development
Being a web developer (php, symfony, doctrine) for 2 years now, I was recently asked by a friend to come up with a desktop solution. So I developed a project, installed a LAMP on his machine and he is mostly happy using it now. But I'm not. It just doesn't seem right to wa... | Switching from web to desktop development | Being a web developer (php, symfony, doctrine) for 2 years now, I was recently asked by a friend to come up with a desktop solution. So I developed a project, installed a LAMP on his machine and he is mostly happy using it now. But I'm not. It just doesn't seem right to wait for a server response from a localhost. Obvi... | [
"You should definitely use Python. It's great and really easy to get up and running and extremely powerful.\nutilizing an ORM and(or) HTML-based GUI\n\nPlease don't do this. HTML has its purposes, and it's not in desktop apps. Please don't force your experience into new technologies.\nYou should look at the various... | [
2,
1,
0,
0
] | [
"Is the target platform windows? If so, consider C# with WPF. The UI is constructed using XAML which is very similar to HTML/CSS. C# uses the .NET framework, so while it is a much different programming language than PHP, the transition should not be too difficult. \n"
] | [
-1
] | [
"air",
"orm",
"python"
] | stackoverflow_0004578957_air_orm_python.txt |
Q:
python twisted DeferedList ErrorBack ( Unhandled error in Deferred )
In my below code I pass a host:port combination and try to get some information from the server using twisted Defered. I have shown a very basic code of what I am trying to do. The connection to host port is made via httplib. It works correctly i... | python twisted DeferedList ErrorBack ( Unhandled error in Deferred ) | In my below code I pass a host:port combination and try to get some information from the server using twisted Defered. I have shown a very basic code of what I am trying to do. The connection to host port is made via httplib. It works correctly if the host is up. Correct callback methods are called. But when it fails (... | [
"The problem is that you have assumed that conn.request (on your line 17) will raise a httplib.HTTPException, but that's not the exception type it raises. Since you're not terribly sure what exception it will raise, I'd recommend you make a blanket except... statement and fetch the exception data from sys.exc_info(... | [
1
] | [] | [] | [
"deferred",
"python",
"twisted"
] | stackoverflow_0004661661_deferred_python_twisted.txt |
Q:
Trying to determine if file has been uuencoded
I am trying to process a large collection of txt files which themselves are containers for the actual files that I am wanting to process. The txt files have sgml tags that set boundaries for the individual files I am processing. Sometimes, the contained files are bi... | Trying to determine if file has been uuencoded | I am trying to process a large collection of txt files which themselves are containers for the actual files that I am wanting to process. The txt files have sgml tags that set boundaries for the individual files I am processing. Sometimes, the contained files are binary that have been uuencoded. I have solved the pr... | [
"Wikipedia says that every uuencoded file begins with this line\nbegin <perm> <name>\n\nSo probably a line matching the regexp ^begin [0-7]{3} (.*)$ denotes the beginning reliably enough.\n",
"Two ways:\n(1) On Unix-based systems, you can robustly use the file command.\nhttp://unixhelp.ed.ac.uk/CGI/man-cgi?file\n... | [
2,
1
] | [] | [] | [
"python",
"uudecode",
"uuencode"
] | stackoverflow_0004662903_python_uudecode_uuencode.txt |
Q:
Is it possible to install specific version of Python more than once on Windows?
I'd like to know if installing specific version of Python more than once on Windows is possible.
I'm asking about normal installation procedure leading to full Python environment so virtualenv is not an option here.
I'm concerned for e... | Is it possible to install specific version of Python more than once on Windows? | I'd like to know if installing specific version of Python more than once on Windows is possible.
I'm asking about normal installation procedure leading to full Python environment so virtualenv is not an option here.
I'm concerned for example with registry key HKEY_LOCAL_MACHINE/SOFTWARE/Python/PythonCore/<Version> whic... | [
"I use multiple registry files (*.reg) to switch between multiple Python interpreters of the same version but installed in different locations. Adjust version number and location in this template:\nREGEDIT4\n\n[HKEY_LOCAL_MACHINE\\SOFTWARE\\Python\\PythonCore\\X.Y]\n\n[HKEY_LOCAL_MACHINE\\SOFTWARE\\Python\\PythonCo... | [
1
] | [
"You can install several Python versions on Windows; I did this and did not notice any adverse effects. \nWhen you install a package, you just run the version of interpreter to which you want to install the package, that is, python31 setup.py install or such. The interpreter knows where its home is.\nAlso, consider... | [
-1
] | [
"installation",
"pyside",
"python",
"registry",
"windows"
] | stackoverflow_0004662098_installation_pyside_python_registry_windows.txt |
Q:
python protobufs - avoid the install step?
i'm writing a small python utility which will be consumed by moderately non-technical users and which needs to interface w/ some protobufs.
ideally, i would like the only prerequisites to using this on a local machine to be:
have python installed
* have an SVN checkout of... | python protobufs - avoid the install step? | i'm writing a small python utility which will be consumed by moderately non-technical users and which needs to interface w/ some protobufs.
ideally, i would like the only prerequisites to using this on a local machine to be:
have python installed
* have an SVN checkout of the repository
* run a simple bash script to bu... | [
"Does the file __ init __.py exist in google/protobuf directory?\n",
"commenting out the import of descriptor_pb2.py in descriptor_pb2.py itself fixed my issue. thanks to tim mcclarren for suggesting that !\n"
] | [
0,
0
] | [] | [] | [
"descriptor",
"import",
"protocol_buffers",
"python"
] | stackoverflow_0004653494_descriptor_import_protocol_buffers_python.txt |
Q:
Are there any more elegant ways of handling lists in Java ? (Python VS Java)
I do like the way I can treat lists in Python. It does any recursion solution to look easy and clean. For instance the typical problem of getting all the permutations of elements in a list, in Python looks like:
def permutation_recursion(... | Are there any more elegant ways of handling lists in Java ? (Python VS Java) | I do like the way I can treat lists in Python. It does any recursion solution to look easy and clean. For instance the typical problem of getting all the permutations of elements in a list, in Python looks like:
def permutation_recursion(numbers,sol):
if not numbers:
print "this is a permutation", sol
f... | [
"No. \nBut this is why Martin Odersky created Scala. He's even said that one of his goals for Scala is that it be the Python of the Java world. Scala compiles to Java bytecode and easily interops with Java compiled classes. \nIf that's not an option, you could take a look at the Commons Collection Library.\n",
"Y... | [
8,
2,
1,
1,
0
] | [] | [] | [
"java",
"language_design",
"list",
"operators",
"python"
] | stackoverflow_0004662091_java_language_design_list_operators_python.txt |
Q:
How do I sum the first value in a set of lists within a tuple?
Hey, I would like to be able to perform this but with being selective for which lists I sum up. Let's say, that same example, but with only adding up the first number from the 3rd and 4th list.
A:
Something like:
sum(int(tuple_list[i][0]) for i in ra... | How do I sum the first value in a set of lists within a tuple? | Hey, I would like to be able to perform this but with being selective for which lists I sum up. Let's say, that same example, but with only adding up the first number from the 3rd and 4th list.
| [
"Something like:\nsum(int(tuple_list[i][0]) for i in range(3,5))\n\nrange(x, y) generates a list of integers from x(included) to y(excluded) and 1 as the step. If you want to change the range(x, y, step) will do the same but increasing by step.\nYou can find the official documentation here\nOr you can do:\nsum(floa... | [
8,
1,
0,
0
] | [] | [] | [
"python",
"tuples"
] | stackoverflow_0004663024_python_tuples.txt |
Q:
Find entity that matches the most criteria
I have some properties, let's say
color = blue
age = 22
name = Tom
Of a number of entities in the datastore, how can I get one that matches most of the properties? Of course I could do:
query.filter('color =', 'blue')
query.filter('age =', '22')
query.filter('name =', 'T... | Find entity that matches the most criteria | I have some properties, let's say
color = blue
age = 22
name = Tom
Of a number of entities in the datastore, how can I get one that matches most of the properties? Of course I could do:
query.filter('color =', 'blue')
query.filter('age =', '22')
query.filter('name =', 'Tom')
But if no such entity with the exact prope... | [
"You are basically asking for an OR operator, which is not possible to do with a single query. I think you have two options:\n1) Add an OR operator by subclassing MultiQuery. This will still execute several queries under the hood and ordering and cursors won't work.\n2) Pre-compute all possible combinations of your... | [
2
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"gql",
"python"
] | stackoverflow_0004662532_google_app_engine_google_cloud_datastore_gql_python.txt |
Q:
How to return every 5 items from a list in python?
I am using python and would like to return every 5 items from a list and put them into csv format.
Also, if there are less than 5 items in the iteration then I need to zero fill to get 5 items.
I am using a fairly old version of python 2.1 which can not be changed... | How to return every 5 items from a list in python? | I am using python and would like to return every 5 items from a list and put them into csv format.
Also, if there are less than 5 items in the iteration then I need to zero fill to get 5 items.
I am using a fairly old version of python 2.1 which can not be changed so i do not have access to 'iter'.
Thanks.
| [
"Including the padding, this might work. (There are list comprehensions in 2.1, right? Just looked it up -- they were added in 2.0.)\na = the_list\na += [0] * (-len(a) % 5)\nresult = [a[i:i + 5] for i in range(0, len(a), 5)]\n\nIn less ancient Python, I would replace the last line by\nresult = zip(*[iter(a)] * 5)\... | [
5,
3,
0,
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0004660250_list_python.txt |
Q:
A Read-Only Relational Database on Google App Engine?
I have a medium size (~100mb) read-only database that I want to put on google app engine. I could put it into the datastore, but the datastore is kind of slow, has no relational features, and has many other frustrating limitations (not going into them here). ... | A Read-Only Relational Database on Google App Engine? | I have a medium size (~100mb) read-only database that I want to put on google app engine. I could put it into the datastore, but the datastore is kind of slow, has no relational features, and has many other frustrating limitations (not going into them here). Another option is loading all the data into memory, but I q... | [
"I don't think you're likely to find anything like that...surely not over blobstore. Because if all your data is stored in a single blob, you'd have to read the entire database into memory for any operation, and you said you can't do that.\nUsing the datastore as your backend is more plausible, but not much. The bi... | [
2,
2,
1
] | [] | [] | [
"google_app_engine",
"non_relational_database",
"python",
"relational_database",
"sqlite"
] | stackoverflow_0004663071_google_app_engine_non_relational_database_python_relational_database_sqlite.txt |
Q:
How to send newsletter from my pc?
Is there a way to send newsletter from my pc ( ubuntu 10.04 ) and python ?
maybe with a smtp library ?
A:
If this is going to be a regular task, install Mailman (if you don't already have it) and learn how to use it.
A:
Here is a script that can be used to send an email using... | How to send newsletter from my pc? | Is there a way to send newsletter from my pc ( ubuntu 10.04 ) and python ?
maybe with a smtp library ?
| [
"If this is going to be a regular task, install Mailman (if you don't already have it) and learn how to use it.\n",
"Here is a script that can be used to send an email using a gmail or Google domain apps email account. It uses Google's SMTP server, so you don't need to configure one locally.\nUsing its 'mail' fu... | [
2,
1,
0
] | [] | [] | [
"python",
"smtp"
] | stackoverflow_0004659535_python_smtp.txt |
Q:
Writing Socket Servers in PHP is it good idea?
Is it good idea to write Socket Servers using php??
here is how to article:
http://devzone.zend.com/article/1086
question:
What is different from writing socket servers in other languages like c, c++, python, ..?
how about security?
speed?
"Socket Servers normally r... | Writing Socket Servers in PHP is it good idea? | Is it good idea to write Socket Servers using php??
here is how to article:
http://devzone.zend.com/article/1086
question:
What is different from writing socket servers in other languages like c, c++, python, ..?
how about security?
speed?
"Socket Servers normally run continuously as a service or a daemon."
php runni... | [
"It is not generally a good idea to write a (nontrivial) PHP program which executes for a long time. This is because its memory management is deficient in various ways, in particular, it fails to ever deallocate circularly referenced structures. Some other objects also leak. For example http://uk.php.net/manual/en/... | [
3
] | [] | [] | [
"c++",
"linux",
"php",
"python"
] | stackoverflow_0004659364_c++_linux_php_python.txt |
Q:
Django subclassing multiwidget - reconstructing date on post using custom multiwidget
So my django book is back at university and I'm struggling to work this one out.
I've subclassed django.forms.widgets.MultiWidget like so:
class DateSelectorWidget(widgets.MultiWidget):
def __init__(self, attrs=None, dt=None,... | Django subclassing multiwidget - reconstructing date on post using custom multiwidget | So my django book is back at university and I'm struggling to work this one out.
I've subclassed django.forms.widgets.MultiWidget like so:
class DateSelectorWidget(widgets.MultiWidget):
def __init__(self, attrs=None, dt=None, mode=0):
if dt is not None:
self.datepos = dt
else:
... | [
"Answered my own question!\nI implemented this method:\ndef value_from_datadict(self, data, files, name):\n datelist = [widget.value_from_datadict(data, files, name + '_%s' % i) \\ \n for i, widget in enumerate(self.widgets)]\n try:\n D = date(day=int(datelist[0]), ... | [
12
] | [] | [] | [
"django",
"django_multiwidget",
"django_widget",
"python"
] | stackoverflow_0004662835_django_django_multiwidget_django_widget_python.txt |
Q:
lookbehind in a for loop
How are you doing?
Am kinda stuck with this problem, I need to use a for loop to find a word that ends with 'ing' and is preceded by a tag that is IN, I come from a background of C and java and there its easy to do, but I cant yet grasp how to do it in python!!
I searched around and here i... | lookbehind in a for loop | How are you doing?
Am kinda stuck with this problem, I need to use a for loop to find a word that ends with 'ing' and is preceded by a tag that is IN, I come from a background of C and java and there its easy to do, but I cant yet grasp how to do it in python!!
I searched around and here is what I think i need to do:
f... | [
"Based on your comment, sounds like you want this:\ndef transform(li):\n new_li = []\n prev_tag = None\n for word, tag in li:\n if word.endswith('ing') and prev_tag == 'NN':\n tag = 'VBG'\n new_li += [(word, tag)]\n prev_tag = tag\n return new_li\n\nYou can also do this i... | [
1,
1,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004663486_python_regex.txt |
Q:
OpenID login on local development server for google app engine
Are you able to use open id to log into the local development server with google app engine sdk version 1.4.1 and python 2.5?
When I execute this
self.redirect(users.create_login_url(continue_url, None, openid_url))
I get redirected to http://localhos... | OpenID login on local development server for google app engine | Are you able to use open id to log into the local development server with google app engine sdk version 1.4.1 and python 2.5?
When I execute this
self.redirect(users.create_login_url(continue_url, None, openid_url))
I get redirected to http://localhost/_ah/login rather than the openid url.
The openid url and continue ... | [
"No - in the SDK, openid logins are treated the same way as regular logins, using the same Users mockup. It's intended purely for testing.\n"
] | [
6
] | [] | [] | [
"google_app_engine",
"openid",
"python"
] | stackoverflow_0004634929_google_app_engine_openid_python.txt |
Q:
boto: EC2 instance get_attribute results in AttributeError: 'EC2Connection' object has no attribute 'describe_attribute'
What steps will reproduce the problem?
1.attempt to get a running EBS-backed instance's kernel attribute with instance.get_attribute('kernel')
>>> import boto.ec2
>>> regions = boto.ec2.regions(... | boto: EC2 instance get_attribute results in AttributeError: 'EC2Connection' object has no attribute 'describe_attribute' | What steps will reproduce the problem?
1.attempt to get a running EBS-backed instance's kernel attribute with instance.get_attribute('kernel')
>>> import boto.ec2
>>> regions = boto.ec2.regions()
>>> regions
[RegionInfo:eu-west-1, RegionInfo:us-east-1, RegionInfo:us-west-1, RegionInfo:ap-southeast-1]
>>> usw = regions[... | [
"Problem was promptly fixed by the developers!\nhttps://github.com/boto/boto/commit/899ab55752d31af22f41168f92fe39553504d6fc\nHowever at time of writing, it's still not on pypi (so pip install --upgrade) won't help - must git clone and install from there.\n"
] | [
0
] | [] | [] | [
"amazon_ec2",
"amazon_web_services",
"boto",
"python"
] | stackoverflow_0004656020_amazon_ec2_amazon_web_services_boto_python.txt |
Q:
Making an object's attributes iterable
I'm getting returned a list with objects that have multiple attributes like so:
results = q.fetch(5)
for p in results:
print "%s %s, %d inches tall" % (p.first_name, p.last_name, p.height
Is it possible to iterate over these attributes so I can do something like for x i... | Making an object's attributes iterable | I'm getting returned a list with objects that have multiple attributes like so:
results = q.fetch(5)
for p in results:
print "%s %s, %d inches tall" % (p.first_name, p.last_name, p.height
Is it possible to iterate over these attributes so I can do something like for x in p. I want to check the value of each one, ... | [
"I warn against doing this. There are rare exceptions where it's warranted, but almost all the time it's better avoiding this sort of hackish solution. If you want to though, you could use vars() to get a dictionary of attributes and iterate through it. As @Nick points out below, App Engine uses properties instead ... | [
6,
3,
1,
0
] | [] | [] | [
"google_app_engine",
"iteration",
"python"
] | stackoverflow_0004631601_google_app_engine_iteration_python.txt |
Q:
Would using a WSDL to generate REST clients be the wrong direction?
I'm out to create a fairly simple web service for intranet use. The service will ultimately be the interface to a DB that will allow me to keep track of what the various internal tools within the company are doing. I'm thinking I want a web serv... | Would using a WSDL to generate REST clients be the wrong direction? | I'm out to create a fairly simple web service for intranet use. The service will ultimately be the interface to a DB that will allow me to keep track of what the various internal tools within the company are doing. I'm thinking I want a web service so that various tools (and thus different languages) within the organ... | [
"I don't get the code generation issue here.\nREST rarely requires any code generation of any kind. It's just HTTP requests with simple JSON (or XML) payloads. \nYou use the existing HTTP libraries (e.g. Apache Commons, or Python urrlib2). You use existing JSON (or XML) libraries. (the Jersey project has a nice... | [
5,
1,
1,
1,
1
] | [] | [] | [
"java",
"perl",
"python",
"rest",
"soap"
] | stackoverflow_0002314399_java_perl_python_rest_soap.txt |
Q:
How do I set a top level variable in Python?
Let's say I have a script file, like so:
foo = 1
def bar():
return foo
# The Main function for this script.
def main(argv=None):
foo = 2
print bar()
return
This prints 1.
Is there any way to set the value of foo at the script-level from main?
A:
foo... | How do I set a top level variable in Python? | Let's say I have a script file, like so:
foo = 1
def bar():
return foo
# The Main function for this script.
def main(argv=None):
foo = 2
print bar()
return
This prints 1.
Is there any way to set the value of foo at the script-level from main?
| [
"foo = 1\n\ndef bar():\n return foo\n\n# The Main function for this script.\ndef main(argv=None):\n global foo\n foo = 2\n print bar()\n return\n\nThis is in the python documentation.\n",
"def main(argv=None):\n global foo\n foo = 2\n print bar()\n return\n\n"
] | [
8,
6
] | [] | [] | [
"python"
] | stackoverflow_0004664345_python.txt |
Q:
How to run a python script on a Rails server?
I have a Rails server which will need to run a python script at the background. I know that I can run it like I run terminal commands in ruby, but how is the performance like? is it better to use a python framework and not Rails? Is there better ways (optimization wise... | How to run a python script on a Rails server? | I have a Rails server which will need to run a python script at the background. I know that I can run it like I run terminal commands in ruby, but how is the performance like? is it better to use a python framework and not Rails? Is there better ways (optimization wise) to run python scripts on a Rails server?
| [
"If you mean that it needs to run periodically, just set it up as a cron job, no special performance characteristics to worry about there.\nIf you mean that it needs to run when pages are requested from your Ruby website, then simply running the script each time won't perform well as it needs to fire up the Python ... | [
5,
1,
1
] | [] | [] | [
"python",
"ruby",
"ruby_on_rails"
] | stackoverflow_0004664325_python_ruby_ruby_on_rails.txt |
Q:
Why can I not read more than 16 bytes of a JPEG file in Python?
I am trying to read a JPG image in Python.
So far i have:
f = open("test.jpg")
ima = f.read(16)
print "'%s'"% (ima)
It reads 16 bytes and displays the string in console, but it looks like I cannot display more than 32 bytes. Why?
When it tries to re... | Why can I not read more than 16 bytes of a JPEG file in Python? | I am trying to read a JPG image in Python.
So far i have:
f = open("test.jpg")
ima = f.read(16)
print "'%s'"% (ima)
It reads 16 bytes and displays the string in console, but it looks like I cannot display more than 32 bytes. Why?
When it tries to read 32 or more bytes, the output will be the same as when it read 16 b... | [
"Two issues here:\n\nSet read mode to binary. This way file.read function won't try to convert '\\r\\n' sequences.\nYou're trying to print NULL-terminated string to the console. print function finds first zero character in your string and terminates. Use binascii.hexlify to convert it to the hex:\n\n\nf = open(\"te... | [
11,
5
] | [] | [] | [
"byte",
"image",
"jpeg",
"python"
] | stackoverflow_0004664343_byte_image_jpeg_python.txt |
Q:
slicing a 2d numpy array
The following code:
import numpy as p
myarr=[[0,1],[0,6],[0,1],[0,6],[0,1],[0,6],[0,1],[0,6],[0,1],[0,6],[0,1],[0,6],[0,1],[0,6],[0,1],[0,6],[0,1],[0,6]]
copy=p.array(myarr)
p.mean(copy)[:,1]
Is generating the following error message:
Traceback (most recent call last):
File "<pyshell#3>... | slicing a 2d numpy array | The following code:
import numpy as p
myarr=[[0,1],[0,6],[0,1],[0,6],[0,1],[0,6],[0,1],[0,6],[0,1],[0,6],[0,1],[0,6],[0,1],[0,6],[0,1],[0,6],[0,1],[0,6]]
copy=p.array(myarr)
p.mean(copy)[:,1]
Is generating the following error message:
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
p.m... | [
"You probably mean p.mean(copy[:,1]) with the indexing before the mean() function call. I don't see the problem with the contents of copy - it looks right to me.\n",
"x = numpy.array(myarr)\nx[:,1].mean()\n\nor\nnumpy.array(myarr)[:,1].mean()\n\nor if you really hate yourself,\nnumpy.array(myarr).mean(axis=0)[1]\... | [
1,
1
] | [] | [] | [
"arrays",
"matplotlib",
"numpy",
"python",
"slice"
] | stackoverflow_0004664502_arrays_matplotlib_numpy_python_slice.txt |
Q:
What's the equivalent of this in Javascript?
print dir(someOjbect)
How can I print that in console?
A:
You can install Firebug and do
console.log(someObject);
A:
If you're using Chrome, just open up your JavaScript Console or Developer Tools.
var red = {color: 'red'};
console.log(red);
A:
The quickest and d... | What's the equivalent of this in Javascript? | print dir(someOjbect)
How can I print that in console?
| [
"You can install Firebug and do\nconsole.log(someObject);\n\n",
"If you're using Chrome, just open up your JavaScript Console or Developer Tools.\nvar red = {color: 'red'};\nconsole.log(red);\n\n",
"The quickest and dirtiest way is alert(someObject), but it does not help much with objects. You can write a crude... | [
4,
1,
1,
0,
0,
0,
0,
0
] | [] | [] | [
"javascript",
"python"
] | stackoverflow_0004664568_javascript_python.txt |
Q:
How to change folder icons with Python on windows?
I would like to write a utility script that changes the icon of folders with a specific name. Is this possible in python? If not, is there any other way of doing this?
Thanks
A:
import os
import ctypes
from ctypes import POINTER, Structure, c_wchar, c_int, sizeo... | How to change folder icons with Python on windows? | I would like to write a utility script that changes the icon of folders with a specific name. Is this possible in python? If not, is there any other way of doing this?
Thanks
| [
"import os\nimport ctypes\nfrom ctypes import POINTER, Structure, c_wchar, c_int, sizeof, byref\nfrom ctypes.wintypes import BYTE, WORD, DWORD, LPWSTR, LPSTR\nimport win32api \n\nHICON = c_int\nLPTSTR = LPWSTR\nTCHAR = c_wchar\nMAX_PATH = 260\nFCSM_ICONFILE = 0x00000010\nFCS_FORCEWRITE = 0x00000002\nSHGFI_ICONLO... | [
11,
1
] | [] | [] | [
"python",
"winapi",
"windows"
] | stackoverflow_0004662759_python_winapi_windows.txt |
Q:
How to fetch dictionaries within dictionaries in a JSON string?
Using the Facebook Graph API I want to get location data.
{
"name": "Joe Smith",
"link": "http://www.facebook.com/joey",
"location": {
"id": "105590706140862",
"name": "Fairfield, Iowa"
}
}
I can take this object and do things... | How to fetch dictionaries within dictionaries in a JSON string? | Using the Facebook Graph API I want to get location data.
{
"name": "Joe Smith",
"link": "http://www.facebook.com/joey",
"location": {
"id": "105590706140862",
"name": "Fairfield, Iowa"
}
}
I can take this object and do things like object["name"] to get the name Joe Smith. But how do I get the... | [
"import json\n\njson_text = \"\"\"\n{\n \"name\": \"Joe Smith\",\n \"link\": \"http://www.facebook.com/joey\",\n \"location\": {\n \"id\": \"105590706140862\",\n \"name\": \"Fairfield, Iowa\"\n }\n}\"\"\"\n\nobj = json.loads(json_text)\nprint obj[\"location\"][\"name\"]\n\n"
] | [
7
] | [] | [] | [
"dictionary",
"facebook_graph_api",
"json",
"python"
] | stackoverflow_0004664974_dictionary_facebook_graph_api_json_python.txt |
Q:
How to code a wxPython GUI program for orientating disks in a cube?
I am a geology student and am trying to come up with a program for illustrating joint networks in rock masses.
Basically I just need wxPython script, or any snippets of script that would be able to create a GUI program which displays a number of ... | How to code a wxPython GUI program for orientating disks in a cube? | I am a geology student and am trying to come up with a program for illustrating joint networks in rock masses.
Basically I just need wxPython script, or any snippets of script that would be able to create a GUI program which displays a number of disks inside a box, with the parameters (ie relative position, orientatio... | [
"I'm not sure I understand exactly what you are trying to do here. Are you creating an interactive GUI or just a visualization? It sounds like you want something in 3D. In that can you should check out VPython which has some tutorials and demo code. Also much more powerful is PyOpenGL. For something and actual... | [
0
] | [] | [] | [
"geometry",
"python",
"wxpython"
] | stackoverflow_0004665118_geometry_python_wxpython.txt |
Q:
How can I quickly dump a query result set into JSON?
import simplejson as json
results = Content.objects.filter(blah)
theresult_json = json.dumps(results)
This doesn't work!!
A:
How about http://docs.djangoproject.com/en/dev/topics/serialization/
?
from django.core import serializers
data = serializers.serializ... | How can I quickly dump a query result set into JSON? | import simplejson as json
results = Content.objects.filter(blah)
theresult_json = json.dumps(results)
This doesn't work!!
| [
"How about http://docs.djangoproject.com/en/dev/topics/serialization/\n?\nfrom django.core import serializers\ndata = serializers.serialize('json', SomeModel.objects.all())\n\n# it's pretty useful and quick.\ndata = serializers.serialize('json', SomeModel.objects.all(), fields=('foo','bar'))\n\n",
"results is a p... | [
6,
1,
0
] | [] | [] | [
"django",
"javascript",
"json",
"python"
] | stackoverflow_0004665413_django_javascript_json_python.txt |
Q:
The efficiency when using a big data structure in a function in Python
I need to use a big data structure, more specifically, a big dictionary to do the looking up job.
At the very first my code is like this:
#build the dictionary
blablabla
#look up some information in the ditionary
blablabla
As I need to look u... | The efficiency when using a big data structure in a function in Python | I need to use a big data structure, more specifically, a big dictionary to do the looking up job.
At the very first my code is like this:
#build the dictionary
blablabla
#look up some information in the ditionary
blablabla
As I need to look up many times, I begin to realize that it is a good idea to implement it as a... | [
"Answering the core question, parameter passing is not inefficient, it's not like your values will get copied around. Python passed references around, which is not to say that the way parameters are passed fits the well-known schemes of \"pass-by-value\" or \"pass-by-reference\". \nIt's best imagined as initializin... | [
9,
6
] | [] | [] | [
"function_call",
"pass_by_reference",
"python"
] | stackoverflow_0004665461_function_call_pass_by_reference_python.txt |
Q:
Is there any way to make an asynchronous function call from Python [Django]?
I am creating a Django application that does various long computations with uploaded files. I don't want to make the user wait for the file to be handled - I just want to show the user a page reading something like 'file is being parsed'.... | Is there any way to make an asynchronous function call from Python [Django]? | I am creating a Django application that does various long computations with uploaded files. I don't want to make the user wait for the file to be handled - I just want to show the user a page reading something like 'file is being parsed'.
How can I make an asynchronous function call from a view?
Something that may look... | [
"Rather than trying to manage this via subprocesses or threads, I recommend you separate it out completely. There are two approaches: the first is to set a flag in a database table somewhere, and have a cron job running regularly that checks the flag and performs the required operation.\nThe second option is to use... | [
7,
2,
0,
0
] | [] | [] | [
"asynchronous",
"django",
"python"
] | stackoverflow_0001352678_asynchronous_django_python.txt |
Q:
CLI git log statistics
I'm being faced with the task of generating statistics about the history of a Git project, and I need to produce some specific numbers and representations for various metrics - things like commits per author, commits-over-time/date histograms, that sort of thing.
The trouble is that I need a... | CLI git log statistics | I'm being faced with the task of generating statistics about the history of a Git project, and I need to produce some specific numbers and representations for various metrics - things like commits per author, commits-over-time/date histograms, that sort of thing.
The trouble is that I need all this data generated in a ... | [
"How about using XML logs instead, and then you can parse the xml in python relativily easily and build your stats\nsee this answer for how to get an xml log from git\n"
] | [
1
] | [] | [] | [
"git",
"metrics",
"python",
"statistics",
"text"
] | stackoverflow_0004665553_git_metrics_python_statistics_text.txt |
Q:
Is there an Image.point() method in PIL that allows you to operate on all three channels at once?
I want to write a point filter that is based on the red, green and blue channels for each pixel, but it appears that this might fall short of point()'s abilities -- it seems that it operates on a single pixel in a sin... | Is there an Image.point() method in PIL that allows you to operate on all three channels at once? | I want to write a point filter that is based on the red, green and blue channels for each pixel, but it appears that this might fall short of point()'s abilities -- it seems that it operates on a single pixel in a single channel at a time. I'd like to do something like this:
def colorswap(pixel):
"""Shifts the ch... | [
"You can use the load method to get fast access to all the pixels.\ndef colorswap(pixel):\n \"\"\"Shifts the channels of the image.\"\"\"\n return (pixel[1], pixel[2], pixel[0])\n\ndef applyfilter(image, func):\n \"\"\" Applies a function to each pixel of an image.\"\"\"\n width,height = im.size\n pi... | [
3,
2
] | [] | [] | [
"python",
"python_imaging_library"
] | stackoverflow_0004529515_python_python_imaging_library.txt |
Q:
How to receive uploaded file from the inlined form in django?
I'm trying to create a "cool" image uploading interface in django admin panel. The problem is that I'm using inline interface for uploading image instances, but I'm using jQuery Ajax form to upload images, so there were another form I need to create for... | How to receive uploaded file from the inlined form in django? | I'm trying to create a "cool" image uploading interface in django admin panel. The problem is that I'm using inline interface for uploading image instances, but I'm using jQuery Ajax form to upload images, so there were another form I need to create for uploading. And now django view function can't receive request.FILE... | [
"request.FILES should work fine with that handmade form. Django doesn't do anything different with the field except adding the id=\"id_file\". I'm fairly certain that your not having an id wouldn't interfere with the transference into request.FILES.\nIn [5]: from django import forms\n\nIn [6]: class GenericFileFo... | [
2,
0,
0,
0
] | [] | [] | [
"django",
"forms",
"image",
"python",
"upload"
] | stackoverflow_0002184284_django_forms_image_python_upload.txt |
Q:
Running python in 32-bit more for wxPython
I am trying to run python in 32 bit mode on Mac OS X Snow Leopard, and I have been having some success, but with the following weirdness.
If I run it with /usr/bin/python, it seems to not want to run in 32 bit mode, but if I run it using /usr/bin/python2.6, it runs in 32 ... | Running python in 32-bit more for wxPython | I am trying to run python in 32 bit mode on Mac OS X Snow Leopard, and I have been having some success, but with the following weirdness.
If I run it with /usr/bin/python, it seems to not want to run in 32 bit mode, but if I run it using /usr/bin/python2.6, it runs in 32 bit mode fine. As far as I could tell before thi... | [
"In OS X 10.6, Apple provided a way to permanently select whether the Python 2.6 supplied in OS X runs in 64-bit mode or 32-bit mode (VERSIONER_PYTHON_PREFER_32_BIT) and other options. See man 1 python for details. The /usr/bin/python program is a front-end to that and examines the selected options, set either by... | [
4,
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0004665818_python_wxpython.txt |
Q:
How do I set the _path_ as a variable?
I'm trying to code a program in python which will create a folder for each file in a directory (local) with the same name, then move that file into the folder. I've been looking everywhere for the correct code, or bits, but I havn't been able to find (or recognise) it. Any he... | How do I set the _path_ as a variable? | I'm trying to code a program in python which will create a folder for each file in a directory (local) with the same name, then move that file into the folder. I've been looking everywhere for the correct code, or bits, but I havn't been able to find (or recognise) it. Any help (or hints) would be very much appreciated... | [
"This does what I think you're asking:\n#!/usr/bin/env python\n\nimport os\n\nallfiles = [fn for fn in os.listdir('.') if not os.path.isdir(fn)]\n\nfor fn in allfiles:\n # The file must be moved out of the way before you can create a\n # directory with the same name.\n tmpname = fn + \".tmp\"\n # Then w... | [
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0004666046_python.txt |
Q:
Macports and virtualenv site-packages Fallback
I've installed django and python as this link suggested with macports. However, I'd like to use virtualenv to install more packages. My understanding is that if I do not pass in the --no-site-packages to virtualenv, I should get the currently installed packages in ad... | Macports and virtualenv site-packages Fallback | I've installed django and python as this link suggested with macports. However, I'd like to use virtualenv to install more packages. My understanding is that if I do not pass in the --no-site-packages to virtualenv, I should get the currently installed packages in addition to whatever packages I install into the virtu... | [
"You are not using the MacPorts Python as evidenced by the version and date displayed. (Try typing /usr/bin/python2.6 and then /opt/local/bin/python2.6.) Just setting MacPorts python_select does no good if you do not put the MacPorts bin directory first on your shell execution PATH:\n$ export PATH=/opt/local/bin:... | [
1
] | [] | [] | [
"django",
"macos",
"macports",
"python",
"virtualenv"
] | stackoverflow_0004666058_django_macos_macports_python_virtualenv.txt |
Q:
secure xml parsing in python
Hi i am able to parse a normal xml like xml = lxml.etree.parse(''http://abc.com/A.xml')
but now i have this path authenticated with a user name and password is it possible to input the username and password and parse the url, like in connecting a database where you can give the user na... | secure xml parsing in python | Hi i am able to parse a normal xml like xml = lxml.etree.parse(''http://abc.com/A.xml')
but now i have this path authenticated with a user name and password is it possible to input the username and password and parse the url, like in connecting a database where you can give the user name password in the connection stri... | [
"Yes, it's possible. Before parsing the XML document with lxml, you need to get it by making an HTTP request that handles the HTTP Basic/Digest Authentication properly. For example, with urllib2.HTTPBasicAuthHandler like in this solution: Python urllib2 HTTPBasicAuthHandler\n",
"Guys i found a way to parse passwo... | [
3,
3
] | [] | [] | [
"parsing",
"python",
"xml"
] | stackoverflow_0004659613_parsing_python_xml.txt |
Q:
python regex for repeating string
I am wanting to verify and then parse this string (in quotes):
string = "start: c12354, c3456, 34526; other stuff that I don't care about"
//Note that some codes begin with 'c'
I would like to verify that the string starts with 'start:' and ends with ';'
Afterward, I would like t... | python regex for repeating string | I am wanting to verify and then parse this string (in quotes):
string = "start: c12354, c3456, 34526; other stuff that I don't care about"
//Note that some codes begin with 'c'
I would like to verify that the string starts with 'start:' and ends with ';'
Afterward, I would like to have a regex parse out the strings. I... | [
"In Python, this isn’t possible with a single regular expression: each capture of a group overrides the last capture of that same group (in .NET, this would actually be possible since the engine distinguishes between captures and groups).\nYour easiest solution is to first extract the part between start: and ; and ... | [
5,
5,
2,
0
] | [] | [] | [
"parsing",
"python",
"regex"
] | stackoverflow_0004651870_parsing_python_regex.txt |
Q:
How to upload a file, using Python Mechanize, with a twist :)
Ok I have only been using Mechanize for one day, so be nice :P
I would like complete a form including one (or two if possible) file upload style fields. The ones where you click, and it lets you browse for a file.
(I want to automate the uploading of a ... | How to upload a file, using Python Mechanize, with a twist :) | Ok I have only been using Mechanize for one day, so be nice :P
I would like complete a form including one (or two if possible) file upload style fields. The ones where you click, and it lets you browse for a file.
(I want to automate the uploading of a .torrent to a private tracker / site)
Now the two issues I have had... | [
"Community: Please fix, I'm a casual passerby who encountered this error and solved it.\nbr.form.add_file(open(filename), 'text/plain', filename, **kwargs)\n\nYou need to resolve the ambiguity by passing in an extra keyword argument to identify the specific control you want to add the file to. You can add name, id,... | [
9
] | [] | [] | [
"file_upload",
"html",
"mechanize",
"python"
] | stackoverflow_0004264694_file_upload_html_mechanize_python.txt |
Q:
python and palindromes
i recently wrote a method to cycle through /usr/share/dict/words and return a list of palindromes using my ispalindrome(x) method
here's some of the code...what's wrong with it? it just stalls for 10 minutes and then returns a list of all the words in the file
def reverse(a):
return a[:... | python and palindromes | i recently wrote a method to cycle through /usr/share/dict/words and return a list of palindromes using my ispalindrome(x) method
here's some of the code...what's wrong with it? it just stalls for 10 minutes and then returns a list of all the words in the file
def reverse(a):
return a[::-1]
def ispalindrome(a):
... | [
"wordlist = wl.readlines()\n\nWhen you do this, there is a new line character at the end, so your list is like:\n['eye\\n','bye\\n', 'cyc\\n']\n\nthe elements of which are obviously not a palindrome.\nYou need this:\n['eye','bye', 'cyc']\n\nSo strip the newline character and it should be fine.\nTo do this in one li... | [
8,
3,
3,
2,
1
] | [] | [] | [
"arrays",
"file",
"list",
"palindrome",
"python"
] | stackoverflow_0004666339_arrays_file_list_palindrome_python.txt |
Q:
Reqular expression to separate equalities
Does anyone have some good resources on learning more advanced regular expressions
I keep having problems where I want to make sure something is not enclosed in quotation marks
i.e. I am trying to make an expression that will match lines in a python file containing an equa... | Reqular expression to separate equalities | Does anyone have some good resources on learning more advanced regular expressions
I keep having problems where I want to make sure something is not enclosed in quotation marks
i.e. I am trying to make an expression that will match lines in a python file containing an equality, i.e.
a = 4
which is easy enough, but I a... | [
"Parsing code with regular expressions is generally not a good idea, as the grammar of a programming language is not a regular language. I'm not much of a python programmer, but I think you would be a lot better off parsing python code with python modules such as this one or this one\n",
"A think that you have to... | [
4,
1,
1
] | [] | [] | [
"equality",
"python",
"regex"
] | stackoverflow_0004666527_equality_python_regex.txt |
Q:
Python minidom and UTF-8 encoded XML with hash references
I am experiencing some difficulty in my home project where I need to parse a SOAP request. The SOAP is generated with gSOAP and involves string parameters with special characters like the danish letters "æøå".
gSOAP builds SOAP requests with UTF-8 encoding ... | Python minidom and UTF-8 encoded XML with hash references | I am experiencing some difficulty in my home project where I need to parse a SOAP request. The SOAP is generated with gSOAP and involves string parameters with special characters like the danish letters "æøå".
gSOAP builds SOAP requests with UTF-8 encoding by default, but instead of sending the special chatacters in ra... | [
"æble is actually æble.\nTo get the expected Unicode string u'\\xe6ble' after parsing, the string in the request should be æble.\n",
"Some more detail about my problem. The project I am creating uses wsgi. The SOAP request is extracted using environ['wsgi.input'].read(). It always seems to return... | [
1,
0,
0,
0,
0
] | [] | [] | [
"character",
"hash",
"minidom",
"python",
"reference"
] | stackoverflow_0004663250_character_hash_minidom_python_reference.txt |
Q:
How to deal with Internationalization when using mako on django ,
this is code :
{% load i18n %}
{% trans 'hello test' %}
but , this code cant be read by mako,
so how to Internationalization using mako ,
thanks
A:
I've checked the documentation and it describes that Mako uses Babel for i18n. So you can either... | How to deal with Internationalization when using mako on django , | this is code :
{% load i18n %}
{% trans 'hello test' %}
but , this code cant be read by mako,
so how to Internationalization using mako ,
thanks
| [
"I've checked the documentation and it describes that Mako uses Babel for i18n. So you can either use that, or as @Yuji suggests, use Django's i18n by calling arbitrary Python code.\nBut I think using Babel is prettier:\n# /myproj/babel.cfg\n\n# this loads all Django templates, \n# e.g. /myproj/templates/myapp/hell... | [
1
] | [] | [] | [
"django",
"internationalization",
"mako",
"python"
] | stackoverflow_0004666658_django_internationalization_mako_python.txt |
Q:
MATLAB's griddata3 for NumPy?
I realize that there is a griddata for NumPy via Matplotlib, but is there a griddata3 (same has griddata, but for higher dimensions)?
In other words, I have (x,y,z,d(x,y,z)) where (x,y,z) form an irregular grid and d(x,y,z) is a scalar function of three variables. I need to generate d... | MATLAB's griddata3 for NumPy? | I realize that there is a griddata for NumPy via Matplotlib, but is there a griddata3 (same has griddata, but for higher dimensions)?
In other words, I have (x,y,z,d(x,y,z)) where (x,y,z) form an irregular grid and d(x,y,z) is a scalar function of three variables. I need to generate d(xi, yi, zi) for a new set of (xi, ... | [
"Not sure how you intend to render a surface of a scalar function of 3 variables, except perhaps using cutplanes or something similar. Mayavi (really VTK which powers Mayavi) has support for efficient Delaunay triangulation via enthought.mayavi.mlab.pipeline.delaunay3d, which is the core of the algorithm used by gr... | [
1,
1,
0
] | [] | [] | [
"analysis",
"interpolation",
"numpy",
"python",
"scientific_computing"
] | stackoverflow_0001972877_analysis_interpolation_numpy_python_scientific_computing.txt |
Q:
Python 3.1.3 open mbox file, really slow compared to python 2.x?
I tried in python 3.1.3 to open an mbox file, with the mailbox module. There are only 3 mails in it and it is only 27k big.
But when reading the mails my CPU uses 100% for about 2-3 minutes, until it completes it task without an error.
I tried the sa... | Python 3.1.3 open mbox file, really slow compared to python 2.x? | I tried in python 3.1.3 to open an mbox file, with the mailbox module. There are only 3 mails in it and it is only 27k big.
But when reading the mails my CPU uses 100% for about 2-3 minutes, until it completes it task without an error.
I tried the same with python 2.7.1 and it takes only about 1-2 seconds?!
Did I found... | [
"Yes, it's a bug. http://bugs.python.org/issue9124\n"
] | [
3
] | [] | [] | [
"mbox",
"performance",
"python",
"python_3.x"
] | stackoverflow_0004666786_mbox_performance_python_python_3.x.txt |
Q:
How OS detects USB Hard Disk when it's Connected
How OS detects external Hard-Drive. I mean what procedure or system calls it makes to know about disk.
Is there any way to automatically determine if External HDD got connected ?
A:
(Answering the only question in your question.)
For Windows, you need to create a ... | How OS detects USB Hard Disk when it's Connected | How OS detects external Hard-Drive. I mean what procedure or system calls it makes to know about disk.
Is there any way to automatically determine if External HDD got connected ?
| [
"(Answering the only question in your question.)\nFor Windows, you need to create a window and handle the WM_DEVICECHANGE message, specifically the DBT_DEVICEARRIVAL event (which is sent automatically without having to register).\nTo do this from Python without creating a window, as far as I know the best you can d... | [
3
] | [] | [] | [
"operating_system",
"python"
] | stackoverflow_0004666276_operating_system_python.txt |
Q:
catching optional part in regular expression
I have an input text which can be either:
"URL: http://www.cnn.com Cookie: xxx; yyy"
or just:
"URL: http://www.cnn.com"
How do I capture both URL and cookie into two separate variables in Python? The part I don't know how specify is the optional cookie.
Thanks.
A:
i... | catching optional part in regular expression | I have an input text which can be either:
"URL: http://www.cnn.com Cookie: xxx; yyy"
or just:
"URL: http://www.cnn.com"
How do I capture both URL and cookie into two separate variables in Python? The part I don't know how specify is the optional cookie.
Thanks.
| [
"import re\n\ninputstring = \"URL: http://www.cnn.com Cookie: xxx; yyy\"\n\nif 'Cookie' in inputstring:\n m = re.match('URL: (.*?) Cookie: (.*)', inputstring)\n if m:\n url = m.group(1)\n cookie = m.group(2)\n print url\n print cookie\nelse:\n m = re.match('URL: (.*)', inputstri... | [
1,
1,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004667217_python_regex.txt |
Q:
using GeoIP with django on appengine
I tried geodjango recently, and worked just fine for me, even without installing that C library.
But when I used the same project in the appengine sdk, it fails whenever it tries to import the GeoIP class
then I looked into the differences, I downloaded the new appengine sdk + ... | using GeoIP with django on appengine | I tried geodjango recently, and worked just fine for me, even without installing that C library.
But when I used the same project in the appengine sdk, it fails whenever it tries to import the GeoIP class
then I looked into the differences, I downloaded the new appengine sdk + django 1.2, and the problem remains!
I tri... | [
"The GeoIP class is a wrapper around the GeoIP C API. Unfortunately, you can't use C extensions in appengine, so you can't use the GeoIP support that comes with Django.\npygeoip is a GeoIP library implemented in pure Python, you can try to integrate that.\n"
] | [
3
] | [] | [] | [
"django",
"geoip",
"google_app_engine",
"python"
] | stackoverflow_0004601684_django_geoip_google_app_engine_python.txt |
Q:
Help me write my LISP :) LISP environments, Ruby Hashes
I'm implementing a rudimentary version of LISP in Ruby just in order to familiarize myself with some concepts. I'm basing my implementation off of Peter Norvig's Lispy (http://norvig.com/lispy.html).
There's something I'm missing here though, and I'd appreci... | Help me write my LISP :) LISP environments, Ruby Hashes | I'm implementing a rudimentary version of LISP in Ruby just in order to familiarize myself with some concepts. I'm basing my implementation off of Peter Norvig's Lispy (http://norvig.com/lispy.html).
There's something I'm missing here though, and I'd appreciate some help...
He subclasses Python's dict as follows:
clas... | [
"If variable bindings in your Lisp are immutable, then copying environments is equivalent to linking them. But consider the following case:\n(define main\n (lambda ()\n (define i 0)\n (define increment-i\n (lambda ()\n (set! i (+ i 1))))\n (increment-i)\n i))\n\n(main)\n\nIf increment-i's ... | [
5,
1
] | [] | [] | [
"lisp",
"programming_languages",
"python",
"ruby",
"scheme"
] | stackoverflow_0004665416_lisp_programming_languages_python_ruby_scheme.txt |
Q:
Python / Tracing - How to stop a function's execution (return from it ) from within a tracer
Is there a way to return out of a function badfunc() using a tracer function tracer(), if we set sys.settrace(tracer). I want to count the number of lines that badfunc() executes, and return out of it if it executes more ... | Python / Tracing - How to stop a function's execution (return from it ) from within a tracer | Is there a way to return out of a function badfunc() using a tracer function tracer(), if we set sys.settrace(tracer). I want to count the number of lines that badfunc() executes, and return out of it if it executes more than a given amount of lines.
e.g:
def badfunc():
while True:
import time
time.s... | [
"Something like this maybe:\nimport sys\n\nMAX_NUMLINES = 7\ncounter = 0\n\nclass TooMuchLine(Exception):\n pass\n\ndef tracer(frame, event, arg):\n global counter\n if event == \"line\":\n counter += 1\n print \"counter\", counter\n if counter > MAX_NUMLINES:\n raise TooMu... | [
1
] | [] | [] | [
"debugging",
"python",
"trace"
] | stackoverflow_0004667490_debugging_python_trace.txt |
Q:
appengine python Set-Cookie problem
below code is working as it should in the server...while coming to localhost cookie not setting please help me to fix this..
def set_cookie(self, key, value='', max_age=None,
path='/', domain=None, secure=None, httponly=False,
version=None... | appengine python Set-Cookie problem | below code is working as it should in the server...while coming to localhost cookie not setting please help me to fix this..
def set_cookie(self, key, value='', max_age=None,
path='/', domain=None, secure=None, httponly=False,
version=None, comment=None):
"""
Set ... | [
"Try to use\nself.response.headers.add_header(\"Set-Cookie\", header_value)\n\ninstead of\nself.response.headers._headers.append(('Set-Cookie', header_value))\n\nAlso try Cookie.SimpleCookie() instead of Cookie.BaseCookie()\n"
] | [
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0004643645_google_app_engine_python.txt |
Q:
Porting a Python program to C
I would like to port a program which is using urllib and json (Python 3) to C. My question is which libraries exist to replace urllib and json in C and which are the best (easier, documented, fast)? If there are not good libraries in C I also accept C++
Thank you all.
A:
For JSON, j... | Porting a Python program to C | I would like to port a program which is using urllib and json (Python 3) to C. My question is which libraries exist to replace urllib and json in C and which are the best (easier, documented, fast)? If there are not good libraries in C I also accept C++
Thank you all.
| [
"For JSON, json.org has a list of implementations for a variety of languages, including C. Most of them should be fairly lightweight and fast.\nTo replace urllib, you probably want to look at libcURL.\n"
] | [
3
] | [] | [] | [
"c",
"c++",
"json",
"python",
"urllib2"
] | stackoverflow_0004667461_c_c++_json_python_urllib2.txt |
Q:
how to search for one of a set of strings in python
I need extracted a string from certain column of a data file and perform some algorithms on that string based on what is contained in that string.
So for example, if the string contains iPhone, iPad etc I need to run algorithm 'A' and if it contains Android, Sym... | how to search for one of a set of strings in python | I need extracted a string from certain column of a data file and perform some algorithms on that string based on what is contained in that string.
So for example, if the string contains iPhone, iPad etc I need to run algorithm 'A' and if it contains Android, Symbian etc I need to run algorithm 'B'.
I have never done p... | [
"You can do it without regexp:\ndef funcA(text):\n ...\n\ndef funcB(text):\n ...\n\nalgo = ( ('iPhone', funcA),\n ('Android', funcA),\n ('Symbian', funcA),\n ('Dell', funcB),\n ('Asus', funcB),\n ('HP', funcB) )\n\ntext = '... your text ...'\n\nfor word, func in algo:\n ... | [
4
] | [] | [] | [
"python",
"regex",
"string"
] | stackoverflow_0004667787_python_regex_string.txt |
Q:
python csv linux urllib2
I am loading the data from url to csv file, how can we load it correctly?
however, i got some python scripts to read the data but it is not loading the data,it is replacing the data within that file?
I am new to python so send me the documentation and also send me the code for getting and ... | python csv linux urllib2 | I am loading the data from url to csv file, how can we load it correctly?
however, i got some python scripts to read the data but it is not loading the data,it is replacing the data within that file?
I am new to python so send me the documentation and also send me the code for getting and loading the data from html int... | [
"No problem:\n\ncsv library docs\nurllib2 library docs\n\nFor the second part, we would need to know what the data you're downloading looks like.\n"
] | [
1
] | [] | [] | [
"csv",
"html",
"python"
] | stackoverflow_0004667904_csv_html_python.txt |
Q:
Additional fields in Django admin interface
Suppose I have some persistent model property that's not backed up by a model field, how do I allow editing this field in the admin interface?
Example setup:
# models.py
# appropriate imports...
class MyModel(Model):
# regular fields.
foo = CharField(max_leng... | Additional fields in Django admin interface | Suppose I have some persistent model property that's not backed up by a model field, how do I allow editing this field in the admin interface?
Example setup:
# models.py
# appropriate imports...
class MyModel(Model):
# regular fields.
foo = CharField(max_length=50)
bar = BooleanField()
# ...
... | [
"Ny Django knowledge isn't that great, but depending on how complicated you want it to be, I'm not sure something like this can be easily done without much hackery.\nAnyhow, if you want to add it to Add MyModel page, you can edit the appropriate admin template.\nSo in your template directory, create something like:... | [
1,
1
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0004307658_django_django_admin_python.txt |
Q:
Is it possible to use Nose to run one test multiple times, concurrently?
Is it possible to use nose to run a single test concurrently (across multiple processes) and aggregate the result in to a single pass/fail result?
We have the need to run the same test multiple times concurrently to ensure resource locking is... | Is it possible to use Nose to run one test multiple times, concurrently? | Is it possible to use nose to run a single test concurrently (across multiple processes) and aggregate the result in to a single pass/fail result?
We have the need to run the same test multiple times concurrently to ensure resource locking isn't being affected. If nose can't do this, is there a specific testing/design ... | [
"This seems like something you want in the test definition itself because you want to assert on the aggregation of the results. I would take a look at using multiprocessing in the test. Create a pool to execute your code in parallel. You can use a Queue to aggregate the results.\n",
"It is possible to run tests... | [
11,
9
] | [] | [] | [
"nose",
"python",
"unit_testing"
] | stackoverflow_0004088354_nose_python_unit_testing.txt |
Q:
wxPython GetClientSize() returning (0, 0)
I am creating a small drawing application from a python book, "wxPython in Action", and it uses self.GetClientSize() to get the size of a window. For some reason this is return (0, 0) for me instead of the expected value (800, 600).
The program crashes when wx.EmptyBitmap ... | wxPython GetClientSize() returning (0, 0) | I am creating a small drawing application from a python book, "wxPython in Action", and it uses self.GetClientSize() to get the size of a window. For some reason this is return (0, 0) for me instead of the expected value (800, 600).
The program crashes when wx.EmptyBitmap is called with 0, 0 as its parameters. If I put... | [
"I don't know if there is a better solution, but the problem is that when the object was being initialized it didn't have a parent yet, so it didn't know what size it should be. Thus it was width 0 and height 0. However, it needed to initialize the buffer. What I did to fix this was \nif size == (0, 0):\n size.w... | [
1,
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0004666768_python_wxpython.txt |
Q:
Accepting mobile short code texts (e.g. Twitter) with Django
Ive tried to look up how to accept texts from mobile phones with Django (e.g. like Twitter) to post data to user accounts. All i have ran across is how to make a mobile web app with django as in different layouts etc.. Has anyone any idea where a tutoria... | Accepting mobile short code texts (e.g. Twitter) with Django | Ive tried to look up how to accept texts from mobile phones with Django (e.g. like Twitter) to post data to user accounts. All i have ran across is how to make a mobile web app with django as in different layouts etc.. Has anyone any idea where a tutorial on this might be or how in the world to start doing this with dj... | [
"There are two ways to achieve what you want:\nHome-grown solution\nAttach a mobile phone to a PC and periodically read incoming SMS from the phone. Probably the easiest way to accomplish this is with gammu, specifically gammu-smsd-mysql. It writes incoming SMS to a MySQL database. Just make sure the phone you use ... | [
1,
0,
0
] | [] | [] | [
"django",
"mobile_phones",
"mobile_website",
"python",
"sms_gateway"
] | stackoverflow_0004662738_django_mobile_phones_mobile_website_python_sms_gateway.txt |
Q:
How to check if an object is iterable in Python?
How does one check if a Python object supports iteration, a.k.a an iterable object (see definition
Ideally I would like function similar to isiterable(p_object) returning True or False (modelled after isinstance(p_object, type)).
A:
You can check for this using is... | How to check if an object is iterable in Python? | How does one check if a Python object supports iteration, a.k.a an iterable object (see definition
Ideally I would like function similar to isiterable(p_object) returning True or False (modelled after isinstance(p_object, type)).
| [
"You can check for this using isinstance and collections.Iterable\n>>> from collections.abc import Iterable # for python >= 3.6\n>>> l = [1, 2, 3, 4]\n>>> isinstance(l, Iterable)\nTrue\n\nNote: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated since Python 3.3, and in 3.... | [
87,
10,
4
] | [] | [] | [
"iterable",
"python"
] | stackoverflow_0004668621_iterable_python.txt |
Q:
Using Python PyQT4 slots and signals in Monkey Studio
I'm writing my first GUI application using PyQT4 and the Monkey Studio ide.
I've made a dialog (mainwindow.ui) with a button that sends the signal clicked() to the MainWindow's slot slot1()
This is the MainWindow code:
from PyQt4 import uic
(Ui_MainWindow, QMa... | Using Python PyQT4 slots and signals in Monkey Studio | I'm writing my first GUI application using PyQT4 and the Monkey Studio ide.
I've made a dialog (mainwindow.ui) with a button that sends the signal clicked() to the MainWindow's slot slot1()
This is the MainWindow code:
from PyQt4 import uic
(Ui_MainWindow, QMainWindow) = uic.loadUiType('mainwindow.ui')
class MainWind... | [
"Turns out I also had to import from PyQt4.QtCore import *, which made me able to use @pyqtSlot().\nWithout the quotes, because that would throw another C++ error.\n"
] | [
2
] | [] | [] | [
"pyqt",
"pyqt4",
"python"
] | stackoverflow_0004668712_pyqt_pyqt4_python.txt |
Q:
GAE + Javascript push : multiline to push
I have this in the Google App Engine python code,
class ABC(db.Model):
StringA = db.StringProperty()
StringB = db.StringProperty(multiline=True)
abcs = ABC.all()
template_values = {'abcs': abcs,}
path = os.path.join(os.path.dirname(__file__), 'index.html')
self.respon... | GAE + Javascript push : multiline to push | I have this in the Google App Engine python code,
class ABC(db.Model):
StringA = db.StringProperty()
StringB = db.StringProperty(multiline=True)
abcs = ABC.all()
template_values = {'abcs': abcs,}
path = os.path.join(os.path.dirname(__file__), 'index.html')
self.response.out.write(template.render(path, template_val... | [
"If you are generating a Javascript expression, you need to be careful to escape the string so you always get a valid Javascript expression and you don't introduce a XSS vulnerability (in case the strings are provided by users). You can use the addslashes Django template filter to escape special chars for a Javascr... | [
1,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0004615462_google_app_engine_python.txt |
Q:
How to write a "&" in button text in wxpython
This looks simple but I have not found any documentation. Tried with &&, which does not work. Want a button like this:
Button1=wx.Button(self, 5, "abc&abc", (130, 230))
A:
Works for me with this:
import wx
class MainWindow(wx.Frame):
def __init__(self,parent,title... | How to write a "&" in button text in wxpython | This looks simple but I have not found any documentation. Tried with &&, which does not work. Want a button like this:
Button1=wx.Button(self, 5, "abc&abc", (130, 230))
| [
"Works for me with this:\nimport wx\n\nclass MainWindow(wx.Frame):\n def __init__(self,parent,title):\n wx.Frame.__init__(self,parent,title=title,size=(200,-1))\n self.sizer = wx.BoxSizer(wx.HORIZONTAL)\n self.buttons = [\n wx.Button(self,-1,\"Button &One\"),\n wx.Button(self,-1,\"Button &&Two\"... | [
5,
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0004667881_python_wxpython.txt |
Q:
What is a good solution to a bogus OSError, 13 (EACCES) using Python on Windows
Here is the code:
def make_dir(dir_name):
if os.path.exists(dir_name):
shutil.rmtree(dir_name)
try:
os.makedirs(dir_name)
except OSError, e:
print "ErrorNo: %s (%s)" % (e.errno, errno.errorcode[e.errno])
raise
IFF the direc... | What is a good solution to a bogus OSError, 13 (EACCES) using Python on Windows | Here is the code:
def make_dir(dir_name):
if os.path.exists(dir_name):
shutil.rmtree(dir_name)
try:
os.makedirs(dir_name)
except OSError, e:
print "ErrorNo: %s (%s)" % (e.errno, errno.errorcode[e.errno])
raise
IFF the directory already exists, I get the following:
ErrorNo: 13 (EACCES)
Traceback (most recent... | [
"I had the same problem, and this looks similar to my solution, except I was sleeping (0.1).\n",
"Can't you simply use an «except» statement ?\ndef make_dir(dir_name):\n retry = True\n if os.path.exists(dir_name):\n shutil.rmtree(dir_name)\n while retry:\n try:\n os.makedirs(dir_... | [
0,
0,
0
] | [] | [] | [
"directory",
"exception",
"python",
"shutil",
"windows"
] | stackoverflow_0004609572_directory_exception_python_shutil_windows.txt |
Q:
Where does the newline come from in Python?
In Python when I do
print "Line 1 is"
print "big"
The output I get is
Line 1 is
big
Where does the newline come from? And how do I type both statements in the same line using two print statements?
A:
print adds a newline by default. To avoid this, use a trailing ,:
... | Where does the newline come from in Python? | In Python when I do
print "Line 1 is"
print "big"
The output I get is
Line 1 is
big
Where does the newline come from? And how do I type both statements in the same line using two print statements?
| [
"print adds a newline by default. To avoid this, use a trailing ,:\nprint \"Line 1 is\",\nprint \"big\"\n\nThe , will still yield a space. To avoid the space as well, either concatenate your strings and use a single print statement, or use sys.stdout.write() instead.\n",
"From the documentation:\n\nA '\\n' char... | [
16,
4,
4,
2
] | [] | [] | [
"python",
"python_2.x"
] | stackoverflow_0004669260_python_python_2.x.txt |
Q:
Which version of python does IronPython 2.6.2 support?
Which version of python does IronPython 2.6.2 support?
A:
The release page for IronPython 2.6 state that it supports Python 2.6.
A:
Isn't it obvious that it's 2.6?
| Which version of python does IronPython 2.6.2 support? | Which version of python does IronPython 2.6.2 support?
| [
"The release page for IronPython 2.6 state that it supports Python 2.6.\n",
"Isn't it obvious that it's 2.6?\n"
] | [
4,
2
] | [] | [] | [
"ironpython",
"python"
] | stackoverflow_0004669630_ironpython_python.txt |
Q:
Embed variable using sys.stdout.write in Python
I can embed variables using the print statement in python in this way
i=10
print "Value is %s" % (i)
Output
Value is 10
but doing this
i=10
sys.stdout.write ("Value is %s") % (i)
gives me the following error
TypeError: unsupported operand type(s) for %: 'NoneTy... | Embed variable using sys.stdout.write in Python | I can embed variables using the print statement in python in this way
i=10
print "Value is %s" % (i)
Output
Value is 10
but doing this
i=10
sys.stdout.write ("Value is %s") % (i)
gives me the following error
TypeError: unsupported operand type(s) for %: 'NoneType' and 'int'
Can I embed variables using sys.stdo... | [
"You got the parentheses wrong. Should be\ni=10\nsys.stdout.write(\"Value is %s\" % i)\n\nThe % operator takes a string and a tuple (or a single object) as arguments. You tried to apply the operator to the return value of sys.stdout.write(), which is None. You need to apply it to the string before it is passed t... | [
16
] | [] | [] | [
"python",
"python_2.x"
] | stackoverflow_0004669791_python_python_2.x.txt |
Q:
Python kill all processes owned by user
I need to make a function that can kill all processes owned by user and later to start few.
My main problem is that I cannot figure how to check if all processes were killed, and if there are still running processes, to retry for 1-2 times to kill them, and then return error... | Python kill all processes owned by user | I need to make a function that can kill all processes owned by user and later to start few.
My main problem is that I cannot figure how to check if all processes were killed, and if there are still running processes, to retry for 1-2 times to kill them, and then return error. I want to use only python code.
Here is my ... | [
"can't you do the same thing you did to find the processes? that function should return 0..\n",
"The default way to check if a process is running, in Linux (it's POSIX compatible also), is to use kill -0 PID, so here you can simply do an os.kill but with 0 as a signal, if the process is dead it should throw an e... | [
1,
1
] | [] | [] | [
"linux",
"python"
] | stackoverflow_0004669754_linux_python.txt |
Q:
Filtering by entity key name in Google App Engine on Python
On Google App Engine to query the data store with Python, one can use GQL or Entity.all() and then filter it. So for example these are equivalent
gql = "SELECT * FROM User WHERE age >= 18"
db.GqlQuery(gql)
and
query = User.all()
query.filter("age >=", 18... | Filtering by entity key name in Google App Engine on Python | On Google App Engine to query the data store with Python, one can use GQL or Entity.all() and then filter it. So for example these are equivalent
gql = "SELECT * FROM User WHERE age >= 18"
db.GqlQuery(gql)
and
query = User.all()
query.filter("age >=", 18)
Now, it's also possible to query things by key name. I know th... | [
"from google.appengine.api.datastore import Key\nquery.filter(\"__key__ >=\", Key.from_path('User', 'abc'))\n\n",
"For me a similar way worked, while the \"from_path\" function did not worked in my case, this one did:\nfrom google.appengine.api.datastore import Key\n\nkey = Key(your_string_with_key)\nquery.filter... | [
16,
3
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0002544565_google_app_engine_google_cloud_datastore_python.txt |
Q:
How to make a QListView resize its items according to editor size
I have a qlistview whose editing is made in a qtableview, by means of a delegate. When the qtableview shows up, I'd like the qlistview to resize its row to fit all of qtableview. Here is the code:
import sys
from PyQt4 import QtGui, QtCore
class My... | How to make a QListView resize its items according to editor size | I have a qlistview whose editing is made in a qtableview, by means of a delegate. When the qtableview shows up, I'd like the qlistview to resize its row to fit all of qtableview. Here is the code:
import sys
from PyQt4 import QtGui, QtCore
class MyDelegate(QtGui.QStyledItemDelegate):
def createEditor(self, parent,... | [
"The widget you should be trying to resize is the editor, that being said\nimport sys\nfrom PyQt4 import QtGui, QtCore\n\nclass MyDelegate(QtGui.QStyledItemDelegate):\n def createEditor(self, parent, option, index):\n mtview = QtGui.QTableView(parent)\n mtview.verticalHeader().setVisible(False)\n ... | [
0
] | [] | [] | [
"pyqt",
"python",
"qlistview",
"qt"
] | stackoverflow_0004658368_pyqt_python_qlistview_qt.txt |
Q:
django-south with django-audit-log
I'm trying to do a django-south migration to an existing application to add django-audit-log to it (to track user-initiated changes of a module), but am running into significant errors. Specifically with the action_user_id field that is a LastUserField (which stores the user who... | django-south with django-audit-log | I'm trying to do a django-south migration to an existing application to add django-audit-log to it (to track user-initiated changes of a module), but am running into significant errors. Specifically with the action_user_id field that is a LastUserField (which stores the user who specified the change that is being trac... | [
"Here's finally the answer (and explanation).\nWhen migrating South not only stores the names of the fields in your models, but also the type and the arguments that are passed to it. The result of this is that South has to understand which parameters are given by the field and which should be stored.\nSo when you c... | [
8,
3
] | [] | [] | [
"django",
"django_south",
"python"
] | stackoverflow_0004475377_django_django_south_python.txt |
Q:
zipfile module giving unreliable results
I made a dictionary attack on encrypted zip files, using the zipfile library. When I started using BIG dictionaries sometimes I got false positive results, i.e. password could be "wool" and "12630" was considered correct. In that case the decrypted file contained gibberish ... | zipfile module giving unreliable results | I made a dictionary attack on encrypted zip files, using the zipfile library. When I started using BIG dictionaries sometimes I got false positive results, i.e. password could be "wool" and "12630" was considered correct. In that case the decrypted file contained gibberish obviously.
It's not a bug in my code, but in ... | [
"From this zipfile bug report\n\nThe password-checking scheme uses a one-byte check against the zip header for consistency.\nSo there is a (near) 1/256 chance of false positives, that is of bad passwords mistakenly detected as good; then the ZipFile class proceeds with unarchiving and that's where things fail (beca... | [
3
] | [] | [] | [
"python",
"python_zipfile"
] | stackoverflow_0004670831_python_python_zipfile.txt |
Q:
python script for installing boost
I used a python script to install boost (without bjam) but I cannot find it anymore. Does anybody know where it is located?
Thanks
A:
If on Windows, do a 'Find' (or download and use Agent Ransack). If on linux, grep for it. If it is on your local computer, one of these will f... | python script for installing boost | I used a python script to install boost (without bjam) but I cannot find it anymore. Does anybody know where it is located?
Thanks
| [
"If on Windows, do a 'Find' (or download and use Agent Ransack). If on linux, grep for it. If it is on your local computer, one of these will find it.\n"
] | [
0
] | [] | [] | [
"boost",
"build",
"c++",
"python"
] | stackoverflow_0004666274_boost_build_c++_python.txt |
Q:
Python string list to string
I am doing something painfuly simple, and rather than looping over the list, and += everything, I was wondering if there was a "sleezier" way to do it.
Simple concept I have something like:
some_string_array = [ "s", "t", "a", "c", "k", " ", "o", "v", "e", "r", "f", "l", "o","w" ]
som... | Python string list to string | I am doing something painfuly simple, and rather than looping over the list, and += everything, I was wondering if there was a "sleezier" way to do it.
Simple concept I have something like:
some_string_array = [ "s", "t", "a", "c", "k", " ", "o", "v", "e", "r", "f", "l", "o","w" ]
some_string = some_string_array.--sle... | [
"Just use\n\"\".join(some_string_array)\n\n",
"even more sleazier:\nreduce(lambda a,b:a+b,some_string_array)\n\nhttp://docs.python.org/library/functions.html#reduce\n"
] | [
12,
0
] | [] | [] | [
"python"
] | stackoverflow_0004671026_python.txt |
Q:
Different results for the same RSS feed fetching from different user agents
If I add a feed URL to Google Reader or to a desktop feed aggregator, I receive nice results. The URL is:
http://estaticos03.marca.com/rss/futbol_1adivision.xml
But when I fetch the same URL from a script (python script, using feedparser l... | Different results for the same RSS feed fetching from different user agents | If I add a feed URL to Google Reader or to a desktop feed aggregator, I receive nice results. The URL is:
http://estaticos03.marca.com/rss/futbol_1adivision.xml
But when I fetch the same URL from a script (python script, using feedparser library) I am getting slightly different content for the same results (the title f... | [
"AFAIK Google Reader does some \"magic\" in the content to beautify it. They strip some tags and styles to avoid breaking their interface.\nCan you provide more details on the differences?\n",
"Did you changed the user agent of your script? Try to mimic Firefox and see what happen.\n",
"All right folks, I found... | [
0,
0,
0
] | [] | [] | [
"atom_feed",
"feedparser",
"python",
"rss",
"syndication"
] | stackoverflow_0004642251_atom_feed_feedparser_python_rss_syndication.txt |
Q:
capture screenshot/frame of a video file
is there a way to capture a single frame of a video file in python?
it could also be done by command line. im using handbrakecli to convert the videos,
but i would need some screenshots of it too.
thank you
A:
You should first check out PyFFmpeg.
PyFFmpeg is a wrapper ar... | capture screenshot/frame of a video file | is there a way to capture a single frame of a video file in python?
it could also be done by command line. im using handbrakecli to convert the videos,
but i would need some screenshots of it too.
thank you
| [
"You should first check out PyFFmpeg.\n\nPyFFmpeg is a wrapper around FFmpeg's\n libavcodec, libavformat and libavutil\n libraries whose main purpose is to\n provide access to individual frames of\n video files of various formats\n (including MPEG and DIVX encoded\n videos). It also provides access to\n audi... | [
7
] | [] | [] | [
"frame",
"python",
"screenshot",
"video"
] | stackoverflow_0004671864_frame_python_screenshot_video.txt |
Q:
POSTing data to a django admin form
I'm writing a Django app whose data will be coming from different sources, including Excel spreadsheets. I've written some code to do an initial import from those sheets, but I don't like the idea to re-import the whole data each time a row is added - and my client does not want... | POSTing data to a django admin form | I'm writing a Django app whose data will be coming from different sources, including Excel spreadsheets. I've written some code to do an initial import from those sheets, but I don't like the idea to re-import the whole data each time a row is added - and my client does not want to re-type the data himself.
A possible ... | [
"If you're already writing code that is specific to your form, why not create the objects in that same function instead of trying to fake a POST request to the admin site?\nTo me, it sounds more difficult to use the default admin form than to use your existing pre-processing view to start creating or updating objec... | [
2,
1
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0004671067_django_django_admin_python.txt |
Q:
How to map coordinates in AxesImage to coordinates in saved image file?
I use matplotlib to display a matrix of numbers as an image, attach labels along the axes, and save the plot to a PNG file. For the purpose of creating an HTML image map, I need to know the pixel coordinates in the PNG file for a region in th... | How to map coordinates in AxesImage to coordinates in saved image file? | I use matplotlib to display a matrix of numbers as an image, attach labels along the axes, and save the plot to a PNG file. For the purpose of creating an HTML image map, I need to know the pixel coordinates in the PNG file for a region in the image being displayed by imshow.
I have found an example of how to do this ... | [
"This is one of the more confusing parts of trying to get exact pixel values from matplotlib. Matplotlib separates the renderer that handles exact pixel values from the canvas that the figure and axes are drawn on. \nBasically, the renderer that exists when the figure is initially created (but not yet displayed) i... | [
12,
1
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0004668432_matplotlib_python.txt |
Q:
How to test xmpp/jabber on local machine?
I just started reading Oreilly's XMPP The Definitive Guide and for the hello world, they have this script:
def main():
bot = EchoBot("echobot@wonderland.lit/HelloWorld", "mypass")
bot.run()
class EchoBot(object):
def __init__(self, jid, password):
self... | How to test xmpp/jabber on local machine? | I just started reading Oreilly's XMPP The Definitive Guide and for the hello world, they have this script:
def main():
bot = EchoBot("echobot@wonderland.lit/HelloWorld", "mypass")
bot.run()
class EchoBot(object):
def __init__(self, jid, password):
self.xmpp = sleekxmpp.ClientXMPP(jid, password)
... | [
"Yes, you probably need to install your own server if you want to test it locally. Many servers have a one-click install system that should make it easy to install on your platform.\nIt should also work with an hosted XMPP account if you have one on a platform like Google Chat (which is XMPP), or any other on platf... | [
3
] | [] | [] | [
"python",
"xmpp"
] | stackoverflow_0004672028_python_xmpp.txt |
Q:
How to remove border in wx.Notebook
How can I remove the border, that looks horrible in my program, from a wx.Notebook? I tried the style flag wx.NO_BORDER, but it doesn't work.
A:
Citing Robin Dunn from here
The border styles are a suggestion, not a commandment. It is up to each
widget and/or platform to ... | How to remove border in wx.Notebook | How can I remove the border, that looks horrible in my program, from a wx.Notebook? I tried the style flag wx.NO_BORDER, but it doesn't work.
| [
"Citing Robin Dunn from here \n\nThe border styles are a suggestion, not a commandment. It is up to each \n widget and/or platform to decide what to do with them. \n\n"
] | [
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0004665975_python_wxpython.txt |
Q:
Django - storing logical tests as records
I'm working on a Gran Turismo 5 Django application. Here's a very simplified data model:
class Event(models.Model):
name = models.CharField(max_length=256, unique=True)
class EventCriteria(models.Model):
name = models.CharField(max_length=256, unique=True)
eve... | Django - storing logical tests as records | I'm working on a Gran Turismo 5 Django application. Here's a very simplified data model:
class Event(models.Model):
name = models.CharField(max_length=256, unique=True)
class EventCriteria(models.Model):
name = models.CharField(max_length=256, unique=True)
events = models.ManyToManyField(Event)
test = ... | [
"It's not clear on why your \"test\" isn't a simple boolean field. The question is confusing.\nI'm assuming that really want a persistent filter, since that's often requested.\nA Django filter is a dictionary.\nSomeModel.objects.filter( column=value, column__contains=value )\n\nSomeModel.objects.filter( **{'column... | [
2
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0004672531_django_django_models_python.txt |
Q:
Text file to list in Python
Suppose I have a document called test1.txt that contains the following numbers:
133213
123123
349135
345345
I want to be able to take each number and append it to the end of the URL below to make a HTTP request. How do I stuff the id's into a list and call each one? This is what I have... | Text file to list in Python | Suppose I have a document called test1.txt that contains the following numbers:
133213
123123
349135
345345
I want to be able to take each number and append it to the end of the URL below to make a HTTP request. How do I stuff the id's into a list and call each one? This is what I have so far.
file = open('C:\Users\Ow... | [
">>> from urllib import urlencode\n>>> with open('C:\\Users\\Owner\\Desktop\\\\test1.txt') as myfile:\n... for line in myfile:\n... params = urlencode({'userid': line.strip()})\n... f = opener.open('http://www.test.com/?' + params)\n... # do sth\n... \n\n",
"Try this:\no = ... | [
2,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004672560_python.txt |
Q:
Problems installing PyCurl on python2.7.0+
pycurl installs fine on python2.6 but i get the following error when I try to install in on 2.7 via easy_install on maverick
$ sudo easy_install pycurl
install_dir /usr/local/lib/python2.7/dist-packages/
Searching for pycurl
Reading http://pypi.python.org/simple/pycurl/
R... | Problems installing PyCurl on python2.7.0+ | pycurl installs fine on python2.6 but i get the following error when I try to install in on 2.7 via easy_install on maverick
$ sudo easy_install pycurl
install_dir /usr/local/lib/python2.7/dist-packages/
Searching for pycurl
Reading http://pypi.python.org/simple/pycurl/
Reading http://pycurl.sourceforge.net/
Reading ht... | [
"sudo apt-get install python-dev\n\nThis installs the Python development package that is required and fixes the problem of the missing header file.\n(Please read the comment by Corey)\n"
] | [
8
] | [] | [] | [
"pycurl",
"python",
"ubuntu_10.10"
] | stackoverflow_0004672682_pycurl_python_ubuntu_10.10.txt |
Q:
Own log file for every testcase / Get name of next testcase
I would like to setup a new log file for every testcase. Something like the following:
import unittest
import logging
log = logging.getLogger()
class TestExample(unittest.TestCase):
def setUp(self):
next_testcase = ???
self.hdl = log... | Own log file for every testcase / Get name of next testcase | I would like to setup a new log file for every testcase. Something like the following:
import unittest
import logging
log = logging.getLogger()
class TestExample(unittest.TestCase):
def setUp(self):
next_testcase = ???
self.hdl = logging.FileHandler(
'testcase_%s.log' % next_testca... | [
"Tricky! :-)\nThe problem here is that you can't know which function is the next one to be called - not\nwithout interfering in the unittest code directly.\nHowever, if it where possible to change each test case into another method,\nthat would call a \"setup\" custom made for that test case, and then execute the ... | [
2,
1
] | [] | [] | [
"installation",
"logging",
"python",
"unit_testing"
] | stackoverflow_0004567583_installation_logging_python_unit_testing.txt |
Q:
Routing http to https using nginx as a reverse proxy
I have a site which has a login page that I need to use https with. I am running the site using django on apache with an nginx front-end acting as a reverse proxy doing two things:
1) serving all the django static content
2) configured to support ssl
the ssl stu... | Routing http to https using nginx as a reverse proxy | I have a site which has a login page that I need to use https with. I am running the site using django on apache with an nginx front-end acting as a reverse proxy doing two things:
1) serving all the django static content
2) configured to support ssl
the ssl stuff is all setup and seems to be working correctly....i.e. ... | [
"These redirects are better suited for configuration in your web app, not Nginx, because while you might hardcode redirects in Nginx, it's just easier to set them up in Python where it's directly related to your views.\nJust my opinion of course. \nThere are tons of SSL redirect middlewares on djangosnippets that w... | [
1,
1
] | [] | [] | [
"django",
"https",
"nginx",
"python",
"ssl"
] | stackoverflow_0004672300_django_https_nginx_python_ssl.txt |
Q:
OpenGL basics: calling glDrawElements once per object
continuing on from my explorations of the basics of OpenGL (see this question), I'm trying to figure out the basic principles of drawing a scene with OpenGL.
I am trying to render a simple cube repeated n times in every direction.
My method appears to yield ter... | OpenGL basics: calling glDrawElements once per object | continuing on from my explorations of the basics of OpenGL (see this question), I'm trying to figure out the basic principles of drawing a scene with OpenGL.
I am trying to render a simple cube repeated n times in every direction.
My method appears to yield terrible performance : 1000 cubes brings performance below 50f... | [
"Basically, as you're looping through data once per frame, you're probably starting to hit Python's performance limits. It's probable that if you rewrote your code in, say, C you'd have much better performance.\nAnyway, to increase performance in OpenGL, independently of the language, you have to limit the number o... | [
3
] | [] | [] | [
"opengl",
"pyglet",
"python"
] | stackoverflow_0004672748_opengl_pyglet_python.txt |
Q:
gae-sessions with django on gae
I'm using gae-sessions with django for writing a gae based app. From here
I've added gaesessions.DjangoSessionMiddleware to settings.py. A modification is required in
self.wrapped_wsgi_middleware = SessionMiddleware(fake_app, cookie_key='you MUST change this')
I have put the cook... | gae-sessions with django on gae | I'm using gae-sessions with django for writing a gae based app. From here
I've added gaesessions.DjangoSessionMiddleware to settings.py. A modification is required in
self.wrapped_wsgi_middleware = SessionMiddleware(fake_app, cookie_key='you MUST change this')
I have put the cookie_key but what is required in place ... | [
"It is just an anonymous function.\nI have taken a look at the gae-sessions source, and what I found for fake-app is this:\n[snip]\n\nclass DjangoSessionMiddleware(object):\n def __init__(self):\n fake_app = lambda environ, start_response : start_response\n self.wrapped_wsgi_middleware = SessionMid... | [
1,
0
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0004416756_django_google_app_engine_python.txt |
Q:
Clear threads in python?
I'm trying to set up a very simple UDP socket server with python that accepts asynchronous connections. Now I have never used Python much before but I like the language a lot from what I've read about it, which is why I am using it for this test.
I am following the example given here:
http... | Clear threads in python? | I'm trying to set up a very simple UDP socket server with python that accepts asynchronous connections. Now I have never used Python much before but I like the language a lot from what I've read about it, which is why I am using it for this test.
I am following the example given here:
http://docs.python.org/library/soc... | [
"No need for threads. Use real asynchronous IO. It scales a lot better. Threads to wait for IO just add overhead, no performance gain.\nfrom twisted.internet.protocol import DatagramProtocol\nfrom twisted.internet import reactor\n\nclass Echo(DatagramProtocol):\n\n def datagramReceived(self, data, (host, port)):... | [
6
] | [] | [] | [
"asynchronous",
"multithreading",
"python"
] | stackoverflow_0004673164_asynchronous_multithreading_python.txt |
Q:
Force delete windows directory from python
Possible Duplicate:
DirectoryInfo.Delete(True) Doesn't Delete When Folder Structure is Open in Windows Explorer
Folks, I am writing a python testing harness and part of the project involves uninstalling an application and then reinstalling it every night. Part of the u... | Force delete windows directory from python |
Possible Duplicate:
DirectoryInfo.Delete(True) Doesn't Delete When Folder Structure is Open in Windows Explorer
Folks, I am writing a python testing harness and part of the project involves uninstalling an application and then reinstalling it every night. Part of the uninstall task involves deleting the data direct... | [
"So it looks like sysinternals provides the solution.\nhandle.exe does the job.\nDo a system call (subprocess module in python for example) and search the output for the directory you are trying to delete. Get the pid and then kill the process with another system call to psKill.exe.\nI have not written the code ye... | [
1
] | [] | [] | [
"python",
"windows"
] | stackoverflow_0004672981_python_windows.txt |
Q:
Is it possible to build exe on Vista and deploy on XP using py2exe
I have created some program using python on Windows Vista. But I want to deploy it on Windows XP. Is it necessary to make new build on windows XP? Or there is possibility to make build that will work on both of these systems?
EDIT (EDIT 2 - very si... | Is it possible to build exe on Vista and deploy on XP using py2exe | I have created some program using python on Windows Vista. But I want to deploy it on Windows XP. Is it necessary to make new build on windows XP? Or there is possibility to make build that will work on both of these systems?
EDIT (EDIT 2 - very simple program does not work also):
My setup:
from distutils.core import s... | [
"Create a file named \"Microsoft.VC90.CRT.manifest\" with the following content next to the executable created by py2exe and the msvcr90.dll, msvcp90.dll, and msvcm90.dll files:\n<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\" manifestVersion=\"1.0... | [
3,
2
] | [] | [] | [
"exe",
"py2exe",
"python",
"windows_vista"
] | stackoverflow_0004635356_exe_py2exe_python_windows_vista.txt |
Q:
Python Golf: what's the most concise way of turning this list of lists into a dictionary:
I have a list of lists that looks like this:
[['Tom', 'Dick'], ['Harry', 'John', 'Mike'], ['Bob']]
and I want to turn it into a dictionary where each key is a name and each value is a number corresponding to the position of ... | Python Golf: what's the most concise way of turning this list of lists into a dictionary: | I have a list of lists that looks like this:
[['Tom', 'Dick'], ['Harry', 'John', 'Mike'], ['Bob']]
and I want to turn it into a dictionary where each key is a name and each value is a number corresponding to the position of its sublist in the list:
{'Tom': 0, 'Dick': 0, 'Harry': 1, 'John': 1, 'Mike': 1, 'Bob': 2}
I t... | [
"Same idea as MizardX, but slightly smaller and prettier in Python 3.0 using dict comprehensions:\n>>> names = [['Tom', 'Dick'], ['Harry', 'John', 'Mike'], ['Bob']]\n>>> names_dict = {name:index for index, lst in enumerate(names) for name in lst}\n>>> names_dict\n{'Tom': 0, 'Mike': 1, 'Dick': 0, 'Harry': 1, 'Bob': ... | [
19,
14,
1
] | [] | [] | [
"code_golf",
"python"
] | stackoverflow_0000534608_code_golf_python.txt |
Q:
Use Popen to execute a Powershell script in Python, how can I get the Powershell script's output and update it to web page?
I create a simple HTML with a button. When user clicks the button, it will call a Python file executed in server side. In the Python file, I use Popen to call a Powershell script, like below ... | Use Popen to execute a Powershell script in Python, how can I get the Powershell script's output and update it to web page? | I create a simple HTML with a button. When user clicks the button, it will call a Python file executed in server side. In the Python file, I use Popen to call a Powershell script, like below code:
command_line = r'"C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe" -psc "C:\Program Files\VMware\Infrastructure\v... | [
"Is it perhaps possible to use the stdout argument to subprocess.Popen?\nI mean something like:\nretcode = subprocess.Popen(args, stdout=sys.stdout)\n\n"
] | [
0
] | [] | [] | [
"powershell",
"python"
] | stackoverflow_0004668610_powershell_python.txt |
Q:
Python. Redirect stderr to log file
I have Django web-site working on tornado and nginx.
I took this tornado launcher script (tornading.py)
Then I'm using python openid that outputs some information to sys.stderr.
As a result I get IOError.
How can I redirect it using logging package?
I thought about
f = open("my... | Python. Redirect stderr to log file | I have Django web-site working on tornado and nginx.
I took this tornado launcher script (tornading.py)
Then I'm using python openid that outputs some information to sys.stderr.
As a result I get IOError.
How can I redirect it using logging package?
I thought about
f = open("myfile.log", "w")
sys.stderr = f
or
pytho... | [
"The best way would be if the openid library didn't print to stderr, but used some kind of logging API instead (e.g. the logging module). I agree with thkala that modifying third-party code is not good in the long term, so you should fix it, and then provide the fix to the openid authors.\nFor the objective of adva... | [
4,
1
] | [] | [] | [
"django",
"python",
"stderr",
"tornado"
] | stackoverflow_0004673513_django_python_stderr_tornado.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.