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 python (2 5 2 specifically r252:60911) without an issue I found <a href="http://www nabble com/problem-under-some-windows-desktop-td15868057 html" rel="nofollow">this link</a> which describes my problem Trying what was outlined there I confirmed Python could find svn (it is in my path): ``` P:\>python Python 2 5 2 (r252:60911 Feb 21 2008 13:11:45) [MSC v 1310 32 bit (Intel)] on win32 Type "help" "copyright" "credits" or "license" for more information >>> import os >>> i k = os popen4("svn --version") >>> i close() >>> k readline() 'svn version 1 4 2 (r22196)\n' ``` Looking at the svnmerge py code though I noticed for python versions 2 4 and higher it was following a different execution path Rather than invoking os popen4() it uses subprocess Popen() Trying that reproduces the error: ``` C:\>python Python 2 5 2 (r252:60911 Feb 21 2008 13:11:45) [MSC v 1310 32 bit (Intel)] on win32 Type "help" "copyright" "credits" or "license" for more information >>> import subprocess >>> p = subprocess Popen("svn --version" stdout=subprocess PIPE >>> close_fds=False stderr=subprocess PIPE) Traceback (most recent call last): File "" line 1 in File "C:\Python25\lib\subprocess py" line 594 in __init__ errread errwrite) File "C:\Python25\lib\subprocess py" line 816 in _execute_child startupinfo) WindowsError: [Error 2] The system cannot find the file specified >>> ``` For now I have commented out the 2 4-and-higher specific code but I would like to find a proper solution If it is not obvious I am a complete python newbie but google has not helped Any pointers?
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 "svn --version" which it does not find I do not know why it would work for your colleagues though if they are running the same OS and version of Python FWIW it gives me the same error message on a mac and either of the two ways I gave fixes it
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 build both my view and my template? Please keep in mind that I do not really know all that much Python and i am very new to Django How can I do this all without using this existing django admin interface
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 whatever database type you are using
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 (or an empty tuple if there were no excess positional arguments) If any keyword argument does not correspond to a formal parameter name a TypeError exception is raised unless a formal parameter using the syntax "**identifier" is present; in this case that formal parameter receives a dictionary containing the excess keyword arguments (using the keywords as keys and the argument values as corresponding values) or a (new) empty dictionary if there were no excess keyword arguments </blockquote>
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/">PEP 435</a>) you can make Enum the base class This gets you a little bit of extra functionality described in the PEP For example enum values are distinct from integers ````class Animal(Enum): DOG = 1 CAT = 2 print(Animal DOG) <Animal DOG: 1&gt; ```` <hr> If you do not want to type the values use the following shortcut: ````class Animal(Enum): DOG CAT = range(2) ````
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 google com/p/hotwire-she will/source/browse/trunk/hotwire/externals/shlex py">lexes</a> <a href="http://code google com/p/hotwire-she will/source/browse/trunk/hotwire/command py">parses and tokenises</a> the commands entered into it As it is real working code it is fairly complex and a bit hard to work out I have not worked on code to lex/parse/tokenise before so I was thinking one approach would be to work through a tutorial or two on this aspect I would hope to learn enough to navigate around the code I actually want to alter Is there anything suitable out there? (Ideally it could be done in an afternoon without having to buy and read the dragon book first ) <strong>Edit:</strong> (7 Oct 2008) None of the below answers quite give what I want With them I could generate parsers from scratch but I want to learn how to write my own basic parser from scratch not using lex and yacc or similar tools Having done that I can then understand the existing code better So could someone point me to a tutorial where I can build a basic parser from scratch using just python?
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/display/ANTLR3/Antlr3PythonTarget" rel="nofollow">ANTLR</a> can generate python too
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: httpd-vhosts (included in httpd-conf) ``` NameVirtualHost tred:80 ServerName tred Alias /admin_media /usr/lib/python2 5/site-packages/django/contrib/admin/media Order allow deny Allow from all Alias /media /Users/dmg/Sites/tred/media Order allow deny Allow from all Alias / /Users/dmg/Sites/tred/ Order allow deny Allow from all WSGIScriptAlias / /Users/dmg/Sites/tred/mod_wsgi-handler wsgi WSGIDaemonProcess tred user=dmg group=staff processes=1 threads=10 WSGIProcessGroup tred ``` mod_wsgi-handle wsgi ``` import sys import os sys path append(os path dirname(os path abspath(__file__)) '/ ') os environ['DJANGO_SETTINGS_MODULE'] = 'tred settings' import django core handlers wsgi application = django core handlers wsgi WSGIHandler() ``` When I go to <a href="http://tred">http://tred</a> I get a directory listing rather than the rendered website I think I have followed the tutorials correctly but it is obviously not right What can I do to make this work?
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 have a global interpreter lock (GIL) that is used to protect potentially shared data structures so this inhibits multi-processor execution Even though the portions in those languajes that are written in C or C++ can be free-threaded that is not possible with pure interpreted code unless you use multiple processes What is the best way to achieve this? <a href="http://blogs codehaus org/people/tirsen/archives/001041_ruby_on_rails_and_fastcgi_scaling_using_processes_instead_of_threads html">Using FastCGI</a>? Creating a <a href="http://blog innerewut de/files/images/stage_2 png">cluster or a farm</a> of virtualized servers? Using their Java equivalents JRuby and Jython?
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 modules It still supports running requests in separate processes FastCGI-style though so that is apparently the current accepted solution
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(object): pass # with own __repr__ inst_x=ClassX() inst_y=ClassY() inst_z=[ i*i for i in range(25) ] inst_b=True class HTMLDecorator(object): def html(self): # an "enhanced" version of __repr__ return cgi escape(self __repr__()) join(("<H1&gt;" "</H1&gt;")) print HTMLDecorator(inst_x) html() print HTMLDecorator(inst_y) html() wrapped_z = HTMLDecorator(inst_z) inst_z[0] = 70 wrapped_z[0] = 71 print wrapped_z html() print HTMLDecorator(inst_b) html() ```` Output: ```Traceback (most recent call last): File "html py" line 21 in print HTMLDecorator(inst_x) html() TypeError: default __new__ takes no parameters``` Is what I am trying to do possible? If so what am I doing wrong?
<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 @decorator def a (): return "a" def b (): return "b" print a() # new_func a print decorator (b)() # new_func b ````
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 href="http://www physics ox ac uk/users/santoso/dbf py src">`dbf py`</a> and it works nicely One gotcha: The memo file name extension must be lower case i e ` fpt` not ` FPT` which was how the filename came over from Windows
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/users/santoso/dbf py src" rel="nofollow">memo fields</a>
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 for what I would done with `static` methods in Java but now I am not sure when I would use them All the advice I can find about Python Class methods is along the lines of newbies like me should steer clear of them and the standard documentation is at its most opaque when discussing them Does anyone have a good example of using a Class method in Python or at least can someone tell me when Class methods can be sensibly used?
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 win32all package) I tried the following: ````import dbi odbc connection = odbc odbc("Driver=Oracle in OraHome92;Dbq=SERVER;Uid=USER;Pwd=PASSWD") cursor = connection cursor() cursor execute("SELECT WhenAdded FROM Log") results = cursor fetchall() ```` When I run this I get the following: ````Traceback (most recent call last): results = cursor fetchall() dbi operation-error: [Oracle][ODBC][Ora]ORA-00932: inconsistent datatypes: expected %s got %s in FETCH ```` The other data types I have tried (VARCHAR2 BLOB) do not because this problem Is there a way of retrieving timestamps?
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 Oracle-specific solution (such as TO_CHAR) will not work
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 string but there is no equivalent in Python I am still very new to Python and the only thing I can think of is to return a tuple with the boolean and modified string Related question: <a href="http://stackoverflow com/questions/61605/is-it-pythonic-for-a-function-to-return-multiple-values">Is it pythonic for a function to return multiple values?</a>
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 widgets but I do not know how to use it? Here is my template that I want it applied on ````<form action=" " method="POST"&gt; <table&gt; {% for f in form %} <tr&gt; <td&gt; {{ f name }}</td&gt; <td&gt;{{ f }}</td&gt; </tr&gt; {% endfor %} </table&gt; <input type="submit" name="submit" value="Add Product"&gt; </form&gt; ```` Also I think it should be noted that I have not really written a view up myself for this form I am using a generic view Here is the entry from the url py: ````(r'^admin/products/add/$' create_object {'model': Product 'post_save_redirect': ''}) ```` And I am relevantly new to the whole Django/MVC/MTV thing so please go easy
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 another JS calendar widget and using that That said here is what you have to do if you are determined to make this work: - Define your own ModelForm subclass for your model (best to put it in forms py in your app) and tell it to use the AdminDateWidget / AdminTimeWidget / AdminSplitDateTime (replace 'mydate' etc with the proper field names from your model): ````from django import forms from my_app models import Product from django contrib admin import widgets class ProductForm(forms ModelForm): class Meta: model = Product def __init__(self *args **kwargs): super(ProductForm self) __init__(*args **kwargs) self fields['mydate'] widget = widgets AdminDateWidget() self fields['mytime'] widget = widgets AdminTimeWidget() self fields['mydatetime'] widget = widgets AdminSplitDateTime() ```` - Change your URLconf to pass 'form_class': ProductForm instead of 'model': Product to the generic create_object view (that will mean "from my_app forms import ProductForm" instead of "from my_app models import Product" of course) - In the head of your template include {{ form media }} to output the links to the Javascript files - And the hacky part: the admin date/time widgets presume that the i18n JS stuff has been loaded and also require core js but do not provide either one automatically So in your template above {{ form media }} you will need: ````<script type="text/javascript" src="/my_admin/jsi18n/"&gt;</script&gt; <script type="text/javascript" src="/media/admin/js/core js"&gt;</script&gt; ```` You may also wish to use the following admin CSS (thanks <a href="http://stackoverflow com/questions/38601/using-django-time-date-widgets-in-custom-form/719583#719583">Alex</a> for mentioning this): ````<link rel="stylesheet" type="text/css" href="/media/admin/css/forms css"/&gt; <link rel="stylesheet" type="text/css" href="/media/admin/css/base css"/&gt; <link rel="stylesheet" type="text/css" href="/media/admin/css/global css"/&gt; <link rel="stylesheet" type="text/css" href="/media/admin/css/widgets css"/&gt; ```` This implies that Django's admin media (ADMIN_MEDIA_PREFIX) is at /media/admin/ - you can change that for your setup Ideally you would use a context processor to pass this values to your template instead of hardcoding it but that is beyond the scope of this question This also requires that the URL /my_admin/jsi18n/ be manually wired up to the django views i18n javascript_catalog view (or null_javascript_catalog if you are not using I18N) You have to do this yourself instead of going through the admin application so it is accessible regardless of whether you are logged into the admin (thanks <a href="http://stackoverflow com/questions/38601/using-django-time-date-widgets-in-custom-form/408230#408230">Jeremy</a> for pointing this out) Sample code for your URLconf: ````(r'^my_admin/jsi18n' 'django views i18n javascript_catalog') ```` Lastly if you are using Django 1 2 or later you need some additional code in your template to help the widgets find their media: ````{% load adminmedia %} /* At the top of the template */ /* In the head section of the template */ <script type="text/javascript"&gt; window __admin_media_prefix__ = "{% filter escapejs %}{% admin_media_prefix %}{% endfilter %}"; </script&gt; ```` Thanks <a href="http://stackoverflow com/questions/38601/using-django-time-date-widgets-in-custom-form/2818128#2818128">lupefiasco</a> for this addition
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': 2} &gt;&gt;&gt; y = {'b':10 'c': 11} &gt;&gt;&gt; z = x update(y) &gt;&gt;&gt; print z None &gt;&gt;&gt; x {'a': 1 'b': 10 'c': 11} ```` How can I get that final merged dict in z not x? (To be extra-clear the last-one-wins conflict-handling of `dict update()` is what I am looking for as well )
````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 this within the following code? ````f = open(file) for line in f: if line contains('foo'): newline = line replace('foo' 'bar') # how to write this newline back to the file ````
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 something like /usr/lib/python2 5/site-packages/mypackage/) How do I store the final location of the database file so my code can access it? Right now I am using a hack based on the `__file__` variable in the module which accesses the database: ``` dbname = os path join(os path dirname(__file__) "database dat") ``` It works but it seems hackish Is there a better way to do this? I would like to have the setup script just grab the final installation location from the distutils module and stuff it into a "dbconfig py" file that gets installed alongside the code that accesses the database
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 DB in the system directory where it gets installed
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 hand-tweak the bit manipulation? I would like something like the way C does bit fields (without having to revert to C) Suggestions?
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 could have the application wrapped in a Python script that detected the operating system and fired off the correct version of the C application Each platform has GCC available and uses the same she will One idea was to have the C compiled to the users local ~/bin with timestamp comparison with C code so it is not compiled each run but only when code is updated Another was to just compile it for each platform and have the wrapper script select the proper executable Is there an accepted/stable process for this? Are there any catches? Are there alternatives (assuming the absolute need to use native C code)? <them>Clarification: Multiple OS's are involved that do not share ABI Eg OS X various Linuxes BSD etc I need to be able to update the code in place in shared folders and have the new code working more or less instantaneously Distributing binary or source packages is less than ideal </them>
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'); }; var bar = function(){ alert('bar'); }; var s = 'foo'; locals()[s](); // alerts 'foo' ```` Is this at all possible or should I just be using a local object for the lookup?
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/unix)
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 quickly fail because I have a manual check for a compatible Python version: ````if sys version_info < (2 4): raise ImportError("Cannot run with Python version < 2 4") ```` I do not want to have to change the shebang line on every executable file if it is possible; however I do not have administrative access to the machine to change the result of `env python` and I do not want to force a particular version as in: ````#!/usr/bin/env python2 4 ```` I would like to avoid this because system may have a newer version than Python 2 4 or may have Python 2 5 but no Python 2 4 What is the elegant solution? [Edit:] I was not specific enough in posing the question -- I would like to let users execute the scripts without manual configuration (e g path alteration or symlinking in `~/bin` and ensuring your PATH has `~/bin` before the Python 2 2 path) Maybe some distribution utility is required to prevent the manual tweaks?
"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 identify them for future requests In my template setup I have base html and the other pages extend this I want to show logged in or register button in the base html but how can I ensure that the necessary variables are always a part of the context? It seems that each view just sets up the context as they like and there is no global context population Is there a way of doing this without including the user in each context creation? Or will I have to make my own custom shortcuts to setup the context properly?
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 the contents of your Cookie Edit: @Staale - I always use the <a href="http://www djangobook com/en/1 0/chapter04/" rel="nofollow">`locals()` trick</a> for my context so all my templates can see `request` and so `request user` If you are not then I guess it would not be so straightforward
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 I would ideally like to prepend anything to stderr with this sort of information -- Is it possible to change the behaviour of print globally within python?
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 want to get at the bits so I have been using code like this: (jobId label username) = job I have realised however that this is a maintenance nightmare because now I can never add new fields to the result set without breaking all of my existing code How should I have written this? Here are my two best guesses: (jobId label username) = (job[0] job[1] job[2]) but that does not scale nicely when you have 15 20 fields or to convert the results from the SQL query to a dictionary straight away and pass that around (I do not have control over the fact that it starts life as a tuple that is fixed for me)
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 the tuple to a dictionary and the code that actually makes use of the new values For example: ````job={} job['jobid'] job['label'] job['username']=<querycode&gt; ````
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) ```` What about unix/linux? Is there a standard way to do this or do I have to special case gnome/kde/etc and manually run the appropriate application (nautilus/konqueror/etc)? This looks like something that could be specified by the <a href="http://freedesktop org">freedesktop org</a> folks (a python module similar to `webbrowser` would also be nice!)
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 them
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 needed? How is this different from a list?
- 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 reasonable option but it seems like it might be abandoned A Python solution would be ideal but does not appear to be available
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 what is going on when I get the following unexpected result? ````&gt;&gt;&gt; import re &gt;&gt;&gt; s = """// The quick brown fox // Jumped over the lazy dog """ &gt;&gt;&gt; re sub('^//' '' s re MULTILINE) ' The quick brown fox \n// Jumped over the lazy dog ' ````
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 compile('^//' re MULTILINE) '' s) ```` A `flags` argument was added in Python 2 7 so the full definition is now: ````re sub(pattern repl string[ count flags]) ```` Which means that: ````re sub('^//' '' s flags=re MULTILINE) ```` works
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 in Python?
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 it is the current page or not) This is because it will be a lot cleaner to do this in Python than the template language
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/urlresolvers/">https://docs djangoproject com/en/dev/ref/urlresolvers/</a>
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 <blockquote> <h1>2016 edit</h1> Javascript with NativeScript framework is available to use now </blockquote>
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 of 20 characters there GUIs should automatically constrain the user from typing more than 20 characters in a related form field And I have strong antipathy to ORMs which want to define my database tables or are based on some hack where every table needs to have extra numeric ID columns because of the ORM I have looked a bit into Python database frameworks and I think I can conclude the SQLAlchemy fits best to my mentality Now I need to find a web application framework which fits naturally with SQLAlchemy (or an equivalent) and perhaps even with my appetite for coupling With "web application framework" I mean products/project such as Pyhons Django TurboGears web2py etc E g it should ideally be able to: - <strong>automatically select a suitable form widget</strong> for data entering a given column if told to do so; e g if the column has a foreign key to a column with 10 different values widget should display the 10 possible values as a dropdown - <strong>auto-generate javascript form validation code</strong> which gives the end-user quick error feedback if a string is entered into a field which is about to end up in an INTEGER column etc - auto-generate a <strong>calendar widget</strong> for data which will end up in a DATE column - <strong>hint NOT NULL constraints</strong> as javascript which complains about empty or whitespace-only data in a related input field - generate javascript validation code which matches relevant (simple) <strong>CHECK-constraints</strong> - make it easy to <strong>avoid SQL injection</strong> by using prepared statements and/or validation of externally derived data - make it easy to <strong>avoid cross site scripting</strong> by automatically escape outgoing strings when appropriate - <strong>make use of constraint names</strong> to generate somewhat user friendly error messages in case a constrataint is violated All this should happen dynamically so table adjustments are automatically reflected on the frontend - probably with a caching mechanism so that all the model introspection would not kill performance In other words I do not want to repeat my model definition in an XML file (or alike) when it has already been carefully been defined in my database Does such a framework exist for Python (or for any language for that matter)? If not: Which of the several Python web application frameworks will be least in the way if I were to add parts of the above features myself?
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 server side validation with automated generation of error messages/pages for the user Adding ajax validation is also <a href="http://lukeplant me uk/blog php?id=1107301681" rel="nofollow">possible</a>
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 use by the mime-type (content-type?) header in the HTTP response Based on that assumption in addition to the bytes of the file you also want to save the MIME type How would you find the MIME type of a file? I am currently on a Mac but this should also work on Windows Does the browser add this information when posting the file to the web page? Is there a neat python library for finding this information? A WebService or (even better) a downloadable database?
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 attribute of the <a href="https://docs djangoproject com/en/dev/topics/http/file-uploads/#uploadedfile-objects">UploadedFile</a> object
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 job themselves And a huge lot of stuff in between like <a href="http://webpy org/">web py</a> <a href="http://pyroxide org/">Pyroxide</a> and <a href="http://wiki python org/moin/Django">Django</a> - What are the <strong>pros</strong> and <strong>cons</strong> of the frameworks or approaches that <them>you have worked on</them>? - What <strong>trade-offs</strong> are there? - For <strong>what kind of projects</strong> they do well and for what they do not? Edit: I have not got much experience with web programing yet <br /> I would like to avoid the basic and tedious things like parsing the URL for parameters etc <br /> On the other hand while the video of <a href="http://www rubyonrails org/screencasts">blog created in 15 minutes</a> with <a href="http://www rubyonrails org/">Ruby on Rails</a> left me impressed I realized that there were hundreds of things hidden from me - which is cool if you need to write a working webapp in no time but not that great for really understanding the magic - and that is what I seek now
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 all your future web applications however you write them Personally I now use <a href="http://www djangoproject com/" rel="nofollow">Django</a> The real benefit is very fast application deployment The object relational mapping gets things moving fast and the template library is a joy to use Also the admin interface gives you basic CRUD screens for all your objects so you do not need to write any of the "boring" stuff The downside of using an ORM based solution is that if you do want to handcraft some SQL say for performance reasons it much harder than it would have been otherwise although still very possible
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 `''` respectively ) I usually end up using something like `'' join(map(lambda x: x+' ' l))[:-1]` but also feeling somewhat unsatisfied Edit: I am both ashamed and happy that the solution is so simple Obviously I have hardly a clue as to what I am doing (I probably needed "simple" concatenation in the past and somehow memorised `s join([e1 e2 ])` as a shorthand for `s+e1+e2+ ` )
````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(map(str myList)) ````
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 Charles to confirm that all of the content -- the HTML the images the CSS the javascript <strong>everything</strong> is the same The ONLY difference in the traffic is that (because the local site is served from the Django development mode server) the response headers look like this: ````HTTP/1 0 200 OK Server WSGIServer/0 1 Python/2 5 2 Date Thu 04 Sep 2008 23:56:10 GMT Vary Cookie Content-Length 2301 Content-Type text/html; charset=utf-8 ```` Whereas on the staging server (where Django is running inside Apache) the headers look like this: ````HTTP/1 1 200 OK Date Thu 04 Sep 2008 23:56:06 GMT Server Apache/2 2 8 (Ubuntu) mod_python/3 3 1 Python/2 5 2 PHP/5 2 4-2ubuntu5 with Suhosin-Patch Vary Cookie Content-Length 2301 Content-Type text/html; charset=utf-8 ```` So as far as I can tell the only differences are HTTP/1 1 vs HTTP/1 0 the server identifer (Apache vs WSGIServer) and the order of the Date/Server headers To elaborate a bit further on the differences in appearance basically it appears as if the version of the site on the staging server is "zoomed in" by about 10% For example the primary logo which dominates our home page is 220 pixels wide but when server from our staging server shows up as 245 pixels wide Everything else on the page (other images text spacing etc) is also proportionately larger This is all in Firefox 3 I do not have any other browsers available to test with at the moment Has anyone else encountered any bizarre behavior anything like this before? I am at a loss
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 able to do: ````from app controllers import Project ```` How would this be done?
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 `project`) i e ````from project import Project ````
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=result#PRA1-PA479 M1" rel="nofollow">Here</a> page 476 and on It is written around optimization techniques for Python; It is mostly Big-O notation of time efficiencies not much memory
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 png file to ico format so at least ImageMagick supports the ico format
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 panel applet that shows how much pressure is being applied to your wacom tablet by the current device Clicking on the panel icon brings up a dialog allowing you to select a different device and check what pressure and tilt information is being recieved from it This dialog also contains a small drawing test area to give your pen a quick test " <a href="http://www google com/search?q=wacom+tablet+python" rel="nofollow">Google is your friend</a>
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 system The MIPS binaries are in ELF format using DWARF for the symbolic debugging information I am currently planning to fork objdump passing in a list of hex addresses and parsing the output to get function names and source line numbers I have compiled an objdump with support for MIPS binaries and it is working I would prefer to have a package allowing me to look things up natively from the Python code without forking another process I can find no mention of libdwarf libelf or libbfd on python org nor any mention of python on dwarfstd org Is there a suitable module available somewhere?
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 tkMessageBox root = Tk() root withdraw() # TODO not if a window with this title exists tkMessageBox showinfo("Key you!" " " join(sys argv[1:])) ```` Any idea how to check that?
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 many people may be more conservative if their current version seems to be working fine What version would hit the sweet spot but still allow me to enjoy the newest and coolest language enhancements?
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/add in a template without hardcoding it How can i do this? <strong>Edit:</strong> I am not using the default admin (well i am but it is at another url) this is my own
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 about anything else Does anyone have experience getting a <strong>Python</strong> framework <strong>running under IIS</strong> using something other that plain old CGI? If so can you explain to direct me to some instructions on setting this up?
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-platform solution It is Python after all :)
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 have any experience with GNU Debugger (GDB) which is cross platform however I found this <a href="http://wiki python org/moin/DebuggingWithGdb" rel="nofollow">link</a> and it may start you on the right path It explains how to add debug symbols (handy for reading stack traces) and how to instruct gdb to attach to a running python process
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 checked and satisfied at runtime as well as allowing projects to provide plugins for other projects There are several binary formats that embody eggs but the most common is ' egg' zipfile format because it is a convenient one for distributing projects All of the formats support including package-specific data project-wide metadata C extensions and Python code The primary benefits of Python Eggs are: - They enable tools like the "Easy Install" Python package manager - egg files are a "zero installation" format for a Python package; no build or install step is required just put them on PYTHONPATH or sys path and use them (may require the runtime installed if C extensions or data files are used) - They can include package metadata such as the other eggs they depend on - They allow "namespace packages" (packages that just contain other packages) to be split into separate distributions (e g zope <them> twisted </them> peak * packages can be distributed as separate eggs unlike normal packages which must always be placed under the same parent directory This allows what are now huge monolithic packages to be distributed as separate components ) - They allow applications or libraries to specify the needed version of a library so that you can e g require("Twisted-Internet>=2 0") before doing an import twisted internet - They are a great format for distributing extensions or plugins to extensible applications and frameworks (such as Trac which uses eggs for plugins as of 0 9b1) because the egg runtime provides simple APIs to locate eggs and find their advertised entry points (similar to Eclipse's "extension point" concept) - There are also other benefits that may come from having a standardized format similar to the benefits of Java's "jar" format </blockquote>
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 the more experienced ones among us (remember I am just a beginner) could point out the benefits and caveats of using Glade as opposed to creating everything in the code itself (assuming that learning the correct gtk bindings would not exactly be a problem)
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 remote IPython she will? Any tips for redirecting the input/output streams for IPython or how to hook it up to a telnet server library or recommendations for other libraries that could be used to implement this are much appreciated
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 html" rel="nofollow">Here is an example</a> As for hooking these things together that is up to you
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> However as it has grown and features have been added it has gotten really difficult to keep things organized - mainly due to the fact that this is my first python project and I did not know anything about it until I started working What I have: - Main Level contains: - all py files (did not know how to make packages work) - all html templates for main level pages - Subdirectories: - separate folders for css images js etc - folders that hold html templates for subdirecty-type urls Example:<br/> <a href="http://www bowlsk com/" rel="nofollow">http://www bowlsk com/</a> maps to HomePage (default package) template at "index html"<br/> <a href="http://www bowlsk com/games/view-series html?series=7130" rel="nofollow">http://www bowlsk com/games/view-series html?series=7130</a> maps to ViewSeriesPage (again default package) template at "games/view-series html" It is nasty How do I restructure? I had 2 ideas: - Main Folder containing: appdef indexes main py? - Subfolder for code Does this have to be my first package? - Subfolder for templates Folder heirarchy would match package heirarchy - Individual subfolders for css images js etc - Main Folder containing appdef indexes main py? - Subfolder for code templates This way I have the handler class right next to the template because in this stage I am adding lots of features so modifications to one mean modifications to the other Again do I have to have this folder name be the first package name for my classes? I would like the folder to be "src" but I do not want my classes to be "src WhateverPage" Is there a best practice? With Django 1 0 on the horizon is there something I can do now to improve my ability to integrate with it when it becomes the official GAE templating engine? I would simply start trying these things and seeing which seems better but pyDev's refactoring support does not seem to handle package moves very well so it will likely be a non-trivial task to get all of this working again
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 secondly I had the directory structure layout mimic that of the website - making it (for me) a bit easier too remember where everything was
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" rel="nofollow">script</a> to validate that the check-in file does not have a Carriage Return in the EOL formatting The EOL format is CR LF in Windows and LF in Unix When a User checks-in code with the Windows format It does not compile in Unix anymore I know this can be done on the client side but I need to have this validation done on the server side To achieve this I need to do the following: 1) Make sure the file I check is not a binary I do not know how to do this with svnlook should I check the mime:type of the file? The <a href="http://svnbook red-bean com/nightly/en/svn reposadmin create html" rel="nofollow">Red Book</a> does not indicate this clearly or I must have not seen it 2) I would like to run the <a href="http://linux about com/od/commands/l/blcmdl1_dos2uni htm" rel="nofollow">dos2unix</a> command to validate that the file has the correct EOL format I would compare the output of the dos2unix command against the original file If there is a different between both I give an error message to the client and cancel the check-in I would like your comments/feedback on this approach
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="nofollow"> here</a> and in the <a href="http://svnbook red-bean com/nightly/en/svn reposadmin create html" rel="nofollow">Red Book</a>) but it depends what you are trying to do and what is available on your system Can you be more specific?
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 know it is not a problem with the app itself However I need to get it working on this Debian box It originally had python 2 4 but after AppEngine complained about it I installed the python2 5 and python2 5-dev packages (to no avail) I saw on this <a href="http://groups google com/group/google-appengine/browse_thread/thread/8f2459d2df9d735a/df2b1e9bb76f87c0?show_docid=df2b1e9bb76f87c0&amp;fwc=1" rel="nofollow">Google Group post</a> that it may be due to the version of AppEngine and just to reinstall it but that did not work Any ideas? Edit 1: Also tried uninstalling python2 4 and 2 5 then reinstalling 2 5 which also did not work Edit 2: Turns out when I made AppEngine into a CVS project it did not add the core directory into my project so when I checked it out there literally was no module named core exceptions Re-downloading that folder resolved the problem
`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 process involves creating a `setup py` file then `python setup py bdist_egg` creates an egg package
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 user password and/or an owner password is required to do various things with the document (display print etc) A common use is to lock a PDF so that end users can read it without entering any password but a password is required to do anything else I am trying to parse PDFs that are locked in this way (to get the same privileges as you would get opening them in any reader) Using an empty string as the user password does not work but it seems (section 3 5 2 of the spec) that there has to be a user password to create the hash for the admin password What I would like is either an explanation of how to do this or any code that I can read (ideally Python C or C++ but anything readable will do) that does this so that I can understand what I am meant to be doing Standalone code rather than reading through (e g ) the gsview source would be best
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 MATLAB?
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 for you instead that you have to do it yourself So maybe your best option is to use a <them>standard</them> for loop like this: ````for i=1:length(a) c(i) = a(i) b(i); end ```` or whatever you have to do with the data If you really are talking about parallel computing then you should take a look at the <a href="http://www mathworks com/products/parallel-computing/">Parallel Computing Toolbox</a> for matlab and more specifically at <a href="http://www mathworks com/access/helpdesk/help/toolbox/distcomp/index html?/access/helpdesk/help/toolbox/distcomp/brb2x2l-1 html">parfor</a>
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/12/java-is-not-python-either html">Java is Not Python either</a>
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 program to use Python / <a href="http://numpy scipy org/">NumPy</a> / <a href="http://www scipy org/">SciPy</a> and this is the only function I have not found an equivalent to A NumPy-based solution would be ideal but any language will do
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 to find a pythonic way to do this task Generally I got quite much nothing - <a href="http://mail python org/pipermail/python-list/2000-March/028122 html">this old discussion list link</a> has a way to check if domain exist Quite not what I was looking for But still it was best anwser Google gave me - everything else is just a bunch of unanwsered questions Any of you have succeeded to get some method up and running? I would very much appreciate some tips or should I just do it the opensource-way sit down and code something by myself? :)
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 `whois` in your program (which would be re-inventing the wheel) running `whois` on the OS and parsing the output (ie what you are doing now) seems like the right way to do it
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">execfile</a>: - `script_1 py` calls `script_2 py` - In turn `script_2 py` calls `script_3 py` How can I get the file name and path of <strong>`script_3 py`</strong> <them>from code within `script_3 py`</them> without having to pass that information as arguments from `script_2 py`? (Executing `os getcwd()` returns the original starting script's filepath not the current file's )
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 more details As @Tim and @Pat Notz have pointed out the __file__ attribute provides access to <blockquote> the file from which the module was loaded if it was loaded from a file </blockquote>
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 and some of your session data being lost If you are a really really high traffic website and code carefully so you can cope with losing a session then use memcache If you are not using a database use the file system cache but the default database backend is the best safest and simplest option in almost all cases
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">wearkref module docs</a> for more details You can also use `weakref proxy` to create an object that proxies o Will throw `ReferenceError` if used when the referent is no longer referenced
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 best way to do this?
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">http://bugs python org/issue3250</a>
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 progress indicator showing the percentage of the download progress Here is what I came up with: ``` sys stdout write(rem_file " ") urllib urlretrieve(rem_file loc_file reporthook=dlProgress) def dlProgress(count blockSize totalSize): percent = int(count*blockSize*100/totalSize) sys stdout write("%2d%%" % percent) sys stdout write("\b\b\b") sys stdout flush() ``` Output: MyFileName 9% Any other ideas or recommendations to do this? One thing that is somewhat annoying is the blinking cursor in the terminal on the first digit of the percentage Is there a way to prevent this? Is there a way to hide the cursor? <strong>EDIT:</strong> Here a better alternative using a global variable for the filename in dlProgress and the '\r' code: ``` global rem_file # global variable to be used in dlProgress urllib urlretrieve(rem_file loc_file reporthook=dlProgress) def dlProgress(count blockSize totalSize): percent = int(count*blockSize*100/totalSize) sys stdout write("\r" rem_file " %d%%" % percent) sys stdout flush() ``` Output: MyFileName 9% And the cursor shows up at the END of the line Much better
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 characters `| \ - /` which actually looks nice under blinking cursor
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 positional rather than named variable arguments ````def methodA(arg **kwargs): methodB("argvalue" kwargs) ```` How do I make sure that the **kwargs in methodA gets passed as **kwargs to methodB?
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 require tons of speed has been more of a boon than a bane in writing projects However coming from this land of brackets and parentheses and structs as far as the naked eye can see I come across a small problem: I find Python difficult to read For example the following block of text is hard for me to decipher unless I stare at it (which I dislike doing): ````if foo: bar = baz while bar not biz: bar = i_am_going_to_find_you_biz_i_swear_on_my_life() did_i_not_warn_you_biz() my_father_is_avenged() ```` The problem occurs at the end of that if block: all the tabbing and then suddenly returning to a jarring block feels almost disturbing As a solution I have started coding my Python like this: ````if foo: bar = baz while bar not biz: bar = i_am_going_to_find_you_biz_i_swear_on_my_life() #-- while -- #-- if -- did_i_not_warn_you_biz() my_father_is_avenged() ```` And this for some odd reason makes me more able to read my own code But I am curious: has anyone else with my strange problem found easier ways to make their tabbed-out code more readable? I would love to find out if there is a better way to do this before this becomes a huge habit for me
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 the docs might not be up to date) Otherwise you can use the <a href="http://sourceforge net/projects/pywin32/" rel="nofollow">pywin32</a> library to directly call the <a href="http://msdn microsoft com/en-us/library/aa364937(VS 85) aspx" rel="nofollow">GetDiskFreeSpaceEx</a> function
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(c) average(d) FROM tuples; ```` Is this normal behaviour when using a SQL database? The schema (the table holds responses to a survey): ````CREATE TABLE tuples (id integer primary key a integer b integer c integer d integer); \copy tuples from '350 000 responses csv' delimiter as ' ' ```` I wrote some tests in Java and Python for context and they crush SQL (except for pure python): ````java 1 5 threads ~ 7 ms java 1 5 ~ 10 ms python 2 5 numpy ~ 18 ms python 2 5 ~ 370 ms ```` Even sqlite3 is competitive with Postgres despite it assumping all columns are strings (for contrast: even using just switching to numeric columns instead of integers in Postgres results in 10x slowdown) Tunings i have tried without success include (blindly following some web advice): ````increased the shared memory available to Postgres to 256MB increased the working memory to 2MB disabled connection and statement logging used a stored procedure via CREATE FUNCTION LANGUAGE SQL ```` So my question is is my experience here normal and this is what I can expect when using a SQL database? I can understand that ACID must come with costs but this is kind of crazy in my opinion I am not asking for realtime game speed but since Java can process millions of doubles in under 20 ms I feel a bit jealous Is there a better way to do simple OLAP on the cheap (both in terms of money and server complexity)? I have looked into Mondrian and Pig Hadoop but not super excited about maintaining yet another server application and not sure if they would even help <hr> No the Python code and Java code do all the work in house so to speak I just generate 4 arrays with 350 000 random values each then take the average I do not include the generation in the timings only the averaging step The java threads timing uses 4 threads (one per array average) overkill but it is definitely the fastest The sqlite3 timing is driven by the Python program and is running from disk (not :memory:) I realize Postgres is doing much more behind the scenes but most of that work does not matter to me since this is read only data The Postgres query does not change timing on subsequent runs I have rerun the Python tests to include spooling it off the disk The timing slows down considerably to nearly 4 secs But I am guessing that Python's file handling code is pretty much in C (though maybe not the csv lib?) so this indicates to me that Postgres is not streaming from the disk either (or that you are correct and I should bow down before whoever wrote their storage layer!)
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 loading it off disk) If this performance level is a problem for your application in practice but you need a RDBMS for other reasons then you could look at <a href="http://www danga com/memcached/" rel="nofollow">memcached</a> You would then have faster cached access to raw data and could do the calculations in code
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 Authkit to work easily with Pylons? I tried downloading the <a href="http://pypi python org/pypi/SimpleSiteTemplate/">SimpleSiteTemplate</a> from the cheeseshop but was not able to run the setup-app command It throws up an error: ```` File "/home/cnu/env/lib/python2 5/site-packages/SQLAlchemy-0 4 7-py2 5 egg/sqlalchemy/schema py" line 96 in __call__ table = metadata tables[key] AttributeError: 'module' object has no attribute 'tables' ```` I use Pylons 0 9 7rc1 SQLAlchemy 0 4 7 Authkit 0 4
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 tools if you want to use HTTP authentication There is also OpenID which is very easy to setup The python-openid libs have an excellent example that is easy to translate to WSGI for wrapping a Pylons app You can look at an example: <a href="http://ionrock org/hg/brightcontent-main/file/d87b7dcc606c/brightcontent/plugins/openidauth py" rel="nofollow">http://ionrock org/hg/brightcontent-main/file/d87b7dcc606c/brightcontent/plugins/openidauth py</a>
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 do "import directoryname" to import everything in the directory or "import directoryname some_file_in_directory" to import a specific file that is in the directory <blockquote> The __init__ py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name such as "string" from unintentionally hiding valid modules that occur later on the module search path In the simplest case __init__ py can just be an empty file but it can also execute initialization code for the package or set the __all__ variable described later </blockquote>
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 situation?
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 you need to do is alter `module_importer py` per platform
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_distribution" rel="nofollow">Weibull</a> distribution as it "sort of" matches the distribution I have observed (ramps up quickly drops off quickly but not instantly) I use this distribution to generate the number of requests that should be sent each day between a given start and end date I have hacked together an algorithm in Python that sort of works but it feels kludgy: ````how_many_days = (end_date - start_date) days freqs = defaultdict(int) for x in xrange(how_many_responses): freqs[int(how_many_days * weibullvariate(0 5 2))] = 1 timeline = [] day = start_date for i freq in sorted(freqs iteritems()): timeline append((day freq)) day = timedelta(days=1) return timeline ```` What better ways are there to do this?
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 only</a> I think you would have to do a lot of messing about to get your server and client to talk nicely to each other jQuery seems to be the most popular JavaScript library option in the <a href="http://www djangosnippets org/tags/ajax/?page=1" rel="nofollow">AJAX Tag at DjangoSnippets com</a> <strong>Edit:</strong> The above is only true of Google App Engine applications written in Python As Google App Engine now supports Java GWT could now be a good choice for writing an AJAX front end <a href="http://code google com/webtoolkit/doc/latest/tutorial/appengine html" rel="nofollow">Google even have a tutorial showing you how to do it </a>
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 to the concept of type: if `x` is an instance of an old-style class then `x __class__` designates the class of `x` but `type(x)` is always `<type 'instance'&gt;` This reflects the fact that all old-style instances independently of their class are implemented with a single built-in type called instance <strong>New-style classes were introduced in Python 2 2 to unify the concepts of class and type</strong> A new-style class is simply a user-defined type no more no less If x is an instance of a new-style class then `type(x)` is typically the same as `x __class__` (although this is not guaranteed – a new-style class instance is permitted to override the value returned for `x __class__`) <strong>The major motivation for introducing new-style classes is to provide a unified object model with a full meta-model</strong> It also has a number of immediate benefits like the ability to subclass most built-in types or the introduction of "descriptors" which enable computed properties <strong>For compatibility reasons classes are still old-style by default</strong> New-style classes are created by specifying another new-style class (i e a type) as a parent class or the "top-level type" object if no other parent is needed The behaviour of new-style classes differs from that of old-style classes in a number of important details in addition to what type returns Some of these changes are fundamental to the new object model like the way special methods are invoked Others are "fixes" that could not be implemented before for compatibility concerns like the method resolution order in case of multiple inheritance <strong>Python 3 only has new-style classes</strong> No matter if you subclass from `object` or not classes are new-style in Python 3 It is however recommended that you still subclass from `object` </blockquote>
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 value and retrieving them in ascending order by key? For example you had this: ````d = {'b' : 'this is b' 'a': 'this is a' 'c' : 'this is c'} ```` I want to print the associated values in the following sequence sorted by key: ````this is a this is b this is c ````
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 follows the format ````<input type="hidden" name="fooId" value="**[id is here]**" /&gt; ```` Can someone provide an example in Python to parse the HTML for the value?
````/<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 SubElement(root 'head') script = ET SubElement(head 'script') script set('type' 'text/javascript') script text = "var a = 'I love &amp;aacute; letters'" body = ET SubElement(root 'body') h1 = ET SubElement(body 'h1') h1 text = "And I like the fact that 3 &gt; 1" tree = ET ElementTree(root) tree write('foo xhtml') # more foo xhtml <html&gt;<head&gt;<script type="text/javascript"&gt;var a = 'I love &amp;amp;aacute; letters'</script&gt;</head&gt;<body&gt;<h1&gt;And I like the fact that 3 &amp;gt; 1</h1&gt; </body&gt;</html&gt; ````
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 to do <them>just that</them>: <a href="http://pypi python org/pypi/magictree" rel="nofollow">magictree</a> You can use it like this: ````from magictree import html head script body h1 p root = html( head( script('''var a = 'I love &amp;amp;aacute; letters''' type='text/javascript')) body( h1('And I like the fact that 3 &gt; 1'))) # root is a plain Element object like those created with ET Element # so you can write it out using ElementTree :) tree = ET ElementTree(root) tree write('foo xhtml') ```` The magic in `magictree` lies in how the importing works: The `Element` factories are created when needed Have a <a href="http://code google com/p/pymagictree/source/browse/trunk/magictree py" rel="nofollow">look at the source</a> it is <a href="http://stackoverflow com/questions/2447353/getattr-on-a-module">based on an answer to another StackOverflow question</a>
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 actuality good old floating point weirdness creeps in and you get: ````5 5999999999999996 ```` For the purposes of UI I need to display `5 6` I poked around the Internet and found some <a href="http://mail python org/pipermail/python-list/2005-September/340383 html">documentation</a> that this is dependent on my implementation of Python Unfortunately this occurs on both my Windows dev machine and each Linux server I have tried <a href="http://www python org/doc/2 5 1/tut/node16 html">See here also</a> Short of creating my own round library is there any way around this?
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 "ǎ" with a tone mark In binary this is represented as the 16 bit 01ce I want to convert the html entity into the value `you'\u01ce'`
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: ````import copy re from BeautifulSoup import BeautifulSoup hexentityMassage = copy copy(BeautifulSoup MARKUP_MASSAGE) # replace hexadecimal character reference by decimal one hexentityMassage = [(re compile('&amp;#x([^;]+);') lambda m: '&amp;#%d;' % int(m group(1) 16))] def convert(html): return BeautifulSoup(html convertEntities=BeautifulSoup HTML_ENTITIES markupMassage=hexentityMassage) contents[0] string html = '<html&gt;&amp;#x01ce;&amp;#462;</html&gt;' print repr(convert(html)) # you'\u01ce\u01ce' ```` <strong>EDIT</strong>: <a href="http://effbot org/zone/re-sub htm#unescape-html" rel="nofollow">`unescape()`</a> function mentioned by <a href="http://stackoverflow com/questions/57708/convert-xml-html-entities-into-unicode-string-in-python/58125#58125">@dF</a> which uses `htmlentitydefs` standard module and `unichr()` might be more appropriate in this case
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 do I go to find if a given Python library call may throw exception(s) and what those are?
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 # invalid expression sre_constants error: unbalanced parenthesis ```` <a href="http://docs python org/lib/node46 html#l2h-408">The documentation</a> does support this in a roundabout way - check the bottom of the "Module Contents" page for (brief) description of the `error` exception Unfortunately I do not have any answer to the general question I suppose the documentation for the various modules varies in quality and thoroughness If there were particular modules you were interested in you might be able to <a href="http://www depython net/">decompile</a> them (if written in Python) or even <a href="http://www python org/download/">look at the source</a> if they are in the standard library
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 Can I just use doxygen? Anything particular to be aware of? I have done some coding in Python but so far only on small projects where I was to lazy to document at all (yeah I know but let us just pretend that is OK for now)
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 details """ def func(): """Documentation for a function More details """ pass ```` In which case the comments will be extracted by doxygen but you will not be able to use any of the <a href="http://www stack nl/~dimitri/doxygen/commands html#cmd_intro">special doxygen commands</a> <strong>Or</strong> you can (similar to C-style languages under doxygen) double up the comment marker (`#`) on the first line before the member: ````## @package pyexample # Documentation for this module # # More details ## Documentation for a function # # More details def func(): pass ```` In that case you can use the special doxygen commands There is no particular Python output mode but you can apparently improve the results by setting `OPTMIZE_OUTPUT_JAVA` to `YES` Honestly I am a little surprised at the difference - it seems like once doxygen can detect the comments in ## blocks or """ blocks most of the work would be done and you would be able to use the special commands in either case Maybe they expect people using """ to adhere to more Pythonic documentation practices and that would interfere with the special doxygen commands?
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!" # and replace the label's text end end ```` This made me think - how would I design a similarly nice-to-use GUI framework in Python? One that does not have the usual tyings of basically being wrappers to a C* library (In the case of GTK Tk wx QT etc etc) Shoes takes things from web devlopment (like `#f0c2f0` style colour notation CSS layout techniques like `:margin =&gt; 10`) and from ruby (extensively using blocks in sensible ways) Python's lack of "rubyish blocks" makes a (metaphorically)-direct port impossible: ````def Shoeless(Shoes app): self t = para("Not clicked!") def on_click_func(self): alert("You clicked the button!") self t replace("clicked!") b = button("The label" click=self on_click_func) ```` No where near as clean and would not be <them>nearly</them> as flexible and I am not even sure if it would be implementable Using decorators seems like an interesting way to map blocks of code to a specific action: ````class BaseControl: def __init__(self): self func = None def clicked(self func): self func = func def __call__(self): if self func is not None: self func() class Button(BaseControl): pass class Label(BaseControl): pass # The actual applications code (that the end-user would write) class MyApp: ok = Button() la = Label() @ok clicked def clickeryHappened(): print "OK Clicked!" if __name__ == '__main__': a = MyApp() a ok() # trigger the clicked action ```` Basically the decorator function stores the function then when the action occurred (say a click) the appropriate function would be executed The scope of various stuff (say the `la` label in the above example) could be rather complicated but it seems doable in a fairly neat manner
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 the ideas without melting your brain The source code from an ORM like SQLObject might help too since it uses this same kind of declarative syntax
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 to see if the average of the random data matches pollsters numbers (Most companies poll numbers are three day averages) Currently it works well for one iteration but my goal is to have it produce the most common simulation that matches the average polling data I could then change the code of anywhere from 1 to 1000 iterations And this is my problem At the end of the test I have an array in a single variable that looks something like this: ````[40 1 39 4 56 7 60 0 20 0 19 0] ```` The program currently produces one array for each correct simulation <them>I can store each array in a single variable but I then have to have a program that could generate 1 to 1000 variables depending on how many iterations I requested!?</them> How do I avoid this? I know there is an intelligent way of doing this that does not require the program to generate variables to store arrays depending on how many simulations I want Code testing for McCain: ```` test = [] while x < 5: test = round(100*random random()) mctest append(test) x = x 1 mctestavg = (mctest[0] mctest[1] mctest[2])/3 #mcavg is real data if mctestavg == mcavg[2]: mcwork = mctest ```` How do I repeat without creating multiple mcwork vars?
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' ````