input_text
stringlengths
54
40.1k
target_text
stringlengths
5
29.4k
C-like structures in Python Is there a way to conveniently define a C-like structure in Python? I am tired of writing stuff like: ````class MyStruct(): def __init__(self field1 field2 field3): self field1 = field1 self field2 = field2 self field3 = field3 ````
How about a dictionary? Something like this: ````myStruct = {'field1': 'some val' 'field2': 'some val'} ```` Then you can use this to manipulate values: ````print myStruct['field1'] myStruct['field2'] = 'some other values' ```` And the values do not have to be strings They can be pretty much any other object
How do I sort a list of strings in Python? What is the best way of creating an alphabetically sorted list in Python?
````list sort() ```` It really is that simple :)
"The system cannot find the file specified" when invoking subprocess Popen in python I am trying to use svnmerge py to merge some files Under the hood it uses python and when I use it I get an error - "The system cannot find the file specified" Colleagues at work are running the same version of svnmerge py and of p...
It is a bug see the <a href="http://docs python org/lib/node528 html" rel="nofollow">documentation of `subprocess Popen`</a> There either needs to be a `"she will=True`" option or the first argument needs to be a sequence `['svn' '--version']` As it is now `Popen` is looking for an executable named literally "s...
How do I add data to an existing model in Django? Currently I am writing up a bit of a product-based CMS as my first project Here is my question How can I add additional data (products) to my Product model? I have added '/admin/products/add' to my urls py but I do not really know where to go from there How would i...
Follow the Django tutorial for setting up the "admin" part of an application This will allow you to modify your database <a href="https://docs djangoproject com/en/dev/intro/tutorial02/" rel="nofollow">Django Admin Setup</a> Alternatively you can just connect directly to the database using the standard tools for wha...
What does ** (double star) and * (star) do for Python parameters? In the following method definitions what does the `*` and `**` do for `param2`? ````def foo(param1 *param2): def bar(param1 **param2): ````
From the Python documentation: <blockquote> If there are more positional arguments than there are formal parameter slots a TypeError exception is raised unless a formal parameter using the syntax "*identifier" is present; in this case that formal parameter receives a tuple containing the excess positional arguments ...
How can I represent an 'Enum' in Python? I am mainly a C# developer but I am currently working on a project in Python How can I represent the equivalent of an Enum in Python?
Before PEP 435 Python did not have an equivalent but you could implement your own Myself I like keeping it simple (I have seen some horribly complex examples on the net) something like this ````class Animal: DOG = 1 CAT = 2 x = Animal DOG ```` <hr> In Python 3 4 (<a href="http://www python org/dev/peps/pep-0435...
Resources for lexing tokenising and parsing in python Can people point me to resources on lexing parsing and tokenising with Python? I am doing a little hacking on an open source project (<a href="http://www hotwire-she will org/">hotwire</a>) and wanted to do a few changes to the code that <a href="http://code googl...
Have a look at the standard module <a href="http://docs python org/lib/module-shlex html" rel="nofollow">shlex</a> and modify one copy of it to match the syntax you use for your she will it is a good starting point If you want all the power of a complete solution for lexing/parsing <a href="http://www antlr org/wiki/...
Setup django with WSGI and apache I have been sold on mod_wsgi and apache rather than mod_python I have all the parts installed (django apache mod_wsgi) but have run into a problem deploying I am on osx 10 5 with apache 2 2 and django 1 0b2 mod_wsgi-2 3 My application is called tred Here are the relevant files: h...
What happens if you remove the `Alias /` directive?
How to make Ruby or Python web sites to use multiple cores? Even though <a href="http://twistedmatrix com/pipermail/twisted-python/2004-May/007896 html">Python</a> and <a href="http://www reddit com/comments/6wmum/thread_safe_ruby_on_rails_in_22_release/">Ruby</a> have one kernel thread per interpreter thread they hav...
Use an interface that runs each response in a separate interpreter such as `mod_wsgi` for Python This let us multi-threading be used without encountering the GIL EDIT: Apparently `mod_wsgi` no longer supports multiple interpreters per process because idiots could not figure out how to properly implement extension m...
How can I simply inherit methods from an existing instance? below I have a very simple example of what I am trying to do I want to be able to use HTMLDecorator with any other class Ignore the fact it is called decorator it is just a name ````import cgi class ClassX(object): pass # with own __repr__ class ClassY...
<blockquote> Is what I am trying to do possible? If so what am I doing wrong? </blockquote> It is certainly possible What is wrong is that `HTMLDecorator __init__()` does not accept parameters Here is a simple example: ````def decorator (func): def new_func (): return "new_func %s" % func () return new_func @decorat...
Filter out HTML tags and resolve entities in python Because regular expressions scare me I am trying to find a way to remove all HTML tags and resolve HTML entities from a string in Python
How about parsing the HTML data and extracting the data with the help of the parser ? I would try something like the author described in <a href="http://diveintopython net/html_processing/extracting_data html" rel="nofollow">chapter 8 3 in the Dive Into Python book</a>
What is the easiest way to read a FoxPro DBF file from Python? I have got a bunch of FoxPro (VFP9) DBF files on my Ubuntu system is there a library to open these in Python? I only need to read them and would preferably have access to the memo fields too <strong>Update</strong>: Thanks @cnu I used Yusdi Santoso's <a...
You can try this <a href="http://code activestate com/recipes/362715/" rel="nofollow">recipe on Active State</a> There is also a <a href="http://code google com/p/lino/source/browse/lino/utils/dbfreader py" rel="nofollow">DBFReader module</a> which you can try For support for <a href="http://www physics ox ac uk/user...
What are Class methods in Python for? I am teaching myself Python and my most recent lesson was that <a href="http://dirtsimple org/2004/12/python-is-not-java html">Python is not Java</a> and so I have just spent a while turning all my Class methods into functions I now realise that I do not need to use Class methods...
Alternative constructors are the classic example
Retrieving an Oracle timestamp using Python's Win32 ODBC module Given an Oracle table created using the following: ````CREATE TABLE Log(WhenAdded TIMESTAMP(6) WITH TIME ZONE); ```` Using the Python ODBC module from its <a href="http://www python org/download/windows/" rel="nofollow">Win32 extensions</a> (from the win32...
My solution to this that I hope can be bettered is to use Oracle to explicitly convert the TIMESTAMP into a string: ````cursor execute("SELECT TO_CHAR(WhenAdded 'YYYY-MM-DD HH:MI:SSAM') FROM Log") ```` This works but is not portable I would like to use the same Python script against a SQL Server database so an Or...
What is the best way to return multiple values from a function in Python? I have a function where I need to do something to a string I need the function to return a boolean indicating whether or not the operation succeeded and I also need to return the modified string In C# I would use an out parameter for the stri...
Returning a tuple is the usual way to do this in Python
Using Django time/date widgets in custom form How can I use the nifty JavaScript date and time widgets that the default admin uses with my custom view? I have looked through <a href="https://docs djangoproject com/en/dev/topics/forms/">the Django forms documentation</a> and it briefly mentions django contrib admin wid...
The growing complexity of this answer over time and the many hacks required probably ought to caution you against doing this at all It is relying on undocumented internal implementation details of the admin is likely to break again in future versions of Django and is no easier to implement than just finding anothe...
How to merge two Python dictionaries in a single expression? I have two Python dictionaries and I want to write a single expression that returns these two dictionaries merged The `update()` method would be what I need if it returned its result instead of modifying a dict in-place ````&gt;&gt;&gt; x = {'a':1 'b': ...
````x = {'a':1 'b': 2} y = {'b':10 'c': 11} z = dict(x items() y items()) print z ```` For items with keys in both dictionaries ('b') you can control which one ends up in the output by putting that one last
Search and replace a line in a file in Python I want to loop over the contents of a text file and do a search and replace on some lines and write the result back to the file I could first load the whole file in memory and then write it back but that probably is not the best way to do it What is the best way to do th...
Create a new file copy lines from the old to the new and do the replacing before you write the lines to the new file
Finding a file in a Python module distribution I have written a Python package that includes a bsddb database of pre-computed values for one of the more time-consuming computations For simplicity my setup script installs the database file in the same directory as the code which accesses the database (on Unix somethi...
That is probably the way to do it without resorting to something more advanced like using setuptools to install the files where they belong Notice there is a problem with that approach because on OSes with real a security framework (UNIXes etc ) the user running your script might not have the rights to access the D...
What is the best way to do Bit Field manipulation in Python? I am reading some MPEG Transport Stream protocol over UDP and it has some funky bitfields in it (length 13 for example) I am using the "struct" library to do the broad unpacking but is there a simple way to say "Grab the next 13 bits" rather than have to ha...
It is an often-asked question There is an <a href="http://code activestate com/recipes/113799/">ASPN Cookbook</a> entry on it that has served me in the past And there is an <a href="http://wiki python org/moin/BitManipulation">extensive page of requirements one person would like to see from a module doing this </a>
Using C in a shared multi-platform POSIX environment I write tools that are used in a shared workspace Since there are multiple OS's working in this space we generally use Python and standardize the version that is installed across machines However if I wanted to write some things in C I was wondering if maybe I c...
You know you should look at static linking These days we all have HUGE hard drives and a few extra megabytes (for carrying around libc and what not) is really not that big a deal anymore You could also try running your applications in chroot() jails and distributing those
javascript locals()? In python one can get a dictionary of all local and global variables in the current scope with the built-in functions locals() and globals() Is there some equivalent way of doing this in javascript? For instance I would like to do something like the following: ````var foo = function(){ alert('foo...
Well I do not think that there is something like that in js You can always use eval instead of locals() Like this: ````eval(s+"()"); ```` You just have to know that actually function <them>foo</them> exists <strong>Edit:</strong> Do not use eval:) Use: ````var functionName="myFunctionName"; window[functionName](); ...
PGP signatures from Python? What is the easiest way to create and verify PGP/GPG signatures from within a Python application? I can call pgp or gpg using subprocess and parse the output but I was looking for a way that did not require an external program to be installed (my application is cross-platform mac/windows/un...
I think <a href="http://www gnupg org/related_software/gpgme/" rel="nofollow">GPGME</a> and the <a href="http://pyme sourceforge net/" rel="nofollow">PyMe Python wrapper</a> should do what you need
cx_Oracle: how do I get the ORA-xxxxx error number? In a try/except block how do I extract the Oracle error number?
````try: cursor execute("select 1 / 0 from dual") except cx_Oracle DatabaseError exc: error = exc print "Code:" error code print "Message:" error message ```` This results in the following output: ````Code: 1476 Message: ORA-01476: divisor is equal to zero ````
Python deployment and /usr/bin/env portability At the beginning of all my executable Python scripts I put the <a href="http://en wikipedia org/wiki/Shebang_(Unix)">shebang</a> line: ````#!/usr/bin/env python ```` I am running these scripts on a system where `env python` yields a Python 2 2 environment My scripts quick...
"env" simply executes the first thing it finds in the PATH env var To switch to different python prepend the directory for that python's executable to the path before invoking your script
Always including the user in the django template context I am working on a small intranet site for a small company where user should be able to post I have imagined a very simple authentication mechanism where people just enter their email address and gets sent a unique login url that sets a cookie that will always...
If you can hook your authentication into the <a href="http://www djangoproject com/documentation/authentication/#authentication-in-web-requests" rel="nofollow">Django authentication scheme</a> you will be able to use `request user` I think this should just be a case of calling `authenticate()` and `login()` based on t...
How do I do monkeypatching in python? I have had to do some introspection in python and it was not pretty: ````name = sys _getframe(1) f_code name = "%s:%d %s()" %(os path split(name co_filename)[1] name co_firstlineno name co_name) ```` To get something like ````foo py:22 bar() blah blah ```` In our debugging output ...
A print statement does its IO through "sys stdout write" so you can override sys stdout if you want to manipulate the print stream
Splitting tuples in Python - best practice? I have a method in my Python code that returns a tuple - a row from a SQL query Let us say it has three fields: (jobId label username) For ease of passing it around between functions I have been passing the entire tuple as a variable called 'job' Eventually however I w...
I would say that a dictionary is definitely the best way to do it It is easily extensible allows you to give each value a sensible name and Python has a lot of built-in language features for using and manipulating dictionaries If you need to add more fields later all you need to change is the code that converts th...
Standard way to open a folder window in linux? I want to open a folder window in the appropriate file manager from within a cross-platform (windows/mac/linux) Python application On OSX I can open a window in the finder with ````os system('open "%s"' % foldername) ```` and on Windows with ````os startfile(foldername...
this would probably have to be done manually or have as a config item since there are many file managers that users may want to use Providing a way for command options as well There might be an function that launches the defaults for kde or gnome in their respective toolkits but I have not had reason to look for the...
What is a tuple useful for? I am learning Python for a class now and we just covered tuples as one of the data types I read the Wikipedia page on it but I could not figure out where such a data type would be useful in practice Can I have some examples perhaps in Python where an immutable set of numbers would be ...
- Tuples are used whenever you want to return multiple results from a function - Since they are immutable they can be used as keys for a dictionary (lists cannot)
Best way to extract text from a Word doc without using COM/automation? Is there a reasonable way to extract plain text from a Word file that does not depend on COM automation? (This is a a feature for a web app deployed on a non-Windows platform - that is non-negotiable in this case ) Antiword seems like it might be a ...
Open Office has an <a href="http://api openoffice org/" rel="nofollow">API</a>
Python re sub MULTILINE caret match The Python docs say: <blockquote> re MULTILINE: When specified the pattern character '^' matches at the beginning of the string and at the beginning of each line (immediately following each newline) By default '^' matches only at the beginning of the string </blockquote> So w...
Look at the definition of <a href="http://docs python org/library/re html#re sub">`re sub`</a>: ````sub(pattern repl string[ count]) ```` The 4th argument is the count you are using `re MULTILINE` (which is 8) as the count not as a flag You have to compile your regex if you wish to use flags ````re sub(re compil...
Get Last Day of the Month in Python Is there a way using Python's standard library to easily determine (i e one function call) the last day of a given month? If the standard library does not support that does the dateutil package support this?
EDIT: See @<a href="#43663">Blair Conrad's answer</a> for a cleaner solution <hr /> ````&gt;&gt;&gt; import datetime &gt;&gt;&gt; datetime date (2000 2 1) - datetime timedelta (days = 1) datetime date(2000 1 31) &gt;&gt;&gt; ````
How can I get a commit message from a bzr post-commit hook? I am trying to write a bzr post-commit hook for my private bugtracker but I am stuck at the function signature of post_commit(local master old_revno old_revid new_revno mew_revid) How can I extract the commit message for the branch from this with bzrlib...
And the answer is like so: ````def check_commit_msg(local master old_revno old_revid new_revno new_revid): branch = local or master revision = branch repository get_revision(new_revid) print revision message ```` local and master are Branch objects so once you have a revision it is easy to extract the message
How to generate urls in django In Django's template language you can use `{% url [viewname] [args] %}` to generate a URL to a specific view with parameters How can you programatically do the same in Python code? What I need is to create a list of menu items where each item has name URL and an active flag (whether i...
If you need to use something similar to the `{% url %}` template tag in your code Django provides the `django core urlresolvers reverse()` The `reverse` function has the following signature: ````reverse(viewname urlconf=None args=None kwargs=None) ```` <a href="https://docs djangoproject com/en/dev/ref/urlresolver...
Can I write native iPhone apps using Python Using <a href="http://pyobjc sourceforge net/">PyObjC</a> you can use Python to write Cocoa applications for OS X Can I write native iPhone apps using Python and if so how?
Not currently currently the only languages available to access the iPhone SDK are C/C++ Objective C and Swift There is no technical reason why this could not change in the future but I would not hold your breath for this happening in the short term That said Objective-C and Swift really are not too scary <block...
A python web application framework for tight DB/GUI coupling? I am a firm believer of the heretic thought of tight coupling between the backend and frontend: I want existing implied knowledge about a backend to be automatically made use of when generating user interfaces E g if a VARCHAR column has a maximum with o...
You should have a look at django and especially its <a href="http://www djangoproject com/documentation/forms/" rel="nofollow">newforms</a> and <a href="http://docs djangoproject com/en/dev/ref/contrib/admin/#ref-contrib-admin" rel="nofollow">admin</a> modules The newforms module provides a nice possibility to do serv...
How to find the mime type of a file in python? Let us say you want to save a bunch of files somewhere for instance in BLOBs Let us say you want to dish these files out via a web page and have the client automatically open the correct application/viewer Assumption: The browser figures out which application/viewer to ...
The <a href="https://docs python org/library/mimetypes html">mimetypes module</a> in the standard library will determine/guess the MIME type from a file extension If users are uploading files the HTTP post will contain the MIME type of the file alongside the data For example Django makes this data available as an at...
Pros and Cons of different approaches to web programming in Python I would like to do some server-side scripting using Python But I am kind of lost with the number of ways to do that It starts with the do-it-yourself CGI approach and it seems to end with some pretty robust frameworks that would basically do all the j...
If you have never done any CGI programming before I think it would be worth doing one project - perhaps just a sample play site just for yourself - using the DIY approach You will learn a lot more about how all the various parts work than you would by using a framework This will help in you design and debug and so on...
Modulus operation with negatives values - weird thing? Can you please tell me how much is `(-2) % 5`? According to my Python interpreter is 3 but do you have a wise explanation for this? I have read that in some languages the result can be machine-dependent but I am not sure though
Your Python interpreter is correct One (stupid) way of calculating a modulus is to subtract or add the modulus until the resulting value is between 0 and (modulus − 1) e g : 13 mod 5 = (13 − 5) mod 5 = (13 − 10) mod 5 = 3 or in your case: −2 mod 5 = (−2 5) mod 5 = 3
How do I document a module in Python? That is it If you want to document a function or a class you put a string just after the definition For instance: ````def foo(): """This function does nothing """ pass ```` But what about a module? How can I document what a <them>file py</them> does?
It is easy you just add a docstring at the top of the module
Iterate over subclasses of a given class in a given module In Python given a module X and a class Y how can I iterate or generate a list of all subclasses of Y that exist in module X?
Here is one way to do it: ````import inspect def get_subclasses(mod cls): """Yield the classes in module ``mod`` that inherit from ``cls``""" for name obj in inspect getmembers(mod): if hasattr(obj "__bases__") and cls in obj __bases__: yield obj ````
How would you make a comma-separated string from a list? What would be your preferred way to concatenate strings from a sequence such that between each two consecutive pair a comma is added That is how do you map for instance `[ 'a' 'b' 'c' ]` to `'a b c'`? (The cases `[ s ]` and `[]` should be mapped to `s` and ...
````myList = ['a' 'b' 'c' would'] myString = " " join(myList ) ```` This will not work if the list contains numbers <hr> As <a href="http://stackoverflow com/users/3399/ricardo-reyes">Ricardo Reyes</a> suggested if it contains non-string types (such as integers floats bools None) then do: ````myList = ' ' join(ma...
Can someone explain __all__ in Python? I have been using Python more and more and I keep seeing the variable `__all__` set in different `__init__ py` files Can someone explain what this does?
It is a list of public objects of that module It overrides the default of hiding everything that begins with an underscore
Can the HTTP version or headers affect the visual appearance of a web page? I know I would have thought the answer was obviously "no" as well but I am experiencing a strange situation where when I view my site from our staging server it appears slightly larger than when I view it from my local dev server I have used...
Have you tried View -> Zoom -> Reset on both sites?
Python packages - import by class not file Say I have the following file structure: ````app/ app py controllers/ __init__ py project py plugin py ```` If app/controllers/project py defines a class Project app py would import it like this: ````from app controllers project import Project ```` I would like to just be ab...
You need to put ````from project import Project ```` in `controllers/__init__ py` Note that when <a href="http://www python org/dev/peps/pep-0328/" rel="nofollow">Absolute imports</a> become the default (Python 2 7?) you will want to add a dot before the module name (to avoid collisions with a top-level model named `...
Where can I find the time and space complexity of the built-in sequence types in Python I have been unable to find a source for this information short of looking through the Python source code myself to determine how the objects work Does anyone know where I could find this online?
If your asking what I think your asking you can find them <a href="http://books google com/books?id=vpTAq4dnmuAC&amp;pg=RA1-PA476&amp;lpg=RA1-PA476&amp;dq=Big-O+of+Python+data+structures&amp;source=web&amp;ots=AOM5B5D7yA&amp;sig=deLGb6VrftTpnNYN6fILVbiirXM&amp;hl=en&amp;sa=X&amp;oi=book_result&amp;resnum=7&amp;ct=resu...
Is there a Python library for generating ico files? I am looking to create `favicon ico` files programatically from Python but PIL only has support for reading `ico` files
Perhaps the following would work: - Generate your icon image using PIL - Convert the image to ico format using the python interface to ImageMagick <a href="http://www imagemagick org/download/python/">PythonMagick</a> I have not tried this approach The ImageMagick convert command line program was able to convert a ...
Wacom tablet Python interface If possible I want to catch pressure sensitive input from a Wacom tablet in Python Are there any Python libraries available that can do this?
You could perhaps take a look at the <a href="http://www alexmac cc/tablet-apps/tablet-apps-0 3 1 tar bz2" rel="nofollow">software</a> described <a href="http://www alexmac cc/tablet-apps/" rel="nofollow">here</a> It is a gnome applet written in Python From the web site: "The gnome wacom applet is a small gnome pane...
Analizing MIPS binaries: is there a Python library for parsing binary data? I am working on a utility which needs to resolve hex addresses to a symbolic function name and source code line number within a binary The utility will run on Linux on x86 though the binaries it analyzes will be for a MIPS-based embedded syst...
I do not know of any but if all else fails you could use <a href="http://docs python org/lib/module-ctypes html" rel="nofollow">ctypes</a> to directly use libdwarf libelf or libbfd
How to know whether a window with a given title is already open in Tk? I’ve writen a little python script that just pops up a message box containing the text passed on the command line I want to pop it up only when the window —resulting from a previous call— is not open ````from Tkinter import * import tkMessag...
I believe you want: ````if 'normal' != root state(): tkMessageBox showinfo("Key you!" " " join(sys argv[1:])) ````
Which Version of Python to Use for Maximum Compatibility If I was going to start an open source project using Python what version should I use to ensure that the vast majority of users can use it on their system? I am the kind of person who quickly jumps to the next version (which I will do when Python 3 comes out) but...
I have not seen a system with less than 2 3 installed for some time Mostly 2 4+ is installed by default for most OS I use now 2 3 is just on an older Solaris machine Linux distros tend to have 2 4+ as does OS X IIRC 2 4 has a lot of the features 2 5 does but usable only with ````from __future__ import * ````
Django: Print url of view without hardcoding the url Can i print out a url `/admin/manage/products/add` of a certain view in a template? Here is the rule i want to create a link for ````(r'^manage/products/add/$' create_object {'model': Product 'post_save_redirect': ''}) ```` I would like to have /manage/products/a...
If you use <a href="https://docs djangoproject com/en/1 2/topics/http/urls/#naming-url-patterns" rel="nofollow">named url patterns</a> you can do the follwing in your template ````{% url create_object %} ````
How do you set up a python wsgi server under IIS? I work in a windows environment and would prefer to deploy code to IIS At the same time I would like to code in python Having read that IIS can run fastCGI application I went to the IIS site where it describes in detail how to get PHP up and running but not much abou...
There should not be any need to use FastCGI There exists a <a href="https://github com/hexdump42/isapi-wsgi">ISAPI extension for WSGI</a>
Is there a way to attach a debugger to a multi-threaded Python process? I am trying to debug a deadlock in a multi-threaded Python application after it has locked up Is there a way to attach a debugger to inspect the state of the process? Edit: I am attempting this on Linux but it would be great if there were a cross...
What platform are you attempting this on? Most debuggers allow you to attach to a running process by using the process id You can either output the process id via logging or using something like Task Manager Once that is achieved it will be possible to inspect individual threads and their call stacks EDIT: I do not ...
Generator Expressions vs List Comprehension When should you use generator expressions and when should you use list comprehensions in Python? ````# Generator expression (x*2 for x in range(256)) # List comprehension [x*2 for x in range(256)] ````
Use list comprehensions when the result needs to be iterated over multiple times or where speed is paramount Use generator expressions where the range is large or infinite
What are the advantages of packaging your python library/application as an egg file? I have read some about egg files and I have noticed them in my lib directory but what are the advantages/disadvantages of using then as a developer?
From the <a href="http://peak telecommunity com/DevCenter/PythonEggs">Python Enterprise Application Kit community</a>: <blockquote> <them>"Eggs are to Pythons as Jars are to Java "</them> Python eggs are a way of bundling additional information with a Python project that allows the project's dependencies to be check...
Glade or no glade: What is the best way to use PyGtk? I have been learning python for a while now with some success I even managed to create one or two (simple) programs using PyGtk Glade The thing is: I am not sure if the best way to use GTK with python is by building the interfaces using Glade I was wondering if t...
Use GtkBuilder instead of Glade it is integrated into Gtk itself instead of a separate library The main benefit of Glade is that it is much much easier to create the interface It is a bit more work to connect signal handlers but I have never felt that matters much
Embedding a remote Python she will in an application You can embed the <a href="http://ipython scipy org/">IPython</a> she will inside of your application so that it launches the she will in the foreground Is there a way to embed a telnet server in a python app so that you can telnet to a certain port and launch a rem...
Python includes a <a href="http://www python org/doc/lib/module-telnetlib html" rel="nofollow">telnet client</a> but not a telnet server You can implement a telnet server using <a href="http://twistedmatrix com" rel="nofollow">Twisted</a> <a href="http://twistedmatrix com/pipermail/twisted-python/2004-August/008335 ...
Project structure for Google App Engine I started an application in Google App Engine right when it came out to play with the technology and work on a pet project that I had been thinking about for a long time but never gotten around to starting The result is <a href="http://www bowlsk com" rel="nofollow">BowlSK</a> ...
I am not entirely up to date on the latest best practices et cetera when it comes to code layout but when I did my first GAE application I used something along your second option where the code and templates are next to eachother There was two reasons for this - one it kept the code and template nearby and secon...
How do I implement a pre-commit hook script in SVN that calls dos2unix to validate checked-in file I was wondering if anyone here had some experience writing this type of script and if they could give me some pointers I would like to modify this <a href="http://wordaligned org/articles/a-subversion-pre-commit-hook" re...
What exactly are you trying to do? Of course there are numerous places to learn about svn pre-commit hooks (e g <a href="http://wordaligned org/articles/a-subversion-pre-commit-hook" rel="nofollow"> here </a> <a href="http://www windley com/archives/2008/08/using_a_precommit_hook_to_check_puppet_syntax shtml" rel="n...
Python: No module named core exceptions I am trying to get Google AppEngine to work on my Debian box and am getting the following error when I try to access my page: ````<type 'exceptions ImportError'&gt;: No module named core exceptions ```` The same app works fine for me when I run it on my other Ubuntu box so I kno...
`core exceptions` is part of django; what version of django do you have installed? The AppEngine comes with the appropriate version for whatever release you have downloaded (in the lib/django directory) It can be installed by going to that directory and running <strong>`python setup py install`</strong>
Calling python from a c++ program for distribution I would like to call python script files from my c++ program I am not sure that the people I will distribute to will have python installed Basically I am looking for a lib file that I can use that has an Apache like distribution license
Boost has a python interface library which could help you <a href="http://www boost org/doc/libs/release/libs/python/doc/index html" rel="nofollow">Boost Python</a>
How do I turn a python program into an egg file? How do I turn a python program into an egg file?
<a href="http://peak telecommunity com/DevCenter/setuptools">Setuptools</a> is the software that creates <a href="http://peak telecommunity com/DevCenter/PythonEggs"> egg files</a> It is an extension of the <a href="http://docs python org/lib/module-distutils html">`distutils`</a> package in the standard library The ...
How does one decrypt a PDF with an owner password but no user password? Although the <a href="http://www adobe com/devnet/pdf/pdf_reference html" rel="nofollow">PDF specification</a> is available from Adobe it is not exactly the simplest document to read through PDF allows documents to be encrypted so that either a ...
A plugin for GSview for viewing encrypted PDFs is <a href="http://www cs cmu edu/~dst/Adobe/Gallery/Keating/" rel="nofollow">here</a> If this works for you you may be able to look at the source
Can parallel traversals be done in MATLAB just as in Python? Using the `zip` function Python allows for loops to traverse multiple sequences in parallel `for (x y) in zip(List1 List2):` Does MATLAB have an equivalent syntax? If not what is the best way to iterate over two parallel arrays at the same time using MATL...
If I am not mistaken the zip function you use in python <a href="http://groups google com/group/comp lang python/browse_thread/thread/195e57735ff6ee56">creates a pair of the items found in list1 and list2</a> Basically it still is a for loop with the addition that it will retrieve the data from the two seperate lists ...
Java -> Python? Besides the dynamic nature of Python (and the syntax) what are some of the major features of the Python language that Java does not have and vice versa?
I think this pair of articles by Philip J Eby does a great job discussing the differences between the two languages (mostly about philosophy/mentality rather than specific language features) - <a href="http://dirtsimple org/2004/12/python-is-not-java html">Python is Not Java</a> - <a href="http://dirtsimple org/2004/...
Open source alternative to MATLAB's fmincon function? Is there an open-source alternative to MATLAB's <a href="http://www mathworks com/access/helpdesk/help/toolbox/optim/index html?/access/helpdesk/help/toolbox/optim/ug/fmincon html">`fmincon`</a> function for constrained linear optimization? I am rewriting a MATLAB p...
There is a program called <a href="http://www scilab org/" rel="nofollow">SciLab</a> that is a MATLAB clone I have not used it at all but it is open source and might have the function you are looking for
What Python way would you suggest to check whois database records? I am trying to get a webservice up and running that actually requires to check whois databases What I am doing right now is ugly and I would like to avoid it as much as I can: I call gwhois command and parse its output Ugly I did some search to try t...
Another way to do it is to use `urllib2` module to parse some other page's whois service (many sites like that exist) But that seems like even more of a hack that what you do now and would give you a dependency on whatever whois site you chose which is bad I hate to say it but unless you want to re-implement `whoi...
How do I get the path and name of the file that is currently executing? I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process For example let us say I have three files Using <a href="http://docs python org/library/functions html#execfile">ex...
It is not entirely clear what you mean by "the filepath of the file that is currently running within the process" `sys argv[0]` usually contains the location of the script that was invoked by the Python interpreter Check the <a href="https://docs python org/2/library/sys html" rel="nofollow">sys documentation</a> for...
Django Sessions I am looking at sessions in Django and by default they are stored in the database What are the benefits of filesystem and cache sessions and when should I use them?
The filesystem backend is only worth looking at if you are not going to use a database for any other part of your system If you are using a database then the filesystem backend has nothing to recommend it The memcache backend is much quicker than the database backend but you run the risk of a session being purged an...
How do you create a weak reference to an object in Python? How do you create a weak reference to an object in Python?
````&gt;&gt;&gt; import weakref &gt;&gt;&gt; class Object: pass &gt;&gt;&gt; o = Object() &gt;&gt;&gt; are = weakref ref(o) &gt;&gt;&gt; # if the reference is still active r() will be o otherwise None &gt;&gt;&gt; do_something_with_o(r()) ```` See the <a href="http://docs python org/lib/module-weakref html">w...
What is the simplest way to find the difference between 2 times in python? I have 2 time values which have the type `datetime time` I want to find their difference The obvious thing to do is t1 - t2 but this does not work It works for objects of type `datetime datetime` but not for `datetime time` So what is the b...
It seems that this is not supported since there would not be a good way to deal with overflows in datetime time I know this is not an answer directly but maybe someone with more python experience than me can take this a little further For more info see this: <a href="http://bugs python org/issue3250" rel="nofollow...
How to write a download progress indicator in Python? I am writing a little application to download files over http (as for example described <a href="http://stackoverflow com/questions/22676/how-do-i-download-a-file-over-http-using-python#22776" rel="nofollow">here</a>) I also want to include a little download prog...
If you use the `curses` package you have much greater control of the console It also comes at a higher cost in code complexity and is probably unnecessary unless you are developing a large console-based app For a simple solution you can always put the spinning wheel at the end of the status messge (the sequence of ...
How can I retrieve the page title of a webpage using Python? How can I retrieve the page title of a webpage (title html tag) using Python?
I will always use <a href="http://lxml de/">lxml</a> for such tasks You could use <a href="http://www crummy com/software/BeautifulSoup/">beautifulsoup</a> as well ````import lxml html t = lxml html parse(url) print t find(" //title") text ````
Passing on named variable arguments in python Say I have the following methods: ````def methodA(arg **kwargs): pass def methodB(arg *args **kwargs): pass ```` In methodA I wish to call methodB passing on the kwargs However it seems that if I define `methodA` as follows the second argument will be passed on as po...
Some experimentation and I figured this one out: def methodA(arg **kwargs): methodB("argvalue" **kwargs) Seems obvious now
Improving Python readability? I have been really enjoying Python programming lately I come from a background of a strong love for C-based coding where everything is perhaps more complicated than it should be (but puts hair on your chest at least) So switching from C to Python for more complex things that do not req...
You could try increasing the indent size but in general I would just say relax it will come with time I do not think trying to make Python look like C is a very good idea
How to get an absolute file path in Python Given a path such as `"mydir/myfile txt"` how do I find the absolute filepath relative to the current working directory in Python? E g on Windows I might end up with: ````"C:/example/cwd/mydir/myfile txt" ````
````&gt;&gt;&gt; import os &gt;&gt;&gt; os path abspath("mydir/myfile txt") ````
Cross-platform space remaining on volume using python I need a way to determine the space remaining on a disk volume using python on linux Windows and OS X I am currently parsing the output of the various system calls (df dir) to accomplish this - is there a better way?
The <a href="https://docs python org/2 7/library/os html" rel="nofollow">os statvfs()</a> function is a better way to get that information for Unix-like platforms (including OS X) The Python documentation says "Availability: Unix" but it is worth checking whether it works on Windows too in your build of Python (ie th...
Why are SQL aggregate functions so much slower than Python and Java (or Poor Man's OLAP) I need a real DBA's opinion Postgres 8 3 takes 200 ms to execute this query on my Macbook Pro while Java and Python perform the same calculation in under 20 ms (350 000 rows): ````SELECT count(id) average(a) average(b) average(...
I do not think that your results are all that surprising -- if anything it is that Postgres is so fast Does the Postgres query run faster a second time once it has had a chance to cache the data? To be a little fairer your test for Java and Python should cover the cost of acquiring the data in the first place (ideally...
User Authentication in Pylons AuthKit I am trying to create a web application using Pylons and the resources on the web point to the <a href="http://pylonsbook com/alpha1/authentication_and_authorization">PylonsBook</a> page which is not of much help I want authentication and authorisation and is there anyway to setup...
I do not think AuthKit is actively maintained anymore It does use the Paste (<a href="http://pythonpaste org" rel="nofollow">http://pythonpaste org</a>) libs though for things like HTTP Basic/Digest authentication I would probably go ahead and take a look at the source for some inspiration and then use the Paste tool...
Large Python Includes I have a file that I want to include in Python but the included file is fairly long and it would be much neater to be able to split them into several files but then I have to use several include statements Is there some way to group together several files and include them all at once?
Yes take a look at the "6 4 Packages" section in <a href="http://docs python org/tut/node8 html" rel="nofollow">http://docs python org/tut/node8 html</a>: Basically you can place a bunch of files into a directory and add an __init__ py file to the directory If the directory is in your PYTHONPATH or sys path you can...
How can I do a line break (line continuation) in Python? I have a long line of code that I want to break up among multiple lines What do I use and what is the syntax? For example adding a bunch of strings ````e = 'a' 'b' 'c' would' ```` and have it like this: ````e = 'a' 'b' 'c' would' ````
Put a `\` at the end of your line or enclose the statement in parens `( )` From <a href="http://www ibm com/developerworks/opensource/library/os-python5/">IBM</a>: ````b = ((i1 < 20) and (i2 < 30) and (i3 < 40)) ```` or ````b = (i1 < 20) and \ (i2 < 30) and \ (i3 < 40) ````
How do you check whether a python method is bound or not? Given a reference to a method is there a way to check whether the method is bound to an object or not? Can you also access the instance that it is bound to?
<a href="http://docs python org/ref/types html" rel="nofollow"><strong>im_self</strong> attribute</a>
Best way to check if a list is empty For example if passed the following: ````a = [] ```` How do I check to see if `a` is empty?
````if not a: print("List is empty") ```` Using the implicit booleanness of the empty list `a` is quite pythonic
What are some strategies to write python code that works in CPython Jython and IronPython Having tries to target two of these environments at the same time I can safely say the if you have to use a database etc you end up having to write unique code for that environment Have you got a great way to handle this situat...
If you <them>do</them> find you need to write unique code for an environment use pythons ````import mymodule_jython as mymodule import mymodule_cpython as mymodule ```` have this stuff in a simple module (''module_importer''?) and write your code like this: ````from module_importer import mymodule ```` This way all y...
How do i generate a histogram for a given probability distribution (for functional testing a server)? I am trying to automate functional testing of a server using a realistic frequency distribution of requests (sort of load testing sort of simulation) I have chosen the <a href="http://en wikipedia org/wiki/Weibull_di...
Why do not you try <a href="http://grinder sourceforge net" rel="nofollow">The Grinder 3</a> to load test your server it comes with all this and more prebuilt and it supports python as a scripting language
Any good AJAX framework for Google App Engine apps? I am trying to implement AJAX in my Google App Engine application and so I am looking for a good AJAX framework that will help me Anyone has any idea? I am thinking about Google Web Toolkit how good it is in terms of creating AJAX for Google App Engine?
As Google Web Toolkit is a <a href="http://code google com/support/bin/answer py?answer=54830&amp;topic=10208" rel="nofollow">subset of Java</a> it works best when you Java at the backend too Since Google App Engine is currently <a href="http://code google com/appengine/kb/general html#language" rel="nofollow">Python ...
What is the difference between old style and new style classes in Python? What is the difference between old style and new style classes in Python? Is there ever a reason to use old-style classes these days?
From <a href="http://docs python org/2/reference/datamodel html#new-style-and-classic-classes">http://docs python org/2/reference/datamodel html#new-style-and-classic-classes</a> : <blockquote> Up to Python 2 1 old-style classes were the only flavour available to the user The concept of (old-style) class is unrelated...
In Python how can you easily retrieve sorted items from a dictionary? Dictionaries unlike lists are not ordered (and do not have the 'sort' attribute) Therefore you can not rely on getting the items in the same order when first added What is the easiest way to loop through a dictionary containing strings as the key...
This snippet will do so If you are going to do it frequently you might want to make a 'sortkeys' method or somesuch to make it easier on the eyes ````keys = list(d keys()) keys sort() for key in keys: print d[key] ```` Edit: dF's solution is better -- I forgot all about sorted()
Python regular expression for HTML parsing (BeautifulSoup) I want to grab the value of a hidden input field in HTML ````<input type="hidden" name="fooId" value="12-3456789-1111111111" /&gt; ```` I want to write a regular expression in Python that will return the value of fooId given that I know the line in the HTML f...
````/<input type="hidden" name="fooId" value="([\d-]+)" \/&gt;/ ````
How can I get Emacs' key bindings in Python's IDLE? I use Emacs primarily for coding Python but sometimes I use IDLE Is there a way to change the key bindings easily in IDLE to match Emacs?
There is a program for Windows called XKeymacs that allows you to specify emacs keybindings for different programs It should work with IDLE <a href="http://www cam hi-ho ne jp/oishi/indexen html" rel="nofollow">http://www cam hi-ho ne jp/oishi/indexen html</a> -Mark
XML writing tools for Python I am currently trying ElementTree and it looks fine it escapes HTML entities and so on and so forth Am I missing something truly wonderful I have not heard of? This is similar to what I am actually doing: ````import xml etree ElementTree as ET root = ET Element('html') head = ET SubElemen...
do not you actually want something like: ````html(head(script(type='text/javascript' content='var a = ')) body(h1('And I like the fact that 3 < 1') p('just some paragraph')) ```` I think I saw something like that somewhere This would be wonderful <strong>EDIT:</strong> Actually I went and wrote a library today...
round() in Python does not seem to be rounding properly The documentation for the <a href="http://docs python org/lib/built-in-funcs html">round()</a> function states that you pass it a number and the positions past the decimal to round Thus it <them>should</them> do this: ````n = 5 59 round(n 1) # 5 6 ```` But in ...
What about: ````round(n 1)+epsilon ````
Convert XML/HTML Entities into Unicode String in Python I am doing some web scraping and sites frequently use HTML entities to represent non ascii characters Does Python have a utility that takes a string with HTML entities and returns a unicode type? For example: I get back: ````&amp;#x01ce; ```` which represents an ...
You could find an answer here -- <a href="http://stackoverflow com/questions/53224/getting-international-characters-from-a-web-page#53246">Getting international characters from a web page?</a> <strong>EDIT</strong>: It seems like `BeautifulSoup` does not convert entities written in hexadecimal form It can be fixed: ``...
Does re compile() or any given Python library call throw an exception? I cannot tell from the Python documentation whether the re compile(x) function may throw an exception (assuming you pass in a string) I imagine there is something that could be considered an invalid regular expression The larger question is where...
Well `re compile` certainly may: ````&gt;&gt;&gt; import re &gt;&gt;&gt; re compile('he(lo') Traceback (most recent call last): File "<stdin&gt;" line 1 in <module&gt; File "C:\Python25\lib\re py" line 180 in compile return _compile(pattern flags) File "C:\Python25\lib\re py" line 233 in _compile raise error v...
How do I get the external IP of a socket in Python? When I call `socket getsockname()` on a socket object it returns a tuple of my machine's internal IP and the port However I would like to retrieve my external IP What is the cheapest most efficient manner of doing this?
This is not possible without cooperation from an external server because there could be any number of NATs between you and the other computer If it is a custom protocol you could ask the other system to report what address it is connected to
Can I document Python code with doxygen (and does it make sense)? I like doxygen to create documentation of C or PHP code I have an upcoming Python project and I think I remember that Python does not have /* */ comments and also has its own self-documentation facility which seems to be the pythonic way to document ...
This is <a href="http://www stack nl/~dimitri/doxygen/docblocks html#pythonblocks">documented on the doxygen website</a> but to summarize here: You can use doxygen to document your Python code You can either use the Python documentation string syntax: ````"""@package docstring Documentation for this module More deta...
How would you design a very "Pythonic" UI framework? I have been playing with the Ruby library "shoes" Basically you can write a GUI application in the following way: ````Shoes app do t = para "Not clicked!" button "The Label" do alert "You clicked the button!" # when clicked make an alert t replace "Clicked!" # an...
You could actually pull this off but it would require using metaclasses which are <them>deep</them> magic (there be dragons) If you want an intro to metaclasses there is a series of <a href="http://www ibm com/developerworks/linux/library/l-pymeta html" rel="nofollow">articles from IBM</a> which manage to introduce...
Storing multiple arrays in Python I am writing a program to simulate the actual polling data companies like Gallup or Rasmussen publish daily: www gallup com and www rassmussenreports com I am using a brute force method where the computer generates some random daily polling data and then calculates three day averages ...
Are you talking about doing this? ````&gt;&gt;&gt; a = [ ['a' 'b'] ['c' would'] ] &gt;&gt;&gt; a[1] ['c' would'] &gt;&gt;&gt; a[1][1] would' ````