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
Skipping Iterations in Python
549,674
42
2009-02-14T19:48:04Z
549,682
94
2009-02-14T19:50:46Z
[ "python", "iteration", "skip" ]
I have a loop going, but there is the possibility for exceptions to be raised inside the loop. This of course would stop my program all together. To prevent that I catch the exceptions and handle them. But then the rest of the iteration runs even though an exception occurred. Is there a keyword to use in my `except:` clause to just skip the rest of the current iteration?
You are lookin for [continue](http://docs.python.org/tutorial/controlflow.html).
Skipping Iterations in Python
549,674
42
2009-02-14T19:48:04Z
549,688
26
2009-02-14T19:52:29Z
[ "python", "iteration", "skip" ]
I have a loop going, but there is the possibility for exceptions to be raised inside the loop. This of course would stop my program all together. To prevent that I catch the exceptions and handle them. But then the rest of the iteration runs even though an exception occurred. Is there a keyword to use in my `except:` clause to just skip the rest of the current iteration?
``` for i in iterator: try: # Do something. pass except: # Continue to next iteration. continue ```
Fully transparent windows in Pygame?
550,001
4
2009-02-14T23:40:50Z
550,007
7
2009-02-14T23:48:12Z
[ "python", "graphics", "sdl", "pygame" ]
Is it possible to get a fully transparent window in Pygame (see the desktop through it)? I've found how to create a window without a frame, but there doesn't seem to be any obvious way to make it transparent. I'd be willing to tie into system-specific technology/frameworks as long as there are solutions for both Windows and Mac OS X, but I'm not sure which direction to be looking. The only topic I was able to find [recommended using wxPython](http://stackoverflow.com/questions/396791/desktop-graphics-or-skinned-windows), which isn't something I can do for this particular project (needs to be Pygame).
PyGame uses SDL, which does not support transparent windows. Although at least on Linux making it transparent is done by the window manager, not the application.
Parsing "From" addresses from email text
550,009
9
2009-02-14T23:49:22Z
550,036
31
2009-02-15T00:15:07Z
[ "python", "string", "email", "parsing", "text" ]
I'm trying to extract email addresses from plain text transcripts of emails. I've cobbled together a bit of code to find the addresses themselves, but I don't know how to make it discriminate between them; right now it just spits out all email addresses in the file. I'd like to make it so it only spits out addresses that are preceeded by "From:" and a few wildcard characters, and ending with ">" (because the emails are set up as From [name]<[email]>). Here's the code now: ``` import re #allows program to use regular expressions foundemail = [] #this is an empty list mailsrch = re.compile(r'[\w\-][\w\-\.]+@[\w\-][\w\-\.]+[a-zA-Z]{1,4}') #do not currently know exact meaning of this expression but assuming #it means something like "[stuff]@[stuff][stuff1-4 letters]" # "line" is a variable is set to a single line read from the file # ("text.txt"): for line in open("text.txt"): foundemail.extend(mailsrch.findall(line)) # this extends the previously named list via the "mailsrch" variable #which was named before print foundemail ```
Try this out: ``` >>> from email.utils import parseaddr >>> parseaddr('From: [email protected]') ('', '[email protected]') >>> parseaddr('From: Van Gale <[email protected]>') ('Van Gale', '[email protected]') >>> parseaddr(' From: Van Gale <[email protected]> ') ('Van Gale', '[email protected]') >>> parseaddr('blah abdf From: Van Gale <[email protected]> and this') ('Van Gale', '[email protected]') ``` Unfortunately it only finds the first email in each line because it's expecting header lines, but maybe that's ok?
Parsing "From" addresses from email text
550,009
9
2009-02-14T23:49:22Z
550,105
8
2009-02-15T01:14:59Z
[ "python", "string", "email", "parsing", "text" ]
I'm trying to extract email addresses from plain text transcripts of emails. I've cobbled together a bit of code to find the addresses themselves, but I don't know how to make it discriminate between them; right now it just spits out all email addresses in the file. I'd like to make it so it only spits out addresses that are preceeded by "From:" and a few wildcard characters, and ending with ">" (because the emails are set up as From [name]<[email]>). Here's the code now: ``` import re #allows program to use regular expressions foundemail = [] #this is an empty list mailsrch = re.compile(r'[\w\-][\w\-\.]+@[\w\-][\w\-\.]+[a-zA-Z]{1,4}') #do not currently know exact meaning of this expression but assuming #it means something like "[stuff]@[stuff][stuff1-4 letters]" # "line" is a variable is set to a single line read from the file # ("text.txt"): for line in open("text.txt"): foundemail.extend(mailsrch.findall(line)) # this extends the previously named list via the "mailsrch" variable #which was named before print foundemail ```
``` import email msg = email.message_from_string(str) # or # f = open(file) # msg = email.message_from_file(f) msg['from'] # and optionally from email.utils import parseaddr addr = parseaddr(msg['from']) ```
What causes Python socket error?
550,032
10
2009-02-15T00:12:53Z
550,034
20
2009-02-15T00:14:39Z
[ "python", "sockets", "permissions" ]
``` File "C:\Python25\lib\SocketServer.py", line 330, in __init__ self.server_bind() File "C:\Python25\lib\BaseHTTPServer.py", line 101, in server_bind SocketServer.TCPServer.server_bind(self) File "C:\Python25\lib\SocketServer.py", line 341, in server_bind self.socket.bind(self.server_address) File "<string>", line 1, in bind socket.error: (10013, 'Permission denied') ``` I tried to start up the Google App Engine development server and received this error the first time I tried to run it. Any ideas? I'm new to python.
It might be possible that you are trying to run on a port the current user account does not have permission to bind to. This could be port 80 or something. Try increasing the portnumber or use a user with sufficient privileges. Hope this helps
Removing the TK icon on a Tkinter window
550,050
16
2009-02-15T00:27:10Z
754,736
30
2009-04-16T04:11:48Z
[ "python", "python-3.x", "tkinter", "tk" ]
Does anybody know how to make the icon not show up? I'm looking for a way to have no icon at all.
### On Windows **Step One:** Create a transparent icon using either an icon editor, or a site like [rw-designer](http://www.rw-designer.com/online_icon_maker.php). Save it as `transparent.ico`. **Step Two:** ``` from tkinter import * tk = Tk() tk.iconbitmap(default='transparent.ico') lab = Label(tk, text='Window with transparent icon.') lab.pack() tk.mainloop() ``` ### On Unix Something similar, but using an `xbm` icon.
Does python have something like C++'s using keyword?
550,148
6
2009-02-15T01:50:34Z
550,161
17
2009-02-15T01:58:04Z
[ "python", "namespaces", "using" ]
In C++ you can often drastically improve the readability of your code by careful usage of the "using" keyword, for example: ``` void foo() { std::vector< std::map <int, std::string> > crazyVector; std::cout << crazyVector[0].begin()->first; } ``` becomes ``` void foo() { using namespace std; // limited in scope to foo vector< map <int, string> > crazyVector; cout << crazyVector[0].begin()->first; } ``` Does something similar exist for python, or do I have to fully qualify everything? I'll add the disclaimer that I know that using has its pitfalls and it should be appropriately limited in scope.
As Bill said, Python does have the construction ``` from X import * ``` but you can also explicitly specify which names you want imported from the module (namespace): ``` from X import foo, bar, blah ``` This tends to make the code even more readable/easier to understand, since someone seeing an identifier in the source doesn't need to hunt through all imported modules to see where it comes from. Here's a related question: <http://stackoverflow.com/questions/539578/namespace-specification-in-absence-of-ambuguity> *EDIT*: in response to Pax's comment, I'll mention that you can also write things like ``` import X.foo ``` but then you'll need to write ``` X.foo.moo() ``` instead of just ``` foo.moo() ``` This is not necessarily a bad thing, of course. I usually use a mixture of the `from X import y` and `import X.y` forms, whatever I feel makes my code clearest. It's certainly a subjective thing to some extent.
overload print python
550,470
26
2009-02-15T07:26:05Z
550,488
26
2009-02-15T07:37:01Z
[ "python", "printing", "overloading" ]
Am i able to overload the print function? and call the normal function? What i want to do is after a specific line i want print to call my print which will call the normal print and write a copy to file. Also i dont know how to overload print. I dont know how to do variable length arguments. i'll look it up soon but <http://stackoverflow.com/questions/550470/overload-print-python/550477#550477> just told me i cant overload print in 2.x which is what i am using.
Overloading `print` is a design feature of python 3.0 to address your lack of ability to do so in python 2.x. However, you can override sys.stdout. ([example](http://code.activestate.com/recipes/119404/).) Just assign it to another file-like object that does what you want. Alternatively, you could just pipe your script through the the unix `tee` command. `python yourscript.py | tee output.txt` will print to both stdout and to output.txt, but this will capture all output.
overload print python
550,470
26
2009-02-15T07:26:05Z
688,816
9
2009-03-27T07:22:31Z
[ "python", "printing", "overloading" ]
Am i able to overload the print function? and call the normal function? What i want to do is after a specific line i want print to call my print which will call the normal print and write a copy to file. Also i dont know how to overload print. I dont know how to do variable length arguments. i'll look it up soon but <http://stackoverflow.com/questions/550470/overload-print-python/550477#550477> just told me i cant overload print in 2.x which is what i am using.
I came across the same problem. How about this: ``` class writer : def __init__(self, *writers) : self.writers = writers def write(self, text) : for w in self.writers : w.write(text) import sys saved = sys.stdout fout = file('out.log', 'w') sys.stdout = writer(sys.stdout, fout) print "There you go." sys.stdout = saved fout.close() ``` It worked like a charm for me. It was taken from <http://mail.python.org/pipermail/python-list/2003-February/188788.html>
overload print python
550,470
26
2009-02-15T07:26:05Z
10,106,489
32
2012-04-11T13:06:25Z
[ "python", "printing", "overloading" ]
Am i able to overload the print function? and call the normal function? What i want to do is after a specific line i want print to call my print which will call the normal print and write a copy to file. Also i dont know how to overload print. I dont know how to do variable length arguments. i'll look it up soon but <http://stackoverflow.com/questions/550470/overload-print-python/550477#550477> just told me i cant overload print in 2.x which is what i am using.
For those reviewing the previously dated answers, as of version release "Python 2.6" there is a new answer to the original poster's question. In Python 2.6 and up, you can disable the print statement in favor of the print function, and then override the print function with your own print function: ``` from __future__ import print_function # This must be the first statement before other statements. # You may only put a quoted or triple quoted string, # Python comments, other future statements, or blank lines before the __future__ line. try: import __builtin__ except ImportError: # Python 3 import builtins as __builtin__ def print(*args, **kwargs): """My custom print() function.""" # Adding new arguments to the print function signature # is probably a bad idea. # Instead consider testing if custom argument keywords # are present in kwargs __builtin__.print('My overridden print() function!') return __builtin__.print(*args, **kwargs) ``` Of course you'll need to consider that this print function is only module wide at this point. You could choose to override `__builtin__.print`, but you'll need to save the original `__builtin__.print`; likely mucking with the `__builtin__` namespace.
Favorite Django Tips & Features?
550,632
309
2009-02-15T10:06:22Z
550,644
222
2009-02-15T10:15:52Z
[ "python", "django", "hidden-features" ]
Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of. * Please, include only one tip per answer. * Add Django version requirements if there are any.
I'm just going to start with a tip from myself :) **Use os.path.dirname() in settings.py to avoid hardcoded dirnames.** Don't hardcode path's in your settings.py if you want to run your project in different locations. Use the following code in settings.py if your templates and static files are located within the Django project directory: ``` # settings.py import os PROJECT_DIR = os.path.dirname(__file__) ... STATIC_DOC_ROOT = os.path.join(PROJECT_DIR, "static") ... TEMPLATE_DIRS = ( os.path.join(PROJECT_DIR, "templates"), ) ``` Credits: I got this tip from the screencast '[Django From the Ground Up](http://thisweekindjango.com/screencasts/episode/10/django-ground-episodes-1-and-2/)'.
Favorite Django Tips & Features?
550,632
309
2009-02-15T10:06:22Z
551,114
119
2009-02-15T16:06:32Z
[ "python", "django", "hidden-features" ]
Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of. * Please, include only one tip per answer. * Add Django version requirements if there are any.
Use [django-annoying's](http://bitbucket.org/offline/django-annoying/wiki/Home) `render_to` decorator instead of `render_to_response`. ``` @render_to('template.html') def foo(request): bars = Bar.objects.all() if request.user.is_authenticated(): return HttpResponseRedirect("/some/url/") else: return {'bars': bars} # equals to def foo(request): bars = Bar.objects.all() if request.user.is_authenticated(): return HttpResponseRedirect("/some/url/") else: return render_to_response('template.html', {'bars': bars}, context_instance=RequestContext(request)) ``` Edited to point out that returning an HttpResponse (such as a redirect) will short circuit the decorator and work just as you expect.
Favorite Django Tips & Features?
550,632
309
2009-02-15T10:06:22Z
551,139
37
2009-02-15T16:20:26Z
[ "python", "django", "hidden-features" ]
Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of. * Please, include only one tip per answer. * Add Django version requirements if there are any.
I like to use the Python debugger pdb to debug Django projects. This is a helpful link for learning how to use it: <http://www.ferg.org/papers/debugging_in_python.html>
Favorite Django Tips & Features?
550,632
309
2009-02-15T10:06:22Z
551,158
35
2009-02-15T16:30:50Z
[ "python", "django", "hidden-features" ]
Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of. * Please, include only one tip per answer. * Add Django version requirements if there are any.
Use [Jinja2](http://jinja.pocoo.org/2/) alongside Django. If you find the Django template language extremely restricting (like me!) then you don't have to be stuck with it. Django is flexible, and the template language is loosely coupled to the rest of the system, so just plug-in another template language and use it to render your http responses! I use [Jinja2](http://jinja.pocoo.org/2/), it's almost like a powered-up version of the django template language, it uses the same syntax, and allows you to use expressions in if statements! no more making a custom if-tags such as `if_item_in_list`! you can simply say `%{ if item in list %}`, or `{% if object.field < 10 %}`. But that's not all; it has many more features to ease template creation, that I can't go though all of them in here.
Favorite Django Tips & Features?
550,632
309
2009-02-15T10:06:22Z
551,499
35
2009-02-15T20:06:58Z
[ "python", "django", "hidden-features" ]
Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of. * Please, include only one tip per answer. * Add Django version requirements if there are any.
Add `assert False` in your view code to dump debug information.
Favorite Django Tips & Features?
550,632
309
2009-02-15T10:06:22Z
551,615
130
2009-02-15T21:18:14Z
[ "python", "django", "hidden-features" ]
Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of. * Please, include only one tip per answer. * Add Django version requirements if there are any.
Install [Django Command Extensions](http://code.google.com/p/django-command-extensions) and [pygraphviz](http://networkx.lanl.gov/pygraphviz/) and then issue the following command to get a really nice looking Django model visualization: ``` ./manage.py graph_models -a -g -o my_project.png ```
Favorite Django Tips & Features?
550,632
309
2009-02-15T10:06:22Z
558,401
88
2009-02-17T19:34:58Z
[ "python", "django", "hidden-features" ]
Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of. * Please, include only one tip per answer. * Add Django version requirements if there are any.
Don't hard-code your URLs! Use [url names](http://docs.djangoproject.com/en/dev/topics/http/urls/#id2) instead, and the [`reverse`](http://docs.djangoproject.com/en/dev/topics/http/urls/#reverse) function to get the URL itself. When you define your URL mappings, give names to your URLs. ``` urlpatterns += ('project.application.views' url( r'^something/$', 'view_function', name="url-name" ), .... ) ``` Make sure the name is unique per URL. I usually have a consistent format "project-appplication-view", e.g. "cbx-forum-thread" for a thread view. **UPDATE** (shamelessly stealing [ayaz's addition](http://stackoverflow.com/questions/550632/favorite-django-tips-features/560111#560111)): This name can be used in templates with the [`url` tag](http://docs.djangoproject.com/en/dev/ref/templates/builtins/#url).
Favorite Django Tips & Features?
550,632
309
2009-02-15T10:06:22Z
559,972
80
2009-02-18T05:37:30Z
[ "python", "django", "hidden-features" ]
Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of. * Please, include only one tip per answer. * Add Django version requirements if there are any.
Don't write your own login pages. If you're using django.contrib.auth. The real, dirty secret is that if you're also using django.contrib.admin, and django.template.loaders.app\_directories.load\_template\_source is in your template loaders, **you can get your templates free too!** ``` # somewhere in urls.py urlpatterns += patterns('django.contrib.auth', (r'^accounts/login/$','views.login', {'template_name': 'admin/login.html'}), (r'^accounts/logout/$','views.logout'), ) ```
Favorite Django Tips & Features?
550,632
309
2009-02-15T10:06:22Z
560,064
16
2009-02-18T06:44:49Z
[ "python", "django", "hidden-features" ]
Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of. * Please, include only one tip per answer. * Add Django version requirements if there are any.
[django.views.generic.list\_detail.object\_list](http://docs.djangoproject.com/en/dev/ref/generic-views/?from=olddocs#django-views-generic-list-detail-object-list) -- It provides all the logic & template variables for pagination (one of those I've-written-that-a-thousand-times-now drudgeries). [Wrapping it](http://www.djangobook.com/en/2.0/chapter11/) allows for any logic you need. This gem has saved me many hours of debugging off-by-one errors in my "Search Results" pages and makes the view code cleaner in the process.
Favorite Django Tips & Features?
550,632
309
2009-02-15T10:06:22Z
560,111
33
2009-02-18T07:07:30Z
[ "python", "django", "hidden-features" ]
Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of. * Please, include only one tip per answer. * Add Django version requirements if there are any.
This adds to the reply above about [Django URL names and reverse URL dispatching](http://stackoverflow.com/questions/550632/favorite-django-tips-features/558401#558401). The URL names can also be effectively used within templates. For example, for a given URL pattern: ``` url(r'(?P<project_id>\d+)/team/$', 'project_team', name='project_team') ``` you can have the following in templates: ``` <a href="{% url project_team project.id %}">Team</a> ```
Favorite Django Tips & Features?
550,632
309
2009-02-15T10:06:22Z
562,998
57
2009-02-18T21:54:03Z
[ "python", "django", "hidden-features" ]
Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of. * Please, include only one tip per answer. * Add Django version requirements if there are any.
When I was starting out, I didn't know that there was a [Paginator](http://docs.djangoproject.com/en/dev/topics/pagination/#topics-pagination), make sure you know of its existence!!
Favorite Django Tips & Features?
550,632
309
2009-02-15T10:06:22Z
709,180
37
2009-04-02T10:30:16Z
[ "python", "django", "hidden-features" ]
Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of. * Please, include only one tip per answer. * Add Django version requirements if there are any.
When trying to exchange data between Django and another application, `request.raw_post_data` is a good friend. Use it to receive and custom-process, say, XML data. Documentation: <http://docs.djangoproject.com/en/dev/ref/request-response/>
Favorite Django Tips & Features?
550,632
309
2009-02-15T10:06:22Z
864,898
19
2009-05-14T18:19:48Z
[ "python", "django", "hidden-features" ]
Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of. * Please, include only one tip per answer. * Add Django version requirements if there are any.
`django.db.models.get_model` does allow you to retrieve a model without importing it. James shows how handy it can be: ["Django tips: Write better template tags — Iteration 4 "](http://www.b-list.org/weblog/2006/jun/07/django-tips-write-better-template-tags/).
Favorite Django Tips & Features?
550,632
309
2009-02-15T10:06:22Z
942,426
19
2009-06-02T23:32:21Z
[ "python", "django", "hidden-features" ]
Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of. * Please, include only one tip per answer. * Add Django version requirements if there are any.
The [webdesign app](http://docs.djangoproject.com/en/dev/ref/contrib/webdesign/#ref-contrib-webdesign) is very useful when starting to design your website. Once imported, you can add this to generate sample text: ``` {% load webdesign %} {% lorem 5 p %} ```
Favorite Django Tips & Features?
550,632
309
2009-02-15T10:06:22Z
946,397
103
2009-06-03T18:34:02Z
[ "python", "django", "hidden-features" ]
Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of. * Please, include only one tip per answer. * Add Django version requirements if there are any.
There's a set of custom tags I use all over my site's templates. Looking for a way to autoload it (DRY, remember?), I found the following: ``` from django import template template.add_to_builtins('project.app.templatetags.custom_tag_module') ``` If you put this in a module that's loaded by default (your main urlconf for instance), you'll have the tags and filters from your custom tag module available in any template, without using `{% load custom_tag_module %}`. The argument passed to `template.add_to_builtins()` can be any module path; your custom tag module doesn't have to live in a specific application. For example, it can also be a module in your project's root directory (eg. `'project.custom_tag_module'`).
Favorite Django Tips & Features?
550,632
309
2009-02-15T10:06:22Z
946,443
97
2009-06-03T18:44:29Z
[ "python", "django", "hidden-features" ]
Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of. * Please, include only one tip per answer. * Add Django version requirements if there are any.
[Virtualenv](http://pypi.python.org/pypi/virtualenv#what-it-does) + Python = life saver if you are working on multiple Django projects and there is a possibility that they all don't depend on the same version of Django/an application.
Favorite Django Tips & Features?
550,632
309
2009-02-15T10:06:22Z
946,497
82
2009-06-03T18:53:46Z
[ "python", "django", "hidden-features" ]
Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of. * Please, include only one tip per answer. * Add Django version requirements if there are any.
Use [django debug toolbar](http://github.com/robhudson/django-debug-toolbar/). For example, it allows to view all SQL queries performed while rendering view and you can also view stacktrace for any of them.
Favorite Django Tips & Features?
550,632
309
2009-02-15T10:06:22Z
1,018,895
20
2009-06-19T16:35:18Z
[ "python", "django", "hidden-features" ]
Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of. * Please, include only one tip per answer. * Add Django version requirements if there are any.
I don't have enough reputation to reply to the comment in question, but it's important to note that if you're going to use [Jinja](http://en.wikipedia.org/wiki/Jinja%5F%28template%5Fengine%29), it does NOT support the '-' character in template block names, while Django does. This caused me a lot of problems and wasted time trying to track down the very obscure error message it generated.
Favorite Django Tips & Features?
550,632
309
2009-02-15T10:06:22Z
1,057,512
13
2009-06-29T10:01:07Z
[ "python", "django", "hidden-features" ]
Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of. * Please, include only one tip per answer. * Add Django version requirements if there are any.
Just found this link: <http://lincolnloop.com/django-best-practices/#table-of-contents> - "Django Best Practices".
Favorite Django Tips & Features?
550,632
309
2009-02-15T10:06:22Z
1,067,267
41
2009-07-01T04:27:35Z
[ "python", "django", "hidden-features" ]
Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of. * Please, include only one tip per answer. * Add Django version requirements if there are any.
From the [django-admin documentation](http://docs.djangoproject.com/en/dev/ref/django-admin/): If you use the Bash shell, consider installing the Django bash completion script, which lives in `extras/django_bash_completion` in the Django distribution. It enables tab-completion of `django-admin.py` and `manage.py` commands, so you can, for instance... * Type `django-admin.py`. * Press [TAB] to see all available options. * Type `sql`, then [TAB], to see all available options whose names start with `sql`.
Favorite Django Tips & Features?
550,632
309
2009-02-15T10:06:22Z
1,300,107
67
2009-08-19T13:53:50Z
[ "python", "django", "hidden-features" ]
Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of. * Please, include only one tip per answer. * Add Django version requirements if there are any.
## Context processors are awesome. Say you have a different user model and you want to include that in every response. Instead of doing this: ``` def myview(request, arg, arg2=None, template='my/template.html'): ''' My view... ''' response = dict() myuser = MyUser.objects.get(user=request.user) response['my_user'] = myuser ... return render_to_response(template, response, context_instance=RequestContext(request)) ``` Context processes give you the ability to pass any variable to your templates. I typically put mine in `'my_project/apps/core/context.py`: ``` def my_context(request): try: return dict(my_user=MyUser.objects.get(user=request.user)) except ObjectNotFound: return dict(my_user='') ``` In your `settings.py` add the following line to your `TEMPLATE_CONTEXT_PROCESSORS` ``` TEMPLATE_CONTEXT_PROCESSORS = ( 'my_project.apps.core.context.my_context', ... ) ``` Now every time a request is made it includes the `my_user` key automatically. ## Also [signals](http://docs.djangoproject.com/en/dev/topics/signals/ "Django Signals") win. I wrote a blog post about this a few months ago so I'm just going to cut and paste: Out of the box Django gives you several signals that are incredibly useful. You have the ability to do things pre and post save, init, delete, or even when a request is being processed. So lets get away from the concepts and demonstrate how these are used. Say we’ve got a blog ``` from django.utils.translation import ugettext_lazy as _ class Post(models.Model): title = models.CharField(_('title'), max_length=255) body = models.TextField(_('body')) created = models.DateTimeField(auto_now_add=True) ``` So somehow you want to notify one of the many blog-pinging services we’ve made a new post, rebuild the most recent posts cache, and tweet about it. Well with signals you have the ability to do all of this without having to add any methods to the Post class. ``` import twitter from django.core.cache import cache from django.db.models.signals import post_save from django.conf import settings def posted_blog(sender, created=None, instance=None, **kwargs): ''' Listens for a blog post to save and alerts some services. ''' if (created and instance is not None): tweet = 'New blog post! %s' instance.title t = twitter.PostUpdate(settings.TWITTER_USER, settings.TWITTER_PASSWD, tweet) cache.set(instance.cache_key, instance, 60*5) # send pingbacks # ... # whatever else else: cache.delete(instance.cache_key) post_save.connect(posted_blog, sender=Post) ``` There we go, by defining that function and using the post\_init signal to connect the function to the Post model and execute it after it has been saved.
Favorite Django Tips & Features?
550,632
309
2009-02-15T10:06:22Z
1,346,574
18
2009-08-28T11:59:46Z
[ "python", "django", "hidden-features" ]
Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of. * Please, include only one tip per answer. * Add Django version requirements if there are any.
I learned this one from the documentation for the [sorl-thumbnails](http://code.google.com/p/sorl-thumbnail/) app. You can use the "as" keyword in template tags to use the results of the call elsewhere in your template. For example: ``` {% url image-processor uid as img_src %} <img src="{% thumbnail img_src 100x100 %}"/> ``` This is mentioned in passing in the Django templatetag documentation, but in reference to loops only. They don't call out that you can use this elsewhere (anywhere?) as well.
Favorite Django Tips & Features?
550,632
309
2009-02-15T10:06:22Z
1,359,196
27
2009-08-31T20:12:58Z
[ "python", "django", "hidden-features" ]
Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of. * Please, include only one tip per answer. * Add Django version requirements if there are any.
Since Django "views" only need to be callables that return an HttpResponse, you can easily create class-based views like those in Ruby on Rails and other frameworks. There are several ways to create class-based views, here's my favorite: ``` from django import http class RestView(object): methods = ('GET', 'HEAD') @classmethod def dispatch(cls, request, *args, **kwargs): resource = cls() if request.method.lower() not in (method.lower() for method in resource.methods): return http.HttpResponseNotAllowed(resource.methods) try: method = getattr(resource, request.method.lower()) except AttributeError: raise Exception("View method `%s` does not exist." % request.method.lower()) if not callable(method): raise Exception("View method `%s` is not callable." % request.method.lower()) return method(request, *args, **kwargs) def get(self, request, *args, **kwargs): return http.HttpResponse() def head(self, request, *args, **kwargs): response = self.get(request, *args, **kwargs) response.content = '' return response ``` You can add all sorts of other stuff like conditional request handling and authorization in your base view. Once you've got your views setup your urls.py will look something like this: ``` from django.conf.urls.defaults import * from views import MyRestView urlpatterns = patterns('', (r'^restview/', MyRestView.dispatch), ) ```
Favorite Django Tips & Features?
550,632
309
2009-02-15T10:06:22Z
1,407,331
11
2009-09-10T19:46:16Z
[ "python", "django", "hidden-features" ]
Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of. * Please, include only one tip per answer. * Add Django version requirements if there are any.
Use [signals](http://docs.djangoproject.com/en/dev/topics/signals/) to add accessor-methods on-the-fly. I saw this technique in [django-photologue](http://code.google.com/p/django-photologue): For any Size object added, the post\_init signal will add the corresponding methods to the Image model. If you add a site *giant*, the methods to retrieve the picture in giant resolution will be `image.get_giant_url()`. The methods are generated by calling `add_accessor_methods` from the `post_init` signal: ``` def add_accessor_methods(self, *args, **kwargs): for size in PhotoSizeCache().sizes.keys(): setattr(self, 'get_%s_size' % size, curry(self._get_SIZE_size, size=size)) setattr(self, 'get_%s_photosize' % size, curry(self._get_SIZE_photosize, size=size)) setattr(self, 'get_%s_url' % size, curry(self._get_SIZE_url, size=size)) setattr(self, 'get_%s_filename' % size, curry(self._get_SIZE_filename, size=size)) ``` See the [source code of photologue.models](http://code.google.com/p/django-photologue/source/browse/trunk/photologue/models.py) for real-world usage.
Favorite Django Tips & Features?
550,632
309
2009-02-15T10:06:22Z
1,735,782
22
2009-11-14T22:15:03Z
[ "python", "django", "hidden-features" ]
Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of. * Please, include only one tip per answer. * Add Django version requirements if there are any.
Instead of using `render_to_response` to bind your context to a template and render it (which is what the Django docs usually show) use the generic view [`direct_to_template`](http://docs.djangoproject.com/en/dev/ref/generic-views/#django-views-generic-simple-direct-to-template). It does the same thing that `render_to_response` does but it also automatically adds RequestContext to the template context, implicitly allowing context processors to be used. You can do this manually using `render_to_response`, but why bother? It's just another step to remember and another LOC. Besides making use of context processors, having RequestContext in your template allows you to do things like: ``` <a href="{{MEDIA_URL}}images/frog.jpg">A frog</a> ``` which is very useful. In fact, +1 on generic views in general. The Django docs mostly show them as shortcuts for not even having a views.py file for simple apps, but you can also use them inside your own view functions: ``` from django.views.generic import simple def article_detail(request, slug=None): article = get_object_or_404(Article, slug=slug) return simple.direct_to_template(request, template="articles/article_detail.html", extra_context={'article': article} ) ```
Favorite Django Tips & Features?
550,632
309
2009-02-15T10:06:22Z
1,774,722
9
2009-11-21T06:29:49Z
[ "python", "django", "hidden-features" ]
Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of. * Please, include only one tip per answer. * Add Django version requirements if there are any.
Instead of running the Django dev server on localhost, run it on a proper network interface. For example: ``` python manage.py runserver 192.168.1.110:8000 ``` or ``` python manage.py runserver 0.0.0.0:8000 ``` Then you can not only easily use Fiddler (<http://www.fiddler2.com/fiddler2/>) or another tool like HTTP Debugger (<http://www.httpdebugger.com/>) to inspect your HTTP headers, but you can also access your dev site from other machines on your LAN to test. Make sure you are protected by a firewall though, although the dev server is minimal and relatively safe.
Favorite Django Tips & Features?
550,632
309
2009-02-15T10:06:22Z
1,837,525
47
2009-12-03T03:55:57Z
[ "python", "django", "hidden-features" ]
Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of. * Please, include only one tip per answer. * Add Django version requirements if there are any.
Use [IPython](http://ipython.scipy.org/moin/) to jump into your code at any level and debug using the power of IPython. Once you have installed IPython just put this code in wherever you want to debug: ``` from IPython.Shell import IPShellEmbed; IPShellEmbed()() ``` Then, refresh the page, go to your runserver window and you will be in an interactive IPython window. I have a snippet set up in TextMate so I just type ipshell and hit tab. I couldn't live without it.
Favorite Django Tips & Features?
550,632
309
2009-02-15T10:06:22Z
2,093,549
19
2010-01-19T12:57:39Z
[ "python", "django", "hidden-features" ]
Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of. * Please, include only one tip per answer. * Add Django version requirements if there are any.
Everybody knows there is a development server you can run with "manage.py runserver", but did you know that there is a development view for serving static files (CSS / JS / IMG) as well ? Newcomers are always puzzled because Django doesn't come with any way to serve static files. This is because the dev team think it is the job for a real life Web server. But when developing, you may not want to set up Apache + mod\_wisgi, it's heavy. Then you can just add the following to urls.py: ``` (r'^site_media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '/path/to/media'}), ``` Your CSS / JS / IMG will be available at www.yoursite.com/site\_media/. Of course, don't use it in a production environment.
Favorite Django Tips & Features?
550,632
309
2009-02-15T10:06:22Z
2,260,327
43
2010-02-14T06:26:28Z
[ "python", "django", "hidden-features" ]
Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of. * Please, include only one tip per answer. * Add Django version requirements if there are any.
Run a development SMTP server that will just output whatever is sent to it (if you don't want to actually install SMTP on your dev server.) command line: ``` python -m smtpd -n -c DebuggingServer localhost:1025 ```
Favorite Django Tips & Features?
550,632
309
2009-02-15T10:06:22Z
2,740,163
7
2010-04-29T19:22:46Z
[ "python", "django", "hidden-features" ]
Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of. * Please, include only one tip per answer. * Add Django version requirements if there are any.
Use `wraps` decorator in custom views decorators to preserve view's name, module and docstring. E.g. ``` try: from functools import wraps except ImportError: from django.utils.functional import wraps # Python 2.3, 2.4 fallback. def view_decorator(fun): @wraps(fun) def wrapper(): # here goes your decorator's code return wrapper ``` **Beware**: will not work on a class-based views (those with `__call__` method definition), if the author hasn't defined a `__name__` property. As a workaround use: ``` from django.utils.decorators import available_attrs ... @wraps(fun, assigned=available_attrs(fun)) ```
Favorite Django Tips & Features?
550,632
309
2009-02-15T10:06:22Z
2,830,887
16
2010-05-13T23:04:24Z
[ "python", "django", "hidden-features" ]
Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of. * Please, include only one tip per answer. * Add Django version requirements if there are any.
[PyCharm IDE](http://www.jetbrains.com/pycharm/) is a nice environment to code and especially debug, with built-in support for Django.
Favorite Django Tips & Features?
550,632
309
2009-02-15T10:06:22Z
2,832,479
7
2010-05-14T07:23:52Z
[ "python", "django", "hidden-features" ]
Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of. * Please, include only one tip per answer. * Add Django version requirements if there are any.
The [Django Debug Toolbar](http://github.com/robhudson/django-debug-toolbar) is really fantastic. Not really a toolbar, it actually brings up a sidepane that tells you all sorts of information about what brought you the page you're looking at - DB queries, the context variables sent to the template, signals, and more.
Favorite Django Tips & Features?
550,632
309
2009-02-15T10:06:22Z
3,247,524
14
2010-07-14T15:06:49Z
[ "python", "django", "hidden-features" ]
Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of. * Please, include only one tip per answer. * Add Django version requirements if there are any.
Use [xml\_models](http://djangorestmodel.sourceforge.net/) to create Django models that use an XML REST API backend (instead of a SQL one). This is very useful especially when modelling third party APIs - you get all the same QuerySet syntax that you're used to. You can install it from PyPI. XML from an API: ``` <profile id=4> <email>[email protected]</email> <first_name>Joe</first_name> <last_name>Example</last_name> <date_of_birth>1975-05-15</date_of_birth> </profile> ``` And now in python: ``` class Profile(xml_models.Model): user_id = xml_models.IntField(xpath='/profile/@id') email = xml_models.CharField(xpath='/profile/email') first = xml_models.CharField(xpath='/profile/first_name') last = xml_models.CharField(xpath='/profile/last_name') birthday = xml_models.DateField(xpath='/profile/date_of_birth') finders = { (user_id,): settings.API_URL +'/api/v1/profile/userid/%s', (email,): settings.API_URL +'/api/v1/profile/email/%s', } profile = Profile.objects.get(user_id=4) print profile.email # would print '[email protected]' ``` It can also handle relationships and collections. We use it every day in heavily used production code, so even though it's beta it's very usable. It also has a good set of stubs that you can use in your tests. (Disclaimer: while I'm not the author of this library, I am now a committer, having made a few minor commits)
Favorite Django Tips & Features?
550,632
309
2009-02-15T10:06:22Z
4,007,078
11
2010-10-24T03:41:54Z
[ "python", "django", "hidden-features" ]
Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of. * Please, include only one tip per answer. * Add Django version requirements if there are any.
# Remove Database Access Information from settings.py One thing I've done in my Django site's `settings.py` is load database access info from a file in `/etc`. This way the access setup (database host, port, username, password) can be different for each machine, and sensitive info like the password isn't in my project's repository. You might want to restrict access to the workers in a similar manner, by making them connect with a different username. You could also pass in the database connection information, or even just a key or path to a configuration file, via environment variables, and handle it in `settings.py`. For example, here's how I pull in my database configuration file: ``` g = {} dbSetup = {} execfile(os.environ['DB_CONFIG'], g, dbSetup) if 'databases' in dbSetup: DATABASES = dbSetup['databases'] else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', # ... } } ``` Needless to say, you need to make sure that the file in `DB_CONFIG` is not accessible to any user besides the db admins and Django itself. The default case should refer Django to a developer's own test database. There may also be a better solution using the `ast` module instead of `execfile`, but I haven't researched it yet. Another thing I do is use separate users for DB admin tasks vs. everything else. In my `manage.py`, I added the following preamble: ``` # Find a database configuration, if there is one, and set it in the environment. adminDBConfFile = '/etc/django/db_admin.py' dbConfFile = '/etc/django/db_regular.py' import sys import os def goodFile(path): return os.path.isfile(path) and os.access(path, os.R_OK) if len(sys.argv) >= 2 and sys.argv[1] in ["syncdb", "dbshell", "migrate"] \ and goodFile(adminDBConfFile): os.environ['DB_CONFIG'] = adminDBConfFile elif goodFile(dbConfFile): os.environ['DB_CONFIG'] = dbConfFile ``` Where the config in `/etc/django/db_regular.py` is for a user with access to only the Django database with SELECT, INSERT, UPDATE, and DELETE, and `/etc/django/db_admin.py` is for a user with these permissions plus CREATE, DROP, INDEX, ALTER, and LOCK TABLES. (The `migrate` command is from [South](http://south.aeracode.org/).) This gives me some protection from Django code messing with my schema at runtime, and it limits the damage an SQL injection attack can cause (though you should still check and filter all user input). (Copied from my answer to [another question](http://stackoverflow.com/questions/3884249/django-celery-database-for-models-on-producer-and-worker/3884535#3884535))
Favorite Django Tips & Features?
550,632
309
2009-02-15T10:06:22Z
4,861,267
40
2011-02-01T10:11:58Z
[ "python", "django", "hidden-features" ]
Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of. * Please, include only one tip per answer. * Add Django version requirements if there are any.
The `./manage.py runserver_plus` facilty which comes with [django\_extensions](http://code.google.com/p/django-command-extensions/) is truly awesome. It creates an enhanced debug page that, amongst other things, uses the Werkzeug debugger to create interactive debugging consoles for each point in the stack (see screenshot). It also provides a very useful convenience debugging method `dump()` for displaying information about an object/frame. ![enter image description here](http://i.stack.imgur.com/M6dJb.jpg) To install, you can use pip: ``` pip install django_extensions pip install Werkzeug ``` Then add `'django_extensions'` to your `INSTALLED_APPS` tuple in `settings.py` and start the development server with the new extension: ``` ./manage.py runserver_plus ``` This will change the way you debug.
Favorite Django Tips & Features?
550,632
309
2009-02-15T10:06:22Z
5,546,778
12
2011-04-05T03:12:34Z
[ "python", "django", "hidden-features" ]
Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of. * Please, include only one tip per answer. * Add Django version requirements if there are any.
Instead of evaluating whole queryset to check whether you got back any results, use .exists() in Django 1.2+ and .count() for previous versions. Both exists() and count() clears order by clauses and retrieves a single integer from DB. However exists() will always return 1 where as count may return higher values on which limits will be applied manually. Source for [has\_result](http://code.djangoproject.com/browser/django/trunk/django/db/models/sql/query.py#L412) used in exists() and [get\_count](http://code.djangoproject.com/browser/django/trunk/django/db/models/sql/query.py#L377) used in count() for the curious. Since they both return a single integer, there's no model instantiation, loading model attributes in memory and no large TextFields being passed between your DB and app. If you have already evaluated the query, .count() computes len(cached\_result) and .exists() computes bool(cached\_result) **Not efficient - Example 1** ``` books = Books.objects.filter(author__last_name='Brown') if books: # Do something ``` **Not efficient - Example 2** ``` books = Books.objects.filter(author__last_name='Brown') if len(books): # Do something ``` **Efficient - Example 1** ``` books = Books.objects.filter(author__last_name='Brown') if books.count(): # Do something ``` **Efficient - Example 2** ``` books = Books.objects.filter(author__last_name='Brown') if books.exists(): # Do something ```
Favorite Django Tips & Features?
550,632
309
2009-02-15T10:06:22Z
5,809,809
14
2011-04-27T19:59:16Z
[ "python", "django", "hidden-features" ]
Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of. * Please, include only one tip per answer. * Add Django version requirements if there are any.
Use database migrations. Use [South](http://south.aeracode.org).
Favorite Django Tips & Features?
550,632
309
2009-02-15T10:06:22Z
6,169,597
12
2011-05-29T18:31:22Z
[ "python", "django", "hidden-features" ]
Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of. * Please, include only one tip per answer. * Add Django version requirements if there are any.
If you make changes into model ``` ./manage.py dumpdata appname > appname_data.json ./manage.py reset appname django-admin.py loaddata appname_data.json ```
Cross-platform way to get PIDs by process name in python
550,653
36
2009-02-15T10:23:56Z
1,226,643
10
2009-08-04T10:00:18Z
[ "python", "cross-platform", "jython", "hp-ux" ]
Several processes with the same name are running on host. What is the cross-platform way to get PIDs of those processes by name using **python** or **jython**? 1. I want something like `pidof` but in python. (I don't have `pidof` anyway.) 2. I can't parse `/proc` because it might be unavailable (on HP-UX). 3. I do not want to run `os.popen('ps')` and parse the output because I think it is ugly (field sequence may be different in different OS). 4. Target platforms are Solaris, HP-UX, and maybe others.
There's no single cross-platform API, you'll have to check for OS. For posix based use /proc. For Windows use following code to get list of all pids with coresponding process names ``` from win32com.client import GetObject WMI = GetObject('winmgmts:') processes = WMI.InstancesOf('Win32_Process') process_list = [(p.Properties_("ProcessID").Value, p.Properties_("Name").Value) for p in processes] ``` You can then easily filter out processes you need. For more info on available properties of Win32\_Process check out [Win32\_Process Class](http://msdn.microsoft.com/en-us/library/aa394372%28VS.85%29.aspx)
Cross-platform way to get PIDs by process name in python
550,653
36
2009-02-15T10:23:56Z
2,241,047
45
2010-02-10T23:12:17Z
[ "python", "cross-platform", "jython", "hp-ux" ]
Several processes with the same name are running on host. What is the cross-platform way to get PIDs of those processes by name using **python** or **jython**? 1. I want something like `pidof` but in python. (I don't have `pidof` anyway.) 2. I can't parse `/proc` because it might be unavailable (on HP-UX). 3. I do not want to run `os.popen('ps')` and parse the output because I think it is ugly (field sequence may be different in different OS). 4. Target platforms are Solaris, HP-UX, and maybe others.
You can use psutil ( <https://github.com/giampaolo/psutil> ), which works on Windows and UNIX: ``` import psutil PROCNAME = "python.exe" for proc in psutil.process_iter(): if proc.name() == PROCNAME: print(proc) ``` The code above prints the following on my machine: ``` psutil.Process (PID:2908; PPID:3944; NAME:'python.exe'; PATH:'C:\Python26'; CMDL INE:['C:\\Python26\\python.exe', 'D:\\pyftpdlib\\svn\\psutil\\foo.py']; UID:-1; GID:-1;) ```
"Private" (implementation) class in Python
551,038
50
2009-02-15T15:29:40Z
551,048
89
2009-02-15T15:34:03Z
[ "python", "design", "access-modifiers" ]
I am coding a small Python module composed of two parts: * some functions defining a public interface, * an implementation class used by the above functions, but which is not meaningful outside the module. At first, I decided to "hide" this implementation class by defining it inside the function using it, but this hampers readability and cannot be used if multiple functions reuse the same class. So, in addition to comments and docstrings, is there a mechanism to mark a class as "private" or "internal"? I am aware of the underscore mechanism, but as I understand it it only applies to variables, function and methods name.
Use a single underscore prefix: ``` class _Internal: ... ``` This is the official Python convention for 'internal' symbols; "from module import \*" does not import underscore-prefixed objects.
"Private" (implementation) class in Python
551,038
50
2009-02-15T15:29:40Z
551,054
22
2009-02-15T15:36:03Z
[ "python", "design", "access-modifiers" ]
I am coding a small Python module composed of two parts: * some functions defining a public interface, * an implementation class used by the above functions, but which is not meaningful outside the module. At first, I decided to "hide" this implementation class by defining it inside the function using it, but this hampers readability and cannot be used if multiple functions reuse the same class. So, in addition to comments and docstrings, is there a mechanism to mark a class as "private" or "internal"? I am aware of the underscore mechanism, but as I understand it it only applies to variables, function and methods name.
Define `__all__`, a list of names that you want to be exported ([see documentation](http://docs.python.org/tutorial/modules.html#importing-from-a-package)). ``` __all__ = ['public_class'] # don't add here the 'implementation_class' ```
"Private" (implementation) class in Python
551,038
50
2009-02-15T15:29:40Z
551,097
8
2009-02-15T15:58:49Z
[ "python", "design", "access-modifiers" ]
I am coding a small Python module composed of two parts: * some functions defining a public interface, * an implementation class used by the above functions, but which is not meaningful outside the module. At first, I decided to "hide" this implementation class by defining it inside the function using it, but this hampers readability and cannot be used if multiple functions reuse the same class. So, in addition to comments and docstrings, is there a mechanism to mark a class as "private" or "internal"? I am aware of the underscore mechanism, but as I understand it it only applies to variables, function and methods name.
A pattern that I sometimes use is this: Define a class: ``` class x(object): def doThis(self): ... def doThat(self): ... ``` Create an instance of the class, overwriting the class name: ``` x = x() ``` Define symbols that expose the functionality: ``` doThis = x.doThis doThat = x.doThat ``` Delete the instance itself: ``` del x ``` Now you have a module that only exposes your public functions.
"Private" (implementation) class in Python
551,038
50
2009-02-15T15:29:40Z
551,361
45
2009-02-15T18:31:49Z
[ "python", "design", "access-modifiers" ]
I am coding a small Python module composed of two parts: * some functions defining a public interface, * an implementation class used by the above functions, but which is not meaningful outside the module. At first, I decided to "hide" this implementation class by defining it inside the function using it, but this hampers readability and cannot be used if multiple functions reuse the same class. So, in addition to comments and docstrings, is there a mechanism to mark a class as "private" or "internal"? I am aware of the underscore mechanism, but as I understand it it only applies to variables, function and methods name.
In short: 1. **You cannot enforce privacy**. There are no private classes/methods/functions in Python. At least, not strict privacy as in other languages, such as Java. 2. **You can only indicate/suggest privacy**. This follows a convention. The python convention for marking a class/function/method as private is to preface it with an \_ (underscore). For example, `def _myfunc()` or `class _MyClass:`. You can also create pseudo-privacy by prefacing the method with two underscores (eg: `__foo`). You cannot access the method directly, but you can still call it through a special prefix using the classname (eg: `_classname__foo`). So the best you can do is indicate/suggest privacy, not enforce it. Python is like perl in this respect. To paraphrase a famous line about privacy from the Perl book, the philosophy is that you should stay of the living room because you weren't invited, not because it is defended with a shotgun. For more information: * [Private variables](http://docs.python.org/tutorial/classes.html#private-variables) *Python Documentation* * [Private functions](http://www.diveintopython.net/object_oriented_framework/private_functions.html) *Dive into Python*, by Mark Pilgrim * [Why are Python’s ‘private’ methods not actually private?](http://stackoverflow.com/questions/70528/why-are-pythons-private-methods-not-actually-private) *StackOverflow question 70528*
Deploying application with Python or another embedded scripting language
551,227
14
2009-02-15T17:12:33Z
551,252
8
2009-02-15T17:28:19Z
[ "c++", "python", "deployment", "scripting-language", "embedded-language" ]
I'm thinking about using Python as an **embedded scripting language** in a hobby project written in **C++**. I would not like to depend on separately installed Python distribution. Python documentation seems to be quite clear about general usage, but I couldn't find a clear answer to this. Is it feasible to deploy a Python interpreter + standard library with my application? Would some other language like Lua, Javascript (Spidermonkey), Ruby, etc. be better for this use? Here's the criteria I'm weighing the different languages against: * No/Few dependencies on externally installed packages * Standard library with good feature set * Nice language :) * Doesn't result in a huge install package edit: I guess the question should be: How do I deploy my own python library + standard library with the installer of my program, so that it doesn't matter whether the platform already has python installed or not? edit2: One more clarification. I don't need info about specifics of linking C and Python code.
The embedding process is fully documented : [Embedding Python in Another Application](http://docs.python.org/extending/embedding.html). The documents suggests a few levels at which embedding is done, choose whatever best fits your requirements. > A simple demo of embedding Python can be found in the directory Demo/embed/ of the source distribution. [The demo is here](http://svn.python.org/view/python/trunk/Demo/embed/), should be able to build from the distro. > * Very High Level Embedding > * Beyond Very High Level Embedding: An overview > * Pure Embedding > * Extending Embedded Python > * Embedding Python in C++ From the standard library you can select the components that do not carry too much dependencies.
Deploying application with Python or another embedded scripting language
551,227
14
2009-02-15T17:12:33Z
551,533
14
2009-02-15T20:28:31Z
[ "c++", "python", "deployment", "scripting-language", "embedded-language" ]
I'm thinking about using Python as an **embedded scripting language** in a hobby project written in **C++**. I would not like to depend on separately installed Python distribution. Python documentation seems to be quite clear about general usage, but I couldn't find a clear answer to this. Is it feasible to deploy a Python interpreter + standard library with my application? Would some other language like Lua, Javascript (Spidermonkey), Ruby, etc. be better for this use? Here's the criteria I'm weighing the different languages against: * No/Few dependencies on externally installed packages * Standard library with good feature set * Nice language :) * Doesn't result in a huge install package edit: I guess the question should be: How do I deploy my own python library + standard library with the installer of my program, so that it doesn't matter whether the platform already has python installed or not? edit2: One more clarification. I don't need info about specifics of linking C and Python code.
Link your application to the python library (pythonXX.lib on Windows) and add the following to your main() function. ``` Py_NoSiteFlag = 1; // Disable importing site.py Py_Initialize(); // Create a python interpreter ``` Put the python standard library bits you need into a zip file (called pythonXX.zip) and place this and pythonXX.dll beside the executable you distribute. Have a look at PyZipFile in the the zipfile module.
Getting "global name 'foo' is not defined" with Python's timeit
551,797
58
2009-02-15T23:15:40Z
551,804
67
2009-02-15T23:18:42Z
[ "python", "scope", "timeit" ]
I'm trying to find out how much time it takes to execute a Python statement, so I looked online and found that the standard library provides a module called [timeit](http://docs.python.org/library/timeit.html) that purports to do exactly that: ``` import timeit def foo(): # ... contains code I want to time ... def dotime(): t = timeit.Timer("foo()") time = t.timeit(1) print "took %fs\n" % (time,) dotime() ``` However, this produces an error: ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, in dotime File "/usr/local/lib/python2.6/timeit.py", line 193, in timeit timing = self.inner(it, self.timer) File "<timeit-src>", line 6, in inner NameError: global name 'foo' is not defined ``` I'm still new to Python and I don't fully understand all the scoping issues it has, but I don't know why this snippet doesn't work. Any thoughts?
have you tried making this line: ``` t = timeit.Timer("foo()") ``` This: ``` t = timeit.Timer("foo()", "from __main__ import foo") ``` Check out the link you provided at the very bottom. > To give the timeit module access to functions you define, you can pass a setup parameter which contains an import statement: I just tested it on my machine and it worked with the changes.
Getting "global name 'foo' is not defined" with Python's timeit
551,797
58
2009-02-15T23:15:40Z
5,390,326
13
2011-03-22T11:16:51Z
[ "python", "scope", "timeit" ]
I'm trying to find out how much time it takes to execute a Python statement, so I looked online and found that the standard library provides a module called [timeit](http://docs.python.org/library/timeit.html) that purports to do exactly that: ``` import timeit def foo(): # ... contains code I want to time ... def dotime(): t = timeit.Timer("foo()") time = t.timeit(1) print "took %fs\n" % (time,) dotime() ``` However, this produces an error: ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, in dotime File "/usr/local/lib/python2.6/timeit.py", line 193, in timeit timing = self.inner(it, self.timer) File "<timeit-src>", line 6, in inner NameError: global name 'foo' is not defined ``` I'm still new to Python and I don't fully understand all the scoping issues it has, but I don't know why this snippet doesn't work. Any thoughts?
You can try this hack: ``` import timeit def foo(): print 'bar' def dotime(): t = timeit.Timer("foo()") time = t.timeit(1) print "took %fs\n" % (time,) import __builtin__ __builtin__.__dict__.update(locals()) dotime() ```
Help me implement Blackjack in Python (updated)
551,840
3
2009-02-15T23:34:26Z
551,852
14
2009-02-15T23:42:10Z
[ "python" ]
I am in the process of writing a blackjack code for python, and i was hoping someone would be able to tell me how to make it: 1. Recognize what someone has typed i.e. "Hit" or "Stand" and react accordingly. 2. Calculate what the player's score is and whether it is an ace and a jack together, and automatically wins. Ok, this is what i have gotten so far. ``` "This imports the random object into Python, it allows it to generate random numbers." import random print("Hello and welcome to Sam's Black Jack!") input("Press <ENTER> to begin.") card1name = 1 card2name = 1 card3name = 1 card4name = 1 card5name = 1 "This defines the values of the character cards." Ace = 1 Jack = 10 Queen = 10 King = 10 decision = 0 "This generates the cards that are in your hand and the dealer's hand to begin with. card1 = int(random.randrange(12) + 1) card2 = int(random.randrange(12) + 1) card3 = int(random.randrange(12) + 1) card4 = int(random.randrange(12) + 1) card5 = int(random.randrange(12) + 1) total1 = card1 + card2 "This makes the value of the Ace equal 11 if the total of your cards is under 21" if total1 <= 21: Ace = 11 "This defines what the cards are" if card1 == 11: card1 = 10 card1name = "Jack" if card1 == 12: card1 = 10 card1name = "Queen" if card1 == 13: card1 = 10 card1name = "King" if card1 == 1: card1 = Ace card1name = "Ace" elif card1: card1name = card1 if card2 == 11: card2 = 10 card2name = "Jack" if card2 == 12: card2 = 10 card2name = "Queen" if card2 == 13: card2 = 10 card2name = "King" if card2 == 1: card2 = Ace card2name = "Ace" elif card2: card2name = card2 if card3 == 11: card3 = 10 card3name = "Jack" if card3 == 12: card3 = 10 card3name = "Queen" if card3 == 13: card3 = 10 card3name= "King" if card3 == 1: card3 = Ace card3name = "Ace" elif card3: card3name = card3 if card4 == 11: card4 = 10 card4name = "Jack" if card4 == 12: card4 = 10 card4name = "Queen" if card4 == 13: card4 = 10 card4name = "King" if card4 == 1: card4 = Ace card4name = "Ace" elif card4: card4name = card4 if card5 == 11: card5 = 10 card5name = "Jack" if card5 == 12: card5 = 10 card5name = "Queen" if card5 == 13: card5 = 10 card5name = "King" if card5 == 1: card5 = Ace card5name = "Ace" elif card5: card5name = card5 "This creates the totals of your hand" total2 = card1 + card2 total3 = card1 + card2 + card3 print("You hand is ", card1name," and", card2name) print("The total of your hand is", total2) decision = input("Do you want to HIT or STAND?").lower() "This is the decision for Hit or Stand" if 'hit' or 'HIT' or 'Hit' in decision: decision = 1 print("You have selected HIT") print("Your hand is ", card1name,",",card2name," and", card3name) print("The total of your hand is", total3) if 'STAND' or 'stand' or 'Stand' in decision: print("You have selected STAND") "Dealer's Hand" dealer = card4 + card5 print() print("The dealer's hand is", card4name," and", card5name) if decision == 1 and dealer < total3: print("Congratulations, you beat the dealer!") if decision == 1 and dealer > total3: print("Too bad, the dealer beat you!") ``` Ok, nevermind, i fixed it :D I just changed the Hit and Stand to Yes or No ``` if total2 < 21: decision = input("Do you want to hit? (Yes or No)") "This is the decision for Hit or Stand" if decision == 'Yes': print("You have selected HIT") print("Your hand is ", card1name,",",card2name," and", card3name) print("The total of your hand is", total3) if decision == 'No': print("You have selected STAND") ```
This can get you started: <http://docs.python.org/library/random.html> <http://docs.python.org/library/strings.html> <http://docs.python.org/library/stdtypes.html> <http://docs.python.org/reference/index.html> I see you have added some code; that's good. Think about the parts of your program that will need to exist. You will need some representation of "cards" -- cards have important features such as their value, their suit, etc. Given a card, you should be able to tell what its value is, whether it's a Jack or an Ace or a 2 of hearts. Read up on "classes" in Python to get started with this. You will also have a hand of cards -- the cards your dealer is currently holding, and the cards your player is currently holding. A "hand" is a collection of cards, which you (the programmer) can add new cards to (when a card is dealt). You might want to do that using "lists" or "arrays" or "classes" that contain those arrays. A hand also has a value, which is usually the sum of card values, but as you know, Aces are special (they can be 1 or 11), so you'll need to treat that case correctly with some "if statements". You will also have a deck; a deck is a special collection -- it has exactly 52 cards when it starts, and none of the cards are repeated (you could, of course, be using several decks to play, but that's a complication you can solve later). How do you populate a deck like that? Your program will want to "deal" from the deck -- so you'll need a way to keep track of which cards have been dealt to players. That's a lot of stuff. Try writing down all the logic of what your program needs to do in simple sentences, without worrying about Python. This is called "pseudo-code". It's not a real program, it's just a plan for what exactly you are going to do -- it's useful the way a map is useful. If you are going to a place you've been to a 100 times, you don't need a map, but if you are driving to some town you've never been to, you want to plan out your route first, before getting behind the wheel.. Update your question with your pseudocode, and any attempts you have made (or will have made) to translate the pseudocode to Python.
Help me implement Blackjack in Python (updated)
551,840
3
2009-02-15T23:34:26Z
552,111
9
2009-02-16T02:57:38Z
[ "python" ]
I am in the process of writing a blackjack code for python, and i was hoping someone would be able to tell me how to make it: 1. Recognize what someone has typed i.e. "Hit" or "Stand" and react accordingly. 2. Calculate what the player's score is and whether it is an ace and a jack together, and automatically wins. Ok, this is what i have gotten so far. ``` "This imports the random object into Python, it allows it to generate random numbers." import random print("Hello and welcome to Sam's Black Jack!") input("Press <ENTER> to begin.") card1name = 1 card2name = 1 card3name = 1 card4name = 1 card5name = 1 "This defines the values of the character cards." Ace = 1 Jack = 10 Queen = 10 King = 10 decision = 0 "This generates the cards that are in your hand and the dealer's hand to begin with. card1 = int(random.randrange(12) + 1) card2 = int(random.randrange(12) + 1) card3 = int(random.randrange(12) + 1) card4 = int(random.randrange(12) + 1) card5 = int(random.randrange(12) + 1) total1 = card1 + card2 "This makes the value of the Ace equal 11 if the total of your cards is under 21" if total1 <= 21: Ace = 11 "This defines what the cards are" if card1 == 11: card1 = 10 card1name = "Jack" if card1 == 12: card1 = 10 card1name = "Queen" if card1 == 13: card1 = 10 card1name = "King" if card1 == 1: card1 = Ace card1name = "Ace" elif card1: card1name = card1 if card2 == 11: card2 = 10 card2name = "Jack" if card2 == 12: card2 = 10 card2name = "Queen" if card2 == 13: card2 = 10 card2name = "King" if card2 == 1: card2 = Ace card2name = "Ace" elif card2: card2name = card2 if card3 == 11: card3 = 10 card3name = "Jack" if card3 == 12: card3 = 10 card3name = "Queen" if card3 == 13: card3 = 10 card3name= "King" if card3 == 1: card3 = Ace card3name = "Ace" elif card3: card3name = card3 if card4 == 11: card4 = 10 card4name = "Jack" if card4 == 12: card4 = 10 card4name = "Queen" if card4 == 13: card4 = 10 card4name = "King" if card4 == 1: card4 = Ace card4name = "Ace" elif card4: card4name = card4 if card5 == 11: card5 = 10 card5name = "Jack" if card5 == 12: card5 = 10 card5name = "Queen" if card5 == 13: card5 = 10 card5name = "King" if card5 == 1: card5 = Ace card5name = "Ace" elif card5: card5name = card5 "This creates the totals of your hand" total2 = card1 + card2 total3 = card1 + card2 + card3 print("You hand is ", card1name," and", card2name) print("The total of your hand is", total2) decision = input("Do you want to HIT or STAND?").lower() "This is the decision for Hit or Stand" if 'hit' or 'HIT' or 'Hit' in decision: decision = 1 print("You have selected HIT") print("Your hand is ", card1name,",",card2name," and", card3name) print("The total of your hand is", total3) if 'STAND' or 'stand' or 'Stand' in decision: print("You have selected STAND") "Dealer's Hand" dealer = card4 + card5 print() print("The dealer's hand is", card4name," and", card5name) if decision == 1 and dealer < total3: print("Congratulations, you beat the dealer!") if decision == 1 and dealer > total3: print("Too bad, the dealer beat you!") ``` Ok, nevermind, i fixed it :D I just changed the Hit and Stand to Yes or No ``` if total2 < 21: decision = input("Do you want to hit? (Yes or No)") "This is the decision for Hit or Stand" if decision == 'Yes': print("You have selected HIT") print("Your hand is ", card1name,",",card2name," and", card3name) print("The total of your hand is", total3) if decision == 'No': print("You have selected STAND") ```
I've covered the entire thing as a (long) series of exercises. <http://homepage.mac.com/s_lott/books/oodesign.html> Just read and do the exercises in the book. You'll implement blackjack (and Craps and Roulette, too.)
"Interfaces" in Python: Yea or Nay?
552,058
16
2009-02-16T02:15:17Z
552,087
10
2009-02-16T02:40:12Z
[ "python", "documentation", "interface", "coding-style" ]
So I'm starting a project using Python after spending a significant amount of time in static land. I've seen some projects that make "interfaces" which are really just classes without any implementations. Before, I'd scoff at the idea and ignore that section of those projects. But now, I'm beginning to warm up to the idea. Just so we're clear, an interface in Python would look something like this: ``` class ISomething(object): def some_method(): pass def some_other_method(some_argument): pass ``` Notice that you aren't passing self to any of the methods, thus requiring that the method be overriden to be called. I see this as a nice form of documentation and completeness testing. So what is everyone here's opinion on the idea? Have I been brainwashed by all the C# programming I've done, or is this a good idea?
There are some cases where interfaces can be very handy. [Twisted](http://twistedmatrix.com/trac/) makes [fairly extensive use](http://twistedmatrix.com/projects/core/documentation/howto/components.html) of [Zope interfaces](http://wiki.zope.org/Interfaces/FrontPage), and in a project I was working on Zope interfaces worked really well. Enthought's traits packaged recently added [interfaces](http://code.enthought.com/projects/traits/docs/html/traits_user_manual/advanced.html#id15), but I don't have any experience with them. Beware overuse though -- duck typing and protocols are a fundamental aspect of Python, only use interfaces if they're absolutely necessary.
"Interfaces" in Python: Yea or Nay?
552,058
16
2009-02-16T02:15:17Z
552,097
10
2009-02-16T02:46:40Z
[ "python", "documentation", "interface", "coding-style" ]
So I'm starting a project using Python after spending a significant amount of time in static land. I've seen some projects that make "interfaces" which are really just classes without any implementations. Before, I'd scoff at the idea and ignore that section of those projects. But now, I'm beginning to warm up to the idea. Just so we're clear, an interface in Python would look something like this: ``` class ISomething(object): def some_method(): pass def some_other_method(some_argument): pass ``` Notice that you aren't passing self to any of the methods, thus requiring that the method be overriden to be called. I see this as a nice form of documentation and completeness testing. So what is everyone here's opinion on the idea? Have I been brainwashed by all the C# programming I've done, or is this a good idea?
The pythonic way is to "Ask for forgiveness rather than receive permission". Interfaces are *all* about receiving permission to perform some operation on an object. Python prefers this: ``` def quacker(duck): try: duck.quack(): except AttributeError: raise ThisAintADuckException ```
"Interfaces" in Python: Yea or Nay?
552,058
16
2009-02-16T02:15:17Z
552,203
27
2009-02-16T03:50:38Z
[ "python", "documentation", "interface", "coding-style" ]
So I'm starting a project using Python after spending a significant amount of time in static land. I've seen some projects that make "interfaces" which are really just classes without any implementations. Before, I'd scoff at the idea and ignore that section of those projects. But now, I'm beginning to warm up to the idea. Just so we're clear, an interface in Python would look something like this: ``` class ISomething(object): def some_method(): pass def some_other_method(some_argument): pass ``` Notice that you aren't passing self to any of the methods, thus requiring that the method be overriden to be called. I see this as a nice form of documentation and completeness testing. So what is everyone here's opinion on the idea? Have I been brainwashed by all the C# programming I've done, or is this a good idea?
I'm not sure what the point of that is. Interfaces (of this form, anyway) are largely to work around the lack of multiple inheritance. But Python has MI, so why not just make an abstract class? ``` class Something(object): def some_method(self): raise NotImplementedError() def some_other_method(self, some_argument): raise NotImplementedError() ```
"Interfaces" in Python: Yea or Nay?
552,058
16
2009-02-16T02:15:17Z
552,917
11
2009-02-16T10:47:32Z
[ "python", "documentation", "interface", "coding-style" ]
So I'm starting a project using Python after spending a significant amount of time in static land. I've seen some projects that make "interfaces" which are really just classes without any implementations. Before, I'd scoff at the idea and ignore that section of those projects. But now, I'm beginning to warm up to the idea. Just so we're clear, an interface in Python would look something like this: ``` class ISomething(object): def some_method(): pass def some_other_method(some_argument): pass ``` Notice that you aren't passing self to any of the methods, thus requiring that the method be overriden to be called. I see this as a nice form of documentation and completeness testing. So what is everyone here's opinion on the idea? Have I been brainwashed by all the C# programming I've done, or is this a good idea?
In Python 2.6 and later, you can use [abstract base classes](http://docs.python.org/library/abc.html) instead. These are useful, because you can then test to see if something implements a given ABC by using "isinstance". As usual in Python, the concept is not as strictly enforced as it would be in a strict language, but it's handy. Moreover there are nice idiomatic ways of declaring abstract methods with decorators - see the link above for examples.
What's the best way to make a time from "Today" or "Yesterday" and a time in Python?
552,073
9
2009-02-16T02:30:50Z
552,229
18
2009-02-16T04:03:58Z
[ "python", "datetime", "parsing" ]
Python has pretty good date parsing but is the only way to recognize a datetime such as "Today 3:20 PM" or "Yesterday 11:06 AM" by creating a new date today and doing subtractions?
A library that I like a lot, and I'm seeing more and more people use, is [python-dateutil](http://labix.org/python-dateutil) but unfortunately neither it nor the other traditional big datetime parser, [mxDateTime from Egenix](http://www.egenix.com/products/python/mxBase/mxDateTime/) can parse the word "tomorrow" in spite of both libraries having very strong "fuzzy" parsers. The only library I've seen that can do this is [magicdate](http://pypi.python.org/pypi/magicdate/0.1.3). Examples: ``` >>> import magicdate >>> magicdate.magicdate('today') datetime.date(2009, 2, 15) >>> magicdate.magicdate('tomorrow') datetime.date(2009, 2, 16) >>> magicdate.magicdate('yesterday') datetime.date(2009, 2, 14) ``` Unfortunately this only returns datetime.date objects, and so won't include time parts and can't handle your example of "Today 3:20 PM". So, you need mxDateTime for that. Examples: ``` >>> import mx.DateTime >>> mx.DateTime.Parser.DateTimeFromString("Today 3:20 PM") <mx.DateTime.DateTime object for '2009-02-15 15:20:00.00' at 28faa28> >>> mx.DateTime.Parser.DateTimeFromString("Tomorrow 5:50 PM") <mx.DateTime.DateTime object for '2009-02-15 17:50:00.00' at 2a86088> ``` EDIT: mxDateTime.Parser is only parsing the time in these examples and ignoring the words "today" and "tomorrow". So for this particular case you need to use a combo of magicdate to get the date and mxDateTime to get the time. My recommendation is to just use python-dateutils or mxDateTime and only accept the string formats they can parse. --- EDIT 2: As noted in the comments it looks python-dateutil can now handle fuzzy parsing. I've also since discovered the [parsedatetime](http://code.google.com/p/parsedatetime/) module that was developed for use in Chandler and it works with the queries in this question: ``` >>> import parsedatetime.parsedatetime as pdt >>> import parsedatetime.parsedatetime_consts as pdc >>> c=pdc.Constants() >>> p=pdt.Calendar(c) >>> p.parse('Today 3:20 PM') ((2010, 3, 12, 15, 20, 0, 4, 71, -1), 3) >>> p.parse('Yesterday 11:06 AM') ((2010, 3, 11, 11, 6, 0, 3, 70, -1), 3) ``` and for reference here is the current time: ``` >>> import datetime >>> datetime.datetime.now() datetime.datetime(2010, 3, 12, 15, 23, 35, 951652) ```
How do python classes work?
552,329
4
2009-02-16T05:26:35Z
552,363
9
2009-02-16T05:49:13Z
[ "python" ]
I have a code file from the boto framework pasted below, all of the print statements are mine, and the one commented out line is also mine, all else belongs to the attributed author. My question is what is the order in which instantiations and allocations occur in python when instantiating a class? The author's code below is under the assumption that 'DefaultDomainName' will exist when an instance of the class is created (e.g. \_\_init\_\_() is called), but this does not seem to be the case, at least in my testing in python 2.5 on OS X. In the class Manager \_\_init\_\_() method, my print statements show as 'None'. And the print statements in the global function set\_domain() further down shows 'None' prior to setting Manager.DefaultDomainName, and shows the expected value of 'test\_domain' after the assignment. But when creating an instance of Manager again after calling set\_domain(), the \_\_init\_\_() method still shows 'None'. Can anyone help me out, and explain what is going on here. It would be greatly appreciated. Thank you. ``` # Copyright (c) 2006,2007,2008 Mitch Garnaat http://garnaat.org/ # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, dis- # tribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the fol- # lowing conditions: # # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL- # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT # SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. import boto from boto.utils import find_class class Manager(object): DefaultDomainName = boto.config.get('Persist', 'default_domain', None) def __init__(self, domain_name=None, aws_access_key_id=None, aws_secret_access_key=None, debug=0): self.domain_name = domain_name self.aws_access_key_id = aws_access_key_id self.aws_secret_access_key = aws_secret_access_key self.domain = None self.sdb = None self.s3 = None if not self.domain_name: print "1: %s" % self.DefaultDomainName print "2: %s" % Manager.DefaultDomainName self.domain_name = self.DefaultDomainName #self.domain_name = 'test_domain' if self.domain_name: boto.log.info('No SimpleDB domain set, using default_domain: %s' % self.domain_name) else: boto.log.warning('No SimpleDB domain set, persistance is disabled') if self.domain_name: self.sdb = boto.connect_sdb(aws_access_key_id=self.aws_access_key_id, aws_secret_access_key=self.aws_secret_access_key, debug=debug) self.domain = self.sdb.lookup(self.domain_name) if not self.domain: self.domain = self.sdb.create_domain(self.domain_name) def get_s3_connection(self): if not self.s3: self.s3 = boto.connect_s3(self.aws_access_key_id, self.aws_secret_access_key) return self.s3 def get_manager(domain_name=None, aws_access_key_id=None, aws_secret_access_key=None, debug=0): return Manager(domain_name, aws_access_key_id, aws_secret_access_key, debug=debug) def set_domain(domain_name): print "3: %s" % Manager.DefaultDomainName Manager.DefaultDomainName = domain_name print "4: %s" % Manager.DefaultDomainName def get_domain(): return Manager.DefaultDomainName def revive_object_from_id(id, manager): if not manager.domain: return None attrs = manager.domain.get_attributes(id, ['__module__', '__type__', '__lineage__']) try: cls = find_class(attrs['__module__'], attrs['__type__']) return cls(id, manager=manager) except ImportError: return None def object_lister(cls, query_lister, manager): for item in query_lister: if cls: yield cls(item.name) else: o = revive_object_from_id(item.name, manager) if o: yield o ```
**A few python notes** When python executes the **class** block, it creates all of the "attributes" of that class as it encounters them. They are usually class variables as well as functions (methods), and the like. So the value for "Manager.DefaultDomainName" is set when it is encountered in the class definition. This code is **only ever run once** - never again. The reason for that is that it is just "defining" the class object called "Manager". When an object of class "Manager" is instantiated, it is an instance of the "Manager" class. (that may sound repetitive). To be perfectly clear, the value: ``` self.DefaultDomainName ``` does not exist. Following the rules of classes, python says "hmm, that does not exist on this object instance, I'll look at the class object(s)". So python actually finds the value at: ``` Manager.DefaultDomainName # also referenced by self.__class__.DefaultDomainName ``` All of that to exemplify the point that the class attribute "Manager.DefaultDomainName" is only created once, can only exist once, and can only hold one value at once. --- In the example above, run the builtin function id() on each of the values: ``` print "1: %s" % id(self.DefaultDomainName) print "2: %s" % id(Manager.DefaultDomainName) ``` You should see that they are referring to exactly the same memory location. --- **Now, in (non)answer to the original question...** I don't know from perusing the code above. I would suggest that you try a couple of techniques to find it out: ``` # Debug with pdb. Follow every step of the process to ensure that you are # setting valeus as you thought, and that the code you thought would be # called is actually being called. I've had many problems like this where # the error was in procedure, not in the actual code at hand. import pdb; pdb.set_trace() # check to see if id(Manager) is the same as id(self.__class__) # in the set_domain() function: # check to see what attributes you can see on Manager, # and if they match the attributes on Manager and self.__class__ in __init__ ``` Please update here when you figure it out.
Use Python 2.6 subprocess module in Python 2.5
552,423
9
2009-02-16T06:41:55Z
554,881
9
2009-02-16T22:43:43Z
[ "python", "subprocess", "python-2.5" ]
I would like to use Python 2.6's version of subprocess, because it allows the [Popen.terminate()](http://docs.python.org/library/subprocess.html#subprocess.Popen.terminate) function, but I'm stuck with Python 2.5. Is there some reasonably clean way to use the newer version of the module in my 2.5 code? Some sort of `from __future__ import subprocess_module`?
I know this question has already been answered, but for what it's worth, I've used the `subprocess.py` that ships with Python 2.6 in Python 2.3 and it's worked fine. If you read the comments at the top of the file it says: > `# This module should remain compatible with Python 2.2, see PEP 291.`
Django Model returning NoneType
552,521
2
2009-02-16T07:44:23Z
552,530
7
2009-02-16T07:50:32Z
[ "python", "django", "django-views" ]
I have a model Product it has two fields size & colours among others ``` colours = models.CharField(blank=True, null=True, max_length=500) size = models.CharField(blank=True, null=True, max_length=500) ``` In my view I have ``` current_product = Product.objects.get(slug=title) if len(current_product.size) != 0 : current_product.size = current_product.size.split(",") ``` and get this error: object of type 'NoneType' has no len() What is NoneType and how can I test for it?
`NoneType` is the type that the `None` value has. You want to change the second snippet to ``` if current_product.size: # This will evaluate as false if size is None or len(size) == 0. blah blah ```
How do I profile memory usage in Python?
552,744
87
2009-02-16T09:34:43Z
552,810
66
2009-02-16T10:00:24Z
[ "python", "memory", "profiling" ]
I've recently become interested in algorithms and have begun exploring them by writing a naive implementation and then optimizing it in various ways. I'm already familiar with the standard Python module for profiling runtime (for most things I've found the timeit magic function in IPython to be sufficient), but I'm also interested in memory usage so I can explore those tradeoffs as well (e.g. the cost of caching a table of previously computed values versus recomputing them as needed). Is there a module that will profile the memory usage of a given function for me?
This one has been answered already here: [Python memory profiler](http://stackoverflow.com/questions/110259/python-memory-profiler) Basically you do something like that (cited from [Guppy-PE](http://guppy-pe.sourceforge.net/#Heapy)): ``` >>> from guppy import hpy; h=hpy() >>> h.heap() Partition of a set of 48477 objects. Total size = 3265516 bytes. Index Count % Size % Cumulative % Kind (class / dict of class) 0 25773 53 1612820 49 1612820 49 str 1 11699 24 483960 15 2096780 64 tuple 2 174 0 241584 7 2338364 72 dict of module 3 3478 7 222592 7 2560956 78 types.CodeType 4 3296 7 184576 6 2745532 84 function 5 401 1 175112 5 2920644 89 dict of class 6 108 0 81888 3 3002532 92 dict (no owner) 7 114 0 79632 2 3082164 94 dict of type 8 117 0 51336 2 3133500 96 type 9 667 1 24012 1 3157512 97 __builtin__.wrapper_descriptor <76 more rows. Type e.g. '_.more' to view.> >>> h.iso(1,[],{}) Partition of a set of 3 objects. Total size = 176 bytes. Index Count % Size % Cumulative % Kind (class / dict of class) 0 1 33 136 77 136 77 dict (no owner) 1 1 33 28 16 164 93 list 2 1 33 12 7 176 100 int >>> x=[] >>> h.iso(x).sp 0: h.Root.i0_modules['__main__'].__dict__['x'] >>> ```
How do I profile memory usage in Python?
552,744
87
2009-02-16T09:34:43Z
15,448,600
11
2013-03-16T11:19:27Z
[ "python", "memory", "profiling" ]
I've recently become interested in algorithms and have begun exploring them by writing a naive implementation and then optimizing it in various ways. I'm already familiar with the standard Python module for profiling runtime (for most things I've found the timeit magic function in IPython to be sufficient), but I'm also interested in memory usage so I can explore those tradeoffs as well (e.g. the cost of caching a table of previously computed values versus recomputing them as needed). Is there a module that will profile the memory usage of a given function for me?
For a really simple approach try: ``` import resource def using(point=""): usage=resource.getrusage(resource.RUSAGE_SELF) return '''%s: usertime=%s systime=%s mem=%s mb '''%(point,usage[0],usage[1], (usage[2]*resource.getpagesize())/1000000.0 ) ``` Just insert `using("Label")` where you want to see what's going on.
Generate a random date between two other dates
553,303
53
2009-02-16T13:30:04Z
553,320
70
2009-02-16T13:35:08Z
[ "python", "datetime", "random" ]
How would I generate a random date that has to be between two other given dates? The functions signature should something like this- ``` randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", 0.34) ^ ^ ^ date generated has date generated has random number to be after this to be before this ``` and would return a date such as- "2/4/2008 7:20 PM"
Convert both strings to timestamps (in your chosen resolution, e.g. milliseconds, seconds, hours, days, whatever), subtract the earlier from the later, multiply your random number (assuming it is distributed in the range [0, 1]) with that difference, and add again to the earlier one. Convert the timestamp back to date string and you have a random time in that range. Python example (output is almost in the format you specified, other than 0 padding - blame the American time format conventions): ``` import random import time def strTimeProp(start, end, format, prop): """Get a time at a proportion of a range of two formatted times. start and end should be strings specifying times formated in the given format (strftime-style), giving an interval [start, end]. prop specifies how a proportion of the interval to be taken after start. The returned time will be in the specified format. """ stime = time.mktime(time.strptime(start, format)) etime = time.mktime(time.strptime(end, format)) ptime = stime + prop * (etime - stime) return time.strftime(format, time.localtime(ptime)) def randomDate(start, end, prop): return strTimeProp(start, end, '%m/%d/%Y %I:%M %p', prop) print randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", random.random()) ```
Generate a random date between two other dates
553,303
53
2009-02-16T13:30:04Z
553,448
67
2009-02-16T14:21:56Z
[ "python", "datetime", "random" ]
How would I generate a random date that has to be between two other given dates? The functions signature should something like this- ``` randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", 0.34) ^ ^ ^ date generated has date generated has random number to be after this to be before this ``` and would return a date such as- "2/4/2008 7:20 PM"
``` from random import randrange from datetime import timedelta def random_date(start, end): """ This function will return a random datetime between two datetime objects. """ delta = end - start int_delta = (delta.days * 24 * 60 * 60) + delta.seconds random_second = randrange(int_delta) return start + timedelta(seconds=random_second) ``` The precision is seconds. You can increase precision up to microseconds, or decrease to, say, half-hours, if you want. For that just change the last lines calculation. example run: ``` d1 = datetime.strptime('1/1/2008 1:30 PM', '%m/%d/%Y %I:%M %p') d2 = datetime.strptime('1/1/2009 4:50 AM', '%m/%d/%Y %I:%M %p') print random_date(d1, d2) ``` output: ``` 2008-12-04 01:50:17 ```
Generate a random date between two other dates
553,303
53
2009-02-16T13:30:04Z
8,170,651
43
2011-11-17T16:25:52Z
[ "python", "datetime", "random" ]
How would I generate a random date that has to be between two other given dates? The functions signature should something like this- ``` randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", 0.34) ^ ^ ^ date generated has date generated has random number to be after this to be before this ``` and would return a date such as- "2/4/2008 7:20 PM"
A tiny version. ``` from datetime import timedelta from random import randint def random_date(start, end): return start + timedelta( seconds=randint(0, int((end - start).total_seconds()))) ``` Note that both `start` and `end` arguments should be `datetime` objects. If you've got strings instead, it's fairly easy to convert. The other answers point to some ways to do so.
Generate a random date between two other dates
553,303
53
2009-02-16T13:30:04Z
17,193,251
12
2013-06-19T13:59:56Z
[ "python", "datetime", "random" ]
How would I generate a random date that has to be between two other given dates? The functions signature should something like this- ``` randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", 0.34) ^ ^ ^ date generated has date generated has random number to be after this to be before this ``` and would return a date such as- "2/4/2008 7:20 PM"
It's very simple using radar ## Installation $ pip install radar ## Usage ``` import datetime import radar # Generate random datetime (parsing dates from str values) radar.random_datetime(start='2000-05-24', stop='2013-05-24T23:59:59') # Generate random datetime from datetime.datetime values radar.random_datetime( start = datetime.datetime(year=2000, month=5, day=24), stop = datetime.datetime(year=2013, month=5, day=24) ) # Just render some random datetime. If no range is given, start defaults to # 1970-01-01 and stop defaults to datetime.datetime.now() radar.random_datetime() ```
Can you use a string to instantiate a class in python?
553,784
27
2009-02-16T16:00:26Z
554,073
12
2009-02-16T18:17:22Z
[ "python", "design-patterns", "reflection" ]
I'm using a builder pattern to seperate a bunch of different configuration possibilities. Basically, I have a bunch of classes that are named an ID (something like ID12345). These all inherit from the base builder class. In my script, I need to instantiate an instance for each class (about 50) every time this app runs. So, I'm trying to see if instead of doing something like this: ``` ProcessDirector = ProcessDirector() ID12345 = ID12345() ID01234 = ID01234() ProcessDirector.construct(ID12345) ProcessDirector.construct(ID01234) ID12345.run() ID01234.run() ``` Can I do something like this (I know this doesn't work): ``` IDS = ["ID12345", "ID01234"] ProcessDirector = ProcessDirector() for id in IDS: builder = id() #some how instantiate class from string ProcessDirector.construct(builder) builder.run() ``` That way, when I need to add a new one in the future, all I have to do is add the id to the IDS list, rather than peppering the new ID throughout the code. ## EDIT Looks like there are some different opinions based on where the data is coming from. These IDs are entered in a file that no one else has access to. I'm not reading the strings from the command line, and I'd like to be able to do as little alteration when adding a new ID in the future.
**Never** use `eval()` if you can help it. Python has **so** many better options (dispatch dictionary, `getattr()`, etc.) that you should never have to use the security hole known as `eval()`.
Can you use a string to instantiate a class in python?
553,784
27
2009-02-16T16:00:26Z
554,462
39
2009-02-16T20:34:50Z
[ "python", "design-patterns", "reflection" ]
I'm using a builder pattern to seperate a bunch of different configuration possibilities. Basically, I have a bunch of classes that are named an ID (something like ID12345). These all inherit from the base builder class. In my script, I need to instantiate an instance for each class (about 50) every time this app runs. So, I'm trying to see if instead of doing something like this: ``` ProcessDirector = ProcessDirector() ID12345 = ID12345() ID01234 = ID01234() ProcessDirector.construct(ID12345) ProcessDirector.construct(ID01234) ID12345.run() ID01234.run() ``` Can I do something like this (I know this doesn't work): ``` IDS = ["ID12345", "ID01234"] ProcessDirector = ProcessDirector() for id in IDS: builder = id() #some how instantiate class from string ProcessDirector.construct(builder) builder.run() ``` That way, when I need to add a new one in the future, all I have to do is add the id to the IDS list, rather than peppering the new ID throughout the code. ## EDIT Looks like there are some different opinions based on where the data is coming from. These IDs are entered in a file that no one else has access to. I'm not reading the strings from the command line, and I'd like to be able to do as little alteration when adding a new ID in the future.
If you wanted to avoid an eval(), you could just do: ``` id = "1234asdf" constructor = globals()[id] instance = constructor() ``` Provided that the class is defined in (or imported into) your current scope.
Can you use a string to instantiate a class in python?
553,784
27
2009-02-16T16:00:26Z
554,812
13
2009-02-16T22:18:24Z
[ "python", "design-patterns", "reflection" ]
I'm using a builder pattern to seperate a bunch of different configuration possibilities. Basically, I have a bunch of classes that are named an ID (something like ID12345). These all inherit from the base builder class. In my script, I need to instantiate an instance for each class (about 50) every time this app runs. So, I'm trying to see if instead of doing something like this: ``` ProcessDirector = ProcessDirector() ID12345 = ID12345() ID01234 = ID01234() ProcessDirector.construct(ID12345) ProcessDirector.construct(ID01234) ID12345.run() ID01234.run() ``` Can I do something like this (I know this doesn't work): ``` IDS = ["ID12345", "ID01234"] ProcessDirector = ProcessDirector() for id in IDS: builder = id() #some how instantiate class from string ProcessDirector.construct(builder) builder.run() ``` That way, when I need to add a new one in the future, all I have to do is add the id to the IDS list, rather than peppering the new ID throughout the code. ## EDIT Looks like there are some different opinions based on where the data is coming from. These IDs are entered in a file that no one else has access to. I'm not reading the strings from the command line, and I'd like to be able to do as little alteration when adding a new ID in the future.
Not totally sure this is what you want, but it seems like a more Python'y way to instantiate a bunch of classes listed in a string: ``` class idClasses: class ID12345:pass class ID01234:pass # could also be: import idClasses class ProcessDirector: def __init__(self): self.allClasses = [] def construct(self, builderName): targetClass = getattr(idClasses, builderName) instance = targetClass() self.allClasses.append(instance) IDS = ["ID12345", "ID01234"] director = ProcessDirector() for id in IDS: director.construct(id) print director.allClasses # [<__main__.ID12345 instance at 0x7d850>, <__main__.ID01234 instance at 0x7d918>] ```
Can anyone provide a more pythonic way of generating the morris sequence?
553,871
5
2009-02-16T16:24:53Z
554,028
23
2009-02-16T18:07:12Z
[ "python", "sequences", "itertools" ]
I'm trying to generate the [morris sequence](http://www.ocf.berkeley.edu/~stoll/answer.html) in python. My current solution is below, but I feel like I just wrote c in python. Can anyone provide a more pythonic solution? ``` def morris(x): a = ['1', '11'] yield a[0] yield a[1] while len(a) <= x: s = '' count = 1 al = a[-1] for i in range(0,len(al)): if i+1 < len(al) and al[i] == al[i+1]: count += 1 else: s += '%s%s' % (count, al[i]) count = 1 a.append(s) yield s a = [i for i in morris(30)] ```
[`itertools.groupby`](http://docs.python.org/library/itertools.html#itertools.groupby) seems to fit perfectly! Just define a `next_morris` function as follows: ``` def next_morris(number): return ''.join('%s%s' % (len(list(group)), digit) for digit, group in itertools.groupby(str(number))) ``` That's all!!! Look: ``` print next_morris(1) 11 print next_morris(111221) 312211 ``` --- I could use that to make a generator: ``` def morris_generator(maxlen, start=1): num = str(start) while len(num) < maxlen: yield int(num) num = next_morris(num) ``` Usage: ``` for n in morris_generator(10): print n ``` results: ``` 1 11 21 1211 111221 312211 13112221 ```
How do I prevent Python's urllib(2) from following a redirect
554,446
40
2009-02-16T20:29:30Z
554,475
11
2009-02-16T20:38:43Z
[ "python", "urllib2" ]
I am currently trying to log into a site using Python however the site seems to be sending a cookie and a redirect statement on the same page. Python seems to be following that redirect thus preventing me from reading the cookie send by the login page. How do I prevent Python's urllib (or urllib2) urlopen from following the redirect?
`urllib2.urlopen` calls `build_opener()` which uses this list of handler classes: ``` handlers = [ProxyHandler, UnknownHandler, HTTPHandler, HTTPDefaultErrorHandler, HTTPRedirectHandler, FTPHandler, FileHandler, HTTPErrorProcessor] ``` You could try calling `urllib2.build_opener(handlers)` yourself with a list that omits `HTTPRedirectHandler`, then call the `open()` method on the result to open your URL. If you really dislike redirects, you could even call `urllib2.install_opener(opener)` to your own non-redirecting opener. It sounds like your real problem is that `urllib2` isn't doing cookies the way you'd like. See also [How to use Python to login to a webpage and retrieve cookies for later usage?](http://stackoverflow.com/questions/189555/how-to-use-python-to-login-to-a-webpage-and-retrieve-cookies-for-later-usage)
How do I prevent Python's urllib(2) from following a redirect
554,446
40
2009-02-16T20:29:30Z
554,580
33
2009-02-16T21:13:43Z
[ "python", "urllib2" ]
I am currently trying to log into a site using Python however the site seems to be sending a cookie and a redirect statement on the same page. Python seems to be following that redirect thus preventing me from reading the cookie send by the login page. How do I prevent Python's urllib (or urllib2) urlopen from following the redirect?
You could do a couple of things: 1. Build your own HTTPRedirectHandler that intercepts each redirect 2. Create an instance of HTTPCookieProcessor and install that opener so that you have access to the cookiejar. This is a quick little thing that shows both ``` import urllib2 #redirect_handler = urllib2.HTTPRedirectHandler() class MyHTTPRedirectHandler(urllib2.HTTPRedirectHandler): def http_error_302(self, req, fp, code, msg, headers): print "Cookie Manip Right Here" return urllib2.HTTPRedirectHandler.http_error_302(self, req, fp, code, msg, headers) http_error_301 = http_error_303 = http_error_307 = http_error_302 cookieprocessor = urllib2.HTTPCookieProcessor() opener = urllib2.build_opener(MyHTTPRedirectHandler, cookieprocessor) urllib2.install_opener(opener) response =urllib2.urlopen("WHEREEVER") print response.read() print cookieprocessor.cookiejar ```
How do I prevent Python's urllib(2) from following a redirect
554,446
40
2009-02-16T20:29:30Z
11,744,894
27
2012-07-31T16:33:51Z
[ "python", "urllib2" ]
I am currently trying to log into a site using Python however the site seems to be sending a cookie and a redirect statement on the same page. Python seems to be following that redirect thus preventing me from reading the cookie send by the login page. How do I prevent Python's urllib (or urllib2) urlopen from following the redirect?
If all you need is stopping redirection, then there is a simple way to do it. For example I only want to get cookies and for a better performance I don't want to be redirected to any other page. Also I hope the code is kept as 3xx. let's use 302 for instance. ``` class MyHTTPErrorProcessor(urllib2.HTTPErrorProcessor): def http_response(self, request, response): code, msg, hdrs = response.code, response.msg, response.info() # only add this line to stop 302 redirection. if code == 302: return response if not (200 <= code < 300): response = self.parent.error( 'http', request, response, code, msg, hdrs) return response https_response = http_response cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj), MyHTTPErrorProcessor) ``` In this way, you don't even need to go into urllib2.HTTPRedirectHandler.http\_error\_302() **Yet more common case is that we simply want to stop redirection (as required):** ``` class NoRedirection(urllib2.HTTPErrorProcessor): def http_response(self, request, response): return response https_response = http_response ``` And normally use it this way: ``` cj = cookielib.CookieJar() opener = urllib2.build_opener(NoRedirection, urllib2.HTTPCookieProcessor(cj)) data = {} response = opener.open('http://www.example.com', urllib.urlencode(data)) if response.code == 302: redirection_target = response.headers['Location'] ```
Stackless python network performance degrading over time?
554,805
8
2009-02-16T22:16:06Z
554,914
14
2009-02-16T22:52:41Z
[ "python", "performance", "networking", "io", "python-stackless" ]
So i'm toying around with stackless python, writing a *very simple* webserver to teach myself programming with microthreads/tasklets. But now to my problem, when I run something like `ab -n 100000 -c 50 http://192.168.0.192/` (100k requests, 50 concurrency) in apache bench I get something like 6k req/s, the second time I run it I get 5.5k, third time 5k, fourth time, 4.5k, etc. all the way down to 100req/s or something. The problem goes away when I restart the python script, though. Now my question is why? Am i forgetting to delete tasklets? I've checked the stackless.getruncount() (and it always seems to return 1, for some reason) so it doesn't seem like there would be any dead tasklets hanging around? I've tried calling .kill() on all tasklets that are done, didn't help. I just can't figure this one out. ``` import socket import select import stackless import time class socket_wrapper(object): def __init__(self, sock, sockets): super(socket_wrapper, self).__init__() self.sock = sock self.fileno = sock.fileno self.sockets_list = sockets self.channel = stackless.channel() self.writable = False self.error = False def remove(self): self.sock.close() self.sockets_list.remove(self) def send(self, data): self.sock.send(data) def push(self, bytes): self.channel.send(self.sock.recv(bytes)) def stackless_accept(accept, handler, recv_size=1024, timeout=0): sockets = [accept] while True: read, write, error = select.select(sockets, sockets, sockets, timeout) for sock in read: if sock is accept: # Accept socket and create wrapper sock = socket_wrapper(sock.accept()[0], sockets) # Create tasklett for this connection tasklet = stackless.tasklet(handler) tasklet.setup(sock) # Store socket sockets.append(sock) else: # Send data to handler sock.push(recv_size) # Tag all writable sockets for sock in write: if sock is not accept: sock.writable = True # Tag all faulty sockets for sock in error: if sock is not accept: sock.error = True else: pass # should do something here if the main socket is faulty timeout = 0 if socket else 1 stackless.schedule() def simple_handler(tsock): data = "" while data[-4:] != "\r\n\r\n": data += tsock.channel.receive() while not tsock.writable and not tsock.error: stackless.schedule() if not tsock.error: tsock.send("HTTP/1.1 200 OK\r\nContent-length: 8\r\n\r\nHi there") tsock.remove() sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(("192.168.0.192", 8000)) sock.listen(5) stackless.tasklet(stackless_accept)(sock, simple_handler) stackless.run() ```
Two things. First, please make Class Name start with an Upper Case Letter. It's more conventional and easier to read. More importantly, in the `stackless_accept` function you accumulate a `list` of `Sock` objects, named `sockets`. This list appears to grow endlessly. Yes, you have a `remove`, but it isn't *always* invoked. If the socket gets an error, then it appears that it will be left in the collection forever.
Euler problem number #4
555,009
2
2009-02-16T23:21:46Z
555,020
9
2009-02-16T23:25:00Z
[ "python", "palindrome" ]
Using Python, I am trying to solve [problem #4](http://projecteuler.net/index.php?section=problems&id=4) of the [Project Euler](http://projecteuler.net/) problems. Can someone please tell me what I am doing incorrectly? The problem is to **Find the largest palindrome made from the product of two 3-digit numbers**. Here is what I have thus far. ``` import math def main(): for z in range(100, 1000): for y in range(100, 1000): for x in range(1, 1000000): x = str(x) if x == x[::-1] and x == z*y: print x if __name__ == '__main__': main() ```
Try computing x from the product of z and y rather than checking every number from 1 to a million. Think about it: if you were asked to calculate 500\*240, which is more efficient - multiplying them, or counting up from 1 until you find the right answer?
Euler problem number #4
555,009
2
2009-02-16T23:21:46Z
555,107
9
2009-02-17T00:08:11Z
[ "python", "palindrome" ]
Using Python, I am trying to solve [problem #4](http://projecteuler.net/index.php?section=problems&id=4) of the [Project Euler](http://projecteuler.net/) problems. Can someone please tell me what I am doing incorrectly? The problem is to **Find the largest palindrome made from the product of two 3-digit numbers**. Here is what I have thus far. ``` import math def main(): for z in range(100, 1000): for y in range(100, 1000): for x in range(1, 1000000): x = str(x) if x == x[::-1] and x == z*y: print x if __name__ == '__main__': main() ```
Some efficiency issues: 1. start at the top (since we can use this in skipping a lot of calculations) 2. don't double-calculate > ``` > def is_palindrome(n): > s = str(n) > return s == s[::-1] > > def biggest(): > big_x, big_y, max_seen = 0,0, 0 > for x in xrange(999,99,-1): > for y in xrange(x, 99,-1): # so we don't double count > if x*y < max_seen: continue # since we're decreasing, > # nothing else in the row can be bigger > if is_palindrome(x*y): > big_x, big_y, max_seen = x,y, x*y > > return big_x,big_y,max_seen > > biggest() > # (993, 913, 906609) > ```
Match series of (non-nested) balanced parentheses at end of string
555,344
3
2009-02-17T02:29:03Z
555,404
7
2009-02-17T03:02:58Z
[ "python", "regex" ]
How can I match one or more parenthetical expressions appearing at the end of string? Input: ``` 'hello (i) (m:foo)' ``` Desired output: ``` ['i', 'm:foo'] ``` Intended for a python script. Paren marks cannot appear inside of each other ([no nesting](http://i89.photobucket.com/albums/k220/kipper_308/fran_web.jpg)), and the parenthetical expressions may be separated by whitespace. It's harder than it might seem at first glance, at least so it seems to me.
``` paren_pattern = re.compile(r"\(([^()]*)\)(?=(?:\s*\([^()]*\))*\s*$)") def getParens(s): return paren_pattern.findall(s) ``` or even shorter: ``` getParens = re.compile(r"\(([^()]*)\)(?=(?:\s*\([^()]*\))*\s*$)").findall ``` explaination: ``` \( # opening paren ([^()]*) # content, captured into group 1 \) # closing paren (?= # look ahead for... (?:\s*\([^()]*\))* # a series of parens, separated by whitespace \s* # possibly more whitespace after $ # end of string ) # end of look ahead ```
Character Translation using Python (like the tr command)
555,705
28
2009-02-17T06:33:06Z
555,724
29
2009-02-17T06:40:10Z
[ "python" ]
Is there a way to do character translation (kind of like the tr command) using python
See [`string.translate`](http://docs.python.org/library/stdtypes.html#str.translate) ``` import string "abc".translate(string.maketrans("abc", "def")) # => "def" ``` Note the doc's comments about subtleties in the translation of unicode strings. Edit: Since `tr` is a bit more advanced, also consider using `re.sub`.
Character Translation using Python (like the tr command)
555,705
28
2009-02-17T06:33:06Z
1,385,542
14
2009-09-06T12:17:56Z
[ "python" ]
Is there a way to do character translation (kind of like the tr command) using python
If you're using python3 translate is less verbose: ``` >>> 'abc'.translate(str.maketrans('ac','xy')) 'xby' ``` Ahh.. and there is also equivalent to `tr -d`: ``` >>> "abc".translate(str.maketrans('','','b')) 'ac' ``` For `tr -d` with python2.x use an additional argument to translate function: ``` >>> "abc".translate(None, 'b') 'ac' ```
ImportError: No module named copy_reg pickle
556,269
13
2009-02-17T10:42:58Z
556,295
17
2009-02-17T10:52:36Z
[ "python", "pickle" ]
I'm trying to unpickle an object stored as a blob in a MySQL database. I've manually generated and stored the pickled object in the database, but when I try to unpickle the object, I get the following rather cryptic exception: ImportError: No module named copy\_reg Any ideas as to why this happens? **Method of Reproduction** Note: Must do step 1 on a Windows PC and steps 3 and 4 on a Linux PC. 1) On a Windows PC: ``` file = open("test.txt", "w") thing = {'a': 1, 'b':2} cPickle.dump(thing, file) ``` 2) Manually insert contents of text.txt into blob field of MySQL database running on linux 3) In Python running on a linux machine, fetch the contents of column from MySQL 4) Assuming that you put the contents of the blob column into a variable called data, try this: ``` cPickle.loads(rawString) ```
It seems this might be caused by my method of exporting the pickled object. [This bug report](http://www.archivum.info/[email protected]/2007-04/msg00222.html) seens to suggest that my issue can be resolved by exporting to a file writen in binary mode. I'm going to give this a go now and see if this solves my issue. UPDATE: This works. The solution is to make sure you export your pickled object to a file open in binary mode, even if you are using the default protocol 0 (commonly referred to as being "text") Correct code based on orignal example in question: ``` file = open("test.txt", 'wb') thing = {'a': 1, 'b':2} cPickle.dump(thing, file) ```
ImportError: No module named copy_reg pickle
556,269
13
2009-02-17T10:42:58Z
760,499
9
2009-04-17T13:50:01Z
[ "python", "pickle" ]
I'm trying to unpickle an object stored as a blob in a MySQL database. I've manually generated and stored the pickled object in the database, but when I try to unpickle the object, I get the following rather cryptic exception: ImportError: No module named copy\_reg Any ideas as to why this happens? **Method of Reproduction** Note: Must do step 1 on a Windows PC and steps 3 and 4 on a Linux PC. 1) On a Windows PC: ``` file = open("test.txt", "w") thing = {'a': 1, 'b':2} cPickle.dump(thing, file) ``` 2) Manually insert contents of text.txt into blob field of MySQL database running on linux 3) In Python running on a linux machine, fetch the contents of column from MySQL 4) Assuming that you put the contents of the blob column into a variable called data, try this: ``` cPickle.loads(rawString) ```
Also, simply running dos2unix (under linux) over the (windows-created) pickle file solved the problem for me. (Haven't tried the open mode 'wb' thing.) Dan
Python list serialization - fastest method
556,730
11
2009-02-17T13:16:25Z
556,946
7
2009-02-17T14:07:06Z
[ "python", "serialization", "caching" ]
I need to load (de-serialize) a pre-computed list of integers from a file in a Python script (into a Python list). The list is large (upto millions of items), and I can choose the format I store it in, as long as loading is fastest. Which is the fastest method, and why? 1. Using `import` on a .py file that just contains the list assigned to a variable 2. Using `cPickle`'s `load` 3. Some other method (perhaps `numpy`?) Also, how can one benchmark such things reliably? **Addendum:** measuring this reliably is difficult, because `import` is cached so it can't be executed multiple times in a test. The loading with pickle also gets faster after the first time probably because page-precaching by the OS. Loading 1 million numbers with `cPickle` takes 1.1 sec the first time run, and 0.2 sec on subsequent executions of the script. Intuitively I feel `cPickle` should be faster, but I'd appreciate numbers (this is quite a challenge to measure, I think). And yes, it's important for me that this performs quickly. Thanks
I would guess [cPickle](http://docs.python.org/library/pickle.html#module-cPickle) will be fastest if you really need the thing in a list. If you can use an [array](http://docs.python.org/library/array.html), which is a built-in sequence type, I timed this at a quarter of a second for 1 million integers: ``` from array import array from datetime import datetime def WriteInts(theArray,filename): f = file(filename,"wb") theArray.tofile(f) f.close() def ReadInts(filename): d = datetime.utcnow() theArray = array('i') f = file(filename,"rb") try: theArray.fromfile(f,1000000000) except EOFError: pass print "Read %d ints in %s" % (len(theArray),datetime.utcnow() - d) return theArray if __name__ == "__main__": a = array('i') a.extend(range(0,1000000)) filename = "a_million_ints.dat" WriteInts(a,filename) r = ReadInts(filename) print "The 5th element is %d" % (r[4]) ```
How to get distinct Django apps on same subdomain to share session cookie?
556,907
7
2009-02-17T13:58:41Z
557,020
12
2009-02-17T14:21:11Z
[ "python", "django", "deployment", "session", "cookies" ]
We have a couple of Django applications deployed on the same subdomain. A few power users need to jump between these applications. I noticed that each time they bounce between applications their session cookie receives a new session ID from Django. I don't use the Django session table much except in one complex workflow. If the user bounces between applications while in this workflow they lose their session and have to start over. I dug through the Django session code and discovered that the: > django.conf.settings.SECRET\_KEY is used to perform an integrity check on the sessions on each request. If the integrity check fails, a new session is created. Realizing this, I changed the secret key in each of these applications to use the same value, thinking this would allow the integrity check to pass and allow them to share Django sessions. However, it didn't seem to work. Is there a way to do this? Am I missing something else? Thanks in advance
I would instead advise you to set `SESSION_COOKIE_NAME` to *different* values for the two apps. Your users will still have to log in twice initially, but their sessions won't conflict - if they log in to app A, then app B, and return to A, they'll still have their A session. Sharing sessions between Django instances is probably not a good idea. If you want some kind of single-sign-on, look into something like django-cas. You'll still have 2 sessions (as you should), but the user will only log in once.
How to get distinct Django apps on same subdomain to share session cookie?
556,907
7
2009-02-17T13:58:41Z
659,606
8
2009-03-18T18:44:25Z
[ "python", "django", "deployment", "session", "cookies" ]
We have a couple of Django applications deployed on the same subdomain. A few power users need to jump between these applications. I noticed that each time they bounce between applications their session cookie receives a new session ID from Django. I don't use the Django session table much except in one complex workflow. If the user bounces between applications while in this workflow they lose their session and have to start over. I dug through the Django session code and discovered that the: > django.conf.settings.SECRET\_KEY is used to perform an integrity check on the sessions on each request. If the integrity check fails, a new session is created. Realizing this, I changed the secret key in each of these applications to use the same value, thinking this would allow the integrity check to pass and allow them to share Django sessions. However, it didn't seem to work. Is there a way to do this? Am I missing something else? Thanks in advance
I agree that sharing sessions between Django instances is probably not a good idea. If you really wanted to, you could: * make sure the two django applications share the same SECRET\_KEY * make sure the two django applications share the same SeSSON\_COOKIE\_NAME * make sure the SESSION\_COOKIE\_DOMAIN is set to something that lets the two instances share cookies. (If they really share the same subdomain, your current setting is probably fine.) * make sure both Django instances use the same session backend (the same database, the same file directory, the same memcached config, etc.) * make sure that anything put into the session makes sense in both Django databases: at the very least, that'll include the user id, since Django auth uses that to remember which user is logged in. All that said, I haven't actually tried all this, so you may still have trouble!
How to re-use a reusable app in Django
557,171
17
2009-02-17T14:50:22Z
557,509
25
2009-02-17T15:59:50Z
[ "python", "django", "code-reuse" ]
## Hello Django experts I am trying to create my first site in Django and as I'm looking for example apps out there to draw inspiration from, I constantly stumble upon a term called *"reusable apps"*. I understand the *concept* of an app that is reusable easy enough, but the means of reusing an app in Django are quite lost for me. Few questions that are bugging me in the whole business are: What is the preferred way to re-use an existing Django app? Where do I put it and how do I reference it? From what I understand, the recommendation is to put it on your "PYTHONPATH", but that breaks as soon as I need to deploy my app to a remote location that I have limited access to (e.g. on a hosting service). So, if I develop my site on my local computer and intend to deploy it on an ISP where I only have ftp access, how do I re-use 3rd party Django apps so that if I deploy my site, the site keeps working (e.g. the only thing I can count on is that the service provider has Python 2.5 and Django 1.x installed)? How do I organize my Django project so that I could easily deploy it along with all of the reusable apps I want to use?
In general, the only thing required to use a reusable app is to make sure it's on `sys.path`, so that you can import it from Python code. In most cases (if the author follows best practice), the reusable app tarball or bundle will contain a top-level directory with docs, a README, a `setup.py`, and then a subdirectory containing the actual app (see [django-voting](http://code.google.com/p/django-voting/source/browse/#svn/trunk) for an example; the app itself is in the "voting" subdirectory). This subdirectory is what needs to be placed in your Python path. Possible methods for doing that include: * running `pip install appname`, if the app has been uploaded to [PyPI](https://pypi.python.org/pypi) (these days most are) * installing the app with `setup.py install` (this has the same result as `pip install appname`, but requires that you first download and unpack the code yourself; pip will do that for you) * manually symlinking the code directory to your Python site-packages directory * using software like [virtualenv](http://pypi.python.org/pypi/virtualenv) to create a "virtual Python environment" that has its own site-packages directory, and then running `setup.py install` or `pip install appname` with that virtualenv active, or placing or symlinking the app in the virtualenv's site-packages (highly recommended over all the "global installation" options, if you value your future sanity) * placing the application in some directory where you intend to place various apps, and then adding that directory to the PYTHONPATH environment variable You'll know you've got it in the right place if you can fire up a Python interpreter and "import voting" (for example) without getting an ImportError. On a server where you have FTP access only, your only option is really the last one, and they have to set it up for you. If they claim to support Django they must provide *some* place where you can upload packages and they will be available for importing in Python. Without knowing details of your webhost, it's impossible to say how they structure that for you.
Django - having middleware communicate with views/templates
557,460
7
2009-02-17T15:47:49Z
557,538
12
2009-02-17T16:06:36Z
[ "python", "django" ]
Alright, this is probably a really silly question but I am new to Python/Django so I can't really wrap my head around its scoping concepts just yet. Right now I am writing a [middleware](http://docs.djangoproject.com/en/dev/topics/http/middleware/#topics-http-middleware) class to handle some stuff, and I want to set 'global' variables that my views and templates can access. What is the "right" way of doing this? I considered doing something like this: ## middleware.py ``` from django.conf import settings class BeforeFilter(object): def process_request(self, request): settings.my_var = 'Hello World' return None ``` ## views.py ``` from django.conf import settings from django.http import HttpResponse def myview(request): return HttpResponse(settings.my_var) ``` Although this works, I am not sure if it is the "Django way" or the "Python way" of doing this. So, my questions are: 1. Is this the right way? 2. If it is the right way, what is the right way of adding variables that can be used in the actual template from the middleware? Say I want to evaluate something and I want to set a variable `headername` as 'My Site Name' in the middleware, and I want to be able to do `{{ headername }}` in all templates. Doing it the way I have it now I'd have to add `headername` to the context inside every view. Is there anyway to bypass this? I am thinking something along the lines of CakePHP's `$this->set('headername','My Site Name');` 3. I am using the middleware class as an equivalent of CakePHP's `beforeFilter` that runs before every view (or controller in CakePHP) is called. Is this the right way of doing this? 4. Completely unrelated but it is a small question, what is a nice way of printing out the contents of a variable to the browser ala `print_r`? Say I want to see all the stuff inside the `request` that is passed into the view? Is `pprint` the answer?
Here's what we do. We use a context processor like this... ``` def context_myApp_settings(request): """Insert some additional information into the template context from the settings. Specifically, the LOGOUT_URL, MEDIA_URL and BADGES settings. """ from django.conf import settings additions = { 'MEDIA_URL': settings.MEDIA_URL, 'LOGOUT_URL': settings.LOGOUT_URL, 'BADGES': settings.BADGES, 'DJANGO_ROOT': request.META['SCRIPT_NAME'], } return additions ``` Here the setting that activates this. ``` TEMPLATE_CONTEXT_PROCESSORS = ( "django.core.context_processors.auth", "django.core.context_processors.debug", "django.core.context_processors.i18n", "django.core.context_processors.media", "django.core.context_processors.request", "myapp. context_myApp_settings", ) ``` This provides "global" information in the context of each template that gets rendered. This is the standard Django solution. See <http://docs.djangoproject.com/en/dev/ref/templates/api/#ref-templates-api> for more information on context processors. --- "what is a nice way of printing out the contents of a variable to the browser ala print\_r?" In the view? You can provide a `pprint.pformat` string to a template to be rendered for debugging purposes. In the log? You have to use Python's `logging` module and send stuff to a separate log file. The use of simple print statements to write stuff to the log doesn't work wonderfully consistently for all Django implementations (mod\_python, for example, loses all the stdout and stderr stuff.)
Django - having middleware communicate with views/templates
557,460
7
2009-02-17T15:47:49Z
557,540
19
2009-02-17T16:06:49Z
[ "python", "django" ]
Alright, this is probably a really silly question but I am new to Python/Django so I can't really wrap my head around its scoping concepts just yet. Right now I am writing a [middleware](http://docs.djangoproject.com/en/dev/topics/http/middleware/#topics-http-middleware) class to handle some stuff, and I want to set 'global' variables that my views and templates can access. What is the "right" way of doing this? I considered doing something like this: ## middleware.py ``` from django.conf import settings class BeforeFilter(object): def process_request(self, request): settings.my_var = 'Hello World' return None ``` ## views.py ``` from django.conf import settings from django.http import HttpResponse def myview(request): return HttpResponse(settings.my_var) ``` Although this works, I am not sure if it is the "Django way" or the "Python way" of doing this. So, my questions are: 1. Is this the right way? 2. If it is the right way, what is the right way of adding variables that can be used in the actual template from the middleware? Say I want to evaluate something and I want to set a variable `headername` as 'My Site Name' in the middleware, and I want to be able to do `{{ headername }}` in all templates. Doing it the way I have it now I'd have to add `headername` to the context inside every view. Is there anyway to bypass this? I am thinking something along the lines of CakePHP's `$this->set('headername','My Site Name');` 3. I am using the middleware class as an equivalent of CakePHP's `beforeFilter` that runs before every view (or controller in CakePHP) is called. Is this the right way of doing this? 4. Completely unrelated but it is a small question, what is a nice way of printing out the contents of a variable to the browser ala `print_r`? Say I want to see all the stuff inside the `request` that is passed into the view? Is `pprint` the answer?
1. It's not the best way. You could set my\_var on the request rather than on the settings. Settings are global and apply to the whole site. You don't want to modify it for every request. There could be concurrency issues with multiple request updating/reading the variable at the same time. 2. To access request.my\_var in your templates you could do **{{ request.my\_var }}**. To get access to the request variable in your template you will have to add **django.core.context\_processors.request** to your **TEMPLATE\_CONTEXT\_PROCESSORS** setting. 3. Yes. Other terminology to describe request middleware would be request pre-processor/filter/interceptor. Also, if you want to use a common Site name for the header in your templates, you might want to check out the Django Sites application which provides a site name variable for your use.
How do I use easy_install and buildout when pypi is down?
557,462
13
2009-02-17T15:48:23Z
557,832
12
2009-02-17T17:22:44Z
[ "python", "plone", "easy-install", "buildout" ]
I am using [buildout](http://pypi.python.org/pypi/zc.buildout) to automatically download and setup the many dependencies of my Plone installation. buildout more or less uses easy\_install to download and install a bunch of Python eggs. This usually works, but it doesn't work if any of the dependencies cannot be downloaded or if I want buildout to find an internal package not appropriate for pypi. How can I set up my own local version of pypi to automatically mirror the packages I need? Will it still depend on third-party servers for packages that use pypi for their metadata but not their code?
Here are [instructions on how to setup your own PyPi mirror](http://www.zopyx.de/blog/creating-a-local-pypi-mirror). The homepage of this project is [here](http://www.openplans.org/projects/pypi-mirroring/project-home). There also seems to be a growing number of mirrors out there. For instructions on how to setup your own package index, check out [this blog post](http://plope.com/Members/chrism/distribution_links_considered_harmful) where one solution is explained at the end. Then you can also host your own internal packages in there. The advantage is also that the versions are fixed that way. (For a way to pin the versions directly in buildout, check out [this post](http://maurits.vanrees.org/weblog/archive/2008/01/easily-creating-repeatable-buildouts)). If there is only metadata on PyPI and the archive is stored somewhere else you might of course copy that over to your index as well. If you just use a PyPI mirror I assume that you still need access to these servers.
How do I use easy_install and buildout when pypi is down?
557,462
13
2009-02-17T15:48:23Z
3,292,240
8
2010-07-20T16:36:12Z
[ "python", "plone", "easy-install", "buildout" ]
I am using [buildout](http://pypi.python.org/pypi/zc.buildout) to automatically download and setup the many dependencies of my Plone installation. buildout more or less uses easy\_install to download and install a bunch of Python eggs. This usually works, but it doesn't work if any of the dependencies cannot be downloaded or if I want buildout to find an internal package not appropriate for pypi. How can I set up my own local version of pypi to automatically mirror the packages I need? Will it still depend on third-party servers for packages that use pypi for their metadata but not their code?
You can also use a mirror. Put this in the "[global]" section of "~/.pip/pip.conf": ``` index-url = http://d.pypi.python.org/simple/ ``` This is a recent feature as announced [here](http://mail.python.org/pipermail/catalog-sig/2010-July/003132.html).
Want procmail to run a custom python script, everytime a new mail shows up
557,906
9
2009-02-17T17:37:23Z
557,932
11
2009-02-17T17:45:04Z
[ "python", "email", "procmail" ]
I have a pretty usual requirement with procmail but I am unable to get the results somehow. I have procmailrc file with this content: ``` :0 * ^To.*@myhost | /usr/bin/python /work/scripts/privilege_emails_forward.py ``` Wherein my custom python script(privilege\_emails\_forward.py) will be scanning through the email currently received and do some operations on the mail content. But I am unable to get the script getting executed at the first shot(let alone scanning through the mail content). * Is this a correct way of invoking an external program(python) as soon as new mail arrives? * And how does my python program(privilege\_emails\_forward.py) will receive the mail as input? I mean as sys.argv or stdin????
That is just fine, just put `fw` after `:0` (`:0 fw`). Your python program will receive the mail on `stdin`. You have to 'echo' the possibly transformed mail on `stdout`. `fw` means: * `f` Consider the pipe as a filter. * `w` Wait for the filter or program to finish and check its exitcode (normally ignored); if the filter is unsuccessful, then the text will not have been filtered. My SPAM checker (bogofilter) just works like that. It adds headers and later procmail-rules do something depending on these headers.
Debugging web apps
557,927
8
2009-02-17T17:43:59Z
557,938
7
2009-02-17T17:47:05Z
[ "python", "eclipse", "debugging", "google-app-engine" ]
I've gotten pretty used to step-through debuggers over the years, both in builder, and using the pydev debugger in Eclipse. Currently, I'm making something in Python and running it on Google App Engine, and I should add that I'm pretty new to developing any real web app; I've never really done much beyond editing HTML code. So, I'm running Google's dev\_appserver and viewing my work at <http://localhost>, dig, and right now, the only tool I'm using to identify issues is PMD (poor man's debugger). . .basically writing things to the html pages to see the value of local variables. Is there a better technique for dealing with this?
The dev\_appserver is just a python script, you can simply use the pydev debugger on that script with the proper arguments as far as I know. Here is a very detailed guide on how to do that: <http://www.ibm.com/developerworks/opensource/library/os-eclipse-mashup-google-pt1/index.html>