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 |
|---|---|---|---|---|---|---|---|---|---|
Equivalent of Bash Backticks in Python | 1,410,976 | 67 | 2009-09-11T13:47:53Z | 7,469,168 | 13 | 2011-09-19T09:58:22Z | [
"python",
"backticks"
] | What is the equivalent of the backticks found in Ruby and Perl in Python? That is, in Ruby I can do this:
```
foo = `cat /tmp/baz`
```
What does the equivalent statement look like in Python? I've tried `os.system("cat /tmp/baz")` but that puts the result to standard out and returns to me the error code of that operat... | ```
foo = subprocess.check_output(["cat", "/tmp/baz"])
``` |
Twisted - listen to multiple ports for multiple processes with one reactor | 1,411,281 | 3 | 2009-09-11T14:35:53Z | 1,417,980 | 9 | 2009-09-13T15:21:31Z | [
"python",
"process",
"twisted"
] | i need to run multiple instances of my server app each on it's own port. It's not a problem if i start these with os.system or subprocess.Popen, but i'd like to have some process communication with multiprocessing.
I'd like to somehow dynamically set up listening to different port from different processes. Just callin... | I am not sure what error you are getting.
The following is an example from [twisted site](http://twistedmatrix.com/projects/core/documentation/howto/servers.html) (modified)
And as you can see, it listen on two ports, and can listen to many more.
```
from twisted.internet.protocol import Protocol, Factory
from twisted... |
How do I stop getting ImportError: Could not import settings 'mofin.settings' when using django with wsgi? | 1,411,417 | 62 | 2009-09-11T14:58:37Z | 1,438,381 | 8 | 2009-09-17T11:51:54Z | [
"python",
"django",
"apache",
"wsgi"
] | I can't get wsgi to import my settings file for my project 'mofin'.
The list of errors from the apache error log are as follows
```
mod_wsgi (pid=4001): Exception occurred within WSGI script '/var/www/wsgi-scripts/django.wsgi'.
Traceback (most recent call last):
File "/usr/lib/python2.5/site-packages/django/core/ha... | I found the answer... file permissions. /home/django was set to 700. i.e. only django can view the contents. apache runs as Apache and so can't get past /home/django. |
How do I stop getting ImportError: Could not import settings 'mofin.settings' when using django with wsgi? | 1,411,417 | 62 | 2009-09-11T14:58:37Z | 4,181,080 | 21 | 2010-11-15T02:59:13Z | [
"python",
"django",
"apache",
"wsgi"
] | I can't get wsgi to import my settings file for my project 'mofin'.
The list of errors from the apache error log are as follows
```
mod_wsgi (pid=4001): Exception occurred within WSGI script '/var/www/wsgi-scripts/django.wsgi'.
Traceback (most recent call last):
File "/usr/lib/python2.5/site-packages/django/core/ha... | I had a similar permissions problem, and although my settings.py had the right permissions, the .pyc's did not!!! So watch out for this. |
How do I stop getting ImportError: Could not import settings 'mofin.settings' when using django with wsgi? | 1,411,417 | 62 | 2009-09-11T14:58:37Z | 4,750,766 | 18 | 2011-01-20T18:04:09Z | [
"python",
"django",
"apache",
"wsgi"
] | I can't get wsgi to import my settings file for my project 'mofin'.
The list of errors from the apache error log are as follows
```
mod_wsgi (pid=4001): Exception occurred within WSGI script '/var/www/wsgi-scripts/django.wsgi'.
Traceback (most recent call last):
File "/usr/lib/python2.5/site-packages/django/core/ha... | Hey, just adding an additional answer to this problem. I had the exact same issue, but it wasn't file permissions. I was appending "path/to/project", but not also appending "path/to". Linked is mod\_wsgi's [Django integration explanation](http://code.google.com/p/modwsgi/wiki/IntegrationWithDjango) that showed me the a... |
How do I stop getting ImportError: Could not import settings 'mofin.settings' when using django with wsgi? | 1,411,417 | 62 | 2009-09-11T14:58:37Z | 6,949,892 | 46 | 2011-08-04T23:40:02Z | [
"python",
"django",
"apache",
"wsgi"
] | I can't get wsgi to import my settings file for my project 'mofin'.
The list of errors from the apache error log are as follows
```
mod_wsgi (pid=4001): Exception occurred within WSGI script '/var/www/wsgi-scripts/django.wsgi'.
Traceback (most recent call last):
File "/usr/lib/python2.5/site-packages/django/core/ha... | This can also happen if you have an application (subdirectory to the project with an init file in it) named the same thing as the project. Your settings.py file may be in your project folder, but it seems that a part of the django system looks first for a module inside the project by the same name as the project and wh... |
How do I stop getting ImportError: Could not import settings 'mofin.settings' when using django with wsgi? | 1,411,417 | 62 | 2009-09-11T14:58:37Z | 7,347,016 | 7 | 2011-09-08T11:02:35Z | [
"python",
"django",
"apache",
"wsgi"
] | I can't get wsgi to import my settings file for my project 'mofin'.
The list of errors from the apache error log are as follows
```
mod_wsgi (pid=4001): Exception occurred within WSGI script '/var/www/wsgi-scripts/django.wsgi'.
Traceback (most recent call last):
File "/usr/lib/python2.5/site-packages/django/core/ha... | I think you need to have a trailing forward slash on that its what I have to do in my wsgi script in apache before I load up django.
```
import os
import sys
sys.path.append('/home/django/mofin/trunk/')
sys.path.append('/home/django/mofin/trunk/mofin/')
print >> sys.stderr, sys.path
os.environ['DJANGO_SETTINGS_MODULE'... |
Help with basic Python function | 1,411,553 | 4 | 2009-09-11T15:15:28Z | 1,411,569 | 9 | 2009-09-11T15:17:30Z | [
"python"
] | I have a function to connect to a database. This code works:
```
def connect():
return MySQLdb.connect("example.com", "username", "password", "database")
```
But this doesn't:
```
def connect():
host = "example.com"
user = "username"
pass = "password"
base = "database"
return MySQLdb.connect(... | `pass` is a reserved keyword.
Pick different variable names and your code should work fine.
Maybe something like:
```
def connect():
_host = "example.com"
_user = "username"
_pass = "password"
_base = "database"
return MySQLdb.connect(_host, _user, _pass, _base)
``` |
How to get '\x01' to 1 | 1,411,658 | 4 | 2009-09-11T15:34:02Z | 1,411,678 | 13 | 2009-09-11T15:37:28Z | [
"python"
] | I am getting this:
```
_format_ = "7c7sc"
print struct.unpack(self._format_, data)
```
gives
```
('\x7f', 'E', 'L', 'F', '\x01', '\x01', '\x01', '\x00\x00\x00\x00\x00\x00\x00', '\x00')
```
I want to take `'\x01'` and get 1 from it, i.e., convert to ``int. Any ideas?
Thanks | `ord("\x01")` will return 1. |
What difference it makes when I set python thread as a Deamon | 1,411,860 | 7 | 2009-09-11T16:08:29Z | 1,412,230 | 14 | 2009-09-11T17:20:46Z | [
"python",
"multithreading",
"daemon"
] | What difference it makes when I set python thread as a Deamon, using thread.setDaemon(True) ? | A daemon thread will not prevent the application from exiting. The program ends when all non-daemon threads (main thread included) are complete.
So generally, if you're doing something in the background, you might want to set the thread as daemon so you don't have to explicitly have that thread's function return befor... |
Python CGI returning an http status code, such as 403? | 1,411,867 | 14 | 2009-09-11T16:09:29Z | 1,411,969 | 16 | 2009-09-11T16:27:50Z | [
"python",
"http",
"cgi",
"http-status-codes"
] | How can my python cgi return a specific http status code, such as 403 or 418?
I tried the obvious (print "Status:403 Forbidden") but it doesn't work. | ```
print 'Status: 403 Forbidden'
print
```
Works for me. You do need the second print though, as you need a double-newline to end the HTTP response headers. Otherwise your web server may complain you aren't sending it a complete set of headers.
```
sys.stdout('Status: 403 Forbidden\r\n\r\n')
```
may be technically ... |
Reading XML using Python minidom and iterating over each node | 1,412,004 | 21 | 2009-09-11T16:34:26Z | 1,412,170 | 21 | 2009-09-11T17:10:00Z | [
"python",
"xml",
"parsing",
"minidom"
] | I have an XML structure that looks like the following, but on a much larger scale:
```
<root>
<conference name='1'>
<author>
Bob
</author>
<author>
Nigel
</author>
</conference>
<conference name='2'>
<author>
Alice
</author... | your `authortext` is of type 1 (`ELEMENT_NODE`), normally you need to have `TEXT_NODE` to get a string. This will work
```
a.childNodes[0].nodeValue
``` |
Twisted(asynch server) vs Django(or any other framework) | 1,412,169 | 13 | 2009-09-11T17:09:48Z | 1,412,226 | 14 | 2009-09-11T17:20:23Z | [
"python",
"django",
"asynchronous",
"twisted",
"real-time"
] | I need help understanding what the advantage of using an asynch framework is. Suppose I want to develop a simple chat web app. Why cant I write python code in the Django framework that does long polling where I dont send a response back the server until someone enters a new msg. What does Twisted provide that gives it ... | Asynchronous servers support much larger numbers of simultaneous client connections. More conventional servers come up against thread and process limits when servicing large number of concurrent clients, particularly those with long-lived connections. Async servers can also provide better performance as they avoid the ... |
Twisted(asynch server) vs Django(or any other framework) | 1,412,169 | 13 | 2009-09-11T17:09:48Z | 1,412,372 | 18 | 2009-09-11T17:50:55Z | [
"python",
"django",
"asynchronous",
"twisted",
"real-time"
] | I need help understanding what the advantage of using an asynch framework is. Suppose I want to develop a simple chat web app. Why cant I write python code in the Django framework that does long polling where I dont send a response back the server until someone enters a new msg. What does Twisted provide that gives it ... | First off Django is a framework for writing web apps so it provides ORM, html templating, it requires running an http server etc. Twisted helps to write much lower level code than that. You could use twisted to write the http server Django runs on. If you use Django you are limited to http model, with twisted it could ... |
Python Triple Quote / Multi-line indentation | 1,412,374 | 20 | 2009-09-11T17:51:05Z | 1,412,480 | 13 | 2009-09-11T18:12:23Z | [
"python",
"quotes",
"multiline"
] | I have a python editor where the user is entering a script or code, which is then put into a main method behind the scenes, while also having every line indented. The problem is that if a user has a multi line string, the indentation made to the whole script affects the string, by inserting a tab in every space. A prob... | What follows the first line of a multiline string is part of the string, and not treated as indentation by the parser. you may freely write:
```
def main():
"""foo
bar
foo2"""
pass
```
and it will do the right thing.
On the other hand, that's not readable, and python knows it. So if a docstring contains whit... |
Python Triple Quote / Multi-line indentation | 1,412,374 | 20 | 2009-09-11T17:51:05Z | 1,412,728 | 49 | 2009-09-11T19:02:18Z | [
"python",
"quotes",
"multiline"
] | I have a python editor where the user is entering a script or code, which is then put into a main method behind the scenes, while also having every line indented. The problem is that if a user has a multi line string, the indentation made to the whole script affects the string, by inserting a tab in every space. A prob... | [textwrap.dedent](http://docs.python.org/library/textwrap.html#textwrap.dedent) from the standard library is there to automatically undo the wacky indentation. |
How do I programmatically check whether a GIF image is animated? | 1,412,529 | 8 | 2009-09-11T18:21:18Z | 1,413,234 | 11 | 2009-09-11T20:56:52Z | [
"php",
"python",
"image"
] | Here is a link to [another question](http://stackoverflow.com/questions/1401527/how-do-i-programmatically-check-whether-an-image-png-jpeg-or-gif-is-corrupted) I asked concerning the same project I am working on. I think that bit of background will be helpful.
For those that are too lazy to open a new tab to that quest... | If you're on Linux (or any system with [ImageMagick](http://www.imagemagick.org/)) you can use a one-liner shell script and `identify` program:
```
identify *.gif | fgrep '.gif[1] '
```
I know you said you prefer PHP and Python, but you also said you are willing to explore other solutions. :) |
How do I programmatically check whether a GIF image is animated? | 1,412,529 | 8 | 2009-09-11T18:21:18Z | 1,413,365 | 13 | 2009-09-11T21:26:07Z | [
"php",
"python",
"image"
] | Here is a link to [another question](http://stackoverflow.com/questions/1401527/how-do-i-programmatically-check-whether-an-image-png-jpeg-or-gif-is-corrupted) I asked concerning the same project I am working on. I think that bit of background will be helpful.
For those that are too lazy to open a new tab to that quest... | With Python and [PIL](http://www.pythonware.com/products/pil/):
```
from PIL import Image
gif = Image.open('path.gif')
try:
gif.seek(1)
except EOFError:
isanimated = False
else:
isanimated = True
``` |
PicklingError: Can't pickle <class 'decimal.Decimal'>: it's not the same object as decimal.Decimal | 1,412,787 | 6 | 2009-09-11T19:13:23Z | 1,413,299 | 8 | 2009-09-11T21:12:22Z | [
"python",
"django",
"pickle"
] | This is the error I got today at filmaster.com:
> PicklingError: Can't pickle : it's not the same
> object as decimal.Decimal
What does that exactly mean? It does not seem to be making a lot of sense...
It seems to be connected with django caching. You can see the whole traceback here:
> Traceback (most recent call ... | One oddity of Pickle is that the way you import a class before you pickle one of it's instances can subtly change the pickled object. Pickle requires you to have imported the object identically both before you pickle it and before you unpickle it.
So for example:
```
from a.b import c
C = c()
pickler.dump(C)
```
wil... |
Showing an image from console in Python | 1,413,540 | 13 | 2009-09-11T22:22:50Z | 1,413,567 | 22 | 2009-09-11T22:34:22Z | [
"python",
"image"
] | What is the easiest way to show a `.jpg` or `.gif` image from Python console?
I've got a Python console program that is checking a data set which contains links to images stored locally. How should I write the script so that it would display images pop-up graphical windows? | Using the awesome [Pillow](https://pypi.python.org/pypi/Pillow/2.7.0) library:
```
>>> from PIL import Image
>>> img = Image.open('test.png')
>>> img.show()
```
This will open the image in your default image viewer. |
Showing an image from console in Python | 1,413,540 | 13 | 2009-09-11T22:22:50Z | 1,413,575 | 7 | 2009-09-11T22:36:26Z | [
"python",
"image"
] | What is the easiest way to show a `.jpg` or `.gif` image from Python console?
I've got a Python console program that is checking a data set which contains links to images stored locally. How should I write the script so that it would display images pop-up graphical windows? | Why not just display it in the user's web browser? |
Python with matplotlib - reusing drawing functions | 1,413,681 | 11 | 2009-09-11T23:15:09Z | 1,413,894 | 8 | 2009-09-12T00:54:29Z | [
"python",
"matplotlib"
] | I have a follow up question to this [question](http://stackoverflow.com/questions/1401102/python-with-matplotlib-drawing-multiple-figures-in-parallel/1401686#1401686).
Is it possible to streamline the figure generation by having multiple python scripts that work on different parts of the figure?
For example, if I hav... | Here you want to use the [Artist objects](http://matplotlib.sourceforge.net/users/artists.html), and pass them as needed to the functions:
```
import numpy as np
import matplotlib.pyplot as plt
def myhist(ax, color):
ax.hist(np.log(np.arange(1, 10, .1)), facecolor=color)
def say_something(ax, words):
t = ax.... |
Django not sending emails to admins | 1,414,130 | 47 | 2009-09-12T02:57:59Z | 1,414,147 | 12 | 2009-09-12T03:06:46Z | [
"python",
"django"
] | According to the [documentation](http://docs.djangoproject.com/en/dev/howto/error-reporting/), if `DEBUG` is set to `False` and something is provided under the `ADMINS` setting, Django will send an email whenever the code raises a 500 status code. I have the email settings filled out properly (as I can use send\_mail f... | Make sure your EMAIL\_HOST and EMAIL\_PORT are set up right in settings.py (these refer to your SMTP server). It might be assuming that you have an SMTP server running on localhost.
To test this locally, run Python's built-in test SMTP server:
```
python -m smtpd -n -c DebuggingServer localhost:1025
```
Then set the... |
Django not sending emails to admins | 1,414,130 | 47 | 2009-09-12T02:57:59Z | 6,551,508 | 69 | 2011-07-01T17:54:58Z | [
"python",
"django"
] | According to the [documentation](http://docs.djangoproject.com/en/dev/howto/error-reporting/), if `DEBUG` is set to `False` and something is provided under the `ADMINS` setting, Django will send an email whenever the code raises a 500 status code. I have the email settings filled out properly (as I can use send\_mail f... | In my case the cause was missing [SERVER\_EMAIL](https://docs.djangoproject.com/en/dev/ref/settings/#std%3asetting-SERVER_EMAIL) setting.
The default for [`SERVER_EMAIL`](https://docs.djangoproject.com/en/dev/ref/settings/#server-email) is `root@localhost`. But many of email servers including
my email provider do not ... |
Django not sending emails to admins | 1,414,130 | 47 | 2009-09-12T02:57:59Z | 9,541,647 | 21 | 2012-03-02T23:08:40Z | [
"python",
"django"
] | According to the [documentation](http://docs.djangoproject.com/en/dev/howto/error-reporting/), if `DEBUG` is set to `False` and something is provided under the `ADMINS` setting, Django will send an email whenever the code raises a 500 status code. I have the email settings filled out properly (as I can use send\_mail f... | I had the same situation. I created a new project and app and it worked, so I knew it was my code. I tracked it down to the LOGGING dictionary in settings.py. I had made some changes a few weeks back for logging with Sentry, but for some reason the error just started today. I changed back to the original and got it wor... |
Django not sending emails to admins | 1,414,130 | 47 | 2009-09-12T02:57:59Z | 18,136,491 | 31 | 2013-08-08T21:30:20Z | [
"python",
"django"
] | According to the [documentation](http://docs.djangoproject.com/en/dev/howto/error-reporting/), if `DEBUG` is set to `False` and something is provided under the `ADMINS` setting, Django will send an email whenever the code raises a 500 status code. I have the email settings filled out properly (as I can use send\_mail f... | Another possibility for error is trouble with your ADMINS setting. The following setting will cause the sending of mail to admins to fail quietly:
```
ADMINS = (
('your name', '[email protected]')
)
```
What's wrong with that? Well ADMINS needs to be a tuple of tuples, so the above needs to be formatted as
```
ADMIN... |
Local functions in Python | 1,414,304 | 26 | 2009-09-12T04:45:08Z | 1,414,320 | 26 | 2009-09-12T04:54:30Z | [
"python",
"function",
"binding",
"model",
"local"
] | In the following Python code, I get an `UnboundLocalError`. As I understand it, local functions share the local variables of the containing function, but this hardly seems to be the case here. I recognise that `a` is an immutable value in this context, but that should not be a problem.
```
def outer():
a = 0
d... | I believe you're correct in seeing this as a "mutability" problem. While the code you posted does throw an "UnboundLocalError", the following code does not:
```
def outer():
a = 0
def inner():
print a
inner()
outer()
```
Python doesn't allow you to reassign the value of a variable from an outer sc... |
Local functions in Python | 1,414,304 | 26 | 2009-09-12T04:45:08Z | 1,414,323 | 8 | 2009-09-12T04:55:11Z | [
"python",
"function",
"binding",
"model",
"local"
] | In the following Python code, I get an `UnboundLocalError`. As I understand it, local functions share the local variables of the containing function, but this hardly seems to be the case here. I recognise that `a` is an immutable value in this context, but that should not be a problem.
```
def outer():
a = 0
d... | Try binding the variable as an argument.
```
def outer():
a = 0
def inner(a=a):
a += 1
inner()
outer()
```
I'll try and dig up the appropriate documents.
**edit**
Since you want the inner function to have a side effect on the outer scope, then you need to use a mutable datatype like a list. In... |
Python recursive program to prime factorize a number | 1,414,581 | 2 | 2009-09-12T07:50:42Z | 1,414,600 | 9 | 2009-09-12T08:05:27Z | [
"python",
"algorithm",
"recursion",
"primes",
"prime-factoring"
] | I wrote the following program to prime factorize a number:
```
import math
def prime_factorize(x,li=[]):
until = int(math.sqrt(x))+1
for i in xrange(2,until):
if not x%i:
li.append(i)
break
else: #This else belongs to for
li.append(x)
print li ... | Your prime\_factorize function doesn't have a return statement in the recursive case -- you want to invoke "return prime\_factorize(x/i,li)" on its last line. Try it with a prime number (so the recursive call isn't needed) to see that it works in that case.
Also you probably want to make the signature something like:
... |
PyObjC development with Xcode 3.2 | 1,414,727 | 16 | 2009-09-12T09:27:39Z | 1,414,954 | 29 | 2009-09-12T12:01:45Z | [
"python",
"xcode",
"pyobjc"
] | Xcode 3.2 has removed the default templates for the scripting languages (Ruby, Python etc). How do I find these templates to use in Xcode 3.2? Would I need to add anything else to Xcode to support working with and 'building' PyObjC programs?
Additionally, is there any documentation and/or resources that would help me ... | Apple now encourages people to get the templates directly from the PyObjC project. There's a nice thread of explanation archived on [Cocoabuilder](http://www.cocoabuilder.com/archive/message/xcode/2009/8/31/30205), with the following advice from bbum:
> You'll need to download and install the templates from the PyObjC... |
Prompt on exit in PyQt application | 1,414,781 | 13 | 2009-09-12T10:06:04Z | 1,414,906 | 31 | 2009-09-12T11:25:00Z | [
"python",
"pyqt",
"exit"
] | Is there any way to promt user to exit the gui-program written in Python?
Something like "Are you sure you want to exit the program?"
I'm using PyQt. | Yes. You need to override the default close behaviour of the QWidget representing your application so that it doesn't immediately accept the event. The basic structure you want is something like this:
```
def closeEvent(self, event):
quit_msg = "Are you sure you want to exit the program?"
reply = QtGui.QMessa... |
Using safe filter in Django for rich text fields | 1,414,986 | 7 | 2009-09-12T12:20:59Z | 1,414,993 | 10 | 2009-09-12T12:26:04Z | [
"python",
"django",
"django-templates",
"filter"
] | I am using [TinyMCE](http://en.wikipedia.org/wiki/TinyMCE) editor for textarea fileds in [Django](http://en.wikipedia.org/wiki/Django_%28web_framework%29) forms.
Now, in order to display the rich text back to the user, I am forced to use the "safe" filter in Django templates so that HTML rich text can be displayed on ... | You are right to be concerned about raw HTML, but not just for Javascript-disabled browsers. When considering the security of your server, you have to ignore any work done in the browser, and look solely at what the server accepts and what happens to it. Your server accepts HTML and displays it on the page. This is uns... |
Using safe filter in Django for rich text fields | 1,414,986 | 7 | 2009-09-12T12:20:59Z | 3,376,419 | 8 | 2010-07-31T01:36:21Z | [
"python",
"django",
"django-templates",
"filter"
] | I am using [TinyMCE](http://en.wikipedia.org/wiki/TinyMCE) editor for textarea fileds in [Django](http://en.wikipedia.org/wiki/Django_%28web_framework%29) forms.
Now, in order to display the rich text back to the user, I am forced to use the "safe" filter in Django templates so that HTML rich text can be displayed on ... | You can use the template filter "[removetags](http://docs.djangoproject.com/en/1.1/ref/templates/builtins/#removetags)" and just remove 'script'. |
Resources for developing Python and Google App Engine | 1,415,208 | 2 | 2009-09-12T14:07:55Z | 1,419,518 | 7 | 2009-09-14T03:08:32Z | [
"python",
"google-app-engine",
"user-controls",
"controls"
] | I would like to ask about some sources for developing applications with Python and Google App Engine.
For example, some controls to generate automatically pages with the insert/update/delete of a database table, or any other useful resources are welcome.
Thank you! | The Python community tends to look askance at code generation; so, @Hoang, if you think code generation is THE way to go, I suggest you try just about any other language BUT Python.
@Dominic has already suggested some excellent resources, I could point you to more (App Engine Fan, App Engine Utilities, etc, etc) but t... |
Why use **kwargs in python? What are some real world advantages over using named arguments? | 1,415,812 | 42 | 2009-09-12T18:38:01Z | 1,415,826 | 29 | 2009-09-12T18:50:27Z | [
"python",
"kwargs"
] | I come from a background in static languages. Can someone explain (ideally through example) the real world **advantages of using \*\*kwargs over named arguments**?
To me it only seems to make the function call more ambiguous. Thanks. | Real-world examples:
Decorators - they're usually generic, so you can't specify the arguments upfront:
```
def decorator(old):
def new(*args, **kwargs):
# ...
return old(*args, **kwargs)
return new
```
Places where you want to do magic with an unknown number of keyword arguments. Django's ORM... |
Why use **kwargs in python? What are some real world advantages over using named arguments? | 1,415,812 | 42 | 2009-09-12T18:38:01Z | 1,415,830 | 47 | 2009-09-12T18:52:09Z | [
"python",
"kwargs"
] | I come from a background in static languages. Can someone explain (ideally through example) the real world **advantages of using \*\*kwargs over named arguments**?
To me it only seems to make the function call more ambiguous. Thanks. | You may want to accept nearly-arbitrary named arguments for a series of reasons -- and that's what the `**kw` form lets you do.
The most common reason is to pass the arguments right on to some other function you're wrapping (decorators are one case of this, but FAR from the only one!) -- in this case, `**kw` loosens t... |
Why use **kwargs in python? What are some real world advantages over using named arguments? | 1,415,812 | 42 | 2009-09-12T18:38:01Z | 1,415,840 | 9 | 2009-09-12T18:56:22Z | [
"python",
"kwargs"
] | I come from a background in static languages. Can someone explain (ideally through example) the real world **advantages of using \*\*kwargs over named arguments**?
To me it only seems to make the function call more ambiguous. Thanks. | There are two common cases:
First: You are wrapping another function which takes a number of keyword argument, but you are just going to pass them along:
```
def my_wrapper(a, b, **kwargs):
do_something_first(a, b)
the_real_function(**kwargs)
```
Second: You are willing to accept any keyword argument, for ex... |
Why use **kwargs in python? What are some real world advantages over using named arguments? | 1,415,812 | 42 | 2009-09-12T18:38:01Z | 1,415,882 | 29 | 2009-09-12T19:15:33Z | [
"python",
"kwargs"
] | I come from a background in static languages. Can someone explain (ideally through example) the real world **advantages of using \*\*kwargs over named arguments**?
To me it only seems to make the function call more ambiguous. Thanks. | Another reason you might want to use `**kwargs` (and `*args`) is if you're extending an existing method in a subclass. You want to pass all the existing arguments onto the superclass's method, but want to ensure that your class keeps working even if the signature changes in a future version:
```
class MySubclass(Super... |
how can i obtain pattern string from compiled regexp pattern in python | 1,415,924 | 49 | 2009-09-12T19:34:41Z | 1,415,932 | 52 | 2009-09-12T19:38:30Z | [
"python",
"regex"
] | I have some code like this one:
```
>>> import re
>>> p = re.compile('my pattern')
>>> print p
_sre.SRE_Pattern object at 0x02274380
```
Is it possible to get string `"my pattern"` from `p` variable? | ```
p.pattern
```
Read more about re module here:
<http://docs.python.org/library/re.html> |
how can i obtain pattern string from compiled regexp pattern in python | 1,415,924 | 49 | 2009-09-12T19:34:41Z | 1,415,977 | 12 | 2009-09-12T19:59:20Z | [
"python",
"regex"
] | I have some code like this one:
```
>>> import re
>>> p = re.compile('my pattern')
>>> print p
_sre.SRE_Pattern object at 0x02274380
```
Is it possible to get string `"my pattern"` from `p` variable? | From the ["Regular Expression Objects"](http://docs.python.org/library/re.html#regular-expression-objects) section of the `re` module documentation:
> `RegexObject.pattern`
>
> The pattern string from which the RE object was compiled.
For example:
```
>>> import re
>>> p = re.compile('my pattern')
>>> p
<_sre.SRE_Pa... |
Python - Virtualenv , python 3? | 1,416,005 | 8 | 2009-09-12T20:10:43Z | 28,298,765 | 11 | 2015-02-03T12:19:05Z | [
"python",
"osx",
"python-3.x",
"pygame",
"virtualenv"
] | Seems everyone recommends virtualenv for multiple python versions (on osx), but does it even work with python 3.0? I downloaded it, and it doesn't seem to.. And I don't really understand how it works, Can you 'turn on' on env at a time or something? What I want is to leave the system python 2.5 (obviously), and to have... | It's an old question by now, but I found it myself on top of google search for the answer, and I don't think the answers provided are what people are looking for.
As I understand it you want to create different virtual environments with different Python versions?
This is very easy, and you only need virtualenv itself... |
pythonic way to convert variable to list | 1,416,646 | 7 | 2009-09-13T02:01:29Z | 1,416,677 | 9 | 2009-09-13T02:24:29Z | [
"python",
"list",
"arguments"
] | I have a function whose input argument can either be an element or a list of elements. If this argument is a single element then I put it in a list so I can iterate over the input in a consistent manner.
Currently I have this:
```
def my_func(input):
if not isinstance(input, list): input = [input]
for e in in... | Typically, strings (plain and unicode) are the only iterables that you want to nevertheless consider as "single elements" -- the `basestring` builtin exists SPECIFICALLY to let you test for either kind of strings with `isinstance`, so it's very UN-grotty for that special case;-).
So my suggested approach for the most ... |
Emacs defadvice on python-mode function | 1,416,882 | 5 | 2009-09-13T04:52:45Z | 1,851,850 | 7 | 2009-12-05T10:43:59Z | [
"python",
"emacs",
"elisp",
"advising-functions",
"defadvice"
] | In python-mode, there is a function called py-execute-region which sends a highlighted region of code to the Python buffer for evaluation. After evaluation, the cursor is in the Python buffer, but I would prefer that it remain in the script buffer so I can continue producing more code. I wrote a simple advising functio... | In this case the solution appears to be
```
(custom-set-variables
'(py-shell-switch-buffers-on-execute nil))
``` |
Detecting the http request type (GET, HEAD, etc) from a python cgi | 1,417,715 | 9 | 2009-09-13T13:12:30Z | 1,417,722 | 12 | 2009-09-13T13:17:20Z | [
"python",
"http",
"httpwebrequest",
"cgi"
] | How can I find out the http request my python cgi received? I need different behaviors for HEAD and GET.
Thanks! | ```
import os
if os.environ['REQUEST_METHOD'] == 'GET':
# blah
``` |
Parse custom URIs with urlparse (Python) | 1,417,958 | 13 | 2009-09-13T15:10:41Z | 6,264,214 | 22 | 2011-06-07T11:00:59Z | [
"python",
"url",
"python-2.6",
"urlparse"
] | My application creates custom URIs (or URLs?) to identify objects and resolve them. The problem is that Python's urlparse module refuses to parse unknown URL schemes like it parses http.
If I do not adjust urlparse's uses\_\* lists I get this:
```
>>> urlparse.urlparse("qqqq://base/id#hint")
('qqqq', '', '//base/id#h... | You can also register a custom handler with urlparse:
```
import urlparse
def register_scheme(scheme):
for method in filter(lambda s: s.startswith('uses_'), dir(urlparse)):
getattr(urlparse, method).append(scheme)
register_scheme('moose')
```
This will append your url scheme to the lists:
```
uses_frag... |
How to get Python exception text | 1,418,015 | 33 | 2009-09-13T15:36:30Z | 1,418,703 | 37 | 2009-09-13T20:05:17Z | [
"c++",
"python",
"exception",
"boost-python"
] | I want to embed python in my C++ application. I'm using Boost library - great tool. But i have one problem.
If python function throws an exception, i want to catch it and print error in my application or get some detailed information like line number in python script that caused error.
How can i do it? I can't find a... | Well, I found out how to do it.
Without boost (only error message, because code to extract info from traceback is too heavy to post it here):
```
PyObject *ptype, *pvalue, *ptraceback;
PyErr_Fetch(&ptype, &pvalue, &ptraceback);
//pvalue contains error message
//ptraceback contains stack snapshot and many other inform... |
How to get Python exception text | 1,418,015 | 33 | 2009-09-13T15:36:30Z | 6,576,177 | 15 | 2011-07-04T21:22:58Z | [
"c++",
"python",
"exception",
"boost-python"
] | I want to embed python in my C++ application. I'm using Boost library - great tool. But i have one problem.
If python function throws an exception, i want to catch it and print error in my application or get some detailed information like line number in python script that caused error.
How can i do it? I can't find a... | This is the most robust method I've been able to come up so far:
```
try {
...
}
catch (bp::error_already_set) {
if (PyErr_Occurred()) {
msg = handle_pyerror();
}
py_exception = true;
bp::handle_exception();
PyErr_Clear();
}
if (py_except... |
Is it possible to hide the browser in Selenium RC? | 1,418,082 | 76 | 2009-09-13T16:07:53Z | 1,418,419 | 77 | 2009-09-13T18:04:33Z | [
"python",
"selenium",
"selenium-rc"
] | I am using Selenium RC to automate some browser operations but I want the browser to be invisible. Is this possible? How? What about Selenium Grid? Can I hide the Selenium RC window also? | There are a few options:
* You could use Selenium Grid so that the browser is opened on a completely different machine (or virtual machine) that you can then connect to via VNC or Remote Desktop Connection if you wanted to see the browser. Also, another option: if you run a Jenkins foreground process on that remote se... |
Is it possible to hide the browser in Selenium RC? | 1,418,082 | 76 | 2009-09-13T16:07:53Z | 1,419,676 | 13 | 2009-09-14T04:28:56Z | [
"python",
"selenium",
"selenium-rc"
] | I am using Selenium RC to automate some browser operations but I want the browser to be invisible. Is this possible? How? What about Selenium Grid? Can I hide the Selenium RC window also? | +1 for Selenium RC as a windows service.
For having the tests run completely hidden, I think you don't have much solutions if you're on windows.
What I'd do it to dedicate a computer in your LAN to be online all the time and have a selenium RC server running. So you use that computer's IP instead of localhost to run ... |
Is it possible to hide the browser in Selenium RC? | 1,418,082 | 76 | 2009-09-13T16:07:53Z | 8,910,326 | 49 | 2012-01-18T12:48:05Z | [
"python",
"selenium",
"selenium-rc"
] | I am using Selenium RC to automate some browser operations but I want the browser to be invisible. Is this possible? How? What about Selenium Grid? Can I hide the Selenium RC window also? | On \*nix, you can run WebDriver in a headless (virtual) display to hide the browser. This can be done with [Xvfb](http://en.wikipedia.org/wiki/Xvfb).
I personally use Python on Linux, and the [PyVirtualDisplay](http://pypi.python.org/pypi/PyVirtualDisplay) module to handle Xvfb for me.
Code for running headless would... |
Is it possible to hide the browser in Selenium RC? | 1,418,082 | 76 | 2009-09-13T16:07:53Z | 14,155,698 | 11 | 2013-01-04T10:50:19Z | [
"python",
"selenium",
"selenium-rc"
] | I am using Selenium RC to automate some browser operations but I want the browser to be invisible. Is this possible? How? What about Selenium Grid? Can I hide the Selenium RC window also? | On Linux, you can run your test browser on a virtual display. You will need the `xvfb` package for creating a virtual X server. On Debian based distros, just run
```
sudo apt-get install xvfb
```
There is a nice tool [`ephemeral-x.sh`](http://semicomplete.com/blog/geekery/headless-wrapper-for-ephemeral-xservers.html)... |
Is it possible to hide the browser in Selenium RC? | 1,418,082 | 76 | 2009-09-13T16:07:53Z | 23,898,054 | 13 | 2014-05-27T20:11:00Z | [
"python",
"selenium",
"selenium-rc"
] | I am using Selenium RC to automate some browser operations but I want the browser to be invisible. Is this possible? How? What about Selenium Grid? Can I hide the Selenium RC window also? | I easily managed to hide the browser window.
Just [install PhantomJS](http://phantomjs.org/download.html). Then, change this line:
```
driver = webdriver.Firefox()
```
to:
```
driver = webdriver.PhantomJS()
```
The rest of your code won't need to be changed and no browser will open. For debugging purposes, use `dr... |
How expensive are Python dictionaries to handle? | 1,418,588 | 23 | 2009-09-13T19:03:50Z | 1,418,591 | 10 | 2009-09-13T19:05:33Z | [
"python",
"performance",
"data-structures",
"dictionary"
] | As the title states, how expensive are Python dictionaries to handle? Creation, insertion, updating, deletion, all of it.
Asymptotic time complexities are interesting themselves, but also how they compare to e.g. tuples or normal lists. | Dictionaries are one of the more heavily tuned parts of Python, since they underlie so much of the language. For example, members of a class, and variables in a stack frame are both stored internally in dictionaries. They will be a good choice if they are the right data structure.
Choosing between lists and dicts base... |
How expensive are Python dictionaries to handle? | 1,418,588 | 23 | 2009-09-13T19:03:50Z | 1,419,324 | 40 | 2009-09-14T01:27:52Z | [
"python",
"performance",
"data-structures",
"dictionary"
] | As the title states, how expensive are Python dictionaries to handle? Creation, insertion, updating, deletion, all of it.
Asymptotic time complexities are interesting themselves, but also how they compare to e.g. tuples or normal lists. | `dicts` (just like `set`s when you don't need to associate a value to each key but simply record if a key is present or absent) are pretty heavily optimized. Creating a `dict` from N keys or key/value pairs is `O(N)`, fetching is `O(1)`, putting is amortized `O(1)`, and so forth. Can't really do anything substantially ... |
Where is the Python documentation for the special methods? (__init__, __new__, __len__, ...) | 1,418,825 | 11 | 2009-09-13T21:02:02Z | 1,418,832 | 31 | 2009-09-13T21:05:41Z | [
"python",
"class",
"methods",
"double-underscore"
] | Where is a complete list of the special double-underscore/dunder methods that can be used in classes? (e.g., `__init__`, `__new__`, `__len__`, `__add__`) | Please take a look at the [special method names section](http://docs.python.org/reference/datamodel.html#special-method-names) in the Python language reference. |
Where is the Python documentation for the special methods? (__init__, __new__, __len__, ...) | 1,418,825 | 11 | 2009-09-13T21:02:02Z | 1,418,844 | 7 | 2009-09-13T21:11:25Z | [
"python",
"class",
"methods",
"double-underscore"
] | Where is a complete list of the special double-underscore/dunder methods that can be used in classes? (e.g., `__init__`, `__new__`, `__len__`, `__add__`) | Dive Into Python has [an excellent appendix](http://web.archive.org/web/20110131211638/http://diveintopython3.org/special-method-names.html) for them. |
Are Python list comprehensions the same thing as map/grep in Perl? | 1,418,912 | 14 | 2009-09-13T21:41:58Z | 1,418,915 | 13 | 2009-09-13T21:43:16Z | [
"python",
"perl",
"list"
] | I was having some trouble grokking the list comprehension syntax in Python, so I started thinking about how to achieve the same thing in Perl, which I'm more familiar with. I realized that the basic examples (taken from [this page](http://www.secnetix.de/olli/Python/list_comprehensions.hawk)) can all be done in Perl wi... | You are correct: a list comprehension is essentially just syntactic sugar for map and filter (terms from the functional programming world).
Hopefully this sample code demonstrates their equality:
```
>>> # Python 2
>>> [x**2 for x in range(10)] == map(lambda x: x**2, range(10))
True
>>> [2**i for i in range(13)] == m... |
Python normal arguments vs. keyword arguments | 1,419,046 | 115 | 2009-09-13T22:54:00Z | 1,419,098 | 17 | 2009-09-13T23:14:16Z | [
"python",
"arguments",
"keyword",
"optional-parameters",
"named-parameters"
] | How are "keyword arguments" different from regular arguments? Can't all arguments be passed as `name=value` instead of using positional syntax? | There are two ways to assign argument values to function parameters, both are used.
1. By Position. Positional arguments do not have keywords and are assigned first.
2. By Keyword. Keyword arguments have keywords and are assigned second, after positional arguments.
Note that *you* have the option to use positional ar... |
Python normal arguments vs. keyword arguments | 1,419,046 | 115 | 2009-09-13T22:54:00Z | 1,419,107 | 44 | 2009-09-13T23:17:03Z | [
"python",
"arguments",
"keyword",
"optional-parameters",
"named-parameters"
] | How are "keyword arguments" different from regular arguments? Can't all arguments be passed as `name=value` instead of using positional syntax? | Using keyword arguments is the same thing as normal arguments except order doesn't matter. For example the two functions calls below are the same:
```
def foo(bar, baz):
pass
foo(1, 2)
foo(baz=2, bar=1)
``` |
Python normal arguments vs. keyword arguments | 1,419,046 | 115 | 2009-09-13T22:54:00Z | 1,419,110 | 17 | 2009-09-13T23:17:40Z | [
"python",
"arguments",
"keyword",
"optional-parameters",
"named-parameters"
] | How are "keyword arguments" different from regular arguments? Can't all arguments be passed as `name=value` instead of using positional syntax? | # Normal Arguments
They have no keywords before them. The order is important!
```
func(1,2,3, "foo")
```
# Keyword Arguments
They have keywords in the front. They can be in any order!
```
func(foo="bar", baz=5, hello=123)
func(baz=5, foo="bar", hello=123)
```
You should also know that if you use default argument... |
Python normal arguments vs. keyword arguments | 1,419,046 | 115 | 2009-09-13T22:54:00Z | 1,419,149 | 7 | 2009-09-13T23:52:00Z | [
"python",
"arguments",
"keyword",
"optional-parameters",
"named-parameters"
] | How are "keyword arguments" different from regular arguments? Can't all arguments be passed as `name=value` instead of using positional syntax? | I'm surprised no one has mentioned the fact that you can mix positional and keyword arguments to do sneaky things like this using `*args` and `**kwargs` ([from this site](http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/)):
```
def test_var_kwargs(farg, **kwargs):
print "formal arg:", fa... |
Python normal arguments vs. keyword arguments | 1,419,046 | 115 | 2009-09-13T22:54:00Z | 1,419,159 | 78 | 2009-09-13T23:58:17Z | [
"python",
"arguments",
"keyword",
"optional-parameters",
"named-parameters"
] | How are "keyword arguments" different from regular arguments? Can't all arguments be passed as `name=value` instead of using positional syntax? | There is one last language feature where the distinction is important. Consider the following function:
```
def foo(*positional, **keywords):
print "Positional:", positional
print "Keywords:", keywords
```
The `*positional` argument will store all of the positional arguments passed to `foo()`, with no limit t... |
Python normal arguments vs. keyword arguments | 1,419,046 | 115 | 2009-09-13T22:54:00Z | 1,419,160 | 142 | 2009-09-13T23:58:51Z | [
"python",
"arguments",
"keyword",
"optional-parameters",
"named-parameters"
] | How are "keyword arguments" different from regular arguments? Can't all arguments be passed as `name=value` instead of using positional syntax? | there are two related concepts, both called "keyword arguments".
On the calling side, which is what other commenters have mentioned, you have the ability to specify some function arguments by name. You have to mention them after all of the arguments without names (positional arguments), and there must be default value... |
Python normal arguments vs. keyword arguments | 1,419,046 | 115 | 2009-09-13T22:54:00Z | 16,368,276 | 10 | 2013-05-03T22:07:55Z | [
"python",
"arguments",
"keyword",
"optional-parameters",
"named-parameters"
] | How are "keyword arguments" different from regular arguments? Can't all arguments be passed as `name=value` instead of using positional syntax? | I'm surprised that no one seems to have pointed out that one can pass a dictionary of keyed argument parameters, that satisfy the formal parameters, like so.
```
>>> def func(a='a', b='b', c='c', **kwargs):
... print 'a:%s, b:%s, c:%s' % (a, b, c)
...
>>> func()
a:a, b:b, c:c
>>> func(**{'a' : 'z', 'b':'q', 'c':'v... |
Python memory leaks? | 1,419,065 | 7 | 2009-09-13T23:03:01Z | 1,419,264 | 12 | 2009-09-14T01:01:03Z | [
"python",
"memory",
"memory-management",
"valgrind"
] | I am writing a python extension that seems to be leaking memory. I am trying to figure out the soure of the problem using valgrind.
However, it seems that python itself is leaking memory according to valgrind. Using the following simple script:
**hello.py**
```
print "Hello World!"
```
and doing
```
> valgrind -... | There's a whole README.valgrind in the Python sources that explains the various caveats trying to use Valgrind with Python:
<http://svn.python.org/projects/python/trunk/Misc/README.valgrind>
```
Python uses its own small-object allocation scheme on top of malloc,
called PyMalloc.
Valgrind may show some unexpected re... |
In python, is there a "pass" equivalent for a variable assignment | 1,419,077 | 25 | 2009-09-13T23:08:25Z | 1,419,082 | 28 | 2009-09-13T23:09:51Z | [
"python",
"core"
] | I am using a library function called get\_count\_and\_price which returns a 2-tuple (count,price). In many places I use both time and price. However, in some I only need time or price. So right now, if I only need count, I assign to (count,price) and leave the price unused.
This works great and causes no trouble in an... | I think there's nothing wrong with using the [0] subscript, but sometimes people use the "throwaway" variable \_. It's actually just like any other variable (with special usage in the console), except that some Python users decided to have it be "throwaway" as a convention.
```
count, _ = get_count_and_price()
```
A... |
In python, is there a "pass" equivalent for a variable assignment | 1,419,077 | 25 | 2009-09-13T23:08:25Z | 1,419,093 | 7 | 2009-09-13T23:12:10Z | [
"python",
"core"
] | I am using a library function called get\_count\_and\_price which returns a 2-tuple (count,price). In many places I use both time and price. However, in some I only need time or price. So right now, if I only need count, I assign to (count,price) and leave the price unused.
This works great and causes no trouble in an... | If you go to the Eclipse -> Preferences⦠window, you can actually specify which variable names PyDev should ignore if they're unused (I'm looking at the newest PyDev 1.5.X).
If you go to PyDev -> Editor -> Code Analysis and look at the last field that says "Don't report unused variable if name starts with"
Enter wh... |
In python, is there a "pass" equivalent for a variable assignment | 1,419,077 | 25 | 2009-09-13T23:08:25Z | 1,419,265 | 20 | 2009-09-14T01:01:15Z | [
"python",
"core"
] | I am using a library function called get\_count\_and\_price which returns a 2-tuple (count,price). In many places I use both time and price. However, in some I only need time or price. So right now, if I only need count, I assign to (count,price) and leave the price unused.
This works great and causes no trouble in an... | Using `_` as severally proposed may have some issues (though it's mostly OK). By the Python style guidelines we use at work I'd normally use `count, unused_price = ...` since pylint is configured to ignore assignments to barenames starting with `unused_` (and warn on USE of any such barename instead!-). But I don't kno... |
How to Model a Foreign Key in a Reusable Django App? | 1,419,442 | 11 | 2009-09-14T02:24:10Z | 1,419,704 | 21 | 2009-09-14T04:39:11Z | [
"python",
"django",
"django-models"
] | In my django site I have two apps, blog and links. blog has a model blogpost, and links has a model link. There should be a one to many relationship between these two things. There are many links per blogpost, but each link has one and only one blog post. The simple answer is to put a ForeignKey to blogpost in the link... | If you think the link app will always point to a single app then one approach would be to pass the name of the foreign model as a string containing the application label instead of a class reference ([Django docs explanation](http://docs.djangoproject.com/en/dev/ref/models/fields/#foreignkey)).
In other words, instead... |
Python __init__ setattr on arguments? | 1,419,470 | 5 | 2009-09-14T02:41:58Z | 1,419,497 | 7 | 2009-09-14T02:55:37Z | [
"python",
"list",
"parameters",
"initialization",
"setattr"
] | It seems that often `__init__` methods are similar to this:
```
def __init__(self, ivar1, ivar2, ivar3):
self.ivar1 = ivar1
self.ivar2 = ivar2
self.ivar3 = ivar3
```
Is there someway to turn the arguments into a list (without resorting to `*args` or `**kwargs`) and then using `setattr` to set the instance... | Here you go. Yes this is an ugly evil hack. Yes the object needs a \_\_dict\_\_ variable. But hey, its a neat little one liner!
```
def __init__(self):
self.__dict__.update(locals())
```
The constructor can take any type of arguments.
```
class test(object):
def __init__(self, a, b, foo, bar=5)...
a = test(... |
Django LEFT JOIN? | 1,419,537 | 9 | 2009-09-14T03:15:57Z | 1,419,596 | 11 | 2009-09-14T03:51:31Z | [
"python",
"django"
] | I have models, more or less like this:
```
class ModelA(models.Model):
field = models.CharField(..)
class ModelB(models.Model):
name = models.CharField(.., unique=True)
modela = models.ForeignKey(ModelA, blank=True, related_name='modelbs')
class Meta:
unique_together = ('name','modela')
```
... | Use Q to combine the two conditions:
```
from django.db.models import Q
qs = ModelA.objects.exclude(field=condition)
qs = qs.filter(Q(modelbs__name=condition) | Q(modelbs__isnull=True))
```
To examine the resulting SQL query:
```
print qs.query.as_sql()
```
On a similar query, this generates a LEFT OUTER JOIN ... W... |
How to extract and then refer to variables defined in a python module? | 1,419,620 | 2 | 2009-09-14T04:00:43Z | 1,419,642 | 8 | 2009-09-14T04:11:15Z | [
"python",
"variables",
"import"
] | I'm trying to build a simple environment check script for my firm's test environment. My goal is to be able to ping each of the hosts defined for a given test environment instance. The hosts are defined in a file like this:
```
#!/usr/bin/env python
host_ip = '192.168.100.10'
router_ip = '192.168.100.254'
fs_ip = '192... | First off, I strongly recommend not doing it that way. Instead, do:
```
hosts = {
"host_ip": '192.168.100.10',
"router_ip": '192.168.100.254',
"fs_ip": '192.168.200.10',
}
```
Then you can simply import the module and reference it normally--this gives an ordinary, standard way to access this data from any... |
Atlassian Bamboo with Django & Python - Possible? | 1,419,629 | 27 | 2009-09-14T04:04:31Z | 1,419,723 | 23 | 2009-09-14T04:51:13Z | [
"python",
"django",
"deployment",
"continuous-integration",
"bamboo"
] | At my company, we currently use [Atlassian Bamboo](http://www.atlassian.com/software/bamboo/) for our continuous integration tool. We currently use Java for all of our projects, so it works great.
However, we are considering using a Django + Python for one of our new applications. I was wondering if it is possible to ... | Bamboo essentially just runs a shell script, so this could just as easily be:
```
./manage.py test
```
as it typically is:
```
mvn clean install
```
or:
```
ant compile
```
You may have to massage to output of the Django test runner into traditional JUnit XML output, so that Bamboo can give you pretty graphs on h... |
Atlassian Bamboo with Django & Python - Possible? | 1,419,629 | 27 | 2009-09-14T04:04:31Z | 25,667,201 | 9 | 2014-09-04T13:49:23Z | [
"python",
"django",
"deployment",
"continuous-integration",
"bamboo"
] | At my company, we currently use [Atlassian Bamboo](http://www.atlassian.com/software/bamboo/) for our continuous integration tool. We currently use Java for all of our projects, so it works great.
However, we are considering using a Django + Python for one of our new applications. I was wondering if it is possible to ... | You can even add a bootstrap for pip and virtualenv on a clean environment quite easily, which is cool:
```
wget https://bootstrap.pypa.io/get-pip.py
python get-pip.py --root=${bamboo.build.working.directory}/tmp --ignore-installed
export PATH=${bamboo.build.working.directory}/tmp/usr/local/bin:$PATH
export PYTHONPATH... |
Just installed QtOpenGL but cannot import it (from Python) | 1,419,650 | 10 | 2009-09-14T04:15:01Z | 1,419,673 | 24 | 2009-09-14T04:25:35Z | [
"python",
"opengl",
"pyqt",
"apt-get",
"pyopengl"
] | I just installed it with apt-get on debian linux with
```
apt-get install libqt4-opengl
```
the rest of PyQt4 is available, but I cant get to this new module.
```
from PyQt4 import QtOpenGL
```
raises ImportError. any idea what to do? | Did you forget to install the Python bindings?
```
apt-get install python-qt4-gl
``` |
Parsing unstructured text in Python | 1,419,653 | 3 | 2009-09-14T04:15:31Z | 1,419,730 | 11 | 2009-09-14T04:53:47Z | [
"python",
"parsing",
"text"
] | I wanted to parse a text file that contains unstructured text. I need to get the address, date of birth, name, sex, and ID.
```
. 55 MORILLO ZONE VIII,
BARANGAY ZONE VIII
(POB.), LUISIANA, LAGROS
F
01/16/1952
ALOMO, TERESITA CABALLES
3412-00000-A1652TCA2
12
. 22 FABRICANTE ST. ZONE
VIII LUISIANA LAGROS,
BARANGAY Z... | Here is a first stab at a pyparsing solution ([easy-to-copy code at the pyparsing pastebin](http://pyparsing.pastebin.com/f45acc301)). Walk through the separate parts, according to the interleaved comments.
```
data = """\
. 55 MORILLO ZONE VIII,
BARANGAY ZONE VIII
(POB.), LUISIANA, LAGROS
F
01/16/1952
ALOMO, TERESITA... |
Stopping embedded Python | 1,420,957 | 16 | 2009-09-14T11:19:15Z | 1,427,498 | 8 | 2009-09-15T14:21:33Z | [
"python",
"process",
"multithreading",
"embedded-language",
"python-c-api"
] | I'm embedding Python interpreter to a C program. However, it might happen that while running some python script via `PyRun_SimpleString()` will run into infinite loop or execute for too long. Consider `PyRun_SimpleString("while 1: pass");` In preventing the main program to block I thought I could run the interpreter in... | You can use `Py_AddPendingCall()` to add a function raising exception to be called on next check interval (see docs on `sys.setcheckinterval()` for more info). Here is an example with `Py_Exit()` call (which does works for me, but probably is not what you need), replace it with `Py_Finalize()` or one of `PyErr_Set*()`:... |
How do I get the operating system name in a friendly manner using Python 2.5? | 1,421,357 | 7 | 2009-09-14T12:50:23Z | 1,421,365 | 36 | 2009-09-14T12:52:34Z | [
"python"
] | I tried:
```
print os.name
```
And the output I got was:
```
:nt
```
However, I want output more like "Windows 98", or "Linux".
After suggestions in this question, I also tried:
```
import os
print os.name
import platform
print platform.system()
print platform.release()
```
And my output was:
```
Traceback (mos... | Try:
```
import platform
print platform.system(), platform.release()
```
I tried this on my computer with Python 2.6 and I got this as the output:
```
Windows XP
```
After your latest edits, I see that you called your script platform.py. This is causing a naming problem, as when you call `platform.system()` and `pl... |
How do I get the operating system name in a friendly manner using Python 2.5? | 1,421,357 | 7 | 2009-09-14T12:50:23Z | 1,421,623 | 14 | 2009-09-14T13:43:16Z | [
"python"
] | I tried:
```
print os.name
```
And the output I got was:
```
:nt
```
However, I want output more like "Windows 98", or "Linux".
After suggestions in this question, I also tried:
```
import os
print os.name
import platform
print platform.system()
print platform.release()
```
And my output was:
```
Traceback (mos... | it is because you named your program "platform". Hence when importing the module "platform", your program is imported instead in a circular import.
Try renaming the file to test\_platform.py, and it will work. |
Which python mpi library to use? | 1,422,260 | 15 | 2009-09-14T15:26:04Z | 1,422,871 | 15 | 2009-09-14T17:20:57Z | [
"python",
"mpi"
] | I'm starting work on some simulations using MPI and want to do the programming in Python/scipy. The scipy [site](http://www.scipy.org/Topical%5FSoftware#head-cf472934357fda4558aafdf558a977c4d59baecb) lists a number of mpi libraries, but I was hoping to get feedback on quality, ease of use, etc from anyone who has used ... | I have heard good things about [mpi4py](http://mpi4py.scipy.org/) (but I have never used it myself). That's what a colleague recommended who looked at all the alternatives. He mentioned the completeness as one advantage. |
fcntl substitute on Windows | 1,422,368 | 41 | 2009-09-14T15:43:11Z | 1,422,436 | 49 | 2009-09-14T15:54:35Z | [
"python",
"windows",
"linux"
] | I received a Python project (which happens to be a Django project, if that matters,) that uses the `fcntl` module from the standard library, which seems to be available only on Linux. When I try to run it on my Windows machine, it stops with an `ImportError`, because this module does not exist here.
Is there any way f... | The substitute of `fcntl` on windows are `win32api` calls. The usage is completely different. It is not some switch you can just flip.
In other words, porting a `fcntl`-heavy-user module to windows is not trivial. It requires you to analyze what exactly each `fcntl` call does and then find the equivalent `win32api` co... |
fcntl substitute on Windows | 1,422,368 | 41 | 2009-09-14T15:43:11Z | 9,993,103 | 14 | 2012-04-03T12:18:58Z | [
"python",
"windows",
"linux"
] | I received a Python project (which happens to be a Django project, if that matters,) that uses the `fcntl` module from the standard library, which seems to be available only on Linux. When I try to run it on my Windows machine, it stops with an `ImportError`, because this module does not exist here.
Is there any way f... | Although this does not help you right away, there is an alternative that can work with both Unix (fcntl) and Windows (win32 api calls), called: **portalocker**
It describes itself as a cross-platform (posix/nt) API for flock-style file locking for Python. It basically maps fcntl to win32 api calls.
The original code ... |
fcntl substitute on Windows | 1,422,368 | 41 | 2009-09-14T15:43:11Z | 25,471,508 | 16 | 2014-08-24T12:05:33Z | [
"python",
"windows",
"linux"
] | I received a Python project (which happens to be a Django project, if that matters,) that uses the `fcntl` module from the standard library, which seems to be available only on Linux. When I try to run it on my Windows machine, it stops with an `ImportError`, because this module does not exist here.
Is there any way f... | The fcntl module is just used for locking the pinning file, so assuming you don't try multiple access, this can be an acceptable workaround. Place this module in your PYTHONPATH, and it should just work as the official fcntl module.
Try using [this module](https://communities.cisco.com/servlet/JiveServlet/download/150... |
How does AMF communication work? | 1,422,724 | 3 | 2009-09-14T16:53:44Z | 1,422,867 | 7 | 2009-09-14T17:19:40Z | [
"python",
"flash",
"perl",
"actionscript-2",
"amf"
] | How does Flash communicate with services / scripts on servers via [AMF](http://en.wikipedia.org/wiki/Action%5FMessage%5FFormat)?
Regarding the [AMF libraries](http://en.wikipedia.org/wiki/Action%5FMessage%5FFormat#Support%5Ffor%5FAMF) for Python / Perl / PHP which are easier to develop than .NET / Java:
* do they exe... | The only AMF library I'm familiar with is [PyAMF](http://pyamf.org/), which has been great to work with so far. Here are the answers to your questions for PyAMF:
* I'd imagine you can run it as a script (do you mean like CGI?), but the easiest IMO is to set up an app server specifically for AMF requests
* the easiest ... |
pytz: Why is normalize needed when converting between timezones? | 1,422,880 | 14 | 2009-09-14T17:22:31Z | 1,422,900 | 8 | 2009-09-14T17:26:38Z | [
"python",
"timezone",
"pytz"
] | I'm reading the not so complete [pytz documentation](http://pytz.sourceforge.net/) and I'm stuck on understand one part of it.
> Converting between timezones also needs special attention. This also needs to use the normalize method to ensure the conversion is correct.
```
>>> utc_dt = utc.localize(datetime.utcfromtim... | From the pytz documentation:
> In addition, if you perform date arithmetic on local times that cross DST boundaries, the results may be in an incorrect timezone (ie. subtract 1 minute from 2002-10-27 1:00 EST and you get 2002-10-27 0:59 EST instead of the correct 2002-10-27 1:59 EDT). A normalize() method is provided ... |
Python and the built-in heap | 1,422,969 | 2 | 2009-09-14T17:45:13Z | 1,423,016 | 9 | 2009-09-14T17:59:03Z | [
"python"
] | At the moment, I am trying to write a priority queue in Python using the built in heapq library. However, I am stuck trying to get a handle on what Python does with the tie-breaking, I want to have a specific condition where I can dictate what happens with the tie-breaking instead of the heapq library that seems to alm... | `heapq` uses the intrinsic comparisons on queue items (`__le__` and friends). The general way to work around this limit is the good old approach known as "decorate/undecorate" -- that's what we used to do in sorting, before the `key=` parameter was introduced there.
To put it simply, you enqueue and dequeue, not just ... |
Negative lookahead after newline? | 1,423,260 | 2 | 2009-09-14T18:48:01Z | 1,423,344 | 7 | 2009-09-14T19:08:25Z | [
"python",
"regex"
] | I have a CSV-like text file that has about 1000 lines. Between each record in the file is a long series of dashes. The records generally end with a \n, but sometimes there is an extra \n before the end of the record. Simplified example:
```
"1x", "1y", "Hi there"
-------------------------------
"2x", "2y", "Hello - I'... | This is a good place to use a generator function to skip the lines of `----`'s and yield something that the csv module can read.
```
def readCleanLines( someFile ):
for line in someFile:
if line.strip() == len(line.strip())*'-':
continue
yield line
reader= csv.reader( readCleanLines( s... |
Can I run a Python script as a service? | 1,423,345 | 12 | 2009-09-14T19:08:36Z | 1,423,371 | 7 | 2009-09-14T19:14:29Z | [
"python",
"web-services",
"sockets",
"webserver"
] | Is it possible to run a Python script as a background service on a webserver? I want to do this for [socket communication.](http://stackoverflow.com/questions/1422929/socket-communication) | You might want to check out [Twisted](http://twistedmatrix.com/trac/). |
Can I run a Python script as a service? | 1,423,345 | 12 | 2009-09-14T19:08:36Z | 1,423,498 | 8 | 2009-09-14T19:40:18Z | [
"python",
"web-services",
"sockets",
"webserver"
] | Is it possible to run a Python script as a background service on a webserver? I want to do this for [socket communication.](http://stackoverflow.com/questions/1422929/socket-communication) | You can make it a daemon. There is a PEP for a more complete solution, but I have found that this works well.
```
import os, sys
def become_daemon(our_home_dir='.', out_log='/dev/null', err_log='/dev/null', pidfile='/var/tmp/daemon.pid'):
""" Make the current process a daemon. """
try:
# First fork
... |
What is wrong with this python function from "Programming Collective Intelligence"? | 1,423,525 | 4 | 2009-09-14T19:46:12Z | 1,423,580 | 8 | 2009-09-14T19:56:51Z | [
"python",
"algorithm",
"pearson"
] | This is the function in question. It calculates the Pearson correlation coefficient for p1 and p2, which is supposed to be a number between -1 and 1.
When I use this with real user data, it sometimes returns a number greater than 1, like in this example:
```
def sim_pearson(prefs,p1,p2):
si={}
for item in pre... | It looks like you may be unexpectedly using integer division. I made the following change and your function returned `1.0`:
```
num=pSum-(1.0*sum1*sum2/n)
den=sqrt((sum1Sq-1.0*pow(sum1,2)/n)*(sum2Sq-1.0*pow(sum2,2)/n))
```
See [PEP 238](http://docs.python.org/whatsnew/2.2.html#pep-238-changing-the-division-operator) ... |
Writing a connection string when password contains special characters | 1,423,804 | 10 | 2009-09-14T20:41:50Z | 1,424,009 | 22 | 2009-09-14T21:26:51Z | [
"python",
"character-encoding",
"sqlalchemy",
"connection-string"
] | I'm using SQLalchemy for a Python project, and I want to have a tidy connection string to access my database. So for example:
```
engine = create_engine('postgres://user:pass@host/database')
```
The problem is my password contains a sequence of special characters that get interpreted as delimiters when I try to conne... | Backslashes aren't valid escape characters for URL component strings. You need to URL-encode the password portion of the connect string:
```
from urllib import quote_plus as urlquote
from sqlalchemy.engine import create_engine
engine = create_engine('postgres://user:%s@host/database' % urlquote('badpass'))
```
If you... |
hashlib / md5. Compatibility with python 2.4 | 1,423,861 | 8 | 2009-09-14T20:51:42Z | 1,423,871 | 18 | 2009-09-14T20:54:25Z | [
"python",
"import",
"md5",
"backwards-compatibility",
"hashlib"
] | python 2.6 reports that the md5 module is obsolete and hashlib should be used. If I change `import md5` to `import hashlib` I will solve for python 2.5 and python 2.6, but not for python 2.4, which has no hashlib module (leading to a ImportError, which I can catch).
Now, to fix it, I could do a try/catch, and define a... | In general the following construct is just fine:
```
try:
import module
except ImportError:
# Do something else.
```
In your particular case, perhaps:
```
try:
from hashlib import md5
except ImportError:
from md5 import md5
``` |
How can I install specialized environments for different Perl applications? | 1,423,879 | 17 | 2009-09-14T20:56:34Z | 1,423,961 | 20 | 2009-09-14T21:12:15Z | [
"python",
"perl",
"virtualenv"
] | Is there anything equivalent or close in terms of functionality to Python's [virtualenv](http://pypi.python.org/pypi/virtualenv#what-it-does), but for Perl?
I've done some development in Python and a possibility of having non-system versions of modules installed in a separate environment without creating any mess is a... | There's a tool called [`local::lib`](http://search.cpan.org/perldoc/local%3A%3Alib) that wraps up all of the work for you, much like `virtualenv`. It will:
* Set up `@INC` in the process where it's used.
* Set `PERL5LIB` and other such things for child processes.
* Set the right variables to convince CPAN, [`MakeMaker... |
In Python, how do I create a string of n characters in one line of code? | 1,424,005 | 53 | 2009-09-14T21:26:10Z | 1,424,014 | 8 | 2009-09-14T21:28:20Z | [
"python",
"string"
] | I need to generate a string with n characters in Python. Is there a one line answer to achieve this with the existing Python library? For instance, I need a string of 10 letters:
```
string_val = 'abcdefghij'
``` | The first ten lowercase letters are `string.lowercase[:10]` (if you have imported the standard library module `string` previously, of course;-).
Other ways to "make a string of 10 characters": `'x'*10` (all the ten characters will be lowercase `x`s;-), `''.join(chr(ord('a')+i) for i in xrange(10))` (the first ten lowe... |
In Python, how do I create a string of n characters in one line of code? | 1,424,005 | 53 | 2009-09-14T21:26:10Z | 1,424,016 | 130 | 2009-09-14T21:28:40Z | [
"python",
"string"
] | I need to generate a string with n characters in Python. Is there a one line answer to achieve this with the existing Python library? For instance, I need a string of 10 letters:
```
string_val = 'abcdefghij'
``` | To simply repeat the same letter 10 times:
```
string_val = "x" * 10 # gives you "xxxxxxxxxx"
```
And if you want something more complex, like `n` random lowercase letters, it's still only one line of code (not counting the import statements and defining `n`):
```
from random import choice
from string import lowerc... |
Komodo Edit - code-completion for Django? | 1,424,392 | 2 | 2009-09-14T23:26:17Z | 1,424,443 | 8 | 2009-09-14T23:43:24Z | [
"python",
"django",
"ide",
"code-completion",
"komodo"
] | I've been using Komodo Edit for a small project in Django.
The code completion features seem to work pretty well for standard python modules, however, it doesn't know anything about Django modules. Is there any way to configure Komodo Edit to use Django modules for autocomplete as well? | > o to Edit > Preferences. Expand the
> "Languages" group by clicking the [+]
> symbol. Click "Python". Click the
> little "Add..." button under
> "Additional Python Import
> Directories". Add the directory ABOVE
> your project and you should have
> intellisense enabled.
This has always worked for me for both Django a... |
Pad python floats | 1,424,638 | 12 | 2009-09-15T01:07:56Z | 1,424,656 | 28 | 2009-09-15T01:18:13Z | [
"python",
"floating-point",
"zero",
"pad"
] | I want to pad some percentage values so that there are always 3 units before the decimal place. With ints I could use '%03d' - is there an equivalent for floats?
'%.3f' works for after the decimal place but '%03f' does nothing. | '%03.1f' works (1 could be any number, or empty string):
```
>>> "%06.2f"%3.3
'003.30'
>>> "%04.f"%3.2
'0003'
```
Note that the field width includes the decimal and fractional digits. |
Reverse engineer SQLAlchemy declarative class definition from existing MySQL database? | 1,425,412 | 20 | 2009-09-15T06:09:40Z | 1,426,387 | 27 | 2009-09-15T10:42:34Z | [
"python",
"mysql",
"sqlalchemy"
] | I have a pre-existing mysql database containing around 50 tables.
Rather than hand code a declarative style SqlAlchemy class ([as shown here](http://www.sqlalchemy.org/docs/05/ormtutorial.html#creating-table-class-and-mapper-all-at-once-declaratively)) for each table, is there a tool/script/command I can run against t... | use [sqlautocode](http://code.google.com/p/sqlautocode/):
It is a flexible tool to autogenerate a model from an existing database.
This is a slightly different approach to [SqlSoup](http://www.sqlalchemy.org/trac/wiki/SqlSoup), which lets you use tables without explicitly defining them. On the other hand, sqlalutocod... |
Convert hex to binary | 1,425,493 | 49 | 2009-09-15T06:41:37Z | 1,425,500 | 35 | 2009-09-15T06:45:15Z | [
"python",
"string",
"binary",
"hex",
"string-formatting"
] | I have ABC123EFFF.
I want to have 001010101111000001001000111110111111111111 (i.e. binary repr. with, say, 42 digits and leading zeroes).
How? | ```
import binascii
binary_string = binascii.unhexlify(hex_string)
```
Read
[binascii.unhexlify](http://docs.python.org/library/binascii.html#binascii.unhexlify)
Return the binary data represented by the hexadecimal string specified as the parameter. |
Convert hex to binary | 1,425,493 | 49 | 2009-09-15T06:41:37Z | 1,425,558 | 26 | 2009-09-15T06:59:24Z | [
"python",
"string",
"binary",
"hex",
"string-formatting"
] | I have ABC123EFFF.
I want to have 001010101111000001001000111110111111111111 (i.e. binary repr. with, say, 42 digits and leading zeroes).
How? | ```
bin(int("abc123efff", 16))[2:]
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.