input_text
stringlengths
54
40.1k
target_text
stringlengths
5
29.4k
How to retrieve an element from a set without removing it? Suppose the following: ````>>>s = set([1 2 3]) ```` How do I get a value (any value) out of s without doing s pop()? I want to leave the item in the set until I am sure I can remove it - something I can only be sure of after an asynchronous call to another host Quick and dirty: ````>>>elem = s pop() >>>s add(elem) ```` But do you know of a better way? Ideally in constant time
Two options that do not require copying the whole set: ````for e in s: break # e is now an element from s ```` Or ````e = next(iter(s)) ```` But in general sets do not support indexing or slicing
Replacements for switch statement in Python? I want to write a function in Python that returns different fixed values based on the value of an input index In other languages I would use a `switch` or `case` statement but Python does not appear to have a `switch` statement What are the recommended Python solutions in this scenario?
You could use a dictionary: ````def f(x): return { 'a': 1 'b': 2 }[x] ````
Automate firefox with python? Been scouring the net for something like firewatir but for python I am trying to automate firefox on linux Any suggestions?
The languages of choice of Firefox is Javascript Unless you have a specific requirement that requires Python I would advice you to use that
Can distutils create empty __init__ py files? If all of my `__init__ py` files are empty do I have to store them into version control or is there a way to make `distutils` create empty `__init__ py` files during installation?
In Python `__init__ py` files actually have a meaning! They mean that the folder they are in is a Python module As such they have a real role in your code and should most probably be stored in Version Control You could well imagine a folder in your source tree that is NOT a Python module for example a folder containing only resources (e g images) and no code That folder would not need to have a `__init__ py` file in it Now how do you make the difference between folders where distutils should create those files and folders where it should not ?
Windows Mobile development in Python What is the best way to start developing Windows Mobile Professional applications in Python? Is there a reasonable SDK including an emulator? Is it even possible without doing excessive amount of underlaying Windows API calls for UI for instance?
<H2>Python CE</H2> Python port for Windows CE (Pocket PC) devices Intended to be as close to desktop version as possible (console current directory support testsuite passed) <a href="http://pythonce sourceforge net/"><img src="http://pythonce sourceforge net/images/python-logo jpg" alt="Python CE" /></a> <img src="http://sourceforge net/dbimage php?id=76454" alt="alt text" />
cross platform IPC I am looking for suggestions on possible IPC mechanisms that are: - <strong>cross platform</strong> (WIN32 and Linux at least) - Simple to implement in <strong>C++</strong> as well as the <strong>most common scripting languages</strong> (perl ruby python etc) - Finally <strong>simple to use</strong> from a programming point of view! What are my options? I am programming under Linux but I would like what I write to be portable to other OSes in the future I have thought about using sockets named pipes or something like DBus Does anyone have any advice?
For C++ check out <a href="http://www boost org/doc/libs/1_36_0/doc/html/interprocess html">Boost IPC</a> <br /> You can probably create or find some bindings for the scripting languages as well Otherwise if it is really important to be able to interface with scripting languages your best bet is simply to use files pipes or sockets or even a higher level abstraction like HTTP
python regex to match multi-line preprocessor macro What follows is a regular expression I have written to match multi-line pre-processor macros in C / C++ code I am by no means a regular expressions guru so I would welcome any advice on how I can make this better Here is the regex: ````\s*#define( *\\\n)+[\S]+(?!\\) ```` It should match all of this: ````#define foo(x) if(x) \ doSomething(x) ```` But only some of this (should not match the next line of code: ````#define foo(x) if(x) \ doSomething(x) normalCode(); ```` And also should not match single-line preprocessor macros I am pretty sure that the regex above works - but as I said there probably a better way of doing it and I imagine that there are ways of breaking it Can anyone suggest any?
This is a simple test program I knocked up: ````#!/usr/bin/env python TEST1=""" #include "Foo h" #define bar foo\\ x #include "Bar h" """ TEST2=""" #define bar foo #define x 1 \\ 12 \\ 2 \\\\ 3 Foobar """ TEST3=""" #define foo(x) if(x) \\ doSomething(x) """ TEST4=""" #define foo(x) if(x) \\ doSomething(x) normalCode(); """ import re matcher = re compile(r"^[ \t]*#define( *\\\n)+ *$" re MULTILINE) def extractDefines(s): mo = matcher search(s) if not mo: print mo return print mo group(0) extractDefines(TEST1) extractDefines(TEST2) extractDefines(TEST3) extractDefines(TEST4) ```` The re I used: ````r"^[ \t]*#define( *\\\n)+ *$" ```` Is very similar to the one use used the changes: - [ \t] To avoid newlines at the start of the define - I rely on being greedy so I can use a simple *$ at the end to get the first line of the define that does not end with \
How do I write a python HTTP server to listen on multiple ports? I am writing a small web server in Python using BaseHTTPServer and a custom subclass of BaseHTTPServer BaseHTTPRequestHandler Is it possible to make this listen on more than one port? What I am doing now: ````class MyRequestHandler(BaseHTTPServer BaseHTTPRequestHandler): def doGET [ ] class ThreadingHTTPServer(ThreadingMixIn HTTPServer): pass server = ThreadingHTTPServer(('localhost' 80) MyRequestHandler) server serve_forever() ````
Sure; just start two different servers on two different ports in two different threads that each use the same handler Here is a complete working example that I just wrote and tested If you run this code then you will be able to get a Hello World webpage at both <a href="http://localhost:1111/">http://localhost:1111/</a> and <a href="http://localhost:2222/">http://localhost:2222/</a> ````from threading import Thread from SocketServer import ThreadingMixIn from BaseHTTPServer import HTTPServer BaseHTTPRequestHandler class Handler(BaseHTTPRequestHandler): def do_GET(self): self send_response(200) self send_header("Content-type" "text/plain") self end_headers() self wfile write("Hello World!") class ThreadingHTTPServer(ThreadingMixIn HTTPServer): pass def serve_on_port(port): server = ThreadingHTTPServer(("localhost" port) Handler) server serve_forever() Thread(target=serve_on_port args=[1111]) start() serve_on_port(2222) ````
Getting random row through SQLAlchemy How do I select a(or some) random row(s) from a table using SQLAlchemy?
There Is a couple of ways through SQL depending on which data base is being used (I think SQLAlchemy can use all these anyways) mysql: ````SELECT colum FROM table ORDER BY RAND() LIMIT 1 ```` PostgreSQL: ````SELECT column FROM table ORDER BY RANDOM() LIMIT 1 ```` MSSQL: ````SELECT TOP 1 column FROM table ORDER BY NEWID() ```` IBM DB2: ````SELECT column RAND() as IDX FROM table ORDER BY IDX FETCH FIRST 1 ROWS ONLY ```` Oracle: ````SELECT column FROM (SELECT column FROM table ORDER BY dbms_random value) WHERE rownum = 1 ```` However I do not know of any standard way
How do you retrieve items from a dictionary in the order that they are inserted? Is it possible to retrieve items from a Python dictionary in the order that they were inserted?
You cannot do this with the base dict class -- it is ordered by hash You could build your own dictionary that is really a list of key value pairs or somesuch which would be ordered
Where do the Python unit tests go? If you are writing a library or an app where do the unit test files go? It is nice to separate the test files from the main app code but it is awkward to put them into a "tests" subdirectory inside of the app root directory because it makes it harder to import the modules that you will be testing Is there a best practice here?
I do not believe there is an established "best practice" I put my tests in another directory outside of the app code I then add the main app directory to sys path (allowing you to import the modules from anywhere) in my test runner script (which does some other stuff as well) before running all the tests This way I never have to remove the tests directory from the main code when I release it saving me time and effort if an ever so tiny amount
Python dictionary from an object's fields Do you know if there is a built-in function to build a dictionary from an arbitrary object? I would like to do something like this: ````&gt;&gt;&gt; class Foo: bar = 'hello' baz = 'world' &gt;&gt;&gt; f = Foo() &gt;&gt;&gt; props(f) { 'bar' : 'hello' 'baz' : 'world' } ```` <strong>NOTE:</strong> It should not include methods Only fields Thanks
The `dir` builtin will give you all the object's attributes including special methods like `__str__` `__dict__` and a whole bunch of others which you probably do not want But you can do something like: ````&gt;&gt;&gt; class Foo(object): bar = 'hello' baz = 'world' &gt;&gt;&gt; f = Foo() &gt;&gt;&gt; [name for name in dir(f) if not name startswith('__')] [ 'bar' 'baz' ] &gt;&gt;&gt; dict((name getattr(f name)) for name in dir(f) if not name startswith('__')) { 'bar': 'hello' 'baz': 'world' } ```` So can extend this to only return data attributes and not methods by defining your `props` function like this: ````import inspect def props(obj): pr = {} for name in dir(obj): value = getattr(obj name) if not name startswith('__') and not inspect ismethod(value): pr[name] = value return pr ````
Is it pythonic for a function to return multiple values? In python you can have a function return multiple values Here is a contrived example: ````def divide(x y): quotient = x/y remainder = x % y return quotient remainder (q r) = divide(22 7) ```` This seems very useful but it looks like it can also be abused ("Well function X already computes what we need as an intermediate value Let us have X return that value also") When should you draw the line and define a different method?
Firstly note that Python allows for the following (no need for the parenthesis): ````q are = divide(22 7) ```` Regarding your question there is no hard and fast rule either way For simple (and usually contrived) examples it may seem that it is always possible for a given function to have a single purpose resulting in a single value However when using Python for real-world applications you quickly run into many cases where returning multiple values is necessary and results in cleaner code So I would say do whatever makes sense and do not try to conform to an artificial convention Python supports multiple return values so use it when appropriate
python cgi on IIS How do you set up IIS so that you can call python scripts from asp pages? Ok so I found the answer to that question here: <a href="http://support microsoft com/kb/276494" rel="nofollow">http://support microsoft com/kb/276494</a> So on to my next question: How do you call a cgi script from within classic asp (vb) code? Particularly one which is not in the web root directory
You could also do it <a href="http://www 4guysfromrolla com/webtech/082201-1 shtml" rel="nofollow">this way</a>
Comparing runtimes I am trying to get some accurate runtime comparisons of PHP vs Python (and potentially any other language that I have to include) Timing within a script is not my problem but timing within a script does not account for everything from the moment the request is made to run the script to output <blockquote> 1) Is it actually worth taking such things into account? 2) Assuming it is worth taking it into account how do I do this? </blockquote> I am using a Mac so I have got access to Linux commands and I am not afraid to compile/create a command to help me I just do not know how to write such a command
If your idea is to compare the languages I would say anything outside them is not relevant for comparison purposes Nonetheless you can use the time command to measure everything and can compare it with the timing within a script Like this: ````$ time script php HI! real 0m3 218s user 0m0 080s sys 0m0 064s ```` It will give you clock time user time (php interpreter) and sys time (OS time) If you are thinking web then it gets a lot harder because you would be mixing webserver overhead and that is not always easy to compare if say you are using WSGI v/s mod_php Then you would have to hook probes into the webserving parts of the chain as well
What is a good way to find relative paths in Google App Engine? So I have done the trivial "warmup" apps with GAE Now I would like to build something with a more complex directory structure Something along the lines of: ````siteroot/ models/ controllers/ controller1/ controller2/ templates/ template1/ template2/ ```` etc The controllers will be Python modules handling requests They would then need to locate (Django-style) templates in associated folders Most of the demo apps I have seen resolve template paths like this: ````path = os path join(os path dirname(__file__) 'myPage html') ```` the __ file __ property resolves to the currently executing script So in my above example if a Python script were running in controllers/controller1/ then the 'myPage html' would resolve to that same directory -- controllers/controller1/myPage html -- and I would rather cleanly separate my Python code and templates The solution I have hacked together feels hacky: ````base_paths = os path split(os path dirname(__file__)) template_dir = os path join(base_paths[0] "templates") ```` So I am just snipping off the last element of the path for the currently running script and appending the template directory to the new path The other (non-GAE specific) solutions I have seen for resolving Python paths seem pretty heavyweight (such as splitting paths into lists and manipulating accordingly) Django seems to have an answer for this but I would rather stick to the GAE API vs creating a full Django app and modifying it for GAE I am assuming anything hard-coded would be non-starter since the apps live on Google's infinite server farm So what is a better way?
The `dirname` function returns an absolute path use relative paths See what is the current directory when your controllers are executed with `os path abspath(os path curdir)` and build a path to the templates relative to that location (without the `os path abspath` part of course) This will only work if the current directory is somewhere inside <them>siteroot</them> else you could do something like this: ````template_dir = os path join(os path dirname(__file__) os path pardir "templates") ````
Is there a way around coding in Python without the tab indent & whitespace criteria? I want to start using Python for small projects but the fact that a misplaced tab or indent can throw a compile error is really getting on my nerves Is there some type of setting to turn this off? I am currently using NotePad++ Is there maybe an IDE that would take care of the tabs and indenting?
No How would Python parse your script if there was a way to disable this?
Which is the most useful Mercurial hook for programming in a loosely connected team? I recently discovered the notify extension in Mercurial which allows me quickly send out emails whenever I push changes but I am pretty sure I am still missing out on a lot of functionality which could make my life a lot easier - notify-extension: <a href="http://www selenic com/mercurial/wiki/index cgi/NotifyExtension" rel="nofollow">http://www selenic com/mercurial/wiki/index cgi/NotifyExtension</a> Which Mercurial hook or combination of interoperating hooks is the most useful for working in a loosely connected team? Please add links to non-standard parts you use and/or add the hook (or a description how to set it up) so others can easily use it
Take a look at the hgweb stuff You can set up RSS feeds and see all the revisions et cetera
How create threads under Python for Delphi I am hosting Python script with Python for Delphi components inside my Delphi application I would like to create background tasks which keep running by script Is it possible to create threads which keep running even if the script execution ends (but not the host process which keeps going on) I have noticed that the program gets stuck if the executing script ends and there is thread running However if I will wait until the thread is finished everything goes fine I am trying to use "threading" standard module for threads
Threads by definition are part of the same process If you want them to keep running they need to be forked off into a new process; see os fork() and friends You will probably want the new process to end (via exit() or the like) immediately after spawning the script
Classes in Python In Python is there any way to make a class then make a second version of that class with identical dat a but which can be changed then reverted to be the same as the data in the original class? So I would make a class with the numbers 1 to 5 as the data in it then make a second class with the same names for sections (or very similar) Mess around with the numbers in the second class then with one function then reset them to be the same as in the first class The only alternative I have found is to make one aggravatingly long class with too many separate pieces of data in it to be readily usable
A class is a template it allows you to create a blueprint you can then have multiple instances of a class each with different numbers like so ````class dog(object): def __init__(self height width lenght): self height = height self width = width self length = length def revert(self): self height = 1 self width = 2 self length = 3 dog1 = dog(5 6 7) dog2 = dog(2 3 4) dog1 revert() ````
When to create a new app (with startapp) in Django? I have googled around for this but I still have trouble relating to what Django defines as "apps" Should I create a new app for each piece of functionality in a site even though it uses models from the main project? Do you guys have good rule of thumb of when to split off a new app and when to keep functionality together with the "main project" or other apps?
I tend to create new applications for each logically separate set of models e g : - User Profiles - Forum Posts - Blog posts
Best Python supported server/client protocol? I am looking for a good server/client protocol supported in Python for making data requests/file transfers between one server and many clients Security is also an issue - so secure login would be a plus I have been looking into XML-RPC but it looks to be a pretty old (and possibly unused these days?) protocol
<a href="http://pyro sf net">Pyro</a> (Python Remote Objects) is fairly clever if all your server/clients are going to be in Python I use <a href="http://www xmpp org">XMPP</a> alot though since I am communicating with hosts that are not always Python XMPP lends itself to being extended fairly easily too There is an excellent XMPP library for python called <a href="http://pyxmpp jajcus net">PyXMPP</a> which is reasonably up to date and has no dependancy on Twisted
How can I make a time delay in Python? I would like to know how to put a time delay in a Python script
You can use the sleep() function in the time module It can take a float argument for sub second resolution ````from time import sleep sleep(0 1) # Time in seconds ````
Sending mail from Python using SMTP I am using the following method to send mail from Python using SMTP Is it the right method to use or are there gotchas I am missing ? ````from smtplib import SMTP import datetime debuglevel = 0 smtp = SMTP() smtp set_debuglevel(debuglevel) smtp connect('YOUR MAIL SERVER' 26) smtp login('USERNAME@DOMAIN' 'PASSWORD') from_addr = "John Doe <john@doe net&gt;" to_addr = "foo@bar com" subj = "hello" date = datetime datetime now() strftime( "%d/%m/%Y %H:%M" ) message_text = "Hello\nThis is a mail from your server\n\nBye\n" message = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s" % ( from_addr to_addr subj date message_text ) smtp sendmail(from_addr to_addr message) smtp quit() ````
The main gotcha I see is that you are not handling any errors: login() and sendmail() both have documented exceptions that they can throw and it seems like connect() must have some way to indicate that it was unable to connect - probably an exception thrown by the underlying socket code
How to setup VIM autoindentation properly for editing Python files - * py I have troubles setting VIM (7 1 xxx) for editing python files Indenting seems to be broken (optimal 4 spaces) I have followed some tutorials I found via Google Still no effect :/ Please help
I use this on my macbook: ````" configure expanding of tabs for various file types au BufRead BufNewFile * py set expandtab au BufRead BufNewFile * c set noexpandtab au BufRead BufNewFile * h set noexpandtab au BufRead BufNewFile Makefile* set noexpandtab " -------------------------------------------------------------------------------- " configure editor with tabs and nice stuff " -------------------------------------------------------------------------------- set expandtab " enter spaces when tab is pressed set textwidth=120 " break lines when line length increases set tabstop=4 " use 4 spaces to represent tab set softtabstop=4 set shiftwidth=4 " number of spaces to use for auto indent set autoindent " copy indent from current line when starting a new line " make backspaces more powerfull set backspace=indent eol start set ruler " show line and column number syntax on " syntax highlighting set showcmd " show (partial) command in status line ```` (edited to only show stuff related to indent / tabs)
Caching compiled regex objects in Python? Each time a python file is imported that contains a large quantity of static regular expressions cpu cycles are spent compiling the strings into their representative state machines in memory ````a = re compile("a *b") b = re compile("c *d") ```` Question: Is it possible to store these regular expressions in a cache on disk in a pre-compiled manner to avoid having to execute the regex compilations on each import? Pickling the object simply does the following causing compilation to happen anyway: ````&gt;&gt;&gt; import pickle &gt;&gt;&gt; import re &gt;&gt;&gt; x = re compile(" *") &gt;&gt;&gt; pickle dumps(x) "cre\n_compile\np0\n(S' *'\np1\nI0\ntp2\nRp3\n " ```` And re objects are unmarshallable: ````&gt;&gt;&gt; import marshal &gt;&gt;&gt; import re &gt;&gt;&gt; x = re compile(" *") &gt;&gt;&gt; marshal dumps(x) Traceback (most recent call last): File "<stdin&gt;" line 1 in <module&gt; ValueError: unmarshallable object ````
Note that each module initializes itself only once during the life of an app no matter how many times you import it So if you compile your expressions at the module's global scope (ie not in a function) you should be fine
How to add method using metaclass How do I add an instance method to a class using a metaclass (yes I do need to use a metaclass)? The following kind of works but the func_name will still be "foo": ````def bar(self): print "bar" class MetaFoo(type): def __new__(cls name bases dict): dict["foobar"] = bar return type(name bases dict) class Foo(object): __metaclass__ = MetaFoo &gt;&gt;&gt; f = Foo() &gt;&gt;&gt; f foobar() bar &gt;&gt;&gt; f foobar func_name 'bar' ```` My problem is that some library code actually uses the func_name and later fails to find the 'bar' method of the Foo instance I could do: ````dict["foobar"] = types FunctionType(bar func_code {} "foobar") ```` There is also types MethodType but I need an instance that does'nt exist yet to use that Am I missing someting here?
I think what you want to do is this: ````&gt;&gt;&gt; class Foo(): def __init__(self x): self x = x &gt;&gt;&gt; def bar(self): print 'bar:' self x &gt;&gt;&gt; bar func_name = 'foobar' &gt;&gt;&gt; Foo foobar = bar &gt;&gt;&gt; f = Foo(12) &gt;&gt;&gt; f foobar() bar: 12 &gt;&gt;&gt; f foobar func_name 'foobar' ```` Now you are free to pass `Foo`s to a library that expects `Foo` instances to have a method named `foobar` Unfortunately (1) I do not know how to use metaclasses and (2) I am not sure I read your question correctly but I hope this helps Note that `func_name` is only assignable in Python 2 4 and higher
Decorating a parent class method I would like to make a child class that has a method of the parent class where the method is a 'classmethod' in the child class but <strong>not</strong> in the parent class Essentially I am trying to accomplish the following: ````class foo(Object): def meth1(self val): self value = val class bar(foo): meth1 = classmethod(foo meth1) ````
What are you trying to accomplish? If I saw such a construct in live Python code I would consider beating the original programmer
How do I create a new signal in pygtk I have created a python object but I want to send signals on it I made it inherit from gobject GObject but there does not seem to be any way to create a new signal on my object
Here is how: ````import gobject class MyGObjectClass(gobject GObject): gobject signal_new("signal-name" MyGObjectClass gobject SIGNAL_RUN_FIRST None (str int)) ```` Where the second to last argument is the return type and the last argument is a tuple of argument types
Nice Python wrapper for Yahoo's Geoplanet web service? Has anybody created a nice wrapper around Yahoo's geo webservice "GeoPlanet" yet?
After a brief amount of Googling I found nothing that looks like a wrapper for this API but I am not quite sure if a wrapper is what is necessary for GeoPlanet According to Yahoo's <a href="http://developer yahoo com/geo/guide/api_docs html#api_overview" rel="nofollow">documentation</a> for GeoPlanet requests are made in the form of an HTTP GET messages which can very easily be made using Python's <a href="http://docs python org/lib/module-httplib html" rel="nofollow">httplib module</a> and <a href="http://developer yahoo com/geo/guide/response_formats html" rel="nofollow">responses</a> can take one of several forms including XML and JSON Python can very easily parse these formats In fact Yahoo! itself even offers libraries for parsing both <a href="http://developer yahoo com/python/python-xml html" rel="nofollow">XML</a> and <a href="http://developer yahoo com/python/python-json html" rel="nofollow">JSON</a> with Python I know it sounds like a lot of libraries but all the hard work has already been done for the programmer It would just take a little "gluing together" and you would have yourself a nice interface to Yahoo! GeoPlanet using the power of Python
Serving dynamically generated ZIP archives in Django How to serve users a dynamically generated ZIP archive in Django? I am making a site where users can choose any combination of available books and download them as ZIP archive I am worried that generating such archives for each request would slow my server down to a crawl I have also heard that Django does not currently have a good solution for serving dynamically generated files
Cannot you just write a link to a "zip server" or whatnot? Why does the zip archive itself need to be served from Django? A 90's era CGI script to generate a zip and spit it to stdout is really all that is required here at least as far as I can see
How to import a module given the full path? How can I load a Python module given its full path? Note that the file can be anywhere in the filesystem as it is a configuration option
I believe you can use <a href="https://docs python org/2/library/imp html#imp find_module" rel="nofollow">`imp find_module()`</a> and <a href="https://docs python org/2/library/imp html#imp load_module" rel="nofollow">`imp load_module()`</a> to load the specified module You will need to split the module name off of the path i e if you wanted to load `/home/mypath/mymodule py` you would need to do: ````imp find_module('mymodule' '/home/mypath/') ```` but that should get the job done
why might my pyglet vertex lists and batches be very slow on Windows? I am writing opengl code in python using the library pyglet When I draw to the screen using pyglet graphics vertex_list or pyglet graphics batch objects they are very slow (~0 1 fps) compared to plain old pyglet graphics draw() or just glVertex() calls which are about 40fps for the same geometry In Linux the vertex_list is about the same speed as glVertex which is disappointing and batch methods are about twice as fast which is a little better but not as much gain as I was hoping for
I do not know personally but I noticed that you have not posted to <a href="http://groups google com/group/pyglet-users" rel="nofollow">the pyglet mailing list</a> about this More Pyglet users as well as the primary developer read that list
Why do you need explicitly have the "self" argument into a Python method? When defining a method on a class in Python it looks something like this: ````class MyClass(object): def __init__(self x y): self x = x self y = y ```` But in some other languages such as C# you have a reference to the object that the method is bound to with the "this" keyword without declaring it as an argument in the method prototype Was this an intentional language design decision in Python or are there some implementation details that require the passing of "self" as an argument?
It is to minimize the difference between methods and functions It allows you to easily generate methods in metaclasses or add methods at runtime to pre-existing classes e g ````&gt;&gt;&gt; class C(object): def foo(self): print "Hi!" &gt;&gt;&gt; &gt;&gt;&gt; def bar(self): print "Bork bork bork!" &gt;&gt;&gt; &gt;&gt;&gt; c = C() &gt;&gt;&gt; C bar = bar &gt;&gt;&gt; c bar() Bork bork bork! &gt;&gt;&gt; c foo() Hi! &gt;&gt;&gt; ```` It also (as far as I know) makes the implementation of the python runtime easier
How to copy a file to a remote server in Python using SCP or SSH? I have a text file on my local machine that is generated by a daily Python script run in cron I would like to add a bit of code to have that file sent securely to my server over SSH
If you want the simple approach this should work You will want to " close()" the file first so you know it is flushed to disk from Python ````import os os system("scp FILE USER@SERVER:PATH") #e g os system("scp foo bar joe@srvr net:/path/to/foo bar") ```` You need to generate (on the source machine) and install (on the destination machine) an ssh key beforehand so that the scp automatically gets authenticated with your public ssh key (in other words so your script does not ask for a password) <a href="http://www modwest com/help/kb20-90 html">ssh-keygen example</a>
Change command Method for Tkinter Button in Python I create a new Button object but did not specify the `command` option upon creation Is there a way in Tkinter to change the command (onclick) function after the object has been created?
Sure; just use the `bind` method to specify the callback after the button has been created I have just written and tested the example below You can find a nice tutorial on doing this at <a href="http://www pythonware com/library/tkinter/introduction/events-and-bindings htm" rel="nofollow">http://www pythonware com/library/tkinter/introduction/events-and-bindings htm</a> ````from Tkinter import Tk Button root = Tk() button = Button(root text="Click Me!") button pack() def callback(event): print "Hello World!" button bind("<Button-1&gt;" callback) root mainloop() ````
Send file using POST from a Python script Is there a way to send a file using POST from a Python script?
Yes You would use the `urllib2` module and encode using the `multipart/form-data` content type Here is some sample code to get you started -- it is a bit more than just file uploading but you should be able to read through it and see how it works: ````user_agent = "image uploader" default_message = "Image $current of $total" import logging import os from os path import abspath isabs isdir isfile join import random import string import sys import mimetypes import urllib2 import httplib import time import re def random_string (length): return '' join (random choice (string letters) for ii in range (length 1)) def encode_multipart_data (data files): boundary = random_string (30) def get_content_type (filename): return mimetypes guess_type (filename)[0] or 'application/octet-stream' def encode_field (field_name): return ('--' boundary 'Content-Disposition: form-data; name="%s"' % field_name '' str (data [field_name])) def encode_file (field_name): filename = files [field_name] return ('--' boundary 'Content-Disposition: form-data; name="%s"; filename="%s"' % (field_name filename) 'Content-Type: %s' % get_content_type(filename) '' open (filename 'rb') read ()) lines = [] for name in data: lines extend (encode_field (name)) for name in files: lines extend (encode_file (name)) lines extend (('--%s--' % boundary '')) body = '\r\n' join (lines) headers = {'content-type': 'multipart/form-data; boundary=' boundary 'content-length': str (len (body))} return body headers def send_post (url data files): req = urllib2 Request (url) connection = httplib HTTPConnection (req get_host ()) connection request ('POST' req get_selector () *encode_multipart_data (data files)) response = connection getresponse () logging debug ('response = %s' response read ()) logging debug ('Code: %s %s' response status response reason) def make_upload_file (server thread delay = 15 message = None username = None email = None password = None): delay = max (int (delay or '0') 15) def upload_file (path current total): assert isabs (path) assert isfile (path) logging debug ('Uploading %r to %r' path server) message_template = string Template (message or default_message) data = {'MAX_FILE_SIZE': '3145728' 'sub': '' 'mode': 'regist' 'com': message_template safe_substitute (current = current total = total) 'resto': thread 'name': username or '' 'email': email or '' 'pwd': password or random_string (20) } files = {'upfile': path} send_post (server data files) logging info ('Uploaded %r' path) rand_delay = random randint (delay delay 5) logging debug ('Sleeping for % 2f seconds------------------------------\n\n' rand_delay) time sleep (rand_delay) return upload_file def upload_directory (path upload_file): assert isabs (path) assert isdir (path) matching_filenames = [] file_matcher = re compile (r'\ (?:jpe?g|gif|png)$' re IGNORECASE) for dirpath dirnames filenames in os walk (path): for name in filenames: file_path = join (dirpath name) logging debug ('Testing file_path %r' file_path) if file_matcher search (file_path): matching_filenames append (file_path) else: logging info ('Ignoring non-image file %r' path) total_count = len (matching_filenames) for index file_path in enumerate (matching_filenames): upload_file (file_path index 1 total_count) def run_upload (options paths): upload_file = make_upload_file (**options) for arg in paths: path = abspath (arg) if isdir (path): upload_directory (path upload_file) elif isfile (path): upload_file (path) else: logging error ('No such path: %r' % path) logging info ('Done!') ````
Are tuples more efficient than lists in Python? Is there any performance difference between tuples and lists when it comes to instantiation and retrieval of elements?
Tuples should be slightly more efficient and because of that faster than lists because they are immutable
Static class variables in Python Is it possible to have static class variables or methods in python? What syntax is required to do this?
Variables declared inside the class definition but not inside a method are class or static variables: ````&gt;&gt;&gt; class MyClass: i = 3 &gt;&gt;&gt; MyClass i 3 ```` As @<a href="http://stackoverflow com/questions/68645/static-class-variables-in-python#answer-69067">millerdev</a> points out this creates a class-level "i" variable but this is distinct from any instance-level "i" variable so you could have ````&gt;&gt;&gt; m = MyClass() &gt;&gt;&gt; m i = 4 &gt;&gt;&gt; MyClass i m i &gt;&gt;&gt; (3 4) ```` This is different from C++ and Java but not so different from C# where a static member cannot be accessed using a reference to an instance See <a href="https://docs python org/2/tutorial/classes html#class-objects">what the Python tutorial has to say on the subject of classes and class objects</a> @Steve Johnson has already answered regarding <a href="http://web archive org/web/20090214211613/http://pyref infogami com/staticmethod">static methods</a> also documented under <a href="https://docs python org/2/library/functions html#staticmethod">"Built-in Functions" in the Python Library Reference</a> ````class C: @staticmethod def f(arg1 arg2 ): ```` @beidy recommends <a href="https://docs python org/2/library/functions html#classmethod">classmethod</a>s over staticmethod as the method then receives the class type as the first argument but I am still a little fuzzy on the advantages of this approach over staticmethod If you are too then it probably does not matter
Best way to open a socket in Python I want to open a TCP client socket in Python Do I have to go through all the low-level BSD create-socket-handle / connect-socket stuff or is there a simpler one-line way?
Opening sockets in python is pretty simple You really just need something like this: ````import socket sock = socket socket() sock connect((address port)) ```` and then you can `send()` and `recv()` like any other socket
libxml2-p25 on OS X 10 5 needs sudo? When trying to use `libxml2` as myself I get an error saying the package cannot be found If I run as as super user I am able to import fine I have installed `python25` and all `libxml2` and `libxml2-py25` related libraries via fink and own the entire path including the library Any ideas why I would still need to sudo?
Check your path (run 'echo $PATH')
Can I implement a web user authentication system in python without POST? My university does not support the POST cgi method (I know it is crazy) and I was hoping to be able to have a system where a user can have a username and password and log in securely Is this even possible? If it is not how would you do it with POST? Just out of curiosity Cheers!
You could use HTTP Authentication if supported You would have to add SSL as all methods POST GET and HTTP Auth (well except Digest HHTP authentication) send plaintext GET is basically just like POST it just has a limit on the amount of data you can send which is usually a lot smaller than POST and a semantic difference which makes GET not a good candidate from that point of view even if technically they both can do it As for examples what are you using? There are many choices in Python like the cgi module or some framework like Django CherryPy and so on
Take a screenshot via a python script [Linux] I want to take a screenshot via a python script and unobtrusively save it I am only interested in the Linux solution and should support any X based environment
A short search turned up <a href="http://www flagar com/en/software/gtkshots" rel="nofollow">gtkShots</a> looks like it might help you as it is a GPLed python screenshot program so should have what you need in it
Why are Python's 'private' methods not actually private? Python gives us the ability to create 'private' methods and variables within a class by prepending double underscores to the name like this: `__myPrivateMethod()` How then can one explain this ````>>> class MyClass: def myPublicMethod(self): print 'public method' def __myPrivateMethod(self): print 'this is private!!' >>> obj = MyClass() >>> obj myPublicMethod() public method >>> obj __myPrivateMethod() Traceback (most recent call last): File "" line 1 in AttributeError: MyClass instance has no attribute '__myPrivateMethod' >>> dir(obj) ['_MyClass__myPrivateMethod' '__doc__' '__module__' 'myPublicMethod'] >>> obj _MyClass__myPrivateMethod() this is private!! ```` What is the deal?! I will explain this a little for those who did not quite get that ````>>> class MyClass: def myPublicMethod(self): print 'public method' def __myPrivateMethod(self): print 'this is private!!' >>> obj = MyClass() ```` What I did there is create a class with a public method and a private method and instantiate it Next I call its public method ````>>> obj myPublicMethod() public method ```` Next I try and call its private method ````>>> obj __myPrivateMethod() Traceback (most recent call last): File "" line 1 in AttributeError: MyClass instance has no attribute '__myPrivateMethod' ```` Everything looks good here; we are unable to call it It is in fact 'private' Well actually it is not Running <them>dir()</them> on the object reveals a new magical method that python creates magically for all of your 'private' methods ````>>> dir(obj) ['_MyClass__myPrivateMethod' '__doc__' '__module__' 'myPublicMethod'] ```` This new method's name is always an underscore followed by the class name followed by the method name ````>>> obj _MyClass__myPrivateMethod() this is private!! ```` So much for encapsulation eh? In any case I would always heard Python does not support encapsulation so why even try? What gives?
From <a href="http://www faqs org/docs/diveintopython/fileinfo_private html">http://www faqs org/docs/diveintopython/fileinfo_private html</a> <blockquote> Strictly speaking private methods are accessible outside their class just not easily accessible Nothing in Python is truly private; internally the names of private methods and attributes are mangled and unmangled on the fly to make them seem inaccessible by their given names You can access the __parse method of the MP3FileInfo class by the name _MP3FileInfo__parse Acknowledge that this is interesting then promise to never ever do it in real code Private methods are private for a reason but like many other things in Python their privateness is ultimately a matter of convention not force </blockquote>
Python Authentication API I am looking for a python library that will help me to create an authentication method for a desktop app I am writing I have found several method in web framework such as django or turbogears I just want a kind of username-password association stored into a local file I can write it by myself but I am really it already exists and will be a better solution (I am not very fluent with encryption)
I think you should make your own authentication method as you can make it fit your application best but use a library for encryption such as <a href="http://www pycrypto org" rel="nofollow">pycrypto</a> or some other more lightweight library by the way if you need windows binaries for pycrypto you can get them <a href="http://www voidspace org uk/python/modules shtml#pycrypto" rel="nofollow">here</a>
Python: user input and commandline arguments How do I have a Python script that can accept user input (assuming this is possible) and how do I make it read in arguments if run from the command line?
````var = raw_input("Please enter something: ") print "you entered" var ````
Python Psycopg error and connection handling (v MySQLdb) Is there a way to make psycopg and postgres deal with errors without having to reestablish the connection like MySQLdb? The commented version of the below works with MySQLdb the comments make it work with Psycopg2: ````results = {'felicitas': 3 'volumes': 8 'acillevs': 1 'mosaics': 13 'perat\xe9': 1 'representative': 6 } for item in sorted(results): try: cur execute("""insert into resultstab values ('%s' %d)""" % (item results[item])) print item results[item] # conn commit() except: # conn=psycopg2 connect(user='bvm' database='wdb' password='redacted') # cur=conn cursor() print 'choked on' item continue ```` This must slow things down could anyone give a suggestion for passing over formatting errors? Obviously the above chokes on apostrophes but is there a way to make it pass over that without getting something like the following or committing reconnecting etc?: ````agreement 19 agreements 1 agrees 1 agrippa 9 choked on agrippa's choked on agrippina ````
I think your code looks like this at the moment: ````l = "a very long text" split() for e in l: cursor execute("INSERT INTO yourtable (yourcol) VALUES ('" e "')") ```` So try to change it into something like this: ````l = "a very long text" split() for e in l: cursor execute("INSERT INTO yourtable (yourcol) VALUES (%s)" (e )) ```` so never forget to pass your parameters in the parameters list then you do not have to care about your quotes and stuff it is also more secure You can read more about it at <a href="http://www python org/dev/peps/pep-0249/" rel="nofollow">http://www python org/dev/peps/pep-0249/</a> also have a look there at the method executemany() which is specially designed to execute the same statement multiple times
HTML parser in Python Using the Python Documentation I found the <a href="http://docs python org/lib/module-HTMLParser html">HTML parser</a> but I have no idea which library to import to use it how do I find this out (bearing in mind it does not say on the page)
Try: ````import HTMLParser ```` In Python 3 0 the HTMLParser module has been renamed to html parser you can check about this <a href="http://docs python org/library/htmlparser html">here</a> Python 3 0 ````import html parser ```` Python 2 2 and above ````import HTMLParser ````
Using the docstring from one method to automatically overwrite that of another method The problem: I have a class which contains a template method `execute` which calls another method `_execute` Subclasses are supposed to overwrite `_execute` to implement some specific functionality This functionality should be documented in the docstring of `_execute` Advanced users can create their own subclasses to extend the library However another user dealing with such a subclass should only use `execute` so he will not see the correct docstring if he uses `help(execute)` Therefore it would be nice to modify the base class in such a way that in a subclass the docstring of `execute` is automatically replaced with that of `_execute` Any ideas how this might be done? I was thinking of metaclasses to do this to make this completely transparent to the user
Well the doc-string is stored in `__doc__` so it would not be too hard to re-assign it based on the doc-string of `_execute` after the fact Basically: ` ``` class MyClass(object): def execute(self): '''original doc-string''' self _execute() class SubClass(MyClass): def _execute(self): '''sub-class doc-string''' pass # re-assign doc-string of execute def execute(self *args **kw): return MyClass execute(*args **kw) execute __doc__=_execute __doc__ ``` ` Execute has to be re-declared to that the doc string gets attached to the version of execute for the `SubClass` and not for `MyClass` (which would otherwise interfere with other sub-classes) That is not a very tidy way of doing it but from the POV of the user of a library it should give the desired result You could then wrap this up in a meta-class to make it easier for people who are sub-classing
Python and "re" A tutorial I have on Regex in python explains how to use the re module in python I wanted to grab the URL out of an A tag so knowing Regex I wrote the correct expression and tested it in my regex testing app of choice and ensured it worked When placed into python it failed After much head scratching I found out the issue it automatically expects your pattern to be at the start of the string I have found a fix but I would like to know how to change: ````regex = " *(a_regex_of_pure_awesomeness)" ```` into ````regex = "a_regex_of_pure_awesomeness" ```` Okay it is a standard URL regex but I wanted to avoid any potential confusion about what I wanted to get rid of and possibly pretend to be funny
Are you using the re match() or re search() method? My understanding is that re match() assumes a "^" at the begining of your expression and will only search at the beginning of the text while re search() acts more like the Perl regular expressions and will only match the beginning of the text if you include a "^" at the beginning of your expression Hope that helps
Python's unittest logic Can someone explain this result to me The first test succeeds but the second fails although the variable tested is changed in the first test ````&gt;&gt;&gt; class MyTest(unittest TestCase): def setUp(self): self i = 1 def testA(self): self i = 3 self assertEqual(self i 3) def testB(self): self assertEqual(self i 3) &gt;&gt;&gt; unittest main() F ====================================================================== FAIL: testB (__main__ MyTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "<pyshell#61&gt;" line 8 in testB AssertionError: 1 != 3 ---------------------------------------------------------------------- Ran 2 tests in 0 016s ````
If I recall correctly in that test framework the setUp method is run before each test
How to do relative imports in Python? Imagine this directory structure: ````app/ __init__ py sub1/ __init__ py mod1 py sub2/ __init__ py mod2 py ```` I am coding `mod1` and I need to import something from `mod2` How should I do it? I tried `from sub2 import mod2` but I am getting an "Attempted relative import in non-package" I googled around but found only "`sys path` manipulation" hacks Is not there a clean way? <hr> Edit: all my `__init__ py`'s are currently empty Edit2: I am trying to do this because sub2 contains classes that are shared across sub packages (`sub1` `subX` etc ) Edit3: The behaviour I am looking for is the same as described in <a href="http://www python org/dev/peps/pep-0366/">PEP 366</a> (thanks John B)
Why you even need this? Why you just do not import it as ````from app sub2 import mod2 ````
How do I sort a list of dictionaries by values of the dictionary in Python? I got a list of dictionaries and want that to be sorted by a value of that dictionary This ````[{'name':'Homer' 'age':39} {'name':'Bart' 'age':10}] ```` sorted by name should become ````[{'name':'Bart' 'age':10} {'name':'Homer' 'age':39}] ````
You have to implement your own comparison function that will compare the dictionaries by values of name keys See <a href="http://wiki python org/moin/HowTo/Sorting">Sorting Mini-HOW TO from PythonInfo Wiki</a>
mod_python/MySQL error on INSERT with a lot of data: "OperationalError: (2006 'MySQL server has gone away')" When doing an INSERT with a lot of data ie: ````INSERT INTO table (mediumtext_field) VALUES (' lots of text here: about 2MB worth ') ```` MySQL returns <blockquote> "OperationalError: (2006 'MySQL server has gone away')" </blockquote> This is happening within a minute of starting the script so it is not a timeout issue Also `mediumtext_field` should be able to hold ~16MB of data so that should not be a problem Any ideas what is causing the error or how to work around it? Some relevant libraries being used: `mod_python 3 3 1` `MySQL 5 0 51` (on Windows XP SP3 via xampp details below) <strong>ApacheFriends XAMPP (basic package) version 1 6 5</strong> - Apache 2 2 6 - MySQL 5 0 51 - phpMyAdmin 2 11 3
check the max_packet setting in your my cnf file this determines the largest amount of data you can send to your mysql server in a single statement exceeding this values results in that error
How to create a triple-join table with Django Using Django's built in models how would one create a triple-join between three models For example: - Users Roles and Events are the models - Users have many Roles and Roles many Users (ManyToMany) - Events have many Users and Users many Events (ManyToMany) - But for any given Event any User may have only one Role How can this be represented in the model?
I would recommend just creating an entirely separate model for this ````class Assignment(Model): user = ForeignKey(User) role = ForeignKey(Role) event = ForeignKey(Event) ```` This let us you do all the usual model stuff such as ````user assignment_set filter(role__name="Chaperon") role assignment_set filter(event__name="Silly Walkathon") ```` The only thing left is to enforce your one-role-per-user-per-event restriction You can do this in the Assignment class by either overriding the save method (<a href="http://docs djangoproject com/en/dev/topics/db/models/#overriding-predefined-model-methods" rel="nofollow">http://docs djangoproject com/en/dev/topics/db/models/#overriding-predefined-model-methods</a>) or using signals (<a href="http://docs djangoproject com/en/dev/topics/signals/" rel="nofollow">http://docs djangoproject com/en/dev/topics/signals/</a>)
Is there a python package to interface with MS Cluster? I need to write a couple of python scripts to automate the installation of Microsoft Cluster Ressources More specifically I will need to query MS Cluster to be able to get a list of ressources with their parameters And I also need to be able to create resources and set their parameters Is someone knows if there is a package/module Or even some sample scripts using Mark Hammond's pywin32 packages ?
You can accomplish this using Microsoft COM objects You can take a look at <a href="http://www boddie org uk/python/COM html" rel="nofollow">here</a> on how to start using them
Terminating a Python script I am aware of the `die()` command in PHP which stops a script early How can I do this in Python?
````import sys sys exit() ```` details from the <a href="https://docs python org/2/library/constants html#exit">`sys` module documentation</a>: <blockquote> `sys <strong>exit</strong>([<them>arg</them>])` <blockquote> Exit from Python This is implemented by raising the <a href="https://docs python org/2/library/exceptions html#SystemExit">`SystemExit`</a> exception so cleanup actions specified by finally clauses of <a href="https://docs python org/2/reference/compound_stmts html#try">`try`</a> statements are honored and it is possible to intercept the exit attempt at an outer level The optional argument <them>arg</them> can be an integer giving the exit status (defaulting to zero) or another type of object If it is an integer zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like Most systems require it to be in the range 0-127 and produce undefined results otherwise Some systems have a convention for assigning specific meanings to specific exit codes but these are generally underdeveloped; Unix programs generally use 2 for command line syntax errors and 1 for all other kind of errors If another type of object is passed None is equivalent to passing zero and any other object is printed to <a href="https://docs python org/2/library/sys html#sys stderr">`stderr`</a> and results in an exit code of 1 In particular `sys exit("some error message")` is a quick way to exit a program when an error occurs Since <a href="https://docs python org/2/library/constants html#exit">`exit()`</a> ultimately “only” raises an exception it will only exit the process when called from the main thread and the exception is not intercepted </blockquote> </blockquote> Note that this is the 'nice' way to exit @<a href="http://stackoverflow com/questions/73663/terminating-a-python-script#76374">glyphtwistedmatrix</a> below points out that if you want a 'hard exit' you can use os _exit(<them>errorcode</them>) though it is likely os-specific to some extent (it might not take an errorcode under windows for example) and it definitely is less friendly since it does not let the interpreter do any cleanup before the process dies
Sending mail via sendmail from python If I want to send mail not via SMTP but rather via sendmail is there a library for python that encapsulates this process? Better yet is there a good library that abstracts the whole 'sendmail -versus- smtp' choice? I will be running this script on a bunch of unix hosts only some of which are listening on localhost:25; a few of these are part of embedded systems and cannot be set up to accept SMTP As part of Good Practice I would really like to have the library take care of header injection vulnerabilities itself -- so just dumping a string to `popen('/usr/bin/sendmail' 'w')` is a little closer to the metal than I would like If the answer is 'go write a library ' so be it ;-)
It is quite common to just use the sendmail command from Python using os popen Personally for scripts i did not write myself I think just using the SMTP-protocol is better since it would not require installing say an sendmail clone to run on windows <a href="https://docs python org/library/smtplib html" rel="nofollow">https://docs python org/library/smtplib html</a>
Is there a common way to check in Python if an object is any function type? I have a function in Python which is iterating over the attributes returned from dir(obj) and I want to check to see if any of the objects contained within is a function method built-in function etc Normally you could use callable() for this but I do not want to include classes The best I have come up with so far is: ````isinstance(obj (types BuiltinFunctionType types FunctionType types MethodType)) ```` Is there a more future-proof way to do this check? <strong>Edit:</strong> I misspoke before when I said: "Normally you could use callable() for this but I do not want to disqualify classes " I actually <them>do</them> want to disqualify classes I want to match <them>only</them> functions not classes
````if hasattr(obj '__call__'): pass ```` This also fits in better with Python's "duck typing" philosophy because you do not really care <them>what</them> it is so long as you can call it It is worth noting that `callable()` is being removed from Python and is not present in 3 0
Random in python 2 5 not working? I am trying to use the `import random` statement in python but it does not appear to have any methods in it to use Am I missing something?
I think you need to give some more information It is not really possible to answer why it is not working based on the information in the question The basic documentation for random is at: <a href="https://docs python org/library/random html" rel="nofollow">https://docs python org/library/random html</a> You might check there
How do I get the name of a python class as a string? What method do I call to get the name of a class?
It is not a method it is a field The field is called `__name__` `class __name__` will give the name of the class as a string `object __class__ __name__` will give the name of the class of an object
How to use form values from an unbound form I have a web report that uses a Django form (new forms) for fields that control the query used to generate the report (start date end date ) The issue I am having is that the page should work using the form's initial values (unbound) but I cannot access the cleaned_data field unless I call is_valid() But is_valid() always fails on unbound forms It seems like Django's forms were designed with the use case of editing data such that an unbound form is not really useful for anything other than displaying HTML For example if I have: ````if request method == 'GET': form = MyForm() else: form = MyForm(request method POST) if form is_valid(): do_query(form cleaned_data['start_date'] form cleaned_data['end_date']) ```` is_valid() will fail if this is a GET (since it is unbound) and if I do: ````if request method == 'GET': form = MyForm() do_query(form cleaned_data['start_date'] form cleaned_data['end_date']) else: form = MyForm(request method POST) if form is_valid(): do_query(form cleaned_data['start_date'] form cleaned_data['end_date']) ```` the first call to do_query triggers exceptions on form cleaned_data which is not a valid field because is_valid() has not been called It seems like I have to do something like: ````if request method == 'GET': form = MyForm() do_query(form['start_date'] field initial form['end_date'] field initial) else: form = MyForm(request method POST) if form is_valid(): do_query(form cleaned_data['start_date'] form cleaned_data['end_date']) ```` that is there is not a common interface for retrieving the form's values between a bound form and an unbound one Does anyone see a cleaner way to do this?
You can pass a dictionary of initial values to your form: ````if request method == "GET": # calculate my_start_date and my_end_date here form = MyForm( { 'start_date': my_start_date 'end_date': my_end_date} ) ```` See the <a href="http://docs djangoproject com/en/dev/ref/forms/api/" rel="nofollow">official forms API documentation</a> where they demonstrate this <strong>edit</strong>: Based on answers from other users maybe this is the cleanest solution: ````if request method == "GET": form = MyForm() form['start_date'] = form['start_date'] field initial form['end_date'] = form['end_date'] field initial else: form = MyForm(request method POST) if form is_valid(): do_query(form cleaned_data['start_date'] form cleaned_data['end_date']) ```` I have not tried this though; can someone confirm that this works? I think this is better than creating a new method because this approach does not require other code (possibly not written by you) to know about your new 'magic' accessor
Django -vs- Grails -vs-? I am wondering if there is such a thing as Django-like ease of web app development combined with good deployment debugging and other tools? Django is a very productive framework for building content-heavy sites; the best I have tried and a breath of fresh air compared to some of the Java monstrosities out there However it is written in Python which means there is little real support in the way of deployment/packaging debugging profilers and other tools that make building and maintaining applications much easier Ruby has similar issues and although I do like Ruby <strong>much</strong> better than I like Python I get the impression that Rails is roughly in the same boat at Django when it comes to managing/supporting the app Has anyone here tried both Django and Grails (or other web frameworks) for non-trivial projects? How did they compare?
cakephp org Cakephp is really good really close to ruby on rails (1 2) It is in php works very well on shared hosts and is easy to implement The only downside is that the documentation is somewhat lacking but you quickly get it and quickly start doing cool stuff I totally recommend cakephp
Undo with GTK TextView I am trying to keep dependencies to a minimum for a program I contribute to it is a small text editor GTK Textview does not seem to come with a built-in undo function Is there any reference implementation I have been missing on so far? Is everyone writing their own undo function for their TextView widgets? I will be happy about any sample code - most happy about python sample code as our project is in python
As far as I know GTK TextView does not include an undo function So while I am not familiar with Python's GTK library I would think it does not have one The Ruby-GNOME2 project has a <a href="http://ruby-gnome2 sourceforge jp/hiki cgi?Simple+Text+Editor" rel="nofollow">sample text editor</a> that has undo/redo functionality Basically they are connecting to the insert_text and delete_range signals of the TextView widget and recording the events and associated data in a list
Which is faster python webpages or php webpages? Does anyone know how the speed of pylons(or any of the other frameworks) compares to a similar website made with php? I know that serving a python base webpage via cgi is slower than php because of its long start up every time I enjoy using pylons and I would still use it if it was slower than php But if pylons was faster than php I could maybe hopefully eventually convince my employer to allow me to convert the site over to pylons
If it are not broke do not fix it Just write a quick test but bear in mind that each language will be faster with certain functions then the other
What does BlazeDS Livecycle Data Services do that something like PyAMF or RubyAMF not do? I am doing a tech review and looking at AMF integration with various backends (Rails Python Grails etc) Lots of options are out there question is what do the Adobe products do (BlazeDS etc) that something like RubyAMF / pyAMF do not?
Good question I am not a ruby guy (i use java with flex) but what I believe differentiates blazeds vs commercial livecycle ds is - Streaming protocol support (rtmp) - competition for comet and such delivering video - Some advanced stuff for hibernate detached objects and large resultset caching that I do not fully understand or need - support? Might be others but those are the ones I know off the top of my head
'id' is a bad variable name in Python Why is it bad to name a variable `id` in Python?
Because it is the name of a builtin function
iBATIS for Python? At my current gig we use iBATIS through Java to CRUD our databases I like the abstract qualities of the tool especially when working with legacy databases as it does not impose its own syntax on you <strong>I am looking for a Python analogue to this library</strong> since the website only has Java/ NET/Ruby versions available I do not want to have to switch to Jython if I do not need to Are there any other projects similar to iBATIS functionality out there for Python?
Perhaps SQLAlchemy SQL Expression support is suitable See the <a href="http://docs sqlalchemy org/en/rel_0_5/sqlexpression html" rel="nofollow">documentation</a>
Best way to access table instances when using SQLAlchemy's declarative syntax All the docs for SQLAlchemy give `INSERT` and `UPDATE` examples using the local table instance (e g `tablename update()` ) Doing this seems difficult with the declarative syntax I need to reference `Base metadata tables["tablename"]` to get the table reference Am I supposed to do this another way? Is there a different syntax for `INSERT` and `UPDATE` recommended when using the declarative syntax? Should I just switch to the old way?
via the `__table__` attribute on your declarative class
What is the best way to calculate a 3D (or n-D) centroid? As part of a project at work I have to calculate the centroid of a set of points in 3D space Right now I am doing it in a way that seems simple but naive -- by taking the average of each set of points as in: ````centroid = average(x) average(y) average(z) ```` where `x` `y` and `z` are arrays of floating-point numbers I seem to recall that there is a way to get a more accurate centroid but I have not found a simple algorithm for doing so Anyone have any ideas or suggestions? I am using Python for this but I can adapt examples from other languages
Nope that is the only formula for the centroid of a collection of points See Wikipedia: <a href="http://en wikipedia org/wiki/Centroid">http://en wikipedia org/wiki/Centroid</a>
OPENGL User Interface Programming I am developing a graphical application to present data (not a game but a real workhorse app) It needs to be cross platform so I have chosen: - python - openGL (I need 3D blending textures etc) - pyopengl - wx/pywx - windowing dialogs etc The last component - WX - raises the question I can put together a very nice looking app (the prototypes look slick) - but when I need to interact with the user to ask questions get input I have to use WX It makes the app look inconsistent to have traditional UI with traditional dialogs and combos and text entry on top of a full screen 3D app with blending smooth motion textures etc Has anyone developed a GUI using OpenGL and python? Can you share with me the toolkits and/or tricks you used? I need combos text entry buttons radios option buttons tree view There are some toolkits out there but they are either incomplete or old and unmaintained A great example is pyUI (http://pyui sourceforge net/) - looks slick but untouched for years
You might want to look at <a href="http://clutter-project org/" rel="nofollow">Clutter</a> it looks pretty cool I have not used it yet but I intend to in an upcoming personal project
Redirect command to input of another in Python I would like to replicate this in python: ````gvimdiff <(hg cat file txt) file txt ```` (hg cat file txt outputs the most recently committed version of file txt) I know how to pipe the file to gvimdiff but it will not accept another file: ````$ hg cat file txt | gvimdiff file txt - Too many edit arguments: "-" ```` Getting to the python part ````# hgdiff py import subprocess import sys file = sys argv[1] subprocess call(["gvimdiff" "<(hg cat %s)" % file file]) ```` When subprocess is called it merely passes `<(hg cat file)` onto `gvimdiff` as a filename So is there any way to redirect a command as bash does? For simplicity's sake just cat a file and redirect it to different: ````different <(cat file txt) file txt ````
There is also the commands module: ````import commands status output = commands getstatusoutput("gvimdiff <(hg cat file txt) file txt") ```` There is also the popen set of functions if you want to actually grok the data from a command as it is running
Python ReportLab use of splitfirst/splitlast I am trying to use Python with ReportLab 2 2 to create a PDF report <br /> According to the <a href="http://www reportlab com/docs/userguide pdf">user guide</a> <blockquote> Special TableStyle Indeces [sic] In any style command the first row index may be set to one of the special strings 'splitlast' or 'splitfirst' to indicate that the style should be used only for the last row of a split table or the first row of a continuation This allows splitting tables with nicer effects around the split </blockquote> I have tried using several style elements including: ````('TEXTCOLOR' (0 'splitfirst') (1 'splitfirst') colors black) ('TEXTCOLOR' (0 'splitfirst') (1 0) colors black) ('TEXTCOLOR' (0 'splitfirst') (1 -1) colors black) ```` and none of these seems to work The first generates a TypeError with the message: ````TypeError: cannot concatenate 'str' and 'int' objects ```` and the latter two generate TypeErrors with the message: ````TypeError: an integer is required ```` Is this functionality simply broken or am I doing something wrong? If the latter what am I doing wrong?
<blockquote> [ ] In any style command <strong>the first row index</strong> may be set to one of the special strings [ ] </blockquote> In your first example you are setting the <them>second</them> row index to a special string as well Not sure why the other two do not work Are you sure this is where the exception is coming from?
Is there a benefit to defining a class inside another class in Python? What I am talking about here are nested classes Essentially I have two classes that I am modeling A DownloadManager class and a DownloadThread class The obvious OOP concept here is composition However composition does not necessarily mean nesting right? I have code that looks something like this: ````class DownloadThread: def foo(self): pass class DownloadManager(): def __init__(self): dwld_threads = [] def create_new_thread(): dwld_threads append(DownloadThread()) ```` But now I am wondering if there is a situation where nesting would be better Something like: ````class DownloadManager(): class DownloadThread: def foo(self): pass def __init__(self): dwld_threads = [] def create_new_thread(): dwld_threads append(DownloadManager DownloadThread()) ````
No composition does not mean nesting It would make sense to have a nested class if you want to hide it more in the namespace of the outer class Anyway I do not see any practical use for nesting in your case It would make the code harder to read (understand) and it would also increase the indentation which would make the lines shorter and more prone to splitting
How to check for memory leaks in Guile extension modules? I develop an extension module for Guile written in C This extension module embeds a Python interpreter Since this extension module invokes the Python interpreter I need to verify that it properly manages the memory occupied by Python objects I found that the Python interpreter is well-behaved in its own memory handling so that by running valgrind I can find memory leaks due to bugs in my own Python interpreter embedding code if there are no other interfering factors However when I run Guile under valgrind valgrind reports memory leaks Such memory leaks obscure any memory leaks due to my own code The question is what can I do to separate memory leaks due to bugs in my code from memory leaks reported by valgrind as due to Guile Another tool instead of valgrind? Special valgrind options? Give up and rely upon manual code walkthrough?
You have got a couple options One is to write a supressions file for valgrind that turns off reporting of stuff that you are not working on Python has such a file for example: <a href="http://svn python org/projects/python/trunk/Misc/valgrind-python supp" rel="nofollow">http://svn python org/projects/python/trunk/Misc/valgrind-python supp</a> If valgrind does not like your setup another possibility is using `libmudflap`; you compile your program with `gcc -fmudflap -lmudflap` and the resulting code is instrumented for pointer debugging Described in the gcc docs and here: <a href="http://gcc gnu org/wiki/Mudflap_Pointer_Debugging" rel="nofollow">http://gcc gnu org/wiki/Mudflap_Pointer_Debugging</a>
Testing GUI code: should I use a mocking library? Recently I have been experimenting with TDD while developing a GUI application in Python I find it very reassuring to have tests that verify the functionality of my code but it is been tricky to follow some of the recommened practices of TDD Namely writing tests first has been hard And I am finding it difficult to make my tests readable (due to extensive use of a mocking library) I chose a mocking library called <a href="http://labix org/mocker" rel="nofollow">mocker</a> I use it a lot since much of the code I am testing makes calls to (a) other methods in my application that depend on system state or (b) ObjC/Cocoa objects that cannot exist without an event loop etc Anyway I have got a lot of tests that look like this: ````def test_current_window_controller(): def test(config): ac = AppController() m = Mocker() ac iter_window_controllers = iwc = m replace(ac iter_window_controllers) expect(iwc()) result(iter(config)) with m: result = ac current_window_controller() assert result == (config[0] if config else None) yield test [] yield test [0] yield test [1 0] ```` Notice that this is actually three tests; all use the same parameterized test function Here is the code that is being tested: ````def current_window_controller(self): try: # iter_window_controllers() iterates in z-order starting # with the controller of the top-most window # assumption: the top-most window is the "current" one wc = self iter_window_controllers() next() except StopIteration: return None return wc ```` One of the things I have noticed with using mocker is that it is easier to write the application code first and then go back and write the tests second since most of the time I am mocking many method calls and the syntax to write the mocked calls is much more verbose (thus harder to write) than the application code It is easier to write the app code and then model the test code off of that I find that with this testing method (and a bit of discipline) I can easily write code with 100% test coverage I am wondering if these tests are good tests? Will I regret doing it this way down the road when I finally discover the secret to writing good tests? Am I violating the core principles of TDD so much that my testing is in vain?
Unit tests are really useful when you refactor your code (ie completely rewrite or move a module) As long as you have unit tests before you do the big changes you will have confidence that you have not forgotten to move or include something when you finish
How do I get started processing email related to website activity? I am writing a web application that requires user interaction via email I am curious if there is a best practice or recommended source for learning about processing email I am writing my application in Python but I am not sure what mail server to use or how to format the message or subject line to account for automated processing I am also looking for guidance on processing bouncebacks Thanks!
There are some pretty serious concerns here for how to send email automatically and here are a few: Use an email library Python includes one called 'email' This is your friend it will stop you from doing anything tragically wrong Read an example from <a href="http://docs python org/lib/node161 html" rel="nofollow">the Python Manual</a> Some points that will stop you from getting blocked by spam filters: Always send from a valid email address You must be able to send email to this address and have it received (it can go into /dev/null after it is received but it must be possible to /deliver/ there) This will stop spam filters that do Sender Address Verification from blocking your mail The email address you send from on the server sendmail(fromaddr [toaddr]) line will be where bounces go The From: line in the email is a totally different address and that is where mail will go when the user hits 'Reply:' Use this to your advantage bounces can go to one place while reply goes to another Send email to a local mail server I recommend postfix This local server will receive your mail and be responsible for sending it to your upstream server Once it has been delivered to the local server treat it as 'sent' from a programmatic point of view If you have a site that is on a static ip in a datacenter of good reputation do not be afraid to simply relay the mail directly to the internet If you are in a datacenter full of script kiddies and spammers you will need to relay this mail via a public MTA of good reputation hopefully you will be able to work this out without a hassle Do not send an email in only HTML Always send it in Plain and HTML or just Plain Be nice I use a text only email client and you do not want to annoy me Verify that you are not running SPF on your email domain or get it configured to allow your server to send the mail Do this by doing a TXT lookup on your domain ````$ dig google com txt snip ;; ANSWER SECTION: google com 300 IN TXT "v=spf1 include:_netblocks google com ~all" ```` As you can see from that result there is an SPF record there If you do not have SPF there will not be a TXT record Read more about <a href="http://en wikipedia org/wiki/Sender_Policy_Framework" rel="nofollow">SPF on wikipedia</a> Hope that helps
How do I convert local time to UTC in Python? How do I convert a datetime <them>string in local time</them> to a <them>string in UTC time</them>? I am sure I have done this before but cannot find it and SO will hopefully help me (and others) do that in future <strong>Clarification</strong>: For example if I have `2008-09-17 14:02:00` in my local timezone (`+10`) I would like to generate a string with the equivalent `UTC` time: `2008-09-17 04:02:00` Also from <a href="http://lucumr pocoo org/2011/7/15/eppur-si-muove/">http://lucumr pocoo org/2011/7/15/eppur-si-muove/</a> note that in general this is not possible as with DST and other issues there is no unique conversion from local time to UTC time
````def local_to_utc(t): secs = time mktime(t) return time gmtime(secs) def utc_to_local(t): secs = calendar timegm(t) return time localtime(secs) ```` Source: <a href="http://feihonghsu blogspot com/2008/02/converting-from-local-time-to-utc html">http://feihonghsu blogspot com/2008/02/converting-from-local-time-to-utc html</a> Example usage from <a href="http://stackoverflow com/users/8171/bd808">bd808</a>: If your source is a `datetime datetime` object `t` call as: ````local_to_utc(t timetuple()) ````
Unittest causing sys exit() No matter what I do sys exit() is called by unittest even the most trivial examples I cannot tell if my install is messed up or what is going on ````IDLE 1 2 2 ==== No Subprocess ==== &gt;&gt;&gt; import unittest &gt;&gt;&gt; &gt;&gt;&gt; class Test(unittest TestCase): def testA(self): a = 1 self assertEqual(a 1) &gt;&gt;&gt; unittest main() option -n not recognized Usage: idle pyw [options] [test] [ ] Options: -h --help Show this message -v --verbose Verbose output -q --quiet Minimal output Examples: idle pyw - run default set of tests idle pyw MyTestSuite - run suite 'MyTestSuite' idle pyw MyTestCase testSomething - run MyTestCase testSomething idle pyw MyTestCase - run all 'test*' test methods in MyTestCase Traceback (most recent call last): File "<pyshell#7&gt;" line 1 in <module&gt; unittest main() File "E:\Python25\lib\unittest py" line 767 in __init__ self parseArgs(argv) File "E:\Python25\lib\unittest py" line 796 in parseArgs self usageExit(message) File "E:\Python25\lib\unittest py" line 773 in usageExit sys exit(2) SystemExit: 2 &gt;&gt;&gt; ````
Do not try to run `unittest main()` from IDLE It is trying to access `sys argv` and it is getting the args that IDLE was started with Either run your tests in a different way from IDLE or call `unittest main()` in its own Python process
Split a string by spaces -- preserving quoted substrings -- in Python I have a string which is like this: ````this is "a test" ```` I am trying to write something in Python to split it up by space while ignoring spaces within quotes The result I am looking for is: ````['this' 'is' 'a test'] ```` PS I know you are going to ask "what happens if there are quotes within the quotes well in my application that will never happen
You want split from the <a href="https://docs python org/2/library/shlex html">shlex</a> module ````&gt;&gt;&gt; import shlex &gt;&gt;&gt; shlex split('this is "a test"') ['this' 'is' 'a test'] ```` This should do exactly what you want
PubSub lib for c# Is there a c# library which provides similar functionality to the <a href="http://wiki wxpython org/PubSub" rel="nofollow">Python PubSub</a> library? I think it is kind of an Observer Pattern which allows me to subscribe for messages of a given topic instead of using events
These may be a bit heavy for you depending on your needs but: <a href="http://www nservicebus com/" rel="nofollow">http://www nservicebus com/</a> <a href="http://blog phatboyg com/masstransit/" rel="nofollow">http://blog phatboyg com/masstransit/</a>
How do you design data models for Bigtable/Datastore (GAE)? Since the Google App Engine Datastore is based on <a href="http://research google com/archive/bigtable html">Bigtable</a> and we know that is not a relational database how do you design a <strong><them>database schema</them>/*data model*</strong> for applications that use this type of database system?
As GAE builds on how data is managed in Django there is a lot of info on how to address similar questions in the Django documentation (for example see <a href="http://www djangobook com/en/1 0/chapter05/" rel="nofollow">here</a> scroll down to 'Your first model') In short you design you db model as a regular object model and let GAE sort out all of the object-relational mappings
Btrieve without Pervasive? Is there any library available to query Btrieve databases without buying something from Pervasive? I am looking to code in C# or Python
As far as I know that is not possible It is not an open source database so writing drivers for it is really hard
How to skip sys exitfunc when unhandled exceptions occur As you can see even after the program should have died it speaks from the grave Is there a way to "deregister" the exitfunction in case of exceptions? ````import atexit def helloworld(): print("Hello World!") atexit register(helloworld) raise Exception("Good bye cruel world!") ```` outputs ````Traceback (most recent call last): File "test py" line 8 in <module&gt; raise Exception("Good bye cruel world!") Exception: Good bye cruel world! Hello World! ````
If you call ````import os os _exit(0) ```` the exit handlers will not be called yours or those registered by other modules in the application
Asychronous Programming in Python Twisted I am having trouble developing a reverse proxy in Twisted It works but it seems overly complex and convoluted So much of it feels like voodoo Are there any <them>simple solid</them> examples of asynchronous program structure on the web or in books? A sort of best practices guide? When I complete my program I would like to be able to still see the structure in some way not be looking at a bowl of spaghetti
If you are not looking to use twisted there was a great guide I used a while back Here is the <a href="http://www nightmare com/pythonwin/async_sockets html" rel="nofollow">link to it</a>
PythonWin's python interactive she will calling constructors twice? While answering <a href="http://stackoverflow com/questions/68645/python-static-variable#81002">http://stackoverflow com/questions/68645/python-static-variable#81002</a> I noticed that PythonWin PyWin32 build 209 2 interpreter seems to evaluate twice? ````PythonWin 2 5 (r25:51908 Mar 9 2007 17:40:28) [MSC v 1310 32 bit (Intel)] on win32 Portions Copyright 1994-2006 Mark Hammond - see 'Help/About PythonWin' for further copyright information &gt;&gt;&gt; class X: l = [] def __init__(self): self __class__ l append(1) &gt;&gt;&gt; X() l [1 1] &gt;&gt;&gt; ```` while the python interpreter does the right thing ````C:\&gt;python ActivePython 2 5 0 0 (ActiveState Software Inc ) based on Python 2 5 (r25:51908 Mar 9 2007 17:40:28) [MSC v 1310 32 bit (Intel)] on win32 Type "help" "copyright" "credits" or "license" for more information &gt;&gt;&gt; class X: l = [] def __init__(self): self __class__ l append(1) &gt;&gt;&gt; X() l [1] &gt;&gt;&gt; ````
My guess is as follows The PythonWin editor offers autocomplete for an object i e when you type `myobject ` it offers a little popup of all the availble method names So I think when you type `X() ` it is creating an instance of `X` in the background and doing a `dir` or similar to find out the attributes of the object So the constructor is only being run <them>once for each object</them> but to give you the interactivity it is creating objects silently in the background without telling you about it
Upload files in Google App Engine I am planning to create a web app that allows users to downgrade their visual studio project files However It seems Google App Engine accepts files uploading and flat file storing on the Google Server through `db TextProperty` and `db BlobProperty` I will be glad anyone can provide code sample (both the client and the server side) on how this can be done
You can not store files as there is not a traditional file system You can only store them in their own DataStore (in a field defined as a <a href="http://code google com/appengine/docs/datastore/typesandpropertyclasses html" rel="nofollow">BlobProperty</a>) There is an example in the previous link: ````class MyModel(db Model): blob = db BlobProperty() obj = MyModel() obj blob = db Blob( file_contents ) ````
PyQt and PyCairo I know it is possible to place a PyCairo surface inside a Gtk Drawing Area But I think Qt is a lot better to work with so I have been wondering if there is anyway to place a PyCairo surface inside some Qt component?
Qt's own OpenGL based surfaces (using QPainter) are known to be much faster than Cairo Might you explain why you want specifically Cairo in Qt? For the basics of using QPainter see <a href="http://www informit com/articles/article aspx?p=1174421" rel="nofollow">this excerpt</a> from the book "C++ GUI Programming with Qt4" and while it is C++ code the PyQt implementation will be parallel As for joining Cairo with Qt <a href="http://arstechnica com/news ars/post/20080818-nokia-helps-port-firefox-to-qt html" rel="nofollow">This article in ArsTechnica</a> sheds some light - it seems nothing that could help you exists currently (iow nobody tried such marriage)
Is there any list of blog engines written in Django? Is there any list of blog engines written in Django?
**Byteflow** is a blog engine written on Python using Django
How do I check whether a file exists using Python? How do I check whether a file exists without using the <a href="https://docs python org/3 6/reference/compound_stmts html#try">`try`</a> statement?
````import os path if os path isfile(filename): ````
Python DNS : Cannot get RRSIG records: No Answer I get DNS records from a Python program using <a href="http://www dnspython org/" rel="nofollow">DNS Python</a> I can get various DNSSEC-related records: ````&gt;&gt;&gt; import dns resolver &gt;&gt;&gt; myresolver = dns resolver Resolver() &gt;&gt;&gt; myresolver use_edns(1 0 1400) &gt;&gt;&gt; print myresolver query('sources org' 'DNSKEY') <dns resolver Answer object at 0xb78ed78c&gt; &gt;&gt;&gt; print myresolver query('ripe net' 'NSEC') <dns resolver Answer object at 0x8271c0c&gt; ```` But no RRSIG records: ````&gt;&gt;&gt; print myresolver query('sources org' 'RRSIG') Traceback (most recent call last): File "<stdin&gt;" line 1 in <module&gt; File "/usr/lib/python2 5/site-packages/dns/resolver py" line 664 in query answer = Answer(qname rdtype rdclass response) File "/usr/lib/python2 5/site-packages/dns/resolver py" line 121 in __init__ raise NoAnswer ```` I tried several signed domains like absolight fr or ripe net Trying with dig I see that there are indeed RRSIG records Checking with tcpdump I can see that DNS Python sends the correct query and receives correct replies (here eight records): ````16:09:39 342532 IP 192 134 4 69 53381 &gt; 192 134 4 162 53: 22330+ [1au] RRSIG? sources org (40) 16:09:39 343229 IP 192 134 4 162 53 &gt; 192 134 4 69 53381: 22330 8/5/6 RRSIG[|domain] ```` DNS Python 1 6 0 - Python 2 5 2 (r252:60911 Aug 8 2008 09:22:44) [GCC 4 3 1] on linux2
If you try this what happens? <blockquote> <blockquote> <blockquote> print myresolver query('sources org' 'ANY' 'RRSIG') </blockquote> </blockquote> </blockquote>
How to programmatically enable/disable network interfaces? (Windows XP) I need to enable/disable completely network interfaces from a script in Windows XP I am looking for a python solution but any general way (eg WMI some command-line à la netsh some windows call) is welcome and will be adjusted Thanks
The <a href="http://support microsoft com/kb/311272" rel="nofollow">devcon</a> tool can control the NIC but not the interface directly It is a command-line version of the Device Manager applet ````devcon disable (id or portion of name) devcon enable (id or portion of name) ````
Why is not the 'len' function inherited by dictionaries and lists in Python example: ````a_list = [1 2 3] a_list len() # does not work len(a_list) # works ```` Python being (very) object oriented I do not understand why the 'len' function is not inherited by the object Plus I keep trying the wrong solution since it appears as the logical one to me
Maybe you are looking for `__len__` If that method exists then len(a) calls it: ````&gt;&gt;&gt; class Spam: def __len__(self): return 3 &gt;&gt;&gt; s = Spam() &gt;&gt;&gt; len(s) 3 ````
How can I access App Engine through a Corporate proxy? I have corporate proxy that supports https but not HTTP CONNECT (even after authentication) It just gives 403 Forbidden in response anything but HTTP or HTTPS URLS It uses HTTP authenication not NTLM It is well documented the urllib2 does not work with https thru a proxy App Engine trys to connect to a https URL using urllib2 to update the app On *nix urllib2 expects proxies to set using env variables ````export http_proxy="http://mycorporateproxy:8080" export https_proxy="https://mycorporateproxy:8080" ```` This is sited as a work around: <a href="http://code activestate com/recipes/456195/" rel="nofollow">http://code activestate com/recipes/456195/</a> Also see <a href="http://code google com/p/googleappengine/issues/detail?id=126" rel="nofollow">http://code google com/p/googleappengine/issues/detail?id=126</a> None of these fixes have worked for me They seem to rely on the proxy server supporting HTTP CONNECT Does anyone have any other work arounds? I sure I am not the only one behind a restrictive corporate proxy
Do you mean it uses http basic-auth before allowing proxying and does it then allow 'connect' Then you should be able to tunnel over it using http-tunnel or proxytunnel
Running multiple sites from a single Python web framework What are come good (or at least clever) ways of running multiple sites from a single common Python web framework (ie: Pylons TurboGears etc)? I know you can do redirection based on the domain or path to rewrite the URI to point at a site-specific location and I have also seen some brutish "`if site == 'site1' / elseif / elseif / etc`" that I would like to avoid
Django has this built in See <a href="http://docs djangoproject com/en/dev/ref/contrib/sites/#ref-contrib-sites" rel="nofollow">the sites framework</a> As a general technique include a 'host' column in your database schema attached to the data you want to be host-specific then include the `Host` HTTP header in the query when you are retrieving data
Python - time clock() vs time time() - accuracy? Which is better to use for timing in Python? time clock() or time time()? Which one provides more accuracy? for example: ````start = time clock() do something elapsed = (time clock() - start) ```` vs ````start = time time() do something elapsed = (time time() - start) ````
Depends on what you care about If you mean WALL TIME (as in the time on the clock on your wall) time clock() provides NO accuracy because it may manage CPU time
Search for host with MAC-address using Python I would like to search for a given MAC address on my network all from within a Python script I already have a map of all the active IP addresses in the network but I cannot figure out how to glean the MAC address Any ideas?
I do not think there is a built in way to get it from Python itself My question is how are you getting the IP information from your network? To get it from your local machine you could parse ifconfig (unix) or ipconfig (windows) with little difficulty
How to best implement simple crash / error reporting? What would be the best way to implement a simple crash / error reporting mechanism? Details: my app is <strong>cross-platform (mac/windows/linux) and written in Python</strong> so I just need something that will send me a small amount of text e g just a timestamp and a traceback (which I already generate and show in my error dialog) It would be fine if it could simply email it but I cannot think of a way to do this without including a username and password for the smtp server in the application Should I implement a simple web service on the server side and have my app send it an HTTP request with the info? Any better ideas? Thanks!
The web hit is the way to go but make sure you pick a good URL - your app will be hitting it for years to come
What are the pros and cons of the various Python implementations? I am relatively new to Python and I have always used the standard cpython (v2 5) implementation I have been wondering about the other implementations though particularly Jython and IronPython What makes them better? What makes them worse? What other implementations are there? I guess what I am looking for is a summary and list of pros and cons for each implementation
Pros: Access to the libraries available for JVM or CLR Cons: Both naturally lag behind CPython in terms of features
Get list of XML attribute values in Python I need to get a list of attribute values from child elements in Python It is easiest to explain with an example Given some XML like this: ````<elements&gt; <parent name="CategoryA"&gt; <child value="a1"/&gt; <child value="a2"/&gt; <child value="a3"/&gt; </parent&gt; <parent name="CategoryB"&gt; <child value="b1"/&gt; <child value="b2"/&gt; <child value="b3"/&gt; </parent&gt; </elements&gt; ```` I want to be able to do something like: <pre class="lang-python prettyprint-override">`&gt;&gt;&gt; getValues("CategoryA") ['a1' 'a2' 'a3'] &gt;&gt;&gt; getValues("CategoryB") ['b1' 'b2' 'b3'] ```` It looks like a job for XPath but I am open to all recommendations I would also like to hear about your favourite Python XML libraries
I must admit I am a fan of <a href="http://www aaronsw com/2002/xmltramp/" rel="nofollow">xmltramp</a> due to its ease of use Accessing the above becomes: ```` import xmltramp values = xmltramp parse(''' ''') def getValues( values category ): cat = [ parent for parent in values['parent':] if parent(name) == category ] cat_values = [ child(value) for child in parent['child':] for parent in cat ] return cat_values getValues( values "CategoryA" ) getValues( values "CategoryB" ) ````