instruction
stringlengths
12
148
input
stringlengths
16
30.2k
output
stringlengths
11
27.3k
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'm the kind of person who quickly jumps to the next version (which I'll do when Python 3 comes out) but many people may be more conservative if their current versi...
As python is in kind of an transition phase towards python 3 with breaking backward compatibility I don't think it is a good idea to go python 3 only. Based on the time line there will be at least one or two following releases of the 2.x series after 2.6/3.0 in october. Beside not having python 3 available on your targ...
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 getti...
There shouldn't be any need to use FastCGI. There exists a ISAPI extension for WSGI.
Is there a way to attach a debugger to a multi-threaded Python process?
I'm 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'm attempting this on Linux, but it would be great if there were a cross-platform solution. It's Python after all :)
Use Winpdb. It is a platform independent graphical GPL Python debugger with support for remote debugging over a network, multiple threads, namespace modification, embedded debugging, encrypted communication and is up to 20 times faster than pdb. Features: GPL license. Winpdb is Free Software. Compatible with CPython 2...
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)]
John's answer is good (that list comprehensions are better when you want to iterate over something multiple times). However, it's also worth noting that you should use a list if you want to use any of the list methods. For example, the following code won't work: def gen(): return (something for something in get_s...
What are the advantages of packaging your python library/application as an .egg file?
I've read some about .egg files and I've noticed them in my lib directory but what are the advantages/disadvantages of using then as a developer?
From the Python Enterprise Application Kit community: "Eggs are to Pythons as Jars are to Java..." 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 f...
Glade or no glade: What is the best way to use PyGtk?
I've 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'm just ...
I would say that it depends: if you find that using Glade you can build the apps you want or need to make than that's absolutely fine. If however you actually want to learn how GTK works or you have some non-standard UI requirements you will have to dig into GTK internals (which are not that complicated). Personally I'...
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 BowlSK. However, as it has grown, and features have been added, it has gotten really difficult t...
First, I would suggest you have a look at "Rapid Development with Python, Django, and Google App Engine" GvR describes a general/standard project layout on page 10 of his slide presentation. Here I'll post a slightly modified version of the layout/structure from that page. I pretty much follow this pattern myself. Yo...
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'm looking for a .lib file that I can use that has an Apache like distribution license.
I would like to call python script files from my c++ program. This means that you want to embed Python in your C++ application. As mentioned in Embedding Python in Another Application: Embedding Python is similar to extending it, but not quite. The difference is that when you extend Python, the main program of...
How do I turn a python program into an .egg file?
How do I turn a python program into an .egg file?
Setuptools is the software that creates .egg files. It's an extension of the distutils package in the standard library. The process involves creating a setup.py file, then python setup.py bdist_egg creates an .egg package.
Java -> Python?
Besides the dynamic nature of Python (and the syntax), what are some of the major features of the Python language that Java doesn't have, and vice versa?
List comprehensions. I often find myself filtering/mapping lists, and being able to say [line.replace("spam","eggs") for line in open("somefile.txt") if line.startswith("nee")] is really nice. Functions are first class objects. They can be passed as parameters to other functions, defined inside other function, and h...
Open source alternative to MATLAB's fmincon function?
Is there an open-source alternative to MATLAB's fmincon function for constrained linear optimization? I'm rewriting a MATLAB program to use Python / NumPy / SciPy and this is the only function I haven't found an equivalent to. A NumPy-based solution would be ideal, but any language will do.
Is your problem convex? Linear? Non-linear? I agree that SciPy.optimize will probably do the job, but fmincon is a sort of bazooka for solving optimization problems, and you'll be better off if you can confine it to one of the categories below (in increasing level of difficulty to solve efficiently) Linear Program (L...
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's say I have three files. Using execfile: 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 script_3.py, f...
__file__ as others have said. You may want to use: os.path.realpath(__file__)
Django Sessions
I'm 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're 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...
How to write a download progress indicator in Python?
I am writing a little application to download files over http (as, for example, described here). 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...
There's a text progress bar library for python at http://pypi.python.org/pypi/progressbar/2.2 that you might find useful: This library provides a text mode progressbar. This is tipically used to display the progress of a long running operation, providing a visual clue that processing is underway. The ProgressBar cla...
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?
Here's a simplified version of @Vinko Vrsalovic's answer: import urllib2 from BeautifulSoup import BeautifulSoup soup = BeautifulSoup(urllib2.urlopen("https://www.google.com")) print soup.title.string NOTE: soup.title finds the first title element anywhere in the html document title.string assumes it has only one ch...
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. ...
Put the asterisks before the kwargs variable. This makes Python pass the variable (which is assumed to be a dictionary) as keyword arguments. methodB("argvalue", **kwargs)
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"
>>> import os >>> os.path.abspath("mydir/myfile.txt")
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), avg(a), avg(b), avg(c), avg(d) FROM tuples; Is this normal behaviour when using a SQL database? The schema (the table holds ...
I would say your test scheme is not really useful. To fulfill the db query, the db server goes through several steps: parse the SQL work up a query plan, i. e. decide on which indices to use (if any), optimize etc. if an index is used, search it for the pointers to the actual data, then go to the appropriate location ...
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'm currently parsing the output of the various system calls (df, dir) to accomplish this - is there a better way?
import ctypes import os import platform import sys def get_free_space_mb(dirname): """Return folder/drive free space (in megabytes).""" if platform.system() == 'Windows': free_bytes = ctypes.c_ulonglong(0) ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(dirname), None, None, ctypes....
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' + 'd' and have it like this: e = 'a' + 'b' + 'c' + 'd'
What is the line? You can just have arguments on the next line without any problems: a = dostuff(blahblah1, blahblah2, blahblah3, blahblah4, blahblah5, blahblah6, blahblah7) Otherwise you can do something like this: if a == True and \ b == False Check the style guide for more information. From your e...
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's bound to?
def isbound(method): return method.im_self is not None def instance(bounded_method): return bounded_method.im_self User-defined methods: When a user-defined method object is created by retrieving a user-defined function object from a class, its im_self attribute is None and the method object is said ...
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 do 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 modu...
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 subset of Java it works best when you Java at the backend too. Since Google App Engine is currently Python only I think you'd 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 AJA...
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 http://docs.python.org/2/reference/datamodel.html#new-style-and-classic-classes : 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 ...
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...
Do you mean that you need the values sorted by the value of the key? In that case, this should do it: for key in sorted(d): print d[key] EDIT: changed to use sorted(d) instead of sorted(d.keys()), thanks Eli!
XML writing tools for Python
I'm currently trying ElementTree and it looks fine, it escapes HTML entities and so on and so forth. Am I missing something truly wonderful I haven't heard of? This is similar to what I'm actually doing: import xml.etree.ElementTree as ET root = ET.Element('html') head = ET.SubElement(root,'head') script = ET.SubElemen...
Another way is using the E Factory builder from lxml (available in Elementtree too) >>> from lxml import etree >>> from lxml.builder import E >>> def CLASS(*args): # class is a reserved word in Python ... return {"class":' '.join(args)} >>> html = page = ( ... E.html( # create an Element called "html" .....
Anyone used Dabo for a medium-big project?
We're at the beginning of a new ERP-ish client-server application, developed as a Python rich client. We're currently evaluating Dabo as our main framework and it looks quite nice and easy to use, but I was wondering, has anyone used it for medium-to-big sized projects? Thanks for your time!
I'm one of the authors of the Dabo framework. One of our users pointed out to me the extremely negative answer you received, and so I thought I had better chime in and clear up some of the incorrect assumptions in the first reply. Dabo is indeed well-known in the Python community. I have presented it at 3 of the last 4...
round() in Python doesn't seem to be rounding properly
The documentation for the round() function states that you pass it a number, and the positions past the decimal to round. Thus it should 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 p...
Formatting works correctly even without having to round: "%.1f" % n
Convert XML/HTML Entities into Unicode String in Python
I'm 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: ǎ which represents an "ǎ" with a tone mark. In binary, this is represented as the 16 bit ...
Python has the htmlentitydefs module, but this doesn't include a function to unescape HTML entities. Python developer Fredrik Lundh (author of elementtree, among other things) has such a function on his website, which works with decimal, hex and named entities: import re, htmlentitydefs ## # Removes HTML or XML chara...
Does re.compile() or any given Python library call throw an exception?
I can't 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) a...
Well, re.compile certainly may: >>> import re >>> re.compile('he(lo') Traceback (most recent call last): File "<stdin>", line 1, in <module> 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 expre...
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 doesn't 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...
The doxypy input filter allows you to use pretty much all of Doxygen's formatting tags in a standard Python docstring format. I use it to document a large mixed C++ and Python game application framework, and it's working well.
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 ma...
You could actually pull this off, but it would require using metaclasses, which are deep magic (there be dragons). If you want an intro to metaclasses, there's a series of articles from IBM which manage to introduce the ideas without melting your brain. The source code from an ORM like SQLObject might help, too, since ...
How to retrieve an element from a set without removing it?
Suppose the following: >>>s = set([1, 2, 3]) How do I get a value (any value) out of s without doing s.pop()? I want to leave the item in the set until I am sure I can remove it - something I can only be sure of after an asynchronous call to another host. Quick and dirty: >>>elem = s.pop() >>>s.add(elem) But do you k...
Two options that don't require copying the whole set: for e in s: break # e is now an element from s Or... e = next(iter(s)) But in general, sets don't support indexing or slicing.
Replacements for switch statement in Python?
I want to write a function in Python that returns different fixed values based on the value of an input index. In other languages I would use a switch or case statement, but Python does not appear to have a switch statement. What are the recommended Python solutions in this scenario?
If you'd like defaults you could use the dictionary get(key[, default]) method: def f(x): return { 'a': 1, 'b': 2, }.get(x, 9) # 9 is default if x not found
cross platform IPC
I'm looking for suggestions on possible IPC mechanisms that are: cross platform (WIN32 and Linux at least) Simple to implement in C++ as well as the most common scripting languages (perl, ruby python etc). Finally, simple to use from a programming point of view! What are my options? I'm programming under Linux, but I...
In terms of speed, the best cross-platform IPC mechanism will be pipes. That assumes, however, that you want cross-platform IPC on the same machine. If you want to be able to talk to processes on remote machines, you'll want to look at using sockets instead. Luckily, if you're talking about TCP at least, sockets and...
How do I write a python HTTP server to listen on multiple ports?
I'm writing a small web server in Python, using BaseHTTPServer and a custom subclass of BaseHTTPServer.BaseHTTPRequestHandler. Is it possible to make this listen on more than one port? What I'm doing now: class MyRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): def doGET [...] class ThreadingHTTPServer(Threa...
Sure; just start two different servers on two different ports in two different threads that each use the same handler. Here's a complete, working example that I just wrote and tested. If you run this code then you'll be able to get a Hello World webpage at both http://localhost:1111/ and http://localhost:2222/ from t...
Getting random row through SQLAlchemy
How do I select a(or some) random row(s) from a table using SQLAlchemy?
This is very much a database-specific issue. I know that PostgreSQL and MySQL have the ability to order by a random function, so you can use this in SQLAlchemy: from sqlalchemy.sql.expression import func, select select.order_by(func.random()) # for PostgreSQL, SQLite select.order_by(func.rand()) # for MySQL select....
How do you retrieve items from a dictionary in the order that they're inserted?
Is it possible to retrieve items from a Python dictionary in the order that they were inserted?
The standard python dict isn't able to do this. There is a proposal (PEP 372) to add an "ordered dictionary" (that keeps track of the order of insertion) to the collections module in the standard library. It includes links to various implementations of ordered dictionaries (see also these two recipes in the Python Cook...
Where do the Python unit tests go?
If you're writing a library, or an app, where do the unit test files go? It's nice to separate the test files from the main app code, but it's awkward to put them into a "tests" subdirectory inside of the app root directory, because it makes it harder to import the modules that you'll be testing. Is there a best pr...
For a file module.py, the unit test should normally be called test_module.py, following Pythonic naming conventions. There are several commonly accepted places to put test_module.py: In the same directory as module.py. In ../tests/test_module.py (at the same level as the code directory). In tests/test_module.py (one l...
Python dictionary from an object's fields
Do you know if there is a built-in function to build a dictionary from an arbitrary object? I'd like to do something like this: >>> class Foo: ... bar = 'hello' ... baz = 'world' ... >>> f = Foo() >>> props(f) { 'bar' : 'hello', 'baz' : 'world' } NOTE: It should not include methods. Only fields. Thanks
Note that best practice in current versions of Python is to use new-style classes, i.e. class Foo(object): ... Also, there's a difference between an 'object' and a 'class'. To build a dictionary from an arbitrary object, it's sufficient to use __dict__. Usually, you'll declare your methods at class level and your attr...
Is it pythonic for a function to return multiple values?
In python, you can have a function return multiple values. Here's a contrived example: def divide(x, y): quotient = x/y remainder = x % y return quotient, remainder (q, r) = divide(22, 7) This seems very useful, but it looks like it can also be abused ("Well..function X already computes what we need as...
Absolutely (for the example you provided). Tuples are first class citizens in Python There is a builtin function divmod() that does exactly that. q, r = divmod(x, y) # ((x - x%y)/y, x%y) Invariant: div*y + mod == x There are other examples: zip, enumerate, dict.items. for i, e in enumerate([1, 3, 3]): print "inde...
When to create a new app (with startapp) in Django?
I've googled around for this, but I still have trouble relating to what Django defines as "apps". Should I create a new app for each piece of functionality in a site, even though it uses models from the main project? Do you guys have good rule of thumb of when to split off a new app, and when to keep functionality to...
James Bennett has a wonderful set of slides on how to organize reusable apps in Django.
Sending mail from Python using SMTP
I'm using the following method to send mail from Python using SMTP. Is it the right method to use or are there gotchas I'm missing ? from smtplib import SMTP import datetime debuglevel = 0 smtp = SMTP() smtp.set_debuglevel(debuglevel) smtp.connect('YOUR.MAIL.SERVER', 26) smtp.login('USERNAME@DOMAIN', 'PASSWORD') fro...
The script I use is quite similar; I post it here as an example of how to use the email.* modules to generate MIME messages; so this script can be easily modified to attach pictures, etc. I rely on my ISP to add the date time header. My ISP requires me to use a secure smtp connection to send mail, I rely on the ssmtpli...
How to setup VIM autoindentation properly for editing Python files - *.py
I've troubles setting VIM (7.1.xxx) for editing python files. Indenting seems to be broken (optimal 4 spaces). I've followed some tutorials I found via Google. Still no effect :/ Please help.
I use this on my macbook: " configure expanding of tabs for various file types au BufRead,BufNewFile *.py set expandtab au BufRead,BufNewFile *.c set noexpandtab au BufRead,BufNewFile *.h set noexpandtab au BufRead,BufNewFile Makefile* set noexpandtab " -----------------------------------------------------------------...
Caching compiled regex objects in Python?
Each time a python file is imported that contains a large quantity of static regular expressions, cpu cycles are spent compiling the strings into their representative state machines in memory. a = re.compile("a.*b") b = re.compile("c.*d") ... Question: Is it possible to store these regular expressions in a cache on di...
Is it possible to store these regular expressions in a cache on disk in a pre-compiled manner to avoid having to execute the regex compilations on each import? Not easily. You'd have to write a custom serializer that hooks into the C sre implementation of the Python regex engine. Any performance benefits would be vas...
Serving dynamically generated ZIP archives in Django
How to serve users a dynamically generated ZIP archive in Django? I'm making a site, where users can choose any combination of available books and download them as ZIP archive. I'm worried that generating such archives for each request would slow my server down to a crawl. I have also heard that Django doesn't currentl...
The solution is as follows. Use Python module zipfile to create zip archive, but as the file specify StringIO object (ZipFile constructor requires file-like object). Add files you want to compress. Then in your Django application return the content of StringIO object in HttpResponse with mimetype set to application/x-z...
How to import a module given the full path?
How can I load a Python module given its full path? Note that the file can be anywhere in the filesystem, as it is a configuration option.
For Python 3.5+ use: import importlib.util spec = importlib.util.spec_from_file_location("module.name", "/path/to/file.py") foo = importlib.util.module_from_spec(spec) spec.loader.exec_module(foo) foo.MyClass() For Python 3.3 and 3.4 use: from importlib.machinery import SourceFileLoader foo = SourceFileLoader("module...
Why do you need explicitly have the "self" argument into a Python method?
When defining a method on a class in Python, it looks something like this: class MyClass(object): def __init__(self, x, y): self.x = x self.y = y But in some other languages, such as C#, you have a reference to the object that the method is bound to with the "this" keyword without declaring it as a...
I like to quote Peters' Zen of Python. "Explicit is better than implicit." In Java and C++, 'this.' can be deduced, except when you have variable names that make it impossible to deduce. So you sometimes need it and sometimes don't. Python elects to make things like this explicit rather than based on a rule. Addit...
How to copy a file to a remote server in Python using SCP or SSH?
I have a text file on my local machine that is generated by a daily Python script run in cron. I would like to add a bit of code to have that file sent securely to my server over SSH.
To do this in Python (i.e. not wrapping scp through subprocess.Popen or similar) with the Paramiko library, you would do something like this: import os import paramiko ssh = paramiko.SSHClient() ssh.load_host_keys(os.path.expanduser(os.path.join("~", ".ssh", "known_hosts"))) ssh.connect(server, username=username, pas...
Send file using POST from a Python script
Is there a way to send a file using POST from a Python script?
From http://docs.python-requests.org/en/latest/user/quickstart/#post-a-multipart-encoded-file Requests makes it very simple to upload Multipart-encoded files: >>> r = requests.post('http://httpbin.org/post', files={'report.xls': open('report.xls', 'rb')}) That's it. I'm not joking - this is one line of code. File was ...
Are tuples more efficient than lists in Python?
Is there any performance difference between tuples and lists when it comes to instantiation and retrieval of elements?
In general, you might expect tuples to be slightly faster. However you should definitely test your specific case (if the difference might impact the performance of your program -- remember "premature optimization is the root of all evil"). Python makes this very easy: timeit is your friend. $ python -m timeit "x=(1,2,...
Static class variables in Python
Is it possible to have static class variables or methods in python? What syntax is required to do this?
Variables declared inside the class definition, but not inside a method are class or static variables: >>> class MyClass: ... i = 3 ... >>> MyClass.i 3 As @millerdev points out, this creates a class-level "i" variable, but this is distinct from any instance-level "i" variable, so you could have >>> m = MyClass() ...
Best way to open a socket in Python
I want to open a TCP client socket in Python. Do I have to go through all the low-level BSD create-socket-handle / connect-socket stuff or is there a simpler one-line way?
Opening sockets in python is pretty simple. You really just need something like this: import socket sock = socket.socket() sock.connect((address, port)) and then you can send() and recv() like any other socket
Take a screenshot via a python script. [Linux]
I want to take a screenshot via a python script and unobtrusively save it. I'm only interested in the Linux solution, and should support any X based environment.
This works without having to use scrot or ImageMagick. import gtk.gdk w = gtk.gdk.get_default_root_window() sz = w.get_size() print "The size of the window is %d x %d" % sz pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,False,8,sz[0],sz[1]) pb = pb.get_from_drawable(w,w.get_colormap(),0,0,0,0,sz[0],sz[1]) if (pb != None):...
Why are Python's 'private' methods not actually private?
Python gives us the ability to create 'private' methods and variables within a class by prepending double underscores to the name, like this: __myPrivateMethod(). How, then, can one explain this >>> class MyClass: ... def myPublicMethod(self): ... print 'public method' ... def __myPrivateMethod(self...
The name scrambling is used to ensure that subclasses don't accidentally override the private methods and attributes of their superclasses. It's not designed to prevent deliberate access from outside. For example: >>> class Foo(object): ... def __init__(self): ... self.__baz = 42 ... def foo(self): ... ...
Python: user input and commandline arguments
How do I have a Python script that can accept user input (assuming this is possible) and how do I make it read in arguments if run from the command line?
var = raw_input("Please enter something: ") print "you entered", var
How to do relative imports in Python?
Imagine this directory structure: app/ __init__.py sub1/ __init__.py mod1.py sub2/ __init__.py mod2.py I'm coding mod1, and I need to import something from mod2. How should I do it? I tried from ..sub2 import mod2 but I'm getting an "Attempted relative import in non-package". I googl...
Everyone seems to want to tell you what you should be doing rather than just answering the question. The problem is that you're running the module as '__main__' by passing the mod1.py as an argument to the interpreter. From PEP 328: Relative imports use a module's __name__ attribute to determine that module's position...
How do I sort a list of dictionaries by values of the dictionary in Python?
I got a list of dictionaries and want that to be sorted by a value of that dictionary. This [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}] sorted by name, should become [{'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}]
It may look cleaner using a key instead a cmp: newlist = sorted(list_to_be_sorted, key=lambda k: k['name']) or as J.F.Sebastian and others suggested, from operator import itemgetter newlist = sorted(list_to_be_sorted, key=itemgetter('name')) For completeness (as pointed out in comments by fitzgeraldsteele), add rev...
Terminating a Python script
I am aware of the die() command in PHP which stops a script early. How can I do this in Python?
import sys sys.exit() details from the sys module documentation: sys.exit([arg]) Exit from Python. This is implemented by raising the SystemExit exception, so cleanup actions specified by finally clauses of try statements are honored, and it is possible to intercept the exit attempt at an outer level. Th...
Sending mail via sendmail from python
If I want to send mail not via SMTP, but rather via sendmail, is there a library for python that encapsulates this process? Better yet, is there a good library that abstracts the whole 'sendmail -versus- smtp' choice? I'll be running this script on a bunch of unix hosts, only some of which are listening on localhost:25...
Header injection isn't a factor in how you send the mail, it's a factor in how you construct the mail. Check the email package, construct the mail with that, serialise it, and send it to /usr/sbin/sendmail using the subprocess module: from email.mime.text import MIMEText from subprocess import Popen, PIPE msg = MIMET...
How do I get the name of a python class as a string?
What method do I call to get the name of a class?
In [1]: class test(object): ...: pass ...: In [2]: test.__name__ Out[2]: 'test'
Django -vs- Grails -vs-?
I'm wondering if there's such a thing as Django-like ease of web app development combined with good deployment, debugging and other tools? Django is a very productive framework for building content-heavy sites; the best I've tried and a breath of fresh air compared to some of the Java monstrosities out there. However ...
You asked for someone who used both Grails and Django. I've done work on both for big projects. Here's my Thoughts: IDE's: Django works really well in Eclipse, Grails works really well in IntelliJ Idea. Debugging: Practically the same (assuming you use IntelliJ for Grails, and Eclipse for Python). Step debugging, inspe...
Which is faster, python webpages or php webpages?
Does anyone know how the speed of pylons(or any of the other frameworks) compares to a similar website made with php? I know that serving a python base webpage via cgi is slower than php because of its long start up every time. I enjoy using pylons and I would still use it if it was slower than php. But if pylons was ...
It sounds like you don't want to compare the two languages, but that you want to compare two web systems. This is tricky, because there are many variables involved. For example, Python web applications can take advantage of mod_wsgi to talk to web servers, which is faster than any of the typical ways that PHP talks to ...
'id' is a bad variable name in Python
Why is it bad to name a variable id in Python?
id() is a fundamental built-in: Help on built-in function id in module __builtin__: id(...) id(object) -> integer Return the identity of an object. This is guaranteed to be unique among simultaneously existing objects. (Hint: it's the object's memory address.) In general, using variable names t...
Is there a benefit to defining a class inside another class in Python?
What I'm talking about here are nested classes. Essentially, I have two classes that I'm modeling. A DownloadManager class and a DownloadThread class. The obvious OOP concept here is composition. However, composition doesn't necessarily mean nesting, right? I have code that looks something like this: class DownloadThre...
You might want to do this when the "inner" class is a one-off, which will never be used outside the definition of the outer class. For example to use a metaclass, it's sometimes handy to do class Foo(object): class __metaclass__(type): .... instead of defining a metaclass separately, if you're only using i...
Unittest causing sys.exit()
No matter what I do sys.exit() is called by unittest, even the most trivial examples. I can't tell if my install is messed up or what is going on. IDLE 1.2.2 ==== No Subprocess ==== >>> import unittest >>> >>> class Test(unittest.TestCase): def testA(self): a = 1 self.assertEqual(a,1) ...
In new Python 2.7 release, unittest.main() has a new argument. If 'exit' is set to False, sys.exit() is not called during the execution of unittest.main().
How do I convert local time to UTC in Python?
How do I convert a datetime string in local time to a string in UTC time? I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future. Clarification: For example, if I have 2008-09-17 14:02:00 in my local timezone (+10), I'd like to generate a string with the equivale...
First, parse the string into a naive datetime object. This is an instance of datetime.datetime with no attached timezone information. See documentation for datetime.strptime for information on parsing the date string. Use the pytz module, which comes with a full list of time zones + UTC. Figure out what the local timez...
How do you design data models for Bigtable/Datastore (GAE)?
Since the Google App Engine Datastore is based on Bigtable and we know that's not a relational database, how do you design a database schema/*data model* for applications that use this type of database system?
Designing a bigtable schema is an open process, and basically requires you to think about: The access patterns you will be using and how often each will be used The relationships between your types What indices you are going to need The write patterns you will be using (in order to effectively spread load) GAE's data...
Split a string by spaces -- preserving quoted substrings -- in Python
I have a string which is like this: this is "a test" I'm trying to write something in Python to split it up by space while ignoring spaces within quotes. The result I'm looking for is: ['this','is','a test'] PS. I know you are going to ask "what happens if there are quotes within the quotes, well, in my application, ...
You want split, from the shlex module. >>> import shlex >>> shlex.split('this is "a test"') ['this', 'is', 'a test'] This should do exactly what you want.
Asychronous Programming in Python Twisted
I'm having trouble developing a reverse proxy in Twisted. It works, but it seems overly complex and convoluted. So much of it feels like voodoo... Are there any simple, solid examples of asynchronous program structure on the web or in books? A sort of best practices guide? When I complete my program I'd like to be able...
Twisted contains a large number of examples. One in particular, the "evolution of Finger" tutorial, contains a thorough explanation of how an asynchronous program grows from a very small kernel up to a complex system with lots of moving parts. Another one that might be of interest to you is the tutorial about simply ...
Upload files in Google App Engine
I am planning to create a web app that allows users to downgrade their visual studio project files. However, It seems Google App Engine accepts files uploading and flat file storing on the Google Server through db.TextProperty and db.BlobProperty. I'll be glad anyone can provide code sample (both the client and the ser...
In fact, this question is answered in the App Egnine documentation. See an example on Uploading User Images. HTML code, inside <form></form>: <input type="file" name="img"/> Python code: class Guestbook(webapp.RequestHandler): def post(self): greeting = Greeting() if users.get_current_user(): greeting.a...
Is there any list of blog engines, written in Django?
Is there any list of blog engines, written in Django?
EDIT: Original link went dead so here's an updated link with extracts of the list sorted with the most recently updated source at the top. Eleven Django blog engines you should know by Monty Lounge Industries Biblion Django-article Flother Basic-Blog Hello-Newman Banjo djangotechblog Django-YABA Shifting Bits (this i...
How do I check whether a file exists using Python?
How do I check whether a file exists, without using the try statement?
You can also use os.path.isfile Return True if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path. import os.path os.path.isfile(fname) if you need to be sure it's a file. Starting with Python 3.4, the pathlib module offers an object-oriented a...
How to programmatically enable/disable network interfaces? (Windows XP)
I need to enable/disable completely network interfaces from a script in Windows XP. I'm looking for a python solution, but any general way (eg WMI, some command-line à la netsh, some windows call) is welcome and will be adjusted. Thanks.
Using the netsh interface Usage set interface [name = ] IfName [ [admin = ] ENABLED|DISABLED [connect = ] CONNECTED|DISCONNECTED [newname = ] NewName ] Try including everything inside the outer brackets: netsh interface set interface name="thename" admin=disabled connect=DISCONN...
Why isn't the 'len' function inherited by dictionaries and lists in Python
example: a_list = [1, 2, 3] a_list.len() # doesn't work len(a_list) # works Python being (very) object oriented, I don't understand why the 'len' function isn't inherited by the object. Plus I keep trying the wrong solution since it appears as the logical one to me
Guido's explanation is here: First of all, I chose len(x) over x.len() for HCI reasons (def __len__() came much later). There are two intertwined reasons actually, both HCI: (a) For some operations, prefix notation just reads better than postfix — prefix (and infix!) operations have a long tradition in mathematics w...
Python - time.clock() vs. time.time() - accuracy?
Which is better to use for timing in Python? time.clock() or time.time()? Which one provides more accuracy? for example: start = time.clock() ... do something elapsed = (time.clock() - start) vs. start = time.time() ... do something elapsed = (time.time() - start)
As of 3.3, time.clock() is deprecated, and it's suggested to use time.process_time() or time.perf_counter() instead. Previously in 2.7, according to the time module docs: time.clock() On Unix, return the current processor time as a floating point number expressed in seconds. The precision, and in fact the very defin...
How do you configure Django for simple development and deployment?
I tend to use SQLite when doing Django development, but on a live server something more robust is often needed (MySQL/PostgreSQL, for example). Invariably, there are other changes to make to the Django settings as well: different logging locations / intensities, media paths, etc. How do you manage all these changes to ...
Update: django-configurations has been released which is probably a better option for most people than doing it manually. If you would prefer to do things manually, my earlier answer still applies: I have multiple settings files. settings_local.py - host-specific configuration, such as database name, file paths, etc. ...
How do I unit test an __init__() method of a python class with assertRaises()?
I have a class: class MyClass: def __init__(self, foo): if foo != 1: raise Error("foo is not equal to 1!") and a unit test that is supposed to make sure the incorrect arg passed to the constructor properly raises an error: def testInsufficientArgs(self): foo = 0 self.assertRaises((Error), myClass =...
'Error' in this example could be any exception object. I think perhaps you have read a code example that used it as a metasyntatic placeholder to mean, "The Appropriate Exception Class". The baseclass of all exceptions is called 'Exception', and most of its subclasses are descriptive names of the type of error involved...
How do I split a string into a list?
If I have this string: 2+24*48/32 what is the most efficient approach for creating this list: ['2', '+', '24', '*', '48', '/', '32']
It just so happens that the tokens you want split are already Python tokens, so you can use the built-in tokenize module. It's almost a one-liner: from cStringIO import StringIO from tokenize import generate_tokens STRING = 1 list(token[STRING] for token in generate_tokens(StringIO('2+24*48/32').readline) i...
Calling an external command in Python
How can I call an external command (as if I'd typed it at the Unix shell or Windows command prompt) from within a Python script?
Look at the subprocess module in the stdlib: from subprocess import call call(["ls", "-l"]) The advantage of subprocess vs system is that it is more flexible (you can get the stdout, stderr, the "real" status code, better error handling, etc...). I think os.system is deprecated, too, or will be: https://docs.python.or...
How do I verify that a string only contains letters, numbers, underscores and dashes?
I know how to do this if I iterate through all of the characters in the string but I am looking for a more elegant method. Thanks
A regular expression will do the trick with very little code: import re ... if re.match("^[A-Za-z0-9_-]*$", my_little_string): # do something here
Is there a pretty printer for python data?
Working with python interactively, it's sometimes necessary to display a result which is some arbitrarily complex data structure (like lists with embedded lists, etc.) The default way to display them is just one massive linear dump which just wraps over and over and you have to parse carefully to read it. Is there some...
from pprint import pprint a = [0, 1, ['a', 'b', 'c'], 2, 3, 4] pprint(a) Note that for a short list like my example, pprint will in fact print it all on one line. However, for more complex structures it does a pretty good job of pretty printing data.
Python, beyond the basics
I've gotten to grips with the basics of Python and I've got a small holiday which I want to use some of to learn a little more Python. The problem is that I have no idea what to learn or where to start. I'm primarily web development but in this case I don't know how much difference it will make.
Well, there are great ressources for advanced Python programming : Dive Into Python (read it for free) Online python cookbooks (e.g. here and there) O'Reilly's Python Cookbook (see amazon) A funny riddle game : Python Challenge Here is a list of subjects you must master if you want to write "Python" on your resume :...
Stripping non printable characters from a string in python
I use to run $s =~ s/[^[:print:]]//g; on Perl to get rid of non printable characters. In Python there's no POSIX regex classes, and I can't write [:print:] having it mean what I want. I know of no way in Python to detect if a character is printable or not. What would you do? EDIT: It has to support Unicode characte...
Iterating over strings is unfortunately rather slow in Python. Regular expressions are over an order of magnitude faster for this kind of thing. You just have to build the character class yourself. The unicodedata module is quite helpful for this, especially the unicodedata.category() function. See Unicode Character Da...
time.sleep -- sleeps thread or process?
In Python for the *nix, does time.sleep() block the thread or the process?
It blocks the thread. If you look in Modules/timemodule.c in the Python source, you'll see that in the call to floatsleep(), the substantive part of the sleep operation is wrapped in a Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS block, allowing other threads to continue to execute while the current one sleeps. Yo...
What's the easiest non-memory intensive way to output XML from Python?
Basically, something similar to System.Xml.XmlWriter - A streaming XML Writer that doesn't incur much of a memory overhead. So that rules out xml.dom and xml.dom.minidom. Suggestions?
I think you'll find XMLGenerator from xml.sax.saxutils is the closest thing to what you want. import time from xml.sax.saxutils import XMLGenerator from xml.sax.xmlreader import AttributesNSImpl LOG_LEVELS = ['DEBUG', 'WARNING', 'ERROR'] class xml_logger: def __init__(self, output, encoding): """ ...
How do I persist to disk a temporary file using Python?
I am attempting to use the 'tempfile' module for manipulating and creating text files. Once the file is ready I want to save it to disk. I thought it would be as simple as using 'shutil.copy'. However, I get a 'permission denied' IOError: >>> import tempfile, shutil >>> f = tempfile.TemporaryFile(mode ='w+t') >>> f.wri...
hop is right, and dF. is incorrect on why the error occurs. Since you haven't called f.close() yet, the file is not removed. The doc for NamedTemporaryFile says: Whether the name can be used to open the file a second time, while the named temporary file is still open, varies across platforms (it can be so used on Un...
What is the difference between range and xrange functions in Python 2.X?
Apparently xrange is faster but I have no idea why it's faster (and no proof besides the anecdotal so far that it is faster) or what besides that is different about for i in range(0, 20): for i in xrange(0, 20):
range creates a list, so if you do range(1, 10000000) it creates a list in memory with 9999999 elements. xrange is a sequence object that evaluates lazily.
How do I use Django templates without the rest of Django?
I want to use the Django template engine in my (Python) code, but I'm not building a Django-based web site. How do I use it without having a settings.py file (and others) and having to set the DJANGO_SETTINGS_MODULE environment variable? If I run the following code: >>> import django.template >>> from django.template ...
The solution is simple. It's actually well documented, but not too easy to find. (I had to dig around -- it didn't come up when I tried a few different Google searches.) The following code works: >>> from django.template import Template, Context >>> from django.conf import settings >>> settings.configure() >>> t = Temp...
What is the best solution for database connection pooling in python?
I have developed some custom DAO-like classes to meet some very specialized requirements for my project that is a server-side process that does not run inside any kind of framework. The solution works great except that every time a new request is made, I open a new connection via MySQLdb.connect. What is the best "...
In MySQL? I'd say don't bother with the connection pooling. They're often a source of trouble and with MySQL they're not going to bring you the performance advantage you're hoping for. This road may be a lot of effort to follow--politically--because there's so much best practices hand waving and textbook verbiage in ...
What is a metaclass in Python?
What are metaclasses? What do you use them for?
Classes as objects Before understanding metaclasses, you need to master classes in Python. And Python has a very peculiar idea of what classes are, borrowed from the Smalltalk language. In most languages, classes are just pieces of code that describe how to produce an object. That's kinda true in Python too: >>> class ...
What is the standard way to add N seconds to datetime.time in Python?
Given a datetime.time value in Python, is there a standard way to add an integer number of seconds to it, so that 11:34:59 + 3 = 11:35:02, for example? These obvious ideas don't work: >>> datetime.time(11, 34, 59) + 3 TypeError: unsupported operand type(s) for +: 'datetime.time' and 'int' >>> datetime.time(11, 34, 59) ...
You can use full datetime variables with timedelta, and by providing a dummy date then using time to just get the time value. For example: import datetime a = datetime.datetime(100,1,1,11,34,59) b = a + datetime.timedelta(0,3) # days, seconds, then other fields. print a.time() print b.time() results in the two values,...
How can I analyze Python code to identify problematic areas?
I have a large source repository split across multiple projects. I would like to produce a report about the health of the source code, identifying problem areas that need to be addressed. Specifically, I'd like to call out routines with a high cyclomatic complexity, identify repetition, and perhaps run some lint-like s...
For measuring cyclomatic complexity, there's a nice tool available at traceback.org. The page also gives a good overview of how to interpret the results. +1 for pylint. It is great at verifying adherence to coding standards (be it PEP8 or your own organization's variant), which can in the end help to reduce cyclomati...
Python on Windows - how to wait for multiple child processes?
How to wait for multiple child processes in Python on Windows, without active wait (polling)? Something like this almost works for me: proc1 = subprocess.Popen(['python','mytest.py']) proc2 = subprocess.Popen(['python','mytest.py']) proc1.wait() print "1 finished" proc2.wait() print "2 finished" The problem is tha...
It might seem overkill, but, here it goes: import Queue, thread, subprocess results= Queue.Queue() def process_waiter(popen, description, que): try: popen.wait() finally: que.put( (description, popen.returncode) ) process_count= 0 proc1= subprocess.Popen( ['python', 'mytest.py'] ) thread.start_new_thread(proc...
Why is "if not someobj:" better than "if someobj == None:" in Python?
I've seen several examples of code like this: if not someobj: #do something But I'm wondering why not doing: if someobj == None: #do something Is there any difference? Does one have an advantage over the other?
In the first test, Python try to convert the object to a bool value if it is not already one. Roughly, we are asking the object : are you meaningful or not ? This is done using the following algorithm : If the object has a __nonzero__ special method (as do numeric built-ins, int and float), it calls this method. It mu...
How do I read text from the (windows) clipboard from python?
How do I read text from the (windows) clipboard from python?
You can use the module called win32clipboard, which is part of pywin32. Here is an example that first sets the clipboard data then gets it: import win32clipboard # set clipboard data win32clipboard.OpenClipboard() win32clipboard.EmptyClipboard() win32clipboard.SetClipboardText('testing 123') win32clipboard.CloseClipbo...
Is there a zip-like method in .Net?
In Python there is a really neat function called zip which can be used to iterate through two lists at the same time: list1 = [1, 2, 3] list2 = ["a", "b", "c"] for v1, v2 in zip(list1, list2): print v1 + " " + v2 The above code shoul produce the following: 1 a 2 b 3 c I wonder if there is a method like it availabl...
Update: It is built-in in C# 4 as System.Linq.Enumerable.Zip Method Here is a C# 3 version: IEnumerable<TResult> Zip<TResult,T1,T2> (IEnumerable<T1> a, IEnumerable<T2> b, Func<T1,T2,TResult> combine) { using (var f = a.GetEnumerator()) using (var s = b.GetEnumerator()) { while (f.MoveN...
How do you access an authenticated Google App Engine service from a (non-web) python client?
I have a Google App Engine app - http://mylovelyapp.appspot.com/ It has a page - mylovelypage For the moment, the page just does self.response.out.write('OK') If I run the following Python at my computer: import urllib2 f = urllib2.urlopen("http://mylovelyapp.appspot.com/mylovelypage") s = f.read() print s f.close() i...
appcfg.py, the tool that uploads data to App Engine has to do exactly this to authenticate itself with the App Engine server. The relevant functionality is abstracted into appengine_rpc.py. In a nutshell, the solution is: Use the Google ClientLogin API to obtain an authentication token. appengine_rpc.py does this in _...
Is there a way to run Python on Android?
We are working on an S60 version and this platform has a nice Python API. However, there is nothing official about Python on Android, but since Jython exists, is there a way to let the snake and the robot work together?
One way is to use Kivy: Open source Python library for rapid development of applications that make use of innovative user interfaces, such as multi-touch apps. Kivy runs on Linux, Windows, OS X, Android and iOS. You can run the same [python] code on all supported platforms. Kivy Showcase app