title stringlengths 12 150 | question_id int64 469 40.1M | question_score int64 2 5.52k | question_date stringdate 2008-08-02 15:11:16 2016-10-18 06:16:31 | answer_id int64 536 40.1M | answer_score int64 7 8.38k | answer_date stringdate 2008-08-02 18:49:07 2016-10-18 06:19:33 | tags listlengths 1 5 | question_body_md stringlengths 15 30.2k | answer_body_md stringlengths 11 27.8k |
|---|---|---|---|---|---|---|---|---|---|
Communicating with a running python daemon | 656,933 | 44 | 2009-03-18T04:09:31Z | 657,085 | 7 | 2009-03-18T05:38:27Z | [
"python",
"daemon"
] | I wrote a small Python application that runs as a daemon. It utilizes threading and queues.
I'm looking for general approaches to altering this application so that I can communicate with it while it's running. Mostly I'd like to be able to monitor its health.
In a nutshell, I'd like to be able to do something like th... | ```
# your server
from twisted.web import xmlrpc, server
from twisted.internet import reactor
class MyServer(xmlrpc.XMLRPC):
def xmlrpc_monitor(self, params):
return server_related_info
if __name__ == '__main__':
r = MyServer()
reactor.listenTCP(8080, Server.Site(r))
reactor.run()
``... |
Communicating with a running python daemon | 656,933 | 44 | 2009-03-18T04:09:31Z | 657,702 | 14 | 2009-03-18T10:26:16Z | [
"python",
"daemon"
] | I wrote a small Python application that runs as a daemon. It utilizes threading and queues.
I'm looking for general approaches to altering this application so that I can communicate with it while it's running. Mostly I'd like to be able to monitor its health.
In a nutshell, I'd like to be able to do something like th... | Use [werkzeug](http://werkzeug.pocoo.org/) and make your daemon include an HTTP-based WSGI server.
Your daemon has a collection of small WSGI apps to respond with status information.
Your client simply uses urllib2 to make POST or GET requests to localhost:somePort. Your client and server must agree on the port numbe... |
Communicating with a running python daemon | 656,933 | 44 | 2009-03-18T04:09:31Z | 658,156 | 26 | 2009-03-18T12:57:31Z | [
"python",
"daemon"
] | I wrote a small Python application that runs as a daemon. It utilizes threading and queues.
I'm looking for general approaches to altering this application so that I can communicate with it while it's running. Mostly I'd like to be able to monitor its health.
In a nutshell, I'd like to be able to do something like th... | Yet another approach: use [Pyro](https://pypi.python.org/pypi/Pyro4) (Python remoting objects).
Pyro basically allows you to publish Python object instances as services that can be called remotely. I have used Pyro for the exact purpose you describe, and I found it to work very well.
By default, a Pyro server daemon ... |
Tired of ASP.NET, which of the following should I learn and why? | 656,987 | 8 | 2009-03-18T04:41:21Z | 656,998 | 10 | 2009-03-18T04:45:55Z | [
"python",
"asp.net-mvc",
"ruby",
"groovy",
"clojure"
] | Which of the following technology is easy to learn and fun for developing a website? If you could only pick one which would it be and why
* Clojure/Compojure+Ring/Moustache+Ring
* Groovy/Grails
* Python/Django
* Ruby/Rails
* Turbogear
* Cappuccino or Sproutcore
* Javascript/jQuery | I would probably learn Ruby on Rails. It has a lot of different methodologies compared to ASP.NET, and it might open your eyes to some different and very powerful approaches to web apps. |
Tired of ASP.NET, which of the following should I learn and why? | 656,987 | 8 | 2009-03-18T04:41:21Z | 656,999 | 29 | 2009-03-18T04:46:03Z | [
"python",
"asp.net-mvc",
"ruby",
"groovy",
"clojure"
] | Which of the following technology is easy to learn and fun for developing a website? If you could only pick one which would it be and why
* Clojure/Compojure+Ring/Moustache+Ring
* Groovy/Grails
* Python/Django
* Ruby/Rails
* Turbogear
* Cappuccino or Sproutcore
* Javascript/jQuery | Have you considered turning off the computer and going outside instead?
Remember to wear pants! |
Tired of ASP.NET, which of the following should I learn and why? | 656,987 | 8 | 2009-03-18T04:41:21Z | 657,002 | 8 | 2009-03-18T04:46:58Z | [
"python",
"asp.net-mvc",
"ruby",
"groovy",
"clojure"
] | Which of the following technology is easy to learn and fun for developing a website? If you could only pick one which would it be and why
* Clojure/Compojure+Ring/Moustache+Ring
* Groovy/Grails
* Python/Django
* Ruby/Rails
* Turbogear
* Cappuccino or Sproutcore
* Javascript/jQuery | I recommend Clojure and Compojure because Clojure is awesome. Clojure is a new and modern LISP implemented on the JVM and can interact seamlessly with any Java library. It already has 3 IDE plugins in development, a book written about it, a very smart and open-minded person running the whole operation and a great newbi... |
Tired of ASP.NET, which of the following should I learn and why? | 656,987 | 8 | 2009-03-18T04:41:21Z | 657,138 | 12 | 2009-03-18T06:14:25Z | [
"python",
"asp.net-mvc",
"ruby",
"groovy",
"clojure"
] | Which of the following technology is easy to learn and fun for developing a website? If you could only pick one which would it be and why
* Clojure/Compojure+Ring/Moustache+Ring
* Groovy/Grails
* Python/Django
* Ruby/Rails
* Turbogear
* Cappuccino or Sproutcore
* Javascript/jQuery | OK, first, apparently we all need a pants check. Done?
I'm of two minds:
1. if you are looking for a practical language / platform to pick up that you hope to use to help you in your day-to-day then I'd go with Python/Django. Python has developed into a really sweat and powerful language and Django is as nice a web d... |
Tired of ASP.NET, which of the following should I learn and why? | 656,987 | 8 | 2009-03-18T04:41:21Z | 657,198 | 30 | 2009-03-18T06:51:46Z | [
"python",
"asp.net-mvc",
"ruby",
"groovy",
"clojure"
] | Which of the following technology is easy to learn and fun for developing a website? If you could only pick one which would it be and why
* Clojure/Compojure+Ring/Moustache+Ring
* Groovy/Grails
* Python/Django
* Ruby/Rails
* Turbogear
* Cappuccino or Sproutcore
* Javascript/jQuery | Have you tried ASP.NET MVC? It is actually very different to ASP.NET (vanilla), but retains your knowledge of the .NET framework. Most people wouldn't look back...
With the view based on **your** html (rather than whatever the controls decide to emit), it is also ideally placed to work alongside jQuery (it is even ins... |
Tired of ASP.NET, which of the following should I learn and why? | 656,987 | 8 | 2009-03-18T04:41:21Z | 670,680 | 8 | 2009-03-22T07:56:43Z | [
"python",
"asp.net-mvc",
"ruby",
"groovy",
"clojure"
] | Which of the following technology is easy to learn and fun for developing a website? If you could only pick one which would it be and why
* Clojure/Compojure+Ring/Moustache+Ring
* Groovy/Grails
* Python/Django
* Ruby/Rails
* Turbogear
* Cappuccino or Sproutcore
* Javascript/jQuery | Let's start by clarifying your question. Why are you "tired of ASP.NET?" Is it because of the tedious webforms model that tries so hard to protect you from the browser/server conversation that it ends up getting in the way?
Or is it because you have been trying to work with one of the tiresome 3rd party enhancement co... |
Python: Prevent fileinput from adding newline characters | 657,186 | 15 | 2009-03-18T06:44:30Z | 657,197 | 9 | 2009-03-18T06:49:34Z | [
"python",
"file-io"
] | I am using a Python script to **find and replace** certain strings in text files of a given directory. I am using the `fileinput` module to ease the find-and-replace operation, i.e., the file is read, text replaced and written back to the same file.
The code looks as follows:
```
import fileinput
def fixFile(fileName... | Use
```
print line,
```
or
```
file.write(line)
```
to fix extra newlines.
As of [Ctrl]-[M] - that is probably caused by input files in DOS encoding. |
Python: Prevent fileinput from adding newline characters | 657,186 | 15 | 2009-03-18T06:44:30Z | 657,199 | 26 | 2009-03-18T06:54:22Z | [
"python",
"file-io"
] | I am using a Python script to **find and replace** certain strings in text files of a given directory. I am using the `fileinput` module to ease the find-and-replace operation, i.e., the file is read, text replaced and written back to the same file.
The code looks as follows:
```
import fileinput
def fixFile(fileName... | Your newlines are coming from the print function
use:
```
import sys
sys.stdout.write ('some stuff')
```
and your line breaks will go away |
Python : is it ok returning both boolean and string? | 657,857 | 7 | 2009-03-18T11:26:18Z | 657,861 | 25 | 2009-03-18T11:28:22Z | [
"python"
] | Original Question
I have made a function which is waiting for a particular string to appear on a serial port, and returns all character read until the string was found, or false if not. This is quite convenient, but I was wondering if it is considered bad practice or not ?
Clarification :
The primary goal is to wait... | Would it not be more suitable to return a `None` instead of `False`? |
Python : is it ok returning both boolean and string? | 657,857 | 7 | 2009-03-18T11:26:18Z | 658,145 | 10 | 2009-03-18T12:53:35Z | [
"python"
] | Original Question
I have made a function which is waiting for a particular string to appear on a serial port, and returns all character read until the string was found, or false if not. This is quite convenient, but I was wondering if it is considered bad practice or not ?
Clarification :
The primary goal is to wait... | I believe the orthodox Python design would be to return None. The [manual](http://docs.python.org/reference/datamodel.html#the-standard-type-hierarchy) says:
> None
>
> This type has a single value. There is
> a single object with this value. This
> object is accessed through the
> built-in name None. It is used to
> ... |
How would you implement a basic event-loop? | 658,403 | 42 | 2009-03-18T14:12:02Z | 658,459 | 11 | 2009-03-18T14:23:12Z | [
"c++",
"python",
"blocking",
"event-loop"
] | If you have worked with gui toolkits, you know that there is a event-loop/main-loop that should be executed after everything is done, and that will keep the application alive and responsive to different events. For example, for Qt, you would do this in main():
```
int main() {
QApplication app(argc, argv);
// ... | Generally I would do this with some sort of [counting semaphore](http://en.wikipedia.org/wiki/Semaphore%5F%28programming%29):
1. Semaphore starts at zero.
2. Event loop waits on semaphore.
3. Event(s) come in, semaphore is incremented.
4. Event handler unblocks and decrements the semaphore and processes the event.
5. ... |
How would you implement a basic event-loop? | 658,403 | 42 | 2009-03-18T14:12:02Z | 658,495 | 53 | 2009-03-18T14:29:21Z | [
"c++",
"python",
"blocking",
"event-loop"
] | If you have worked with gui toolkits, you know that there is a event-loop/main-loop that should be executed after everything is done, and that will keep the application alive and responsive to different events. For example, for Qt, you would do this in main():
```
int main() {
QApplication app(argc, argv);
// ... | I used to wonder a lot about the same!
A GUI main loop looks like this, in pseudo-code:
```
void App::exec() {
for(;;) {
vector<Waitable> waitables;
waitables.push_back(m_networkSocket);
waitables.push_back(m_xConnection);
waitables.push_back(m_globalTimer);
Waitable* whatH... |
How would you implement a basic event-loop? | 658,403 | 42 | 2009-03-18T14:12:02Z | 659,070 | 9 | 2009-03-18T16:37:08Z | [
"c++",
"python",
"blocking",
"event-loop"
] | If you have worked with gui toolkits, you know that there is a event-loop/main-loop that should be executed after everything is done, and that will keep the application alive and responsive to different events. For example, for Qt, you would do this in main():
```
int main() {
QApplication app(argc, argv);
// ... | I would use a simple, light-weight messaging library called ZeroMQ (<http://www.zeromq.org/>). It is an open source library (LGPL). This is a very small library; on my server, the whole project compiles in about 60 seconds.
ZeroMQ will hugely simplify your event-driven code, AND it is also THE most efficient solution ... |
How would you implement a basic event-loop? | 658,403 | 42 | 2009-03-18T14:12:02Z | 660,785 | 17 | 2009-03-19T01:45:14Z | [
"c++",
"python",
"blocking",
"event-loop"
] | If you have worked with gui toolkits, you know that there is a event-loop/main-loop that should be executed after everything is done, and that will keep the application alive and responsive to different events. For example, for Qt, you would do this in main():
```
int main() {
QApplication app(argc, argv);
// ... | Python:
You can look at the implementation of the [Twisted reactor](http://docs.huihoo.com/python/twisted/howto/reactor-basics.html) which is probably the best implementation for an event loop in python. Reactors in Twisted are implementations of an interface and you can specify a type reactor to run: select, epoll, k... |
How do I suppress scientific notation in Python? | 658,763 | 44 | 2009-03-18T15:27:21Z | 658,777 | 25 | 2009-03-18T15:30:48Z | [
"python",
"floating-point"
] | Here's my code:
```
x = 1.0
y = 100000.0
print x/y
```
My quotient displays as `1.00000e-05`
Is there any way to suppress scientific notation and make it display as
`0.00001`? How to convert the scientific notation into `float`.
Thanks in advance.
This feels somewhat ridiculous to ask but I haven't figured ou... | ```
'%f' % (x/y)
```
but you need to manage precision yourself. e.g.,
```
'%f' % (1/10**8)
```
will display zeros only.
[details are in the docs](http://docs.python.org/library/stdtypes.html#string-formatting-operations)
Or for Python 3 [the equivalent old formatting](http://docs.python.org/py3k/library/stdtypes.... |
How do I suppress scientific notation in Python? | 658,763 | 44 | 2009-03-18T15:27:21Z | 5,463,788 | 24 | 2011-03-28T19:05:07Z | [
"python",
"floating-point"
] | Here's my code:
```
x = 1.0
y = 100000.0
print x/y
```
My quotient displays as `1.00000e-05`
Is there any way to suppress scientific notation and make it display as
`0.00001`? How to convert the scientific notation into `float`.
Thanks in advance.
This feels somewhat ridiculous to ask but I haven't figured ou... | With newer versions of Python (2.6 and later), you can use [`''.format()`](http://docs.python.org/library/string.html#format-string-syntax) to accomplish what @SilentGhost suggested:
```
'{0:f}'.format(x/y)
``` |
How do I suppress scientific notation in Python? | 658,763 | 44 | 2009-03-18T15:27:21Z | 33,219,633 | 15 | 2015-10-19T16:41:27Z | [
"python",
"floating-point"
] | Here's my code:
```
x = 1.0
y = 100000.0
print x/y
```
My quotient displays as `1.00000e-05`
Is there any way to suppress scientific notation and make it display as
`0.00001`? How to convert the scientific notation into `float`.
Thanks in advance.
This feels somewhat ridiculous to ask but I haven't figured ou... | Using the newer version `''.format` (also remember to specify how many digit after the `.` you wish to display, this depends on how small is the floating number). See this example:
```
>>> a = -7.1855143557448603e-17
>>> '{:f}'.format(a)
'-0.000000'
```
as shown above, default is 6 digits! This is not helpful for our... |
Linking to Python import library in Visual Studio 2005 | 658,879 | 8 | 2009-03-18T15:52:48Z | 660,181 | 9 | 2009-03-18T21:26:04Z | [
"python",
"visual-studio",
"import",
"linker"
] | I have a C++ application that has embedded Python. I'm building with Visual Studio 2005. When I try to link to python26.lib, I get a number of unresolved symbols, all of which begin with "\_\_imp":
error LNK2019: unresolved external symbol \_\_imp\_\_Py\_Initialize referenced in function \_main
python26.lib is an imp... | Looks like I was trying to link a 64-bit Python library to a 32-bit application. I wish the linker would tell me something other than "unresolved symbol." Linking to the 32-bit library fixes the problem. |
Python equivalent to "php -s" | 658,939 | 6 | 2009-03-18T16:10:57Z | 659,016 | 12 | 2009-03-18T16:26:33Z | [
"php",
"python",
"syntax-highlighting"
] | As you may or may not know, you can generate a color syntax-higlighted HTML file from a PHP source file using **php -s**.
I know about the [syntaxhighlighter](http://code.google.com/p/syntaxhighlighter/) that Stackoverflow uses and that's not really what I'm looking for. I'm looking for something will generate HTML ou... | ```
$ pygmentize -O full -O style=native -o test.html test.py
```
To install [Pygments](http://pygments.org/):
```
$ easy_install Pygments
```
You can use it as a library.
```
from pygments import highlight
from pygments.lexers import guess_lexer
from pygments.formatters import HtmlFormatter
code = '#!/usr/bin/pyt... |
Accessing Microsoft Automation Objects from Python | 659,018 | 4 | 2009-03-18T16:28:03Z | 659,286 | 13 | 2009-03-18T17:22:27Z | [
"python",
"object",
"automation"
] | I have a set of macros that I have turned into an add-in in excel. The macros allow me to interact with another program that has what are called Microsoft Automation Objects that provide some control over what the other program does. For example, I have a filter tool in the add-in that filters the list provided by the ... | You will probably need the win32com package.
This is a sample exemple I found at : <http://www.markcarter.me.uk/computing/python/excel.html> which shows how to use com with Excel. This might be a good start.
```
# this example starts Excel, creates a new workbook,
# puts some text in the first and second cell
# clos... |
Python sequence naming convention | 659,415 | 4 | 2009-03-18T17:51:50Z | 659,439 | 20 | 2009-03-18T18:00:41Z | [
"python",
"naming-conventions",
"sequence"
] | Since there is no explicit typing in python, I want to be able to make the difference between sequences and non-sequences using a naming convention. I have been programming with python for a little while now, and I still haven't found any logical/practical way to name sequences. Of course, I went through the famous [PE... | In general, avoid this kind of behaviour. Notice from [PEP8](http://www.python.org/dev/peps/pep-0008/)
> A Foolish Consistency is the Hobgoblin
> of Little Minds
which is exactly what calling a variable `weightss` would be doing. So in general have your variables describing what they are, not according to some naming... |
Python sequence naming convention | 659,415 | 4 | 2009-03-18T17:51:50Z | 659,448 | 10 | 2009-03-18T18:03:23Z | [
"python",
"naming-conventions",
"sequence"
] | Since there is no explicit typing in python, I want to be able to make the difference between sequences and non-sequences using a naming convention. I have been programming with python for a little while now, and I still haven't found any logical/practical way to name sequences. Of course, I went through the famous [PE... | > The "s" naming convention would name the variable weightss, which is ugly. I am sure there is be a better naming convention for sequences.
I think the convention you're describing is meant to be interpreted as "whenever you have list of something, make it clear that it's a list by pluralizing it". For example, if yo... |
Reversing Django URLs With Extra Options | 659,832 | 10 | 2009-03-18T19:45:58Z | 2,853,959 | 15 | 2010-05-18T00:52:50Z | [
"python",
"django"
] | Suppose I have a URLconf like below, and `'foo'` and `'bar'` are valid values for `page_slug`.
```
urlpatterns = patterns('',
(r'^page/(?P<page_slug>.*)/', 'myapp.views.someview'),
)
```
Then, I could reconstruct the URLs using the below, right?
```
>>> from django.core.urlresolvers import reverse
>>> reverse('m... | You should try naming your urlconfs. Example:
```
urlpatterns = patterns('',
url(r'^foo-direct/', 'myapp.views.someview', {'page_slug': 'foo'}, name='foo-direct'),
url(r'^my-bar-page/', 'myapp.views.someview', {'page_slug': 'bar'}, name='bar-page'),
)
```
Then just edit your reverses and you should get it wor... |
Python multiprocessing: sharing a large read-only object between processes? | 659,865 | 56 | 2009-03-18T19:58:46Z | 659,888 | 31 | 2009-03-18T20:06:08Z | [
"python",
"multiprocessing"
] | Do child processes spawned via [multiprocessing](http://docs.python.org/library/multiprocessing.html) share objects created earlier in the program?
I have the following setup:
```
do_some_processing(filename):
for line in file(filename):
if line.split(',')[0] in big_lookup_object:
# something ... | "Do child processes spawned via multiprocessing share objects created earlier in the program?"
No.
Processes have independent memory space.
**Solution 1**
To make best use of a large structure with lots of workers, do this.
1. Write each worker as a "filter" -- reads intermediate results from stdin, does work, wri... |
Python multiprocessing: sharing a large read-only object between processes? | 659,865 | 56 | 2009-03-18T19:58:46Z | 660,026 | 19 | 2009-03-18T20:45:37Z | [
"python",
"multiprocessing"
] | Do child processes spawned via [multiprocessing](http://docs.python.org/library/multiprocessing.html) share objects created earlier in the program?
I have the following setup:
```
do_some_processing(filename):
for line in file(filename):
if line.split(',')[0] in big_lookup_object:
# something ... | [S.Lott](http://stackoverflow.com/questions/659865/python-multiprocessing-sharing-a-large-read-only-object-between-processes/659888#659888) is correct. Python's multiprocessing shortcuts effectively give you a separate, duplicated chunk of memory.
On most \*nix systems, using a lower-level call to `os.fork()` will, in... |
Python multiprocessing: sharing a large read-only object between processes? | 659,865 | 56 | 2009-03-18T19:58:46Z | 660,468 | 24 | 2009-03-18T23:17:12Z | [
"python",
"multiprocessing"
] | Do child processes spawned via [multiprocessing](http://docs.python.org/library/multiprocessing.html) share objects created earlier in the program?
I have the following setup:
```
do_some_processing(filename):
for line in file(filename):
if line.split(',')[0] in big_lookup_object:
# something ... | ### Do child processes spawned via multiprocessing share objects created *earlier* in the program?
It depends. For global read-only variables it can be often considered so (apart from the memory consumed) else it should not.
[multiprocessing](http://docs.python.org/dev/library/multiprocessing.html#multiprocessing-pro... |
How to manage a CPU intensive process on a server | 660,059 | 7 | 2009-03-18T20:54:54Z | 660,068 | 7 | 2009-03-18T20:57:42Z | [
"python",
"performance",
"signal-processing"
] | I need to run a CPU- and memory-heavy Python script (analyzing and altering a lengthy WAV file) as a background process on my web server (a VPS), between HTTP requests.
The script takes up to 20 seconds to run and I am concerned about the performance on my server. Is there a good approach to either lower the priority ... | Assuming it's a UNIX server, you could use the [nice command](http://www.builderau.com.au/program/linux/print.htm?TYPE=story&AT=339286637-339028299t-320002022c) to lower its priority. That should do the trick. |
How do I list all tga files in a directory (non recursive) in Python? | 660,160 | 4 | 2009-03-18T21:21:30Z | 660,179 | 13 | 2009-03-18T21:25:51Z | [
"python"
] | How do I list all tga files in a directory (non recursive) in Python? | ```
import glob, os
for filename in glob.glob(os.path.join(yourPath, "*.tga"))
print(filename)
``` |
How do I list all tga files in a directory (non recursive) in Python? | 660,160 | 4 | 2009-03-18T21:21:30Z | 660,190 | 19 | 2009-03-18T21:27:56Z | [
"python"
] | How do I list all tga files in a directory (non recursive) in Python? | If you are doing it based on file extension, you can do something like this:
```
import os
directory = "C:/"
extension = ".tga"
list_of_files = [file for file in os.listdir(directory) if file.lower().endswith(extension)]
```
Obviously you can omit the lower() if you can garantee the case of the files. Also there is t... |
Python: decorator specific argument (unrelated to wrapped function)? | 660,727 | 6 | 2009-03-19T01:11:03Z | 660,751 | 9 | 2009-03-19T01:22:45Z | [
"python",
"decorator"
] | I'm looking to build a caching decorator that given a function caches the result of the function to a location specified in the decoration. Something like this:
```
@cacheable('/path/to/cache/file')
def my_function(a, b, c):
return 'something'
```
The argument to the decorator is completely separate from the argu... | The idea is that your decorator is a function returning a decorator.
**FIRST** Write your decorator as if you knew your argument was a global variable. Let's say something like:
-
```
def decorator(f):
def decorated(*args,**kwargs):
cache = Cache(cachepath)
if cache.iscached(*args,**kwargs):
...... |
Django-way of specifying channel image in rss feed | 660,836 | 9 | 2009-03-19T02:11:26Z | 695,464 | 8 | 2009-03-29T21:55:08Z | [
"python",
"django",
"rss"
] | What is the "django-way" of specifying channel image in rss feed? I can do it manually by rolling my own xml, but was looking for a proper way of doing it.
**Edit**
dobrych's solution is not quite applicable here because I was asking specifically about RSS not Atom feeds | Found the *right* way of doing it. As the [documentation](http://docs.djangoproject.com/en/dev/ref/contrib/syndication/?from=olddocs#custom-feed-generators) describes, I needed to create a custom feed generator by subclassing from *Rss201rev2Feed* and overriding method
```
add_root_elements()
```
like this:
```
clas... |
Overriding python threading.Thread.run() | 660,961 | 17 | 2009-03-19T03:26:56Z | 660,974 | 39 | 2009-03-19T03:35:18Z | [
"python",
"multithreading"
] | Given the documentation at <http://docs.python.org/library/threading.html> which states for Thread.run():
> You may override this method in a subclass. The standard run() method invokes the callable object passed to the objectâs constructor as the target argument, if any, with sequential and keyword arguments taken ... | You really don't need to subclass Thread. The only reason the API supports this is to make it more comfortable for people coming from Java where that's the only way to do it sanely.
The pattern that we recommend you use is to pass a method to the Thread constructor, and just call .start().
```
def myfunc(arg1, arg2)... |
Access to errno from Python? | 661,017 | 18 | 2009-03-19T04:00:33Z | 661,300 | 11 | 2009-03-19T07:19:50Z | [
"python",
"linux",
"python-2.5",
"errno"
] | I am stuck with a fairly complex Python module that does not return useful error codes (it actually fails disturbingly silently). However, the underlying C library it calls sets errno.
Normally errno comes in over OSError attributes, but since I don't have an exception, I can't get at it.
Using ctypes, libc.errno doe... | Belowed code is not reliable (or comprehensive, there are a plefora of ways `errno` could be defined) but it should get you started (or reconsider your position on a tiny extension module (after all on Debian `python setup.py install` or `easy_install` should have no problem to build it)). From <http://codespeak.net/py... |
Access to errno from Python? | 661,017 | 18 | 2009-03-19T04:00:33Z | 661,303 | 15 | 2009-03-19T07:20:16Z | [
"python",
"linux",
"python-2.5",
"errno"
] | I am stuck with a fairly complex Python module that does not return useful error codes (it actually fails disturbingly silently). However, the underlying C library it calls sets errno.
Normally errno comes in over OSError attributes, but since I don't have an exception, I can't get at it.
Using ctypes, libc.errno doe... | Here is a snippet of code that allows to access `errno`:
```
from ctypes import *
libc = CDLL("libc.so.6")
get_errno_loc = libc.__errno_location
get_errno_loc.restype = POINTER(c_int)
def errcheck(ret, func, args):
if ret == -1:
e = get_errno_loc()[0]
raise OSError(e)
return ret
copen = lib... |
Security of Python's eval() on untrusted strings? | 661,084 | 20 | 2009-03-19T04:39:50Z | 661,128 | 41 | 2009-03-19T05:13:44Z | [
"python",
"security",
"eval"
] | If I am evaluating a Python string using eval(), and have a class like:
```
class Foo(object):
a = 3
def bar(self, x): return x + a
```
What are the security risks if I do not trust the string? In particular:
1. Is `eval(string, {"f": Foo()}, {})` unsafe? That is, can you reach os or sys or something unsafe ... | `eval()` will allow malicious data to compromise your entire system, kill your cat, eat your dog and make love to your wife.
There was recently a thread about how to do this kind of thing safely on the python-dev list, and the conclusions were:
* It's really hard to do this properly.
* It requires patches to the pyth... |
Security of Python's eval() on untrusted strings? | 661,084 | 20 | 2009-03-19T04:39:50Z | 664,224 | 9 | 2009-03-19T21:55:19Z | [
"python",
"security",
"eval"
] | If I am evaluating a Python string using eval(), and have a class like:
```
class Foo(object):
a = 3
def bar(self, x): return x + a
```
What are the security risks if I do not trust the string? In particular:
1. Is `eval(string, {"f": Foo()}, {})` unsafe? That is, can you reach os or sys or something unsafe ... | You can get to `os` using builtin functions: `__import__('os')`.
For python 2.6+, the [ast module](http://docs.python.org/library/ast.html#ast-helpers) may help; in particular `ast.literal_eval`, although it depends on exactly what you want to eval. |
Security of Python's eval() on untrusted strings? | 661,084 | 20 | 2009-03-19T04:39:50Z | 10,964,364 | 11 | 2012-06-09T20:28:25Z | [
"python",
"security",
"eval"
] | If I am evaluating a Python string using eval(), and have a class like:
```
class Foo(object):
a = 3
def bar(self, x): return x + a
```
What are the security risks if I do not trust the string? In particular:
1. Is `eval(string, {"f": Foo()}, {})` unsafe? That is, can you reach os or sys or something unsafe ... | You cannot secure eval with a blacklist approach like this. See [Eval really is dangerous](http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html) for examples of input that will segfault the CPython interpreter, give access to any class you like, and so on. |
How do I know if a generator is empty from the start? | 661,603 | 57 | 2009-03-19T09:51:24Z | 661,673 | 7 | 2009-03-19T10:23:37Z | [
"python",
"generator"
] | Is there a simple way of testing if the generator has no items, like peek, hasNext, isEmpty, something along those lines? | I hate to offer a second solution, especially one that I would not use myself, but, if you absolutely *had* to do this and to not consume the generator, as in other answers:
```
def do_something_with_item(item):
print item
empty_marker = object()
try:
first_item = my_generator.next()
except StopIterati... |
How do I know if a generator is empty from the start? | 661,603 | 57 | 2009-03-19T09:51:24Z | 662,925 | 25 | 2009-03-19T16:25:12Z | [
"python",
"generator"
] | Is there a simple way of testing if the generator has no items, like peek, hasNext, isEmpty, something along those lines? | The simple answer to your question: no, there is no simple way. There are a whole lot of work-arounds.
There really shouldn't be a simple way, because of what generators are: a way to output a sequence of values *without holding the sequence in memory*. So there's no backward traversal.
You could write a has\_next fu... |
How do I know if a generator is empty from the start? | 661,603 | 57 | 2009-03-19T09:51:24Z | 664,239 | 33 | 2009-03-19T22:01:31Z | [
"python",
"generator"
] | Is there a simple way of testing if the generator has no items, like peek, hasNext, isEmpty, something along those lines? | Suggestion:
```
def peek(iterable):
try:
first = next(iterable)
except StopIteration:
return None
return first, itertools.chain([first], iterable)
```
Usage:
```
res = peek(mysequence)
if res is None:
# sequence is empty. Do stuff.
else:
first, mysequence = res
# Do something... |
How do I know if a generator is empty from the start? | 661,603 | 57 | 2009-03-19T09:51:24Z | 21,525,143 | 7 | 2014-02-03T10:41:42Z | [
"python",
"generator"
] | Is there a simple way of testing if the generator has no items, like peek, hasNext, isEmpty, something along those lines? | A simple way is to use the optional parameter for [next()](http://docs.python.org/2/library/functions.html#next) which is used if the generator is exhausted (or empty). For example:
```
iterable = some_generator()
_exhausted = object()
if next(iterable, _exhausted) == _exhausted:
print('generator is empty')
```
... |
How to Alter Photographed Document to Look "Scanned" | 662,638 | 6 | 2009-03-19T15:27:18Z | 662,694 | 8 | 2009-03-19T15:37:38Z | [
"python",
"image-processing",
"python-imaging-library",
"image-scanner"
] | How can I [do this](http://www.techcrunch.com/2009/03/17/jotnot-turns-your-iphones-camera-into-a-document-scanner/) in Python/PIL? I.e., given the four points of an offset rectangle (a photographed document), make it look flat on as if it were scanned. Is there a simple algorithm for it?
Also, are there any other mani... | Look at transform() with method set to QUAD
<http://effbot.org/imagingbook/image.htm>
> ```
> im.transform(size, QUAD, data) => image
> im.transform(size, QUAD, data, filter) => image
> ```
>
> Maps a quadrilateral (a region defined by four corners) from the image to a rectangle with the given size.
>
> Data is an 8-... |
Can I write Python web application for Windows and Linux platforms at the same time? | 662,762 | 3 | 2009-03-19T15:52:10Z | 662,789 | 7 | 2009-03-19T15:55:57Z | [
"python",
"cgi",
"fastcgi",
"wsgi"
] | Can I write web application that I can host on Windows(IIS web server) and Linux (Apache or lighttpd) without any changes?
CGI? Maybe something new? WSGI | FastCGI ? | Yes you can. But you can also use apache on windows. If you go the IIS way there's only CGI and it's pretty hard to set up. You can also use python based server like CherryPy which is pretty good and will work on all platforms with python.
Some frameworks like django support both CGI and WSGI, so you don't have to wor... |
Is there a way to substring a string in Python? | 663,171 | 990 | 2009-03-19T17:29:41Z | 663,175 | 1,557 | 2009-03-19T17:30:44Z | [
"python",
"string"
] | Is there a way to substring a string in Python, to get a new string from the 3rd character to the end of the string?
Maybe like `myString[2:end]`?
If leaving the second part means 'till the end', if you leave the first part, does it start from the start? | ```
>>> x = "Hello World!"
>>> x[2:]
'llo World!'
>>> x[:2]
'He'
>>> x[:-2]
'Hello Worl'
>>> x[-2:]
'd!'
>>> x[2:-2]
'llo Worl'
```
Python calls this concept "slicing" and it works on more than just strings. Take a look [here](http://stackoverflow.com/questions/509211/good-primer-for-python-slice-notation) for a compr... |
Is there a way to substring a string in Python? | 663,171 | 990 | 2009-03-19T17:29:41Z | 663,177 | 13 | 2009-03-19T17:30:50Z | [
"python",
"string"
] | Is there a way to substring a string in Python, to get a new string from the 3rd character to the end of the string?
Maybe like `myString[2:end]`?
If leaving the second part means 'till the end', if you leave the first part, does it start from the start? | Yes there is. Your example is very close:
```
myString[2:]
``` |
Is there a way to substring a string in Python? | 663,171 | 990 | 2009-03-19T17:29:41Z | 663,333 | 20 | 2009-03-19T18:02:38Z | [
"python",
"string"
] | Is there a way to substring a string in Python, to get a new string from the 3rd character to the end of the string?
Maybe like `myString[2:end]`?
If leaving the second part means 'till the end', if you leave the first part, does it start from the start? | One example seems to be missing here: full (shallow) copy.
```
>>> x = "Hello World!"
>>> x
'Hello World!'
>>> x[:]
'Hello World!'
>>> x==x[:]
True
>>>
```
This is a common idiom for creating a copy of sequence types (not of interned strings). `[:]` Shallow copies a list, See [python-list-slice-used-for-no-obvious-re... |
Is there a way to substring a string in Python? | 663,171 | 990 | 2009-03-19T17:29:41Z | 9,528,361 | 34 | 2012-03-02T05:19:02Z | [
"python",
"string"
] | Is there a way to substring a string in Python, to get a new string from the 3rd character to the end of the string?
Maybe like `myString[2:end]`?
If leaving the second part means 'till the end', if you leave the first part, does it start from the start? | A common way to achieve this is by String slicing. `MyString[a:b]` gives you a substring from index a to (b - 1) |
Is there a way to substring a string in Python? | 663,171 | 990 | 2009-03-19T17:29:41Z | 9,780,082 | 196 | 2012-03-20T00:58:50Z | [
"python",
"string"
] | Is there a way to substring a string in Python, to get a new string from the 3rd character to the end of the string?
Maybe like `myString[2:end]`?
If leaving the second part means 'till the end', if you leave the first part, does it start from the start? | Just for completeness as nobody else has mentioned it. The third parameter to an array slice is a step. So reversing a string is as simple as:
```
some_string[::-1]
```
Or selecting alternate characters would be:
```
"H-e-l-l-o- -W-o-r-l-d"[::2] # outputs "Hello World"
```
The ability to step forwards and backwards... |
Is there a way to substring a string in Python? | 663,171 | 990 | 2009-03-19T17:29:41Z | 11,808,384 | 49 | 2012-08-04T11:43:03Z | [
"python",
"string"
] | Is there a way to substring a string in Python, to get a new string from the 3rd character to the end of the string?
Maybe like `myString[2:end]`?
If leaving the second part means 'till the end', if you leave the first part, does it start from the start? | Substr() normally (i.e. PHP, Perl) works this way:
```
s = Substr(s, beginning, LENGTH)
```
So the parameters are beginning and LENGTH
But Python's behaviour is different, it expects beginning and one after END (!). **This is difficult to spot by beginners.** So the correct replacement for Substr(s, beginning, LENGT... |
What's the difference between dict() and {}? | 664,118 | 39 | 2009-03-19T21:19:58Z | 664,143 | 55 | 2009-03-19T21:25:14Z | [
"python",
"initialization",
"instantiation"
] | So let's say I wanna make a dictionary. We'll call it `d`. But there are multiple ways to initialize a dictionary in Python! For example, I could do this:
```
d = {'hash': 'bang', 'slash': 'dot'}
```
Or I could do this:
```
d = dict(hash='bang', slash='dot')
```
Or this, curiously:
```
d = dict({'hash': 'bang', 's... | ```
>>> def f():
... return {'a' : 1, 'b' : 2}
...
>>> def g():
... return dict(a=1, b=2)
...
>>> g()
{'a': 1, 'b': 2}
>>> f()
{'a': 1, 'b': 2}
>>> import dis
>>> dis.dis(f)
2 0 BUILD_MAP 0
3 DUP_TOP
4 LOAD_CONST 1 ('a')
... |
What's the difference between dict() and {}? | 664,118 | 39 | 2009-03-19T21:19:58Z | 664,184 | 26 | 2009-03-19T21:41:00Z | [
"python",
"initialization",
"instantiation"
] | So let's say I wanna make a dictionary. We'll call it `d`. But there are multiple ways to initialize a dictionary in Python! For example, I could do this:
```
d = {'hash': 'bang', 'slash': 'dot'}
```
Or I could do this:
```
d = dict(hash='bang', slash='dot')
```
Or this, curiously:
```
d = dict({'hash': 'bang', 's... | As far as performance goes:
```
>>> from timeit import timeit
>>> timeit("a = {'a': 1, 'b': 2}")
0.424...
>>> timeit("a = dict(a = 1, b = 2)")
0.889...
``` |
What's the difference between dict() and {}? | 664,118 | 39 | 2009-03-19T21:19:58Z | 681,358 | 20 | 2009-03-25T12:28:03Z | [
"python",
"initialization",
"instantiation"
] | So let's say I wanna make a dictionary. We'll call it `d`. But there are multiple ways to initialize a dictionary in Python! For example, I could do this:
```
d = {'hash': 'bang', 'slash': 'dot'}
```
Or I could do this:
```
d = dict(hash='bang', slash='dot')
```
Or this, curiously:
```
d = dict({'hash': 'bang', 's... | @Jacob: There is a difference in how the objects are allocated, but they are not copy-on-write. Python allocates a fixed-size "free list" where it can quickly allocate dictionary objects (until it fills). Dictionaries allocated via the `{}` syntax (or a C call to `PyDict_New`) can come from this free list. When the dic... |
Uninitialized value in Python? | 664,219 | 2 | 2009-03-19T21:53:47Z | 664,222 | 8 | 2009-03-19T21:54:54Z | [
"python"
] | What's the uninitialized value in Python, so I can compare if something is initialized, like:
```
val
if val == undefined ?
```
EDIT: added a pseudo keyword.
EDIT2: I think I didn't make it clear, but say val is already there, but nothing is assigned to it.
### Duplicate: [Just declaring a variable in Python?](htt... | Will throw a `NameError` exception:
```
>>> val
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'val' is not defined
```
You can either catch that or use `'val' in dir()`, i.e.:
```
try:
val
except NameError:
print("val not set")
```
or
```
if 'val' in dir():
pr... |
Is it possible only to declare a variable without assigning any value in Python? | 664,294 | 113 | 2009-03-19T22:21:53Z | 664,297 | 147 | 2009-03-19T22:23:05Z | [
"python",
"variable-assignment",
"variable-declaration"
] | Is it possible to declare a variable in Python, like so?:
```
var
```
so that it initialized to None? It seems like Python allows this, but as soon as you access it, it crashes. Is this possible? If not, why?
EDIT: I want to do this for cases like this:
```
value
for index in sequence:
if value == None and con... | Why not just do this:
```
var = None
```
Python is dynamic, so you don't need to declare things; they exist automatically in the first scope where they're assigned. So, all you need is a regular old assignment statement as above.
This is nice, because you'll never end up with an uninitialized variable. But be carefu... |
Is it possible only to declare a variable without assigning any value in Python? | 664,294 | 113 | 2009-03-19T22:21:53Z | 664,299 | 10 | 2009-03-19T22:24:10Z | [
"python",
"variable-assignment",
"variable-declaration"
] | Is it possible to declare a variable in Python, like so?:
```
var
```
so that it initialized to None? It seems like Python allows this, but as soon as you access it, it crashes. Is this possible? If not, why?
EDIT: I want to do this for cases like this:
```
value
for index in sequence:
if value == None and con... | I'm not sure what you're trying to do. Python is a very dynamic language; you don't usually need to declare variables until you're actually going to assign to or use them. I think what you want to do is just
```
foo = None
```
which will assign the value `None` to the variable `foo`.
EDIT: What you *really* seem to ... |
Is it possible only to declare a variable without assigning any value in Python? | 664,294 | 113 | 2009-03-19T22:21:53Z | 664,352 | 37 | 2009-03-19T22:47:39Z | [
"python",
"variable-assignment",
"variable-declaration"
] | Is it possible to declare a variable in Python, like so?:
```
var
```
so that it initialized to None? It seems like Python allows this, but as soon as you access it, it crashes. Is this possible? If not, why?
EDIT: I want to do this for cases like this:
```
value
for index in sequence:
if value == None and con... | I'd heartily recommend that you read [Other languages have "variables"](http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables) (I added it as a related link) â in two minutes you'll know that Python has "names", not "variables".
```
val = None
# ...
if val is None:
v... |
Python: defaultdict became unmarshallable object in 2.6? | 665,061 | 9 | 2009-03-20T05:12:27Z | 665,283 | 11 | 2009-03-20T07:50:49Z | [
"python"
] | Did defaultdict's become not marshal'able as of Python 2.6? The following works under 2.5, fails under 2.6 with "ValueError: unmarshallable object" on OS X 1.5.6, python-2.6.1-macosx2008-12-06.dmg from python.org:
```
from collections import defaultdict
import marshal
dd = defaultdict(list)
marshal.dump(dd, file('/tmp... | [Marshal was deliberately changed to not support subclasses of built-in types](http://svn.python.org/view?view=rev&revision=58893). Marshal was never supposed to handle defaultdicts, but happened to since they are a subclass of dict. [Marshal is **not** a general "persistence" module; only None, integers, long integers... |
Python: defaultdict became unmarshallable object in 2.6? | 665,061 | 9 | 2009-03-20T05:12:27Z | 944,344 | 7 | 2009-06-03T12:01:32Z | [
"python"
] | Did defaultdict's become not marshal'able as of Python 2.6? The following works under 2.5, fails under 2.6 with "ValueError: unmarshallable object" on OS X 1.5.6, python-2.6.1-macosx2008-12-06.dmg from python.org:
```
from collections import defaultdict
import marshal
dd = defaultdict(list)
marshal.dump(dd, file('/tmp... | wrt performance issues.. encoding a list of ~600000 dicts, each with 4 key/values, one of the values has a list (around 1-3 length) of 2 key/val dicts:
```
In [27]: timeit(cjson.encode, data)
4.93589496613
In [28]: timeit(cPickle.dumps, data, -1)
141.412974119
In [30]: timeit(marshal.dumps, data, marshal.version)
1.... |
Redirect command line results to a tkinter GUI | 665,566 | 11 | 2009-03-20T10:10:19Z | 665,598 | 9 | 2009-03-20T10:23:53Z | [
"python",
"user-interface",
"tkinter"
] | I have created a program that prints results on command line.
(It is server and it prints log on command line.)
Now, I want to see the same result to GUI .
**How can I redirect command line results to GUI?**
Please, suggest a trick to easily transform console application to simple GUI.
Note that it should work on L... | You could create a script wrapper that runs your command line program as a sub process, then add the output to something like a text widget.
```
from tkinter import *
import subprocess as sub
p = sub.Popen('./script',stdout=sub.PIPE,stderr=sub.PIPE)
output, errors = p.communicate()
root = Tk()
text = Text(root)
text.... |
Extract array from list in python | 665,652 | 4 | 2009-03-20T10:48:18Z | 665,662 | 14 | 2009-03-20T10:50:37Z | [
"python",
"arrays",
"list"
] | If I have a list like this:
`>>> data = [(1,2),(40,2),(9,80)]`
how can I extract the the two lists [1,40,9] and [2,2,80] ? Of course I can iterate and extract the numbers myself but I guess there is a better way ? | List comprehensions save the day:
```
first = [x for (x,y) in data]
second = [y for (x,y) in data]
``` |
Extract array from list in python | 665,652 | 4 | 2009-03-20T10:48:18Z | 665,684 | 26 | 2009-03-20T10:58:18Z | [
"python",
"arrays",
"list"
] | If I have a list like this:
`>>> data = [(1,2),(40,2),(9,80)]`
how can I extract the the two lists [1,40,9] and [2,2,80] ? Of course I can iterate and extract the numbers myself but I guess there is a better way ? | The unzip operation is:
```
In [1]: data = [(1,2),(40,2),(9,80)]
In [2]: zip(*data)
Out[2]: [(1, 40, 9), (2, 2, 80)]
```
Edit: You can decompose the resulting list on assignment:
```
In [3]: first_elements, second_elements = zip(*data)
```
And if you really need lists as results:
```
In [4]: first_elements, second... |
How to write a function that takes a string and prints the letters in decreasing order of frequency? | 665,942 | 4 | 2009-03-20T12:32:19Z | 665,991 | 12 | 2009-03-20T12:47:42Z | [
"python"
] | I got this far:
```
def most_frequent(string):
d = dict()
for key in string:
if key not in d:
d[key] = 1
else:
d[key] += 1
return d
print most_frequent('aabbbc')
```
Returning:
```
{'a': 2, 'c': 1, 'b': 3}
```
Now I need to:
1. reverse the pair
2. sort by number... | Here's a one line answer
```
sortedLetters = sorted(d.iteritems(), key=lambda (k,v): (v,k))
``` |
What errors/exceptions do I need to handle with urllib2.Request / urlopen? | 666,022 | 43 | 2009-03-20T12:56:21Z | 666,052 | 12 | 2009-03-20T13:06:01Z | [
"python"
] | I have the following code to do a postback to a remote URL:
```
request = urllib2.Request('http://www.example.com', postBackData, { 'User-Agent' : 'My User Agent' })
try:
response = urllib2.urlopen(request)
except urllib2.HTTPError, e:
checksLogger.error('HTTPError = ' + str(e.code))
except urllib2.URLError,... | From the [docs page](http://docs.python.org/library/urllib2.html) `urlopen` entry, it looks like you just need to catch [URLError](http://docs.python.org/library/urllib2.html#urllib2.URLError). If you really want to hedge your bets against problems within the urllib code, you can also catch `Exception` as a fall-back. ... |
What errors/exceptions do I need to handle with urllib2.Request / urlopen? | 666,022 | 43 | 2009-03-20T12:56:21Z | 666,071 | 10 | 2009-03-20T13:11:27Z | [
"python"
] | I have the following code to do a postback to a remote URL:
```
request = urllib2.Request('http://www.example.com', postBackData, { 'User-Agent' : 'My User Agent' })
try:
response = urllib2.urlopen(request)
except urllib2.HTTPError, e:
checksLogger.error('HTTPError = ' + str(e.code))
except urllib2.URLError,... | ```
$ grep "raise" /usr/lib64/python/urllib2.py
IOError); for HTTP errors, raises an HTTPError, which can also be
raise AttributeError, attr
raise ValueError, "unknown url type: %s" % self.__original
# XXX raise an exception if no one else should try to handle
raise HTTPError(req... |
What errors/exceptions do I need to handle with urllib2.Request / urlopen? | 666,022 | 43 | 2009-03-20T12:56:21Z | 666,075 | 40 | 2009-03-20T13:12:45Z | [
"python"
] | I have the following code to do a postback to a remote URL:
```
request = urllib2.Request('http://www.example.com', postBackData, { 'User-Agent' : 'My User Agent' })
try:
response = urllib2.urlopen(request)
except urllib2.HTTPError, e:
checksLogger.error('HTTPError = ' + str(e.code))
except urllib2.URLError,... | Add generic exception handler:
```
request = urllib2.Request('http://www.example.com', postBackData, { 'User-Agent' : 'My User Agent' })
try:
response = urllib2.urlopen(request)
except urllib2.HTTPError, e:
checksLogger.error('HTTPError = ' + str(e.code))
except urllib2.URLError, e:
checksLogger.error('U... |
PyObjC + Python 3.0 Questions | 666,148 | 10 | 2009-03-20T13:30:08Z | 667,584 | 9 | 2009-03-20T19:20:56Z | [
"python",
"cocoa",
"xcode",
"pyobjc"
] | By default, a Cocoa-Python application uses the default Python runtime which is version 2.5. How can I configure my Xcode project so that it would use the newer Python 3.0 runtime? I tried replacing the Python.framework included in the project with the newer version but it did not work.
And another thing, are PyObjc m... | PyObjC does not yet work with Python 3.0. According to Ronald Oussoren, a (the?) PyObjC developer, Python 3.0 support is possible, but not yet implemented:
> Support for Python 3.x is on my todo
> list but is non-trivial to achieve.
> PyObjC contains a large amount of
> pretty low-level C code, getting the
> details w... |
Decorator classes in Python | 666,216 | 29 | 2009-03-20T13:48:00Z | 666,230 | 18 | 2009-03-20T13:52:14Z | [
"python",
"decorator"
] | I want to construct classes for use as decorators with the following principles intact:
1. It should be possible to stack multiple such class decorators on top off 1 function.
2. The resulting function name pointer should be indistinguishable from the same function without a decorator, save maybe for just which type/c... | A do-nothing decorator class would look like this:
```
class NullDecl (object):
def __init__ (self, func):
self.func = func
for name in set(dir(func)) - set(dir(self)):
setattr(self, name, getattr(func, name))
def __call__ (self, *args):
return self.func (*args)
```
And then you can a... |
Decorator classes in Python | 666,216 | 29 | 2009-03-20T13:48:00Z | 666,258 | 10 | 2009-03-20T13:59:10Z | [
"python",
"decorator"
] | I want to construct classes for use as decorators with the following principles intact:
1. It should be possible to stack multiple such class decorators on top off 1 function.
2. The resulting function name pointer should be indistinguishable from the same function without a decorator, save maybe for just which type/c... | The [decorator module](http://pypi.python.org/pypi/decorator) helps you writing signature-preserving decorators.
And the [PythonDecoratorLibrary](http://wiki.python.org/moin/PythonDecoratorLibrary) might provide useful examples for decorators. |
Decorator classes in Python | 666,216 | 29 | 2009-03-20T13:48:00Z | 666,302 | 7 | 2009-03-20T14:10:41Z | [
"python",
"decorator"
] | I want to construct classes for use as decorators with the following principles intact:
1. It should be possible to stack multiple such class decorators on top off 1 function.
2. The resulting function name pointer should be indistinguishable from the same function without a decorator, save maybe for just which type/c... | To create a decorator that wraps functions in a matter that make them indistinguishable from the original function, use `functools.wraps`.
Example:
```
def mydecorator(func):
@functools.wraps(func):
def _mydecorator(*args, **kwargs):
do_something()
try:
return func(*args, **kwargs)... |
Unable to decode unicode string in Python 2.4 | 666,417 | 3 | 2009-03-20T14:36:31Z | 666,440 | 7 | 2009-03-20T14:43:51Z | [
"python",
"unicode",
"decode"
] | This is in python 2.4. Here is my situation. I pull a string from a database, and it contains an umlauted 'o' (\xf6). At this point if I run type(value) it returns str. I then attempt to run .decode('utf-8'), and I get an error ('utf8' codec can't decode bytes in position 1-4).
Really my goal here is just to successfu... | Your string **is not** in UTF8 encoding. If you want to 'decode' string to unicode, your string must be in encoding you specified by parameter. I tried this and it works perfectly:
```
print 'w\xf6rner'.decode('cp1250')
```
**EDIT**
For writing unicode strings to the file you can use codecs module:
```
import codec... |
qt design issue | 666,712 | 2 | 2009-03-20T15:43:31Z | 666,739 | 8 | 2009-03-20T15:48:42Z | [
"python",
"user-interface",
"qt"
] | i'm trying to design interface like this one
<http://www.softpedia.com/screenshots/FlashFXP_2.png>
i'm using the QT design and programming with python
well on the left it's a treeWidget
but what is on the right side ? as everytime i change the cursor on the tree
all widgets replace...
thanks :p | Use [QStackedWidget](http://doc.trolltech.com/4.5/qstackedwidget.html). You insert several widgets which correspond to the **pages**. Changing the active item in tree should switch the active widget/page inside the stacked widget. |
Crunching xml with python | 667,359 | 5 | 2009-03-20T18:22:30Z | 667,466 | 8 | 2009-03-20T18:52:01Z | [
"python",
"xml"
] | I need to remove white spaces between xml tags, e.g. if the original xml looks like:
```
<node1>
<node2>
<node3>foo</node3>
</node2>
</node1>
```
I'd like the end-result to be *crunched* down to single line:
```
<node1><node2><node3>foo</node3></node2></node1>
```
Please note that I will not have co... | This is pretty easily handled with lxml (note: this particular feature isn't in ElementTree):
```
from lxml import etree
parser = etree.XMLParser(remove_blank_text=True)
foo = """<node1>
<node2>
<node3>foo </node3>
</node2>
</node1>"""
bar = etree.XML(foo, parser)
print etree.tostring(bar,pretty_pr... |
What's a good rate limiting algorithm? | 667,508 | 93 | 2009-03-20T19:02:27Z | 667,520 | 19 | 2009-03-20T19:04:30Z | [
"python",
"algorithm",
"message-queue"
] | I could use some pseudo-code, or better, Python. I am trying to implement a rate-limiting queue for a Python IRC bot, and it partially works, but if someone triggers less messages than the limit (e.g., rate limit is 5 messages per 8 seconds, and the person triggers only 4), and the next trigger is over the 8 seconds (e... | A Token Bucket is fairly simple to implement.
Start with a bucket with 5 tokens.
Every 5/8 seconds: If the bucket has less than 5 tokens, add one.
Each time you want to send a message: If the bucket has â¥1 token, take one token out and send the message. Otherwise, wait/drop the message/whatever.
(obviously, in ac... |
What's a good rate limiting algorithm? | 667,508 | 93 | 2009-03-20T19:02:27Z | 667,706 | 34 | 2009-03-20T19:51:44Z | [
"python",
"algorithm",
"message-queue"
] | I could use some pseudo-code, or better, Python. I am trying to implement a rate-limiting queue for a Python IRC bot, and it partially works, but if someone triggers less messages than the limit (e.g., rate limit is 5 messages per 8 seconds, and the person triggers only 4), and the next trigger is over the 8 seconds (e... | Use this decorator @RateLimited(ratepersec) before your function that enqueues.
Basically, this checks if 1/rate secs have passed since the last time and if not, waits the remainder of the time, otherwise it doesn't wait. This effectively limits you to rate/sec. The decorator can be applied to any function you want ra... |
What's a good rate limiting algorithm? | 667,508 | 93 | 2009-03-20T19:02:27Z | 668,327 | 152 | 2009-03-20T23:15:27Z | [
"python",
"algorithm",
"message-queue"
] | I could use some pseudo-code, or better, Python. I am trying to implement a rate-limiting queue for a Python IRC bot, and it partially works, but if someone triggers less messages than the limit (e.g., rate limit is 5 messages per 8 seconds, and the person triggers only 4), and the next trigger is over the 8 seconds (e... | Here the [simplest algorithm](http://en.wikipedia.org/wiki/Token_bucket), if you want just to drop messages when they arrive too quickly (instead of queuing them, which makes sense because the queue might get arbitrarily large):
```
rate = 5.0; // unit: messages
per = 8.0; // unit: seconds
allowance = rate; // unit: ... |
What's a good rate limiting algorithm? | 667,508 | 93 | 2009-03-20T19:02:27Z | 6,415,181 | 8 | 2011-06-20T17:39:35Z | [
"python",
"algorithm",
"message-queue"
] | I could use some pseudo-code, or better, Python. I am trying to implement a rate-limiting queue for a Python IRC bot, and it partially works, but if someone triggers less messages than the limit (e.g., rate limit is 5 messages per 8 seconds, and the person triggers only 4), and the next trigger is over the 8 seconds (e... | to block processing until the message can be sent, thus queuing up further messages, antti's beautiful solution may also be modified like this:
```
rate = 5.0; // unit: messages
per = 8.0; // unit: seconds
allowance = rate; // unit: messages
last_check = now(); // floating-point, e.g. usec accuracy. Unit: seconds
wh... |
Full command line as it was typed | 667,540 | 13 | 2009-03-20T19:11:34Z | 667,554 | 11 | 2009-03-20T19:15:42Z | [
"python",
"command-line"
] | I want to get the full command line as it was typed.
This:
`" ".join(sys.argv[:])`
doesn't work here (deletes double quotes). Also I prefer not to rejoin something that was parsed and splited.
Any ideas?
Thank you in advance. | In a unix environment, this is not generally possible...the best you can hope for is the command line as passed to your process.
Because the shell (essentially *any* shell) may munge the typed command line in several ways before handing it to the OS to for execution. |
Full command line as it was typed | 667,540 | 13 | 2009-03-20T19:11:34Z | 667,556 | 22 | 2009-03-20T19:16:07Z | [
"python",
"command-line"
] | I want to get the full command line as it was typed.
This:
`" ".join(sys.argv[:])`
doesn't work here (deletes double quotes). Also I prefer not to rejoin something that was parsed and splited.
Any ideas?
Thank you in advance. | You're too late. By the time that the typed command gets to Python your shell has already worked its magic. For example, quotes get consumed (as you've noticed), variables get interpolated, etc. |
How to tell if a connection is dead in python | 667,640 | 27 | 2009-03-20T19:31:50Z | 667,702 | 8 | 2009-03-20T19:50:20Z | [
"python",
"sockets"
] | I want my python application to be able to tell when the socket on the other side has been dropped. Is there a method for this? | From the link Jweede posted:
> exception socket.timeout:
>
> ```
> This exception is raised when a timeout occurs on a socket
> which has had timeouts enabled via a prior call to settimeout().
> The accompanying value is a string whose value is currently
> always âtimed outâ.
> ```
Here are the demo server and cl... |
How to tell if a connection is dead in python | 667,640 | 27 | 2009-03-20T19:31:50Z | 667,710 | 17 | 2009-03-20T19:52:41Z | [
"python",
"sockets"
] | I want my python application to be able to tell when the socket on the other side has been dropped. Is there a method for this? | It depends on what you mean by "dropped". For TCP sockets, if the other end closes the connection either through
close() or the process terminating, you'll find out by reading an end of file, or getting a read error, usually the errno being set to whatever 'connection reset by peer' is by your operating system. For pyt... |
How to tell if a connection is dead in python | 667,640 | 27 | 2009-03-20T19:31:50Z | 15,175,067 | 17 | 2013-03-02T13:35:25Z | [
"python",
"sockets"
] | I want my python application to be able to tell when the socket on the other side has been dropped. Is there a method for this? | Short answer:
> use a non-blocking recv(), or a blocking recv() / select() with a very
> short timeout.
Long answer:
The way to handle socket connections is to read or write as you need to, and be prepared to handle connection errors.
TCP distinguishes between 3 forms of "dropping" a connection: timeout, reset, clo... |
Can someone explain Gtk2 packing? | 668,226 | 2 | 2009-03-20T22:24:32Z | 669,033 | 14 | 2009-03-21T09:29:09Z | [
"python",
"ruby",
"pygtk",
"packing",
"gtk2"
] | I need to use Gtk2 for a project. I will be using python/ruby for it. The problem is that packing seems kind of mystical to me. I tried using a VBox so that I could have the following widgets in my window ( in the following order ):
* menubar
* toolbar
* text view/editor control
I've managed to "guess" my way with `p... | Box packing is *really* simple, so perhaps your failure to understand it is because you imagine it is more complicated than it is.
Layout is either Vertical (like a pile of bricks) or horizontal (like a queue of people). Each element in that layout can expand or it can not expand.
Horizontal (HBox)
```
[widget][widg... |
Unicode fonts in PyGame | 668,359 | 8 | 2009-03-20T23:33:33Z | 668,596 | 7 | 2009-03-21T02:10:27Z | [
"python",
"unicode",
"pygame",
"cjk"
] | How can I display Chinese characters in PyGame? And what's a good free/libre font to use for this purpose? | pygame uses SDL\_ttf for rendering, so you should be in fine shape as rendering goes.
[unifont.org](http://www.unifont.org/fontguide/) appears to have some extensive resources on Open-Source fonts for a range of scripts.
I grabbed the Cyberbit pan-unicode font and extracted the encluded ttf. The folowing 'worked on m... |
How to create a class that doesn't re-create an object with identical input parameters | 669,932 | 2 | 2009-03-21T20:24:02Z | 669,941 | 8 | 2009-03-21T20:31:15Z | [
"python",
"multiton"
] | I am trying to create a class that doesn't re-create an object with the same input parameters. When I try to instantiate a class with the same parameters that were used to create an already-existing object, I just want my new class to return a pointer to the already-created (expensively-created) object. This is what I ... | First, use Upper Case Class Names in Python.
Second, use a **Factory** design pattern to solve this problem.
```
class MyObject( object ):
def __init__( self, args ):
pass # Something Expensive
class MyObjectFactory( object ):
def __init__( self ):
self.pool = {}
def makeMyObject( self, a... |
How to create a class that doesn't re-create an object with identical input parameters | 669,932 | 2 | 2009-03-21T20:24:02Z | 7,493,603 | 10 | 2011-09-21T01:27:16Z | [
"python",
"multiton"
] | I am trying to create a class that doesn't re-create an object with the same input parameters. When I try to instantiate a class with the same parameters that were used to create an already-existing object, I just want my new class to return a pointer to the already-created (expensively-created) object. This is what I ... | Here's a class decorator to make a class a multiton:
```
def multiton(cls):
instances = {}
def getinstance(id):
if id not in instances:
instances[id] = cls(id)
return instances[id]
return getinstance
```
(This is a slight variant of the singleton decorator from PEP 318.)
Then, to make... |
How do I develop against OAuth locally? | 670,398 | 32 | 2009-03-22T01:37:13Z | 670,608 | 16 | 2009-03-22T06:15:23Z | [
"python",
"oauth"
] | I'm building a Python application that needs to communicate with an OAuth service provider. The SP requires me to specify a callback URL. Specifying localhost obviously won't work. I'm unable to set up a public facing server. Any ideas besides paying for server/hosting? Is this even possible? | Two things:
1. The OAuth Service Provider in question is violating the OAuth spec if it's giving you an error if you don't specify a callback URL. callback\_url is [spec'd to be an OPTIONAL parameter](http://oauth.net/core/1.0/#auth%5Fstep2).
2. But, pedantry aside, you probably want to get a callback when the user's ... |
How do I develop against OAuth locally? | 670,398 | 32 | 2009-03-22T01:37:13Z | 12,107,449 | 8 | 2012-08-24T10:16:18Z | [
"python",
"oauth"
] | I'm building a Python application that needs to communicate with an OAuth service provider. The SP requires me to specify a callback URL. Specifying localhost obviously won't work. I'm unable to set up a public facing server. Any ideas besides paying for server/hosting? Is this even possible? | In case you are using \*nix style system, create a alias like `127.0.0.1 mywebsite.dev` in `/etc/hosts` (you need have the line which is similar to above mentioned in the file, Use `http://website.dev/callbackurl/for/app` in call back URL and during local testing. |
Asynchronous File Upload to Amazon S3 with Django | 670,442 | 32 | 2009-03-22T02:29:32Z | 671,255 | 23 | 2009-03-22T16:35:38Z | [
"python",
"django",
"amazon-s3"
] | I am using this file storage engine to store files to Amazon S3 when they are uploaded:
<http://code.welldev.org/django-storages/wiki/Home>
It takes quite a long time to upload because the file must first be uploaded from client to web server, and then web server to Amazon S3 before a response is returned to the clie... | I've taken another approach to this problem.
My models have 2 file fields, one uses the standard file storage backend and the other one uses the s3 file storage backend. When the user uploads a file it get's stored localy.
I have a management command in my application that uploads all the localy stored files to s3 an... |
Asynchronous File Upload to Amazon S3 with Django | 670,442 | 32 | 2009-03-22T02:29:32Z | 848,251 | 22 | 2009-05-11T14:01:49Z | [
"python",
"django",
"amazon-s3"
] | I am using this file storage engine to store files to Amazon S3 when they are uploaded:
<http://code.welldev.org/django-storages/wiki/Home>
It takes quite a long time to upload because the file must first be uploaded from client to web server, and then web server to Amazon S3 before a response is returned to the clie... | It's possible to have your users upload files directly to S3 from their browser using a special form (with an encrypted policy document in a hidden field). They will be redirected back to your application once the upload completes.
More information here: <http://developer.amazonwebservices.com/connect/entry.jspa?exter... |
Asynchronous File Upload to Amazon S3 with Django | 670,442 | 32 | 2009-03-22T02:29:32Z | 9,799,520 | 18 | 2012-03-21T06:18:09Z | [
"python",
"django",
"amazon-s3"
] | I am using this file storage engine to store files to Amazon S3 when they are uploaded:
<http://code.welldev.org/django-storages/wiki/Home>
It takes quite a long time to upload because the file must first be uploaded from client to web server, and then web server to Amazon S3 before a response is returned to the clie... | There is an app for that :-)
<https://github.com/jezdez/django-queued-storage>
It does exactly what you need - and much more, because you can set any "local" storage and any "remote" storage. This app will store your file in fast "local" storage (for example MogileFS storage) and then using [Celery](http://celeryproj... |
Line-wrapping problems with IPython shell | 670,764 | 10 | 2009-03-22T09:40:21Z | 672,755 | 9 | 2009-03-23T09:52:26Z | [
"python",
"terminal",
"ipython"
] | If I have run a long line in IPython, and try and recall it (using the up-arrow) or backspace beyond the start of the current line, it displays incorrectly (all smushed into one line)
For example, in the following session I wrote a long line `[1]`, entered a somewhat-blank line `[2]`, then up-arrowed twice to get the ... | Aha! I had an old version of the Python readline module - installing the latest from <http://ipython.scipy.org/dist/> and it works perfectly!
```
sudo easy_install http://ipython.scipy.org/dist/readline-2.5.1-py2.5-macosx-10.5-i386.egg
``` |
Django: specifying a base template by directory | 671,369 | 10 | 2009-03-22T17:59:50Z | 671,378 | 17 | 2009-03-22T18:07:15Z | [
"python",
"django",
"django-templates"
] | I'm working on a Django site that has multiple sections and subsections. I'd like to have several depths of template inheritance: a base template for the whole site, one base template for each section that inherits from the root base template, and so on. Here's a simplified version of my desired directory structure:
`... | May be I oversee something, but all you want can be accomplished with the django template system. All extends calls are relative to template directories.
1. In order for all base.html files in subdirectories to extend base.html, you just have to put a `{% extends "base.html" %}` into the files. section1/base.html woul... |
Memory efficiency: One large dictionary or a dictionary of smaller dictionaries? | 671,403 | 25 | 2009-03-22T18:27:48Z | 671,463 | 13 | 2009-03-22T19:12:25Z | [
"python",
"memory",
"dictionary",
"performance"
] | I'm writing an application in Python (2.6) that requires me to use a dictionary as a data store.
I am curious as to whether or not it is more memory efficient to have one large dictionary, or to break that down into many (much) smaller dictionaries, then have an "index" dictionary that contains a reference to all the ... | If you're using Python, you really shouldn't be worrying about this sort of thing in the first place. Just build your data structure the way it best suits *your* needs, not the computer's.
This smacks of premature optimization, not performance improvement. Profile your code if something is actually bottlenecking, but ... |
Memory efficiency: One large dictionary or a dictionary of smaller dictionaries? | 671,403 | 25 | 2009-03-22T18:27:48Z | 671,522 | 59 | 2009-03-22T19:43:19Z | [
"python",
"memory",
"dictionary",
"performance"
] | I'm writing an application in Python (2.6) that requires me to use a dictionary as a data store.
I am curious as to whether or not it is more memory efficient to have one large dictionary, or to break that down into many (much) smaller dictionaries, then have an "index" dictionary that contains a reference to all the ... | Three suggestions:
1. **Use one dictionary.**
It's easier, it's more straightforward, and someone else has already optimized this problem for you. Until you've actually measured your code and traced a performance problem to this part of it, you have no reason not to do the simple, straightforward thing.
2. **Opti... |
How to do "performance-based" (benchmark) unit testing in Python | 671,503 | 7 | 2009-03-22T19:36:55Z | 671,517 | 7 | 2009-03-22T19:40:24Z | [
"python",
"linux",
"unit-testing",
"benchmarking"
] | Let's say that I've got my code base to as high a degree of unit test coverage as makes sense. (Beyond a certain point, increasing coverage doesn't have a good ROI.)
Next I want to test performance. To benchmark code to make sure that new commits aren't slowing things down needlessly. I was very intrigued by Safari's ... | You will want to do performance testing at a system level if possible - test your application as a whole, in context, with data and behaviour as close to production use as possible.
This is not easy, and it will be even harder to automate it and get consistent results.
Moreover, you can't use a VM for performance tes... |
CL-WHO-like HTML templating for other languages? | 671,572 | 10 | 2009-03-22T20:31:07Z | 672,665 | 11 | 2009-03-23T09:21:02Z | [
"python",
"html",
"perl",
"common-lisp",
"templating"
] | Common Lisp guys have their [CL-WHO](http://www.weitz.de/cl-who/), which makes HTML templating integrated with the "main" language thus making the task easier. For those who don't know CL-WHO, it looks like this (example from CL-WHO's webpage):
```
(with-html-output (*http-stream*)
(:table :border 0 :cellpadding 4
(... | For [CPAN](http://search.cpan.org) offerings have a look at the following (in alphabetical order)...
* [Builder](http://search.cpan.org/dist/Builder/)
* [HTML::AsSubs](http://search.cpan.org/dist/HTML-Tree/lib/HTML/AsSubs.pm)
* [HTML::Tiny](http://search.cpan.org/dist/HTML-Tiny/)
* [Markapl](http://search.cpan.org/dis... |
Using python map and other functional tools | 672,172 | 119 | 2009-03-23T03:46:29Z | 672,197 | 30 | 2009-03-23T04:00:28Z | [
"python",
"dictionary",
"functional-programming"
] | This is quite n00bish, but I'm trying to learn/understand functional programming in python. The following code:
```
foos = [1.0,2.0,3.0,4.0,5.0]
bars = [1,2,3]
def maptest(foo, bar):
print foo, bar
map(maptest, foos, bars)
```
produces:
```
1.0 1
2.0 2
3.0 3
4.0 None
5.0 None
```
**Q. Is there a way to use ma... | Here's the solution you're looking for:
```
>>> foos = [1.0, 2.0, 3.0, 4.0, 5.0]
>>> bars = [1, 2, 3]
>>> [(x, bars) for x in foos]
[(1.0, [1, 2, 3]), (2.0, [1, 2, 3]), (3.0, [1, 2, 3]), (4.0, [1, 2, 3]), (5.0, [
1, 2, 3])]
```
I'd recommend using a list comprehension (the `[(x, bars) for x in foos]` part) over using... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.