instruction
stringlengths
12
148
input
stringlengths
16
30.2k
output
stringlengths
11
27.3k
TFS Webservice Documentation
We use a lot of of python to do much of our deployment and would be handy to connect to our TFS server to get information on iteration paths, tickets etc. I can see the webservice but unable to find any documentation. Just wondering if anyone knew of anything?
The web services are not documented by Microsoft as it is not an officially supported route to talk to TFS. The officially supported route is to use their .NET API. In the case of your sort of application, the course of action I usually recommend is to create your own web service shim that lives on the TFS server (o...
Can you monkey patch methods on core types in python?
Ruby can add methods to the Number class and other core types to get effects like: 1.should_equal(1) But it seems like python cannot do this. Is this true? And if so, why? Does it have something to do with the fact that type can't be modified? Update: Rather than talking about different definitions of monkey patching...
No, you cannot. In Python, all data (classes, methods, functions, etc) defined in C extension modules (including builtins) are immutable. This is because C modules are shared between multiple interpreters in the same process, so monkeypatching them would also affect unrelated interpreters in the same process. However, ...
XML parsing - ElementTree vs SAX and DOM
Python has several ways to parse XML... I understand the very basics of parsing with SAX. It functions as a stream parser, with an event-driven API. I understand the DOM parser also. It reads the XML into memory and coverts it to objects that can be accessed with Python. Generally speaking, it was easy to choose betw...
ElementTree is much easier to use, because it represents an XML tree (basically) as a structure of lists, and attributes are represented as dictionaries. ElementTree needs much less memory for XML trees than DOM (and thus is faster), and the parsing overhead via iterparse is comparable to SAX. Additionally, iterparse r...
Standalone Python applications in Linux
How can I distribute a standalone Python application in Linux? I think I can take for granted the presence of a recent Python interpreter in any modern distribution. The problem is dealing with those libraries that do not belong to the standard library, i.e. wxPython, scipy, python cryptographic toolkit, reportlab, and...
Create a deb (for everything Debian-derived) and an rpm (for Fedora/SuSE). Add the right dependencies to the packaging and you can be reasonably sure that it will work.
What is the best project structure for a Python application?
Imagine that you want to develop a non-trivial end-user desktop (not web) application in Python. What is the best way to structure the project's folder hierarchy? Desirable features are ease of maintenance, IDE-friendliness, suitability for source control branching/merging, and easy generation of install packages. In p...
Doesn't too much matter. Whatever makes you happy will work. There aren't a lot of silly rules because Python projects can be simple. /scripts or /bin for that kind of command-line interface stuff /tests for your tests /lib for your C-language libraries /doc for most documentation /apidoc for the Epydoc-generated AP...
What are good rules of thumb for Python imports?
I am a little confused by the multitude of ways in which you can import modules in Python. import X import X as Y from A import B I have been reading up about scoping and namespaces, but I would like some practical advice on what is the best strategy, under which circumstances and why. Should imports happen at a mo...
In production code in our company, we try to follow the following rules. We place imports at the beginning of the file, right after the main file's docstring, e.g.: """ Registry related functionality. """ import wx # ... Now, if we import a class that is one of few in the imported module, we import the name directly, ...
Python Decimal
Does anyone know of a faster decimal implementation in python. As example below demonstrates, standard python decimal is ~100 times slower than float. from timeit import Timer def run(val, the_class): test = the_class(1) for c in xrange(10000): d = the_class(val) d + test d - test ...
You can try cdecimal: from cdecimal import Decimal
In production, Apache + mod_wsgi or Nginx + mod_wsgi?
What to use for a medium to large python WSGI application, Apache + mod_wsgi or Nginx + mod_wsgi? Which combination will need more memory and CPU time? Which one is faster? Which is known for being more stable than the other? I am also thinking to use CherryPy's WSGI server but I hear it's not very suitable for a very ...
For nginx/mod_wsgi, ensure you read: http://blog.dscpl.com.au/2009/05/blocking-requests-and-nginx-version-of.html Because of how nginx is an event driven system underneath, it has behavioural characteristics which are detrimental to blocking applications such as is the case with WSGI based applications. Worse case scen...
What is the time complexity of popping elements from list in Python?
I wonder what is the time complexity of pop method of list objects in Python (in CPython particulary). Also does the value of N for list.pop(N) affects the complexity?
Yes, it is O(1) to pop the last element of a Python list, and O(N) to pop an arbitrary element (since the whole rest of the list has to be shifted). Here's a great article on how Python lists are stored and manipulated: http://effbot.org/zone/python-list.htm
How to check if a string in Python is in ASCII?
I want to I check whether a string is in ASCII or not. I am aware of ord(), however when I try ord('é'), I have TypeError: ord() expected a character, but string of length 2 found. I understood it is caused by the way I built Python (as explained in ord()'s documentation). Is there another way to check?
I think you are not asking the right question-- A string in python has no property corresponding to 'ascii', utf-8, or any other encoding. The source of your string (whether you read it from a file, input from a keyboard, etc.) may have encoded a unicode string in ascii to produce your string, but that's where you nee...
How to check if OS is Vista in Python?
How, in the simplest possible way, distinguish between Windows XP and Windows Vista, using Python and pywin32 or wxPython? Essentially, I need a function that called will return True iff current OS is Vista: >>> isWindowsVista() True
Python has the lovely 'platform' module to help you out. >>> import platform >>> platform.win32_ver() ('XP', '5.1.2600', 'SP2', 'Multiprocessor Free') >>> platform.system() 'Windows' >>> platform.version() '5.1.2600' >>> platform.release() 'XP' NOTE: As mentioned in the comments proper values may not be returned when ...
Can you list the keyword arguments a Python function receives?
I have a dict, which I need to pass key/values as keyword arguments.. For example.. d_args = {'kw1': 'value1', 'kw2': 'value2'} example(**d_args) This works fine, but if there are values in the d_args dict that are not accepted by the example function, it obviously dies.. Say, if the example function is defined as def...
A little nicer than inspecting the code object directly and working out the variables is to use the inspect module. >>> import inspect >>> def func(a,b,c=42, *args, **kwargs): pass >>> inspect.getargspec(func) (['a', 'b', 'c'], 'args', 'kwargs', (42,)) If you want to know if its callable with a particular set of args,...
Docstrings for data?
Is there a way to describe the module's data in a similar way that a docstring describes a module or a funcion? class MyClass(object): def my_function(): """This docstring works!""" return True my_list = [] """This docstring does not work!"""
To my knowledge, it is not possible to assign docstrings to module data members. PEP 224 suggests this feature, but the PEP was rejected. I suggest you document the data members of a module in the module's docstring: # module.py: """About the module. module.data: contains the word "spam" """ data = "spam"
Can I pickle a python dictionary into a sqlite3 text field?
Any gotchas I should be aware of? Can I store it in a text field, or do I need to use a blob? (I'm not overly familiar with either pickle or sqlite, so I wanted to make sure I'm barking up the right tree with some of my high-level design ideas.)
I needed to achieve the same thing too. I turns out it caused me quite a headache before I finally figured out, thanks to this post, how to actually make it work in a binary format. To insert/update: pdata = cPickle.dumps(data, cPickle.HIGHEST_PROTOCOL) curr.execute("insert into table (data) values (:data)", sqlite3....
Get last answer
In many symbolic math systems, such as Matlab or Mathematica, you can use a variable like Ans or % to retrieve the last computed value. Is there a similar facility in the Python shell?
Underscore. >>> 5+5 10 >>> _ 10 >>> _ + 5 15 >>> _ 15
Shortest Sudoku Solver in Python - How does it work?
I was playing around with my own Sudoku solver and was looking for some pointers to good and fast design when I came across this: def r(a):i=a.find('0');~i or exit(a);[m in[(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3)or a[j]for j in range(81)]or r(a[:i]+m+a[i+1:])for m in'%d'%5**18] from sys import*;r(argv[1]) My own imp...
Well, you can make things a little easier by fixing up the syntax: def r(a): i = a.find('0') ~i or exit(a) [m in[(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3)or a[j]for j in range(81)] or r(a[:i]+m+a[i+1:])for m in'%d'%5**18] from sys import * r(argv[1]) Cleaning up a little: from sys import exit, argv def r(a): i...
Creating self-contained python applications
I'm trying to create a self-contained version of pisa (html to pdf converter, latest version), but I can't succeed due to several errors. I've tried py2exe, bb-freeze and cxfreeze. This has to be in windows, which makes my life a bit harder. I remember that a couple of months ago the author had a zip file containing th...
Check out pyinstaller, it makes standalone executables (as in one .EXE file, and that's it).
Does python support multiprocessor/multicore programming?
What is the difference between multiprocessor programming and multicore programming? preferably show examples in python how to write a small program for multiprogramming & multicore programming
There is no such thing as "multiprocessor" or "multicore" programming. The distinction between "multiprocessor" and "multicore" computers is probably not relevant to you as an application programmer; it has to do with subtleties of how the cores share access to memory. In order to take advantage of a multicore (or mul...
How do I execute a program from python? os.system fails due to spaces in path
I have a python script that needs to execute an external program, but for some reason fails. If I have the following script: import os; os.system("C:\\Temp\\a b c\\Notepad.exe"); raw_input(); Then it fails with the following error: 'C:\Temp\a' is not recognized as an internal or external command, operable program or b...
subprocess.call will avoid problems with having to deal with quoting conventions of various shells. It accepts a list, rather than a string, so arguments are more easily delimited. i.e. import subprocess subprocess.call(['C:\\Temp\\a b c\\Notepad.exe', 'C:\\test.txt'])
Checking for member existence in Python
I regularly want to check if an object has a member or not. An example is the creation of a singleton in a function. For that purpose, you can use hasattr like this: class Foo(object): @classmethod def singleton(self): if not hasattr(self, 'instance'): self.instance = Foo() return se...
These are two different methodologies: №1 is LBYL (look before you leap) and №2 is EAFP (easier to ask forgiveness than permission). Pythonistas typically suggest that EAFP is better, with arguments in style of "what if a process creates the file between the time you test for it and the time you try to create it yo...
Is it possible to compile Python natively (beyond pyc byte code)?
I wonder if it is possible to create an executable module from a Python script. I need to have the most performance and the flexibility of Python script, without needing to run in the Python environment. I would use this code to load on demand user modules to customize my application.
There's pyrex that compiles python like source to python extension modules rpython which allows you to compile python with some restrictions to various backends like C, LLVM, .Net etc. There's also shed-skin which translates python to C++, but I can't say if it's any good. PyPy implements a JIT compiler which attem...
How can I check the syntax of Python code in Emacs without actually executing it?
Python's IDLE has 'Check Module' (Alt-X) to check the syntax which can be called without needing to run the code. Is there an equivalent way to do this in Emacs instead of running and executing the code?
python -m py_compile script.py
Why do attribute references act like this with Python inheritance?
The following seems strange.. Basically, the somedata attribute seems shared between all the classes that inherited from the_base_class. class the_base_class: somedata = {} somedata['was_false_in_base'] = False class subclassthing(the_base_class): def __init__(self): print self.somedata firs...
You are right, somedata is shared between all instances of the class and it's subclasses, because it is created at class definition time. The lines somedata = {} somedata['was_false_in_base'] = False are executed when the class is defined, i.e. when the interpreter encounters the class statement - not when the instan...
Scrape a dynamic website
What is the best method to scrape a dynamic website where most of the content is generated by what appears to be ajax requests? I have previous experience with a Mechanize, BeautifulSoup, and python combo, but I am up for something new. --Edit-- For more detail: I'm trying to scrape the CNN primary database. There is...
This is a difficult problem because you either have to reverse engineer the javascript on a per-site basis, or implement a javascript engine and run the scripts (which has its own difficulties and pitfalls). It's a heavy weight solution, but I've seen people doing this with greasemonkey scripts - allow Firefox to rende...
Python: Difference between class and instance attributes
Is there any meaningful distinction between: class A(object): foo = 5 # some default value vs. class B(object): def __init__(self, foo=5): self.foo = foo If you're creating a lot of instances, is there any difference in performance or space requirements for the two styles? When you read the code, do...
Beyond performance considerations, there is a significant semantic difference. In the class attribute case, there is just one object referred to. In the instance-attribute-set-at-instantiation, there can be multiple objects referred to. For instance >>> class A: foo = [] >>> a, b = A(), A() >>> a.foo.append(5) >>> b...
List of IP addresses/hostnames from local network in Python
How can I get a list of the IP addresses or host names from a local network easily in Python? It would be best if it was multi-platform, but it needs to work on Mac OS X first, then others follow. Edit: By local I mean all active addresses within a local network, such as 192.168.xxx.xxx. So, if the IP address of my com...
Update: The script is now located on github. I wrote a small python script, that leverages scapy's arping().
How to enable MySQL client auto re-connect with MySQLdb?
I came across PHP way of doing the trick: my_bool reconnect = 1; mysql_options(&mysql, MYSQL_OPT_RECONNECT, &reconnect); but no luck with MySQLdb (python-mysql). Can anybody please give a clue? Thanks.
I solved this problem by creating a function that wraps the cursor.execute() method since that's what was throwing the MySQLdb.OperationalError exception. The other example above implies that it is the conn.cursor() method that throws this exception. import MySQLdb class DB: conn = None def connect(self): sel...
Can I use Python as a Bash replacement?
I currently do my textfile manipulation through a bunch of badly remembered AWK, sed, Bash and a tiny bit of Perl. I've seen mentioned a few places that python is good for this kind of thing, I know a little and I would like to know more. Is Python a good choice for this, and is there a good book or guide to learning h...
Any shell has several sets of features. The Essential Linux/Unix commands. All of these are available through the subprocess library. This isn't always the best first choice for doing all external commands. Look also at shutil for some commands that are separate Linux commands, but you could probably implement dire...
Convert hex string to int in Python
How do I convert a hex string to an int in Python? I may have it as "0xffff" or just "ffff".
Without the 0x prefix, you need to specify the base explicitly, otherwise there's no way to tell: x = int("deadbeef", 16) With the 0x prefix, Python can distinguish hex and decimal automatically. >>> print int("0xdeadbeef", 0) 3735928559 >>> print int("10", 0) 10 (You must specify 0 as the base in order to invoke thi...
Map two lists into a dictionary in Python
Imagine that you have: keys = ('name', 'age', 'food') values = ('Monty', 42, 'spam') What is the simplest way to produce the following dictionary ? dict = {'name' : 'Monty', 'age' : 42, 'food' : 'spam'} This code works, but I'm not really proud of it : dict = {} junk = map(lambda k, v: dict.update({k: v}), keys, valu...
Like this: >>> keys = ['a', 'b', 'c'] >>> values = [1, 2, 3] >>> dictionary = dict(zip(keys, values)) >>> print dictionary {'a': 1, 'b': 2, 'c': 3} Voila :-) The pairwise dict constructor and zip function are awesomely useful: https://docs.python.org/2/library/functions.html#func-dict
Python: unsigned 32 bit bitwise arithmetic
Trying to answer to another post whose solution deals with IP addresses and netmasks, I got stuck with plain bitwise arithmetic. Is there a standard way, in Python, to carry on bitwise AND, OR, XOR, NOT operations assuming that the inputs are "32 bit" (maybe negative) integers or longs, and that the result must be a lo...
You can use ctypes and its c_uint32: >>> import ctypes >>> m = 0xFFFFFF00 >>> ctypes.c_uint32(~m).value 255L So what I did here was casting ~m to a C 32-bit unsigned integer and retrieving its value back in Python format.
Python's __import__ doesn't work as expected
When using __import__ with a dotted name, something like: somepackage.somemodule, the module returned isn't somemodule, whatever is returned seems to be mostly empty! what's going on here?
From the python docs on __import__: __import__( name[, globals[, locals[, fromlist[, level]]]]) ... When the name variable is of the form package.module, normally, the top-level package (the name up till the first dot) is returned, not the module named by name. However, when a non-empty fromlist argument is...
Python Inverse of a Matrix
How do I get the inverse of a matrix in python? I've implemented it myself, but it's pure python, and I suspect there are faster modules out there to do it.
You should have a look at numpy if you do matrix manipulation. This is a module mainly written in C, which will be much faster than programming in pure python. Here is an example of how to invert a matrix, and do other matrix manipulation. from numpy import matrix from numpy import linalg A = matrix( [[1,2,3],[11,12,13...
Using SQLite in a Python program
I have created a Python module that creates and populates several SQLite tables. Now, I want to use it in a program but I don't really know how to call it properly. All the tutorials I've found are essentially "inline", i.e. they walk through using SQLite in a linear fashion rather than how to actually use it in produc...
Don't make this more complex than it needs to be. The big, independent databases have complex setup and configuration requirements. SQLite is just a file you access with SQL, it's much simpler. Do the following. Add a table to your database for "Components" or "Versions" or "Configuration" or "Release" or something ...
Binary search (bisection) in Python
Is there a library function that performs binary search on a list/tuple and return the position of the item if found and 'False' (-1, None, etc.) if not? I found the functions bisect_left/right in the bisect module, but they still return a position even if the item is not in the list. That's perfectly fine for their in...
from bisect import bisect_left def binary_search(a, x, lo=0, hi=None): # can't use a to specify default for hi hi = hi if hi is not None else len(a) # hi defaults to len(a) pos = bisect_left(a,x,lo,hi) # find insertion position return (pos if pos != hi and a[pos] == x else -1) # don't walk of...
Opening a handle to a device in Python on Windows
I'm trying to use the giveio.sys driver which requires a "file" to be opened before you can access protected memory. I'm looking at a C example from WinAVR/AVRdude that uses the syntax: #define DRIVERNAME "\\\\.\\giveio" HANDLE h = CreateFile(DRIVERNAME, GENERIC_READ, 0, NULL...
Solution: in python you have to use win32file.CreateFile() instead of open(). Thanks everyone for telling me what I was trying to do, it helped me find the answer!
Keyboard interruptable blocking queue in Python
It seems import Queue Queue.Queue().get(timeout=10) is keyboard interruptible (ctrl-c) whereas import Queue Queue.Queue().get() is not. I could always create a loop; import Queue q = Queue() while True: try: q.get(timeout=1000) except Queue.Empty: pass but this seems like a strange thing t...
Queue objects have this behavior because they lock using Condition objects form the threading module. So your solution is really the only way to go. However, if you really want a Queue method that does this, you can monkeypatch the Queue class. For example: def interruptable_get(self): while True: try: ...
Using django-rest-interface
I have a django application that I'd like to add some rest interfaces to. I've seen http://code.google.com/p/django-rest-interface/ but it seems to be pretty simplistic. For instance it doesn't seem to have a way of enforcing security. How would I go about limiting what people can view and manipulate through the res...
I would look into using django-piston http://bitbucket.org/jespern/django-piston/wiki/Home application if security is your main concern. I have used django-rest-interface in the past, its reliable and though simple can be quite powerful, however django-piston seems more flexible going forward.
A good multithreaded python webserver?
I am looking for a python webserver which is multithreaded instead of being multi-process (as in case of mod_python for apache). I want it to be multithreaded because I want to have an in memory object cache that will be used by various http threads. My webserver does a lot of expensive stuff and computes some large ar...
CherryPy. Features, as listed from the website: A fast, HTTP/1.1-compliant, WSGI thread-pooled webserver. Typically, CherryPy itself takes only 1-2ms per page! Support for any other WSGI-enabled webserver or adapter, including Apache, IIS, lighttpd, mod_python, FastCGI, SCGI, and mod_wsgi Easy to run multiple HTTP ser...
Would Python make a good substitute for the Windows command-line/batch scripts?
I've got some experience with Bash, which I don't mind, but now that I'm doing a lot of Windows development I'm needing to do basic stuff/write basic scripts using the Windows command-line language. For some reason said language really irritates me, so I was considering learning Python and using that instead. Is Pytho...
Python is well suited for these tasks, and I would guess much easier to develop in and debug than Windows batch files. The question is, I think, how easy and painless it is to ensure that all the computers that you have to run these scripts on, have Python installed.
How do you convert YYYY-MM-DDTHH:mm:ss.000Z time format to MM/DD/YYYY time format in Python?
For example, I'm trying to convert 2008-09-26T01:51:42.000Z to 09/26/2008. What's the simplest way of accomplishing this?
The easiest way is to use dateutil.parser.parse() to parse the date string into a timezone aware datetime object, then use strftime() to get the format you want. import datetime, dateutil.parser d = dateutil.parser.parse('2008-09-26T01:51:42.000Z') print d.strftime('%m/%d/%Y') #==> '09/26/2008'
python module dlls
Is there a way to make a python module load a dll in my application directory rather than the version that came with the python installation, without making changes to the python installation (which would then require I made an installer, and be careful I didn't break other apps for people by overwrting python modules ...
If you're talking about Python module DLLs, then simply modifying sys.path should be fine. However, if you're talking about DLLs linked against those DLLs; i.e. a libfoo.dll which a foo.pyd depends on, then you need to modify your PATH environment variable. I wrote about doing this for PyGTK a while ago, but in your ...
Can you add new statements to Python's syntax?
Can you add new statements (like print, raise, with) to Python's syntax? Say, to allow.. mystatement "Something" Or, new_if True: print "example" Not so much if you should, but rather if it's possible (short of modifying the python interpreters code)
You may find this useful - Python internals: adding a new statement to Python, quoted here: This article is an attempt to better understand how the front-end of Python works. Just reading documentation and source code may be a bit boring, so I'm taking a hands-on approach here: I'm going to add an until statement to P...
What is the purpose of the colon before a block in Python?
What is the purpose of the colon before a block in Python? Example: if n == 0: print "The end"
The colon is there to declare the start of an indented block. Technically, it's not necessary; you could just indent and de-indent when the block is done. However, based on the Python koan “explicit is better than implicit” (EIBTI), I believe that Guido deliberately made the colon obligatory, so any statement that ...
Why Python decorators rather than closures?
I still haven't got my head around decorators in Python. I've already started using a lot of closures to do things like customize functions and classes in my coding. Eg. class Node : def __init__(self,val,children) : self.val = val self.children = children def makeRunner(f) : def run(node) : ...
While it is true that syntactically, decorators are just "sugar", that is not the best way to think about them. Decorators allow you to weave functionality into your existing code without actually modifying it. And they allow you to do it in a way that is declarative. This allows you to use decorators to do aspect-orie...
Python embedded in CPP: how to get data back to CPP
While working on a C++ project, I was looking for a third party library for something that is not my core business. I found a really good library, doing exactly what's needed, but it is written in Python. I decided to experiment with embedding Python code in C++, using the Boost.Python library. The C++ code looks somet...
First of all, change your function to return the value. printing it will complicate things since you want to get the value back. Suppose your MyModule.py looks like this: import thirdparty def MyFunc(some_arg): result = thirdparty.go() return result Now, to do what you want, you have to go beyond basic embedd...
In Python, what does it mean if an object is subscriptable or not?
Which types of objects fall into the domain of "subscriptable"?
It basically means that the object implements the __getitem__() method. In other words, it describes objects that are "containers", meaning they contain other objects. This includes lists, tuples, and dictionaries.
How can I determine the display idle time from Python in Windows, Linux, and MacOS?
I would like to know how long it's been since the user last hit a key or moved the mouse - not just in my application, but on the whole "computer" (i.e. display), in order to guess whether they're still at the computer and able to observe notifications that pop up on the screen. I'd like to do this purely from (Py)GTK+...
Gajim does it this way on Windows, OS X and GNU/Linux (and other *nixes): Python wrapper module (also includes Windows idle time detection code, using GetTickCount with ctypes); Ctypes-based module to get X11 idle time (using XScreenSaverQueryInfo, was a C module in old Gajim versions); C module to get OS X idle time ...
Getting method parameter names in python
Given the python function: def aMethod(arg1, arg2): pass How can I extract the number and names of the arguments. Ie. given that I have a reference to func, I want the func.[something] to return ("arg1", "arg2") The usage scenario for this is that I have a decorator, and I wish to use the method arguments in the s...
Take a look at the inspect module - this will do the inspection of the various code object properties for you. >>> inspect.getargspec(aMethod) (['arg1', 'arg2'], None, None, None) The other results are the name of the *args and **kwargs variables, and the defaults provided. ie. >>> def foo(a,b,c=4, *arglist, **keywor...
How Python web frameworks, WSGI and CGI fit together
I have a Bluehost account where I can run Python scripts as CGI. I guess it's the simplest CGI, because to run I have to define the following in .htaccess: Options +ExecCGI AddType text/html py AddHandler cgi-script .py Now, whenever I look up web programming with Python, I hear a lot about WSGI and how most framework...
How WSGI, CGI, and the frameworks are all connected ? Apache listens on port 80. It gets an HTTP request. It parses the request to find a way to respond. Apache has a LOT of choices for responding. One way to respond is to use CGI to run a script. Another way to respond is to simply serve a file. In the case of...
Ensure a single instance of an application in Linux
I'm working on a GUI application in WxPython, and I am not sure how I can ensure that only one copy of my application is running at any given time on the machine. Due to the nature of the application, running more than once doesn't make any sense, and will fail quickly. Under Win32, I can simply make a named mutex and ...
The Right Thing is advisory locking using flock(LOCK_EX); in Python, this is found in the fcntl module. Unlike pidfiles, these locks are always automatically released when your process dies for any reason, have no race conditions exist relating to file deletion (as the file doesn't need to be deleted to release the loc...
Is it possible to implement Python code-completion in TextMate?
PySmell seems like a good starting point. I think it should be possible, PySmell's idehelper.py does a majority of the complex stuff, it should just be a case of giving it the current line, offering up the completions (the bit I am not sure about) and then replacing the line with the selected one. >>> import idehelper ...
EDIT: I've actually took your code above and integrated into a command. It will properly show a completion list for you to choose. You can grab it here: http://github.com/orestis/pysmell/tree/master (hit download and do python setup.py install). It's rough but it works. - please report any errors on http://code.google....
Putting Copyright Symbol into a Python File
I need to include a copyright statement at the top of every Python source file I produce: # Copyright: © 2008 etc. However, when I then run such a file I get this message: SyntaxError: Non-ASCII character '\xa9' in file MyFile.py on line 3, but no encoding declared; see http://www.python.org/peps/pep-0263.html for ...
The copyright symbol in ASCII is spelled (c) or "Copyright". See circular 61, Copyright Registration for Computer Programs. While it's true that the legal formalism (see Circular 1, Copyright Basics) is The symbol © (the letter C in a circle), or the word “Copyright,” or the abbreviation “Copr.”; and.....
ElementTree XPath - Select Element based on attribute
I am having trouble using the attribute XPath Selector in ElementTree, which I should be able to do according to the Documentation Here's some sample code XML <root> <target name="1"> <a></a> <b></b> </target> <target name="2"> <a></a> <b></b> </target> </root> Python def parse(document): root ...
The syntax you're trying to use is new in ElementTree 1.3. Such version is shipped with Python 2.7 or higher. If you have Python 2.6 or less you still have ElementTree 1.2.6 or less.
Sorting a tuple that contains tuples
I have the following tuple, which contains tuples: MY_TUPLE = ( ('A','Apple'), ('C','Carrot'), ('B','Banana'), ) I'd like to sort this tuple based upon the second value contained in inner-tuples (i.e., sort Apple, Carrot, Banana rather than A, B, C). Any thoughts?
from operator import itemgetter MY_SORTED_TUPLE = tuple(sorted(MY_TUPLE, key=itemgetter(1))) or without itemgetter: MY_SORTED_TUPLE = tuple(sorted(MY_TUPLE, key=lambda item: item[1]))
How to use 'super' in Python?
Can someone explain to me the difference between doing: class Child(SomeBaseClass): def __init__(self): super(Child, self).__init__() and this: class Child(SomeBaseClass): def __init__(self): SomeBaseClass.__init__(self) I've seen super being used quite a lot in classes with only single inheri...
The benefits of super() in single-inheritance are minimal -- mostly, you don't have to hard-code the name of the base class into every method that uses its parent methods. However, it's almost impossible to use multiple-inheritance without super(). This includes common idioms like mixins, interfaces, abstract classes, ...
Using Variables for Class Names in Python?
I want to know how to use variables for objects and function names in Python. In PHP, you can do this: $className = "MyClass"; $newObject = new $className(); How do you do this sort of thing in Python? Or, am I totally not appreciating some fundamental difference with Python, and if so, what is it?
Assuming that some_module has a class named "class_name": import some_module klass = getattr(some_module, "class_name") some_object = klass() I should note that you should be careful here: turning strings into code can be dangerous if the string came from the user, so you should keep security in mind in this situatio...
Elegant structured text file parsing
I need to parse a transcript of a live chat conversation. My first thought on seeing the file was to throw regular expressions at the problem but I was wondering what other approaches people have used. I put elegant in the title as i've previously found that this type of task has a danger of getting hard to maintain j...
No and in fact, for the specific type of task you describe, I doubt there's a "cleaner" way to do it than regular expressions. It looks like your files have embedded line breaks so typically what we'll do here is make the line your unit of decomposition, applying per-line regexes. Meanwhile, you create a small state ma...
How do I perform query filtering in django templates
I need to perform a filtered query from within a django template, to get a set of objects equivalent to python code within a view: queryset = Modelclass.objects.filter(somekey=foo) In my template I would like to do {% for object in data.somekey_set.FILTER %} but I just can't seem to find out how to write FILTER.
You can't do this, which is by design. The Django framework authors intended a strict separation of presentation code from data logic. Filtering models is data logic, and outputting HTML is presentation logic. So you have several options. The easiest is to do the filtering, then pass the result to render_to_response...
Javascript style dot notation for dictionary keys unpythonic?
I've started to use constructs like these: class DictObj(object): def __init__(self): self.d = {} def __getattr__(self, m): return self.d.get(m, None) def __setattr__(self, m, v): super.__setattr__(self, m, v) Update: based on this thread, I've revised the DictObj implementation to:...
Your DictObj example is actually quite common. Object-style dot-notation access can be a win if you are dealing with ‘things that resemble objects’, ie. they have fixed property names containing only characters valid in Python identifiers. Stuff like database rows or form submissions can be usefully stored in this ...
RFC 1123 Date Representation in Python?
Is there a fairly easy way to convert a datetime object into an RFC 1123 (HTTP/1.1) date/time string, i.e. a string with the format Sun, 06 Nov 1994 08:49:37 GMT Using strftime does not work, since the strings are locale-dependant. Do I have to build the string by hand?
You can use wsgiref.handlers.format_date_time from the stdlib which does not rely on locale settings from wsgiref.handlers import format_date_time from datetime import datetime from time import mktime now = datetime.now() stamp = mktime(now.timetuple()) print format_date_time(stamp) #--> Wed, 22 Oct 2008 10:52:40 GMT ...
"Pretty" Continuous Integration for Python
This is a slightly.. vain question, but BuildBot's output isn't particularly nice to look at.. For example, compared to.. phpUnderControl Jenkins Hudson CruiseControl.rb ..and others, BuildBot looks rather.. archaic I'm currently playing with Hudson, but it is very Java-centric (although with this guide, I found it...
You might want to check out Nose and the Xunit output plugin. You can have it run your unit tests, and coverage checks with this command: nosetests --with-xunit --enable-cover That'll be helpful if you want to go the Jenkins route, or if you want to use another CI server that has support for JUnit test reporting. Sim...
Batch Renaming of Files in a Directory
Is there an easy way to rename a group of files already contained in a directory, using Python? Example: I have a directory full of *.doc files and I want to rename them in a consistent way. X.doc -> "new(X).doc" Y.doc -> "new(Y).doc"
Such renaming is quite easy, for example with os and glob modules: import glob, os def rename(dir, pattern, titlePattern): for pathAndFilename in glob.iglob(os.path.join(dir, pattern)): title, ext = os.path.splitext(os.path.basename(pathAndFilename)) os.rename(pathAndFilename, os...
Django Forms - How to Use Prefix Parameter
Say I have a form like: class GeneralForm(forms.Form): field1 = forms.IntegerField(required=False) field2 = forms. IntegerField(required=False) And I want to show it twice on a page within one form tag each time with a different prefix e.g.,: rest of page ... <form ..> GeneralForm(data,prefix="form1").as_table...
You process each form as you normally would, ensuring that you create instances which have the same prefixes as those used to generate the form initially. Here's a slightly awkward example using the form you've given, as I don't know what the exact use case is: def some_view(request): if request.method == 'POST': ...
How does one put a link / url to the web-site's home page in Django?
In Django templates, is there a variable in the context (e.g. {{ BASE\_URL }}, {{ ROOT\_URL }}, or {{ MEDIA\_URL }} that one can use to link to the home url of a project? I.e. if Django is running in the root of a project, the variable (let's call it R) {{ R }} in a template would be /. If the root url is a sub-folder ...
You could give the URL configuration which you're using to handle the home page a name and use that: urls.py: from django.conf.urls.defaults import * urlpatterns = patterns('myproject.views', url(r'^$', 'index', name='index'), ) Templates: <a href="{% url index %}">... This note in the Django Book has some tips ...
Python Disk-Based Dictionary
I was running some dynamic programming code (trying to brute-force disprove the Collatz conjecture =P) and I was using a dict to store the lengths of the chains I had already computed. Obviously, it ran out of memory at some point. Is there any easy way to use some variant of a dict which will page parts of itself out ...
The 3rd party shove module is also worth taking a look at. It's very similar to shelve in that it is a simple dict-like object, however it can store to various backends (such as file, SVN, and S3), provides optional compression, and is even threadsafe. It's a very handy module from shove import Shove mem_store = Shove...
How do you create a simple Google Talk Client using the Twisted Words Python library?
I am interested in making a Google Talk client using Python and would like to use the Twisted libraries Words module. I have looked at the examples, but they don't work with the current implementation of Google Talk. Has anybody had any luck with this? Would you mind documenting a brief tutorial? As a simple task, I'...
wokkel is the future of twisted words. metajack wrote a really nice blog post on getting started. If you want a nice, functional sample project to start with, check out my whatsup bot.
ASCII value of a character in Python
How do I get the ASCII value of a character as an int in Python?
From here: function ord() would get the int value of the char. And in case you want to convert back after playing with the number, function chr() does the trick. >>> ord('a') 97 >>> chr(97) 'a' >>> chr(ord('a') + 3) 'd' >>> There is also the unichr function, returning the Unicode character whose ordinal is the...
Open file, read it, process, and write back - shortest method in Python
I want to do some basic filtering on a file. Read it, do processing, write it back. I'm not looking for "golfing", but want the simplest and most elegant method to achieve this. I came up with: from __future__ import with_statement filename = "..." # or sys.argv... with open(filename) as f: new_txt = # ...some t...
Actually an easier way using fileinput is to use the inplace parameter: import fileinput for line in fileinput.input (filenameToProcess, inplace=1): process (line) If you use the inplace parameter it will redirect stdout to your file, so that if you do a print it will write back to your file. This example adds lin...
Passing a list while retaining the original
So I'm teaching myself Python, and I'm having an issue with lists. I want to pass my function a list and pop items off it while retaining the original list. How do I make python "instance" the passed list rather that passing a pointer to the original one? Example: def burninate(b): c = [] for i in range(3): ...
As other answers have suggested, you can provide your function with a copy of the list. As an alternative, your function could take a copy of the argument: def burninate(b): c = [] b = list(b) for i in range(3): c.append(b.pop()) return c Basically, you need to be clear in your mind (and in you...
What's win32con module in python? Where can I find it?
I'm building an open source project that uses python and c++ in Windows. I came to the following error message: ImportError: No module named win32con The same happened in a "prebuilt" code that it's working ( except in my computer :P ) I think this is kind of "popular" module in python because I've saw several messa...
This module contains constants related to Win32 programming. It is not part of the Python 2.6 release, but should be part of the download of the pywin32 project. Edit: I imagine that the executable is an installation program, though the last time I downloaded pywin32 it was just a zip file.
Python debugger: Stepping into a function that you have called interactively
Python is quite cool, but unfortunately, its debugger is not as good as perl -d. One thing that I do very commonly when experimenting with code is to call a function from within the debugger, and step into that function, like so: # NOTE THAT THIS PROGRAM EXITS IMMEDIATELY WITHOUT CALLING FOO() ~> cat -n /tmp/show_per...
And I've answered my own question! It's the "debug" command in pydb: ~> cat -n /tmp/test_python.py 1 #!/usr/local/bin/python 2 3 def foo(): 4 print "hi" 5 print "bye" 6 7 exit(0) 8 ~> pydb /tmp/test_python.py (/tmp/test_python.py:7): <module> 7 exit(0) (Pydb) de...
How do I iterate through a string in Python?
As an example, lets say I wanted to list the frequency of each letter of the alphabet in a string. What would be the easiest way to do it? This is an example of what I'm thinking of... the question is how to make allTheLetters equal to said letters without something like allTheLetters = "abcdefg...xyz". In many other l...
The question you've asked (how to iterate through the alphabet) is not the same question as the problem you're trying to solve (how to count the frequency of letters in a string). You can use string.lowercase, as other posters have suggested: import string allTheLetters = string.lowercase To do things the way you're "...
SQLite parameter substitution problem
Using SQLite3 with Python 2.5, I'm trying to iterate through a list and pull the weight of an item from the database based on the item's name. I tried using the "?" parameter substitution suggested to prevent SQL injections but it doesn't work. For example, when I use: for item in self.inventory_names: self.cursor....
The Cursor.execute() method expects a sequence as second parameter. You are supplying a string which happens to be 8 characters long. Use the following form instead: self.cursor.execute("SELECT weight FROM Equipment WHERE name = ?", [item]) Python library reference 13.13.3: sqlite3 Cursor Objects.
os.walk without digging into directories below
How do I limit os.walk to only return files in the directory I provide it? def _dir_list(self, dir_name, whitelist): outputList = [] for root, dirs, files in os.walk(dir_name): for f in files: if os.path.splitext(f)[1] in whitelist: outputList.append(os.path.join(root, f)) ...
Don't use os.walk. Example: import os root = "C:\\" for item in os.listdir(root): if os.path.isfile(os.path.join(root, item)): print item
How to flush output of Python print?
How do I force Python's print function to output to the screen?
import sys sys.stdout.flush() Print by default prints to sys.stdout. References: http://docs.python.org/reference/simple_stmts.html#the-print-statement http://docs.python.org/library/sys.html http://docs.python.org/library/stdtypes.html#file-objects
Given a list of variable names in Python, how do I a create a dictionary with the variable names as keys (to the variables' values)?
I have a list of variable names, like this: ['foo', 'bar', 'baz'] (I originally asked how I convert a list of variables. See Greg Hewgill's answer below.) How do I convert this to a dictionary where the keys are the variable names (as strings) and the values are the values of the variables? {'foo': foo, 'bar': bar, '...
Forget filtering locals()! The dictionary you give to the formatting string is allowed to contain unused keys: >>> name = 'foo' >>> zip = 123 >>> unused = 'whoops!' >>> locals() {'name': 'foo', 'zip': 123, ... 'unused': 'whoops!', ...} >>> '%(name)s %(zip)i' % locals() 'foo 123'
What does the "yield" keyword do?
What is the use of the yield keyword in Python? What does it do? For example, I'm trying to understand this code1: def _get_child_candidates(self, distance, min_dist, max_dist): if self._leftchild and distance - max_dist < self._median: yield self._leftchild if self._rightchild and distance + max_dist >...
To understand what yield does, you must understand what generators are. And before generators come iterables. Iterables When you create a list, you can read its items one by one. Reading its items one by one is called iteration: >>> mylist = [1, 2, 3] >>> for i in mylist: ... print(i) 1 2 3 mylist is an iterable. W...
Python inheritance - how to disable a function
In C++ you can disable a function in parent's class by declaring it as private in the child class. How can this be done in Python? I.E. How can I hide parent's function from child's public interface?
There really aren't any true "private" attributes or methods in Python. One thing you can do is simply override the method you don't want in the subclass, and raise an exception: >>> class Foo( object ): ... def foo( self ): ... print 'FOO!' ... >>> class Bar( Foo ): ... def foo( self ): ... ra...
Will Django be a good choice for a permissions based web-app?
I've been exploring the details of Django for about a week now and like what I see. However I've come upon some.. negativity in relation to fine-grained control of permissions to the CRUD interface. What I'm writing is an Intranet client management web-app. The organisation is about 6 tiers, and I need to restrict acce...
If I read your updated requirements correctly, I don't think Django's existing auth system will be sufficient. It sounds like you need a full-on ACL system. This subject has come up a number of times. Try googling on django+acl. Random samplings ... There was a Summer of Code project a couple of years ago, but I'm not ...
How do I restrict foreign keys choices to related objects only in django
I have a two way foreign relation similar to the following class Parent(models.Model): name = models.CharField(max_length=255) favoritechild = models.ForeignKey("Child", blank=True, null=True) class Child(models.Model): name = models.CharField(max_length=255) myparent = models.ForeignKey(Parent) How do I rest...
I just came across ForeignKey.limit_choices_to in the Django docs. Not sure yet how this works, but it might just be the right think here. Update: ForeignKey.limit_choices_to allows to specify either a constant, a callable or a Q object to restrict the allowable choices for the key. A constant obviously is no use here,...
Lexical closures in Python
While I was investigating a problem I had with lexical closures in Javascript code, I came along this problem in Python: flist = [] for i in xrange(3): def func(x): return x * i flist.append(func) for f in flist: print f(2) Note that this example mindfully avoids lambda. It prints "4 4 4", which is surpr...
The functions defined in the loop keep accessing the same variable i while its value changes. At the end of the loop, all the functions point to the same variable, which is holding the last value in the loop: the effect is what reported in the example. In order to evaluate i and use its value, a common pattern is to se...
Environment Variables in Python on Linux
Python's access to environment variables does not accurately reflect the operating system's view of the processes environment. os.getenv and os.environ do not function as expected in particular cases. Is there a way to properly get the running process' environment? To demonstrate what I mean, take the two roughly equi...
That's a very good question. It turns out that the os module initializes os.environ to the value of posix.environ, which is set on interpreter start up. In other words, the standard library does not appear to provide access to the getenv function. That is a case where it would probably be safe to use ctypes on unix. Si...
How can I use Python for large scale development?
I would be interested to learn about large scale development in Python and especially in how do you maintain a large code base? When you make incompatibility changes to the signature of a method, how do you find all the places where that method is being called. In C++/Java the compiler will find it for you, how do you...
Don't use a screw driver as a hammer Python is not a statically typed language, so don't try to use it that way. When you use a specific tool, you use it for what it has been built. For Python, it means: Duck typing : no type checking. Only behavior matters. Therefore your code must be designed to use this feature. A ...
How do I convert any image to a 4-color paletted image using the Python Imaging Library?
I have a device that supports 4-color graphics (much like CGA in the old days). I wanted to use PIL to read the image and convert it using my 4-color palette (of red, green, yellow, black), but I can't figure out if it's even possible at all. I found some mailing list archive posts that seem to suggest other people ha...
First: your four colour palette (black, green, red, yellow) has no blue component. So, you have to accept that your output image will hardly approximate the input image, unless there is no blue component to start with. Try this code: import Image def estimate_color(c, bit, c_error): c_new= c - c_error if c_ne...
How to get file creation & modification date/times in Python?
I have a script that needs to do some stuff based on file creation & modification dates but has to run on Linux & Windows. What's the best cross-platform way to get file creation & modification date/times in Python?
You have a couple of choices. For one, you can use the os.path.getmtime and os.path.getctime functions: import os.path, time print "last modified: %s" % time.ctime(os.path.getmtime(file)) print "created: %s" % time.ctime(os.path.getctime(file)) Your other option is to use os.stat: import os, time (mode, ino, dev, nlin...
Is there a reason Python strings don't have a string length method?
I know that python has a len() function that is used to determine the size of a string, but I was wondering why its not a method of the string object. Update Ok, I realized I was embarrassingly mistaken. __len__() is actually a method of a string object. It just seems weird to see object oriented code in Python using t...
Strings do have a length method: __len__() The protocol in Python is to implement this method on objects which have a length and use the built-in len() function, which calls it for you, similar to the way you would implement __iter__() and use the built-in iter() function (or have the method called behind the scenes fo...
Multiple mouse pointers?
Is there a way to accept input from more than one mouse separately? I'm interested in making a multi-user application and I thought it would be great if I could have 2 or more users holding wireless mice each interacting with the app individually with a separate mouse arrow. Is this something I should try to farm out t...
You could try the Microsoft Windows MultiPoint Software Development Kit 1.1 or the new Microsoft Windows MultiPoint Software Development Kit 1.5 and the main Microsoft Multipoint site
How to disable HTML encoding when using Context in django
In my django application I am using a template to construct email body, one of the parameters is url, note there are two parametes separated by ampersand in the url. t = loader.get_template("sometemplate") c = Context({ 'foo': 'bar', 'url': 'http://127.0.0.1/test?a=1&b=2', }) print t.render(c) After rendering it...
To turn it off for a single variable, use mark_safe: from django.utils.safestring import mark_safe t = loader.get_template("sometemplate") c = Context({ 'foo': 'bar', 'url': mark_safe('http://127.0.0.1/test?a=1&b=2'), }) print t.render(c) Alternatively, to totally turn autoescaping off from your Python code, us...
python properties and inheritance
I have a base class with a property which (the get method) I want to overwrite in the subclass. My first thought was something like: class Foo(object): def _get_age(self): return 11 age = property(_get_age) class Bar(Foo): def _get_age(self): return 44 This does not work (subclass bar.ag...
I simply prefer to repeat the property() as well as you will repeat the @classmethod decorator when overriding a class method. While this seems very verbose, at least for Python standards, you may notice: 1) for read only properties, property can be used as a decorator: class Foo(object): @property def age(sel...
How do you log server errors on django sites
So, when playing with the development I can just set settings.DEBUG to True and if an error occures I can see it nicely formatted, with good stack trace and request information. But on kind of production site I'd rather use DEBUG=False and show visitors some standard error 500 page with information that I'm working on ...
Well, when DEBUG = False, Django will automatically mail a full traceback of any error to each person listed in the ADMINS setting, which gets you notifications pretty much for free. If you'd like more fine-grained control, you can write and add to your settings a middleware class which defines a method named process_e...
Pattern matching of lists in Python
I want to do some pattern matching on lists in Python. For example, in Haskell, I can do something like the following: fun (head : rest) = ... So when I pass in a list, head will be the first element, and rest will be the trailing elements. Likewise, in Python, I can automatically unpack tuples: (var1, var2) = func_th...
So far as I know there's no way to make it a one-liner in current Python without introducing another function, e.g.: split_list = lambda lst: (lst[0], lst[1:]) head, rest = split_list(my_func()) However, in Python 3.0 the specialized syntax used for variadic argument signatures and argument unpacking will become avail...
Python list of lists, changes reflected across sublists unexpectedly
I needed to create a list of lists in Python, so I typed the following: myList = [[1] * 4] * 3 The list looked like this: [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]] Then I changed one of the innermost values: myList[0][0] = 5 Now my list looks like this: [[5, 1, 1, 1], [5, 1, 1, 1], [5, 1, 1, 1]] which ...
When you write [x]*3 you get, essentially, the list [x, x, x]. That is, a list with 3 references to the same x. When you then modify this single x it is visible via all three references to it. To fix it, you need to make sure that you create a new list at each position. One way to do it is [[1]*4 for n in range(3)]
Possible to integrate Google AppEngine and Google Code for continuous integration?
Anyone have any thoughts on how/if it is possible to integrate Google Code commits to cause a Google AppEngine deployment of the most recent code? I have a simple Google AppEngine project's source hosted on Google Code and would love if everytime I committed to Subversion, that AppEngine would reflect the latest commit...
Made By Sofa had a blog post about their workflow with Google App Engine. In the second last paragraph they have attached a subversion hook that when when someone commits code it will automatically deploy to Google App Engine. It would take a little bit of tweaking (because it works on the server side not the client) b...
Python lazy list
I would like create my own collection that has all the attributes of python list and also knows how to save/load itself into/from a database. Also I want to make the load implicit and lazy, as in it doesn't happen at the point of creation of the list, but waits until its first used. Is there a single__xxx__method I ca...
Not exactly. For emulating things other than lists, there's __getattribute__, but unfortunately Python doesn't consider operators like x[y] or x(y) to be exactly the same as x.__getitem__(y) or x.__call__(y). Operators like that are attributes of the class, not attributes of the instance, as you can see here: >>> cla...
Single Table Inheritance in Django
Is there explicit support for Single Table Inheritance in Django? Last I heard, the feature was still under development and debate. Are there libraries/hacks I can use in the meantime to capture the basic behavior? I have a hierarchy that mixes different objects. The canonical example of a corporation structure with a...
There are currently two forms of inheritance in Django - MTI (model table inheritance) and ABC (abstract base classes). I wrote a tutorial on what's going on under the hood. You can also reference the official docs on model inheritance.
Python snippet to remove C and C++ comments
I'm looking for Python code that removes C and C++ comments from a string. (Assume the string contains an entire C source file.) I realize that I could .match() substrings with a Regex, but that doesn't solve nesting /*, or having a // inside a /* */. Ideally, I would prefer a non-naive implementation that properly han...
This handles C++-style comments, C-style comments, strings and simple nesting thereof. def comment_remover(text): def replacer(match): s = match.group(0) if s.startswith('/'): return " " # note: a space and not an empty string else: return s pattern = re.compile( ...
SUDS - programmatic access to methods and types
I'm investigating SUDS as a SOAP client for python. I want to inspect the methods available from a specified service, and the types required by a specified method. The aim is to generate a user interface, allowing users to select a method, then fill in values in a dynamically generated form. I can get some information...
Okay, so SUDS does quite a bit of magic. A suds.client.Client, is built from a WSDL file: client = suds.client.Client("http://mssoapinterop.org/asmx/simple.asmx?WSDL") It downloads the WSDL and creates a definition in client.wsdl. When you call a method using SUDS via client.service.<method> it's actually doing a whol...
OpenGl with Python
I am currently in a course that is using OpenGL and I have been using C for all the programs so far. I have Python installed on Fedora as well as OpenGL, however the minute I call an OpenGL command in my Python code, I get a segmentation fault. I have no idea why this is. Just to avoid the "just use C" comments, here i...
You may also want to consider using Pyglet instead of PyOpenGL. It's a ctypes-wrapper around the native OpenGL libs on the local platform, along with windowing support (should handle most of the stuff you want to use GLUT for.) The pyglet-users list is pretty active and very helpful.
Starting python debugger automatically on error
This is a question I have wondered about for quite some time, yet I have never found a suitable solution. If I run a script and I come across, let's say an IndexError, python prints the line, location and quick description of the error and exits. Is it possible to automatically start pdb when an error is encountered? I...
python -m pdb myscript.py You'll need to enter 'c' (for Continue) when execution begins, but then it will run to the error point and give you control there.