Dataset Viewer
Auto-converted to Parquet Duplicate
title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
How can I find the full path to a font from its display name on a Mac?
469
21
2008-08-02T15:11:16Z
3,040
12
2008-08-06T03:01:23Z
[ "python", "osx", "fonts", "photoshop" ]
I am using the Photoshop's javascript API to find the fonts in a given PSD. Given a font name returned by the API, I want to find the actual physical font file that that font name corresponds to on the disc. This is all happening in a python program running on OSX so I guess I'm looking for one of: * Some Photoshop javascript * A Python function * An OSX API that I can call from python
Unfortunately the only API that isn't deprecated is located in the ApplicationServices framework, which doesn't have a bridge support file, and thus isn't available in the bridge. If you're wanting to use ctypes, you can use ATSFontGetFileReference after looking up the ATSFontRef. Cocoa doesn't have any native support, at least as of 10.5, for getting the location of a font.
Get a preview JPEG of a PDF on Windows?
502
27
2008-08-02T17:01:58Z
536
9
2008-08-02T18:49:07Z
[ "python", "windows", "image", "pdf" ]
I have a cross-platform (Python) application which needs to generate a JPEG preview of the first page of a PDF. On the Mac I am spawning [sips](http://developer.apple.com/documentation/Darwin/Reference/ManPages/man1/sips.1.html). Is there something similarly simple I can do on Windows?
You can use ImageMagick's convert utility for this, see some examples in [http://studio.imagemagick.org/pipermail/magick-users/2002-May/002636.html](https://web.archive.org/web/20120413111338/http://studio.imagemagick.org/pipermail/magick-users/2002-May/002636.html) : > ``` > Convert taxes.pdf taxes.jpg > ``` > > Will convert a two page PDF file into [2] jpeg files: taxes.jpg.0, > taxes.jpg.1 > > I can also convert these JPEGS to a thumbnail as follows: > > ``` > convert -size 120x120 taxes.jpg.0 -geometry 120x120 +profile '*' thumbnail.jpg > ``` > > I can even convert the PDF directly to a jpeg thumbnail as follows: > > ``` > convert -size 120x120 taxes.pdf -geometry 120x120 +profile '*' thumbnail.jpg > ``` > > This will result in a thumbnail.jpg.0 and thumbnail.jpg.1 for the two > pages.
Get a preview JPEG of a PDF on Windows?
502
27
2008-08-02T17:01:58Z
7,090
25
2008-08-10T08:08:33Z
[ "python", "windows", "image", "pdf" ]
I have a cross-platform (Python) application which needs to generate a JPEG preview of the first page of a PDF. On the Mac I am spawning [sips](http://developer.apple.com/documentation/Darwin/Reference/ManPages/man1/sips.1.html). Is there something similarly simple I can do on Windows?
ImageMagick delegates the PDF->bitmap conversion to GhostScript anyway, so here's a command you can use (it's based on the actual command listed by the `ps:alpha` delegate in ImageMagick, just adjusted to use JPEG as output): ``` gs -q -dQUIET -dPARANOIDSAFER -dBATCH -dNOPAUSE -dNOPROMPT \ -dMaxBitmap=500000000 -dLastPage=1 -dAlignToPixels=0 -dGridFitTT=0 \ -sDEVICE=jpeg -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r72x72 \ -sOutputFile=$OUTPUT -f$INPUT ``` where `$OUTPUT` and `$INPUT` are the output and input filenames. Adjust the `72x72` to whatever resolution you need. (Obviously, strip out the backslashes if you're writing out the whole command as one line.) This is good for two reasons: 1. You don't need to have ImageMagick installed anymore. Not that I have anything against ImageMagick (I love it to bits), but I believe in simple solutions. 2. ImageMagick does a two-step conversion. First PDF->PPM, then PPM->JPEG. This way, the conversion is one-step. Other things to consider: with the files I've tested, PNG compresses better than JPEG. If you want to use PNG, change the `-sDEVICE=jpeg` to `-sDEVICE=png16m`.
Continuous Integration System for a Python Codebase
535
40
2008-08-02T18:43:54Z
538
23
2008-08-02T18:56:56Z
[ "python", "continuous-integration", "extreme-programming" ]
I'm starting work on a hobby project with a python codebase and would like to set up some form of continuous integration (i.e. running a battery of test-cases each time a check-in is made and sending nag e-mails to responsible persons when the tests fail) similar to CruiseControl or TeamCity. I realize I could do this with hooks in most VCSes, but that requires that the tests run on the same machine as the version control server, which isn't as elegant as I would like. Does anyone have any suggestions for a small, user-friendly, open-source continuous integration system suitable for a Python codebase?
One possibility is Hudson. It's written in Java, but there's integration with Python projects: > [Hudson embraces Python](http://redsolo.blogspot.com/2007/11/hudson-embraces-python.html) I've never tried it myself, however. (**Update**, Sept. 2011: After a trademark dispute Hudson has been renamed to [Jenkins](http://jenkins-ci.org/).)
Continuous Integration System for a Python Codebase
535
40
2008-08-02T18:43:54Z
541
20
2008-08-02T19:06:40Z
[ "python", "continuous-integration", "extreme-programming" ]
I'm starting work on a hobby project with a python codebase and would like to set up some form of continuous integration (i.e. running a battery of test-cases each time a check-in is made and sending nag e-mails to responsible persons when the tests fail) similar to CruiseControl or TeamCity. I realize I could do this with hooks in most VCSes, but that requires that the tests run on the same machine as the version control server, which isn't as elegant as I would like. Does anyone have any suggestions for a small, user-friendly, open-source continuous integration system suitable for a Python codebase?
We run [Buildbot - Trac](http://buildbot.net/trac) at work, I haven't used it too much since my code base isn't part of the release cycle yet. But we run the tests on different environments (OSX/Linux/Win) and it sends emails --and it's written in python.
Continuous Integration System for a Python Codebase
535
40
2008-08-02T18:43:54Z
660
14
2008-08-03T12:09:18Z
[ "python", "continuous-integration", "extreme-programming" ]
I'm starting work on a hobby project with a python codebase and would like to set up some form of continuous integration (i.e. running a battery of test-cases each time a check-in is made and sending nag e-mails to responsible persons when the tests fail) similar to CruiseControl or TeamCity. I realize I could do this with hooks in most VCSes, but that requires that the tests run on the same machine as the version control server, which isn't as elegant as I would like. Does anyone have any suggestions for a small, user-friendly, open-source continuous integration system suitable for a Python codebase?
Second the Buildbot - Trac integration. You can find more information about the integration on the [Buildbot website](http://buildbot.net/trac/wiki/BuildbotAndTrac). At my previous job, we wrote and used the plugin they mention (tracbb). What the plugin does is rewriting all of the Buildbot urls so you can use Buildbot from within Trac. (http://example.com/tracbb). The really nice thing about Buildbot is that the configuration is written in Python. You can integrate your own Python code directly to the configuration. It's also very easy to write your own BuildSteps to execute specific tasks. We used BuildSteps to get the source from SVN, pull the dependencies, publish test results to WebDAV, etcetera. I wrote an X10 interface so we could send signals with build results. When the build failed, we switched on a red lava lamp. When the build succeeded, a green lava lamp switched on. Good times :-)
Continuous Integration System for a Python Codebase
535
40
2008-08-02T18:43:54Z
61,746
13
2008-09-15T00:11:21Z
[ "python", "continuous-integration", "extreme-programming" ]
I'm starting work on a hobby project with a python codebase and would like to set up some form of continuous integration (i.e. running a battery of test-cases each time a check-in is made and sending nag e-mails to responsible persons when the tests fail) similar to CruiseControl or TeamCity. I realize I could do this with hooks in most VCSes, but that requires that the tests run on the same machine as the version control server, which isn't as elegant as I would like. Does anyone have any suggestions for a small, user-friendly, open-source continuous integration system suitable for a Python codebase?
We use both Buildbot and Hudson for Jython development. Both are useful, but have different strengths and weaknesses. Buildbot's configuration is pure Python and quite simple once you get the hang of it (look at the epydoc-generated API docs for the most current info). Buildbot makes it easier to define non-testing tasks and distribute the testers. However, it really has no concept of individual tests, just textual, HTML, and summary output, so if you want to have multi-level browsable test output and so forth you'll have to build it yourself, or just use Hudson. Hudson has terrific support for drilling down from overall results into test suites and individual tests; it also is great for comparing test output between builds, but the distributed (master/slave) stuff is comparatively more complicated because you need a Java environment on the slaves too; also, Hudson is less tolerant of flaky network links between the master and slaves. So, to get the benefits of both tools, we run a single instance of Hudson, which catches the common test failures, then we do multi-platform regression with Buildbot. Here are our instances: * [Jython Hudson](http://bob.underboss.org:8080/job/jython/lastBuild/testReport/) * [Jython buildbot](http://www.acm.uiuc.edu/jython-buildbot/waterfall)
cx_Oracle: How do I iterate over a result set?
594
25
2008-08-03T01:15:08Z
595
25
2008-08-03T01:17:36Z
[ "python", "sql", "database", "oracle", "cx-oracle" ]
There are several ways to iterate over a result set. What are the tradeoff of each?
The canonical way is to use the built-in cursor iterator. ``` curs.execute('select * from people') for row in curs: print row ``` --- You can use `fetchall()` to get all rows at once. ``` for row in curs.fetchall(): print row ``` It can be convenient to use this to create a Python list containing the values returned: ``` curs.execute('select first_name from people') names = [row[0] for row in curs.fetchall()] ``` This can be useful for smaller result sets, but can have bad side effects if the result set is large. * You have to wait for the entire result set to be returned to your client process. * You may eat up a lot of memory in your client to hold the built-up list. * It may take a while for Python to construct and deconstruct the list which you are going to immediately discard anyways. --- If you know there's a single row being returned in the result set you can call `fetchone()` to get the single row. ``` curs.execute('select max(x) from t') maxValue = curs.fetchone()[0] ``` --- Finally, you can loop over the result set fetching one row at a time. In general, there's no particular advantage in doing this over using the iterator. ``` row = curs.fetchone() while row: print row row = curs.fetchone() ```
cx_Oracle: How do I iterate over a result set?
594
25
2008-08-03T01:15:08Z
125,140
17
2008-09-24T02:51:00Z
[ "python", "sql", "database", "oracle", "cx-oracle" ]
There are several ways to iterate over a result set. What are the tradeoff of each?
My preferred way is the cursor iterator, but setting first the arraysize property of the cursor. ``` curs.execute('select * from people') curs.arraysize = 256 for row in curs: print row ``` In this example, cx\_Oracle will fetch rows from Oracle 256 rows at a time, reducing the number of network round trips that need to be performed
Using 'in' to match an attribute of Python objects in an array
683
28
2008-08-03T13:19:16Z
745
8
2008-08-03T15:59:19Z
[ "python", "arrays", "iteration" ]
I don't remember whether I was dreaming or not but I seem to recall there being a function which allowed something like, ``` foo in iter_attr(array of python objects, attribute name) ``` I've looked over the docs but this kind of thing doesn't fall under any obvious listed headers
Are you looking to get a list of objects that have a certain attribute? If so, a [list comprehension](http://docs.python.org/tut/node7.html#SECTION007140000000000000000) is the right way to do this. ``` result = [obj for obj in listOfObjs if hasattr(obj, 'attributeName')] ```
Using 'in' to match an attribute of Python objects in an array
683
28
2008-08-03T13:19:16Z
57,833
29
2008-09-11T22:42:14Z
[ "python", "arrays", "iteration" ]
I don't remember whether I was dreaming or not but I seem to recall there being a function which allowed something like, ``` foo in iter_attr(array of python objects, attribute name) ``` I've looked over the docs but this kind of thing doesn't fall under any obvious listed headers
Using a list comprehension would build a temporary list, which could eat all your memory if the sequence being searched is large. Even if the sequence is not large, building the list means iterating over the whole of the sequence before `in` could start its search. The temporary list can be avoiding by using a generator expression: ``` foo = 12 foo in (obj.id for obj in bar) ``` Now, as long as `obj.id == 12` near the start of `bar`, the search will be fast, even if `bar` is infinitely long. As @Matt suggested, it's a good idea to use `hasattr` if any of the objects in `bar` can be missing an `id` attribute: ``` foo = 12 foo in (obj.id for obj in bar if hasattr(obj, 'id')) ```
Class views in Django
742
30
2008-08-03T15:55:28Z
4,572
7
2008-08-07T10:44:23Z
[ "python", "django", "views", "oop" ]
[Django](http://www.djangoproject.com/) view points to a function, which can be a problem if you want to change only a bit of functionality. Yes, I could have million keyword arguments and even more if statements in the function, but I was thinking more of an object oriented approach. For example, I have a page that displays a user. This page is very similar to page that displays a group, but it's still not so similar to just use another data model. Group also has members etc... One way would be to point views to class methods and then extend that class. Has anyone tried this approach or has any other idea?
If you're simply displaying data from models, why not use the [Django Generic Views](https://docs.djangoproject.com/en/1.2/ref/generic-views/)? They're designed to let you easy show data from a model without having to write your own view and stuff about mapping URL paramaters to views, fetching data, handling edge cases, rendering output, etc.
Class views in Django
742
30
2008-08-03T15:55:28Z
33,957
36
2008-08-29T04:29:22Z
[ "python", "django", "views", "oop" ]
[Django](http://www.djangoproject.com/) view points to a function, which can be a problem if you want to change only a bit of functionality. Yes, I could have million keyword arguments and even more if statements in the function, but I was thinking more of an object oriented approach. For example, I have a page that displays a user. This page is very similar to page that displays a group, but it's still not so similar to just use another data model. Group also has members etc... One way would be to point views to class methods and then extend that class. Has anyone tried this approach or has any other idea?
I've created and used my own generic view classes, defining **`__call__`** so an instance of the class is callable. I really like it; while Django's generic views allow some customization through keyword arguments, OO generic views (if their behavior is split into a number of separate methods) can have much more fine-grained customization via subclassing, which lets me repeat myself a lot less. (I get tired of rewriting the same create/update view logic anytime I need to tweak something Django's generic views don't quite allow). I've posted some code at [djangosnippets.org](http://www.djangosnippets.org/snippets/1009/). The only real downside I see is the proliferation of internal method calls, which may impact performance somewhat. I don't think this is much of a concern; it's rare that Python code execution would be your performance bottleneck in a web app. **UPDATE**: Django's own [generic views](http://docs.djangoproject.com/en/dev/topics/class-based-views/) are now class-based. **UPDATE**: FWIW, I've changed my opinion on class-based views since this answer was written. After having used them extensively on a couple of projects, I feel they tend to lead to code that is satisfyingly DRY to write, but very hard to read and maintain later, because functionality is spread across so many different places, and subclasses are so dependent on every implementation detail of the superclasses and mixins. I now feel that [TemplateResponse](https://docs.djangoproject.com/en/dev/ref/template-response/) and view decorators is a better answer for decomposing view code.
Class views in Django
742
30
2008-08-03T15:55:28Z
2,921,293
11
2010-05-27T13:02:08Z
[ "python", "django", "views", "oop" ]
[Django](http://www.djangoproject.com/) view points to a function, which can be a problem if you want to change only a bit of functionality. Yes, I could have million keyword arguments and even more if statements in the function, but I was thinking more of an object oriented approach. For example, I have a page that displays a user. This page is very similar to page that displays a group, but it's still not so similar to just use another data model. Group also has members etc... One way would be to point views to class methods and then extend that class. Has anyone tried this approach or has any other idea?
I needed to use class based views, but I wanted to be able to use the full name of the class in my URLconf without always having to instantiate the view class before using it. What helped me was a surprisingly simple metaclass: ``` class CallableViewClass(type): def __call__(cls, *args, **kwargs): if args and isinstance(args[0], HttpRequest): instance = super(CallableViewClass, cls).__call__() return instance.__call__(*args, **kwargs) else: instance = super(CallableViewClass, cls).__call__(*args, **kwargs) return instance class View(object): __metaclass__ = CallableViewClass def __call__(self, request, *args, **kwargs): if hasattr(self, request.method): handler = getattr(self, request.method) if hasattr(handler, '__call__'): return handler(request, *args, **kwargs) return HttpResponseBadRequest('Method Not Allowed', status=405) ``` I can now both instantiate view classes and use the instances as view functions, OR I can simply point my URLconf to my class and have the metaclass instantiate (and call) the view class for me. This works by checking the first argument to `__call__` – if it's a `HttpRequest`, it must be an actual HTTP request because it would be nonsense to attept to instantiate a view class with an `HttpRequest` instance. ``` class MyView(View): def __init__(self, arg=None): self.arg = arg def GET(request): return HttpResponse(self.arg or 'no args provided') @login_required class MyOtherView(View): def POST(request): pass # And all the following work as expected. urlpatterns = patterns('' url(r'^myview1$', 'myapp.views.MyView', name='myview1'), url(r'^myview2$', myapp.views.MyView, name='myview2'), url(r'^myview3$', myapp.views.MyView('foobar'), name='myview3'), url(r'^myotherview$', 'myapp.views.MyOtherView', name='otherview'), ) ``` (I posted a snippet for this at <http://djangosnippets.org/snippets/2041/>)
Python and MySQL
766
20
2008-08-03T17:44:07Z
1,619
17
2008-08-04T21:54:11Z
[ "python", "mysql", "postgresql", "bpgsql" ]
I can get Python to work with Postgresql but I cannot get it to work with MySQL. The main problem is that on the shared hosting account I have I do not have the ability to install things such as Django or PySQL, I generally fail when installing them on my computer so maybe it's good I can't install on the host. I found [bpgsql](http://barryp.org/software/bpgsql/) really good because it does not require an install, it's a single file that I can look at, read and then call the functions of. Does anybody know of something like this for MySQL?
MySQLdb is what I have used before. If you host is using Python version 2.5 or higher, support for sqlite3 databases is built in (sqlite allows you to have a relational database that is simply a file in your filesystem). But buyer beware, sqlite is not suited for production, so it may depend what you are trying to do with it. Another option may be to call your host and complain, or change hosts. Honestly these days, any self respecting web host that supports python and mysql ought to have MySQLdb pre installed.
How do I use Python's itertools.groupby()?
773
256
2008-08-03T18:27:09Z
783
52
2008-08-03T18:40:09Z
[ "python", "iteration" ]
I haven't been able to find an understandable explanation of how to actually use Python's `itertools.groupby()` function. What I'm trying to do is this: * Take a list - in this case, the children of an objectified `lxml` element * Divide it into groups based on some criteria * Then later iterate over each of these groups separately. I've reviewed [the documentation](https://docs.python.org/2/library/itertools.html), and [the examples](https://docs.python.org/2/library/itertools.html#itertools.groupby), but I've had trouble trying to apply them beyond a simple list of numbers. So, how do I use of `itertools.groupby()`? Is there another technique I should be using? Pointers to good "prerequisite" reading would also be appreciated.
Can you show us your code? The example on the Python docs is quite straightforward: ``` groups = [] uniquekeys = [] for k, g in groupby(data, keyfunc): groups.append(list(g)) # Store group iterator as a list uniquekeys.append(k) ``` So in your case, data is a list of nodes, keyfunc is where the logic of your criteria function goes and then `groupby()` groups the data. You must be careful to **sort the data** by the criteria before you call `groupby` or it won't work. `groupby` method actually just iterates through a list and whenever the key changes it creates a new group.
How do I use Python's itertools.groupby()?
773
256
2008-08-03T18:27:09Z
7,286
394
2008-08-10T18:45:32Z
[ "python", "iteration" ]
I haven't been able to find an understandable explanation of how to actually use Python's `itertools.groupby()` function. What I'm trying to do is this: * Take a list - in this case, the children of an objectified `lxml` element * Divide it into groups based on some criteria * Then later iterate over each of these groups separately. I've reviewed [the documentation](https://docs.python.org/2/library/itertools.html), and [the examples](https://docs.python.org/2/library/itertools.html#itertools.groupby), but I've had trouble trying to apply them beyond a simple list of numbers. So, how do I use of `itertools.groupby()`? Is there another technique I should be using? Pointers to good "prerequisite" reading would also be appreciated.
As Sebastjan said, **you first have to sort your data. This is important.** The part I didn't get is that in the example construction ``` groups = [] uniquekeys = [] for k, g in groupby(data, keyfunc): groups.append(list(g)) # Store group iterator as a list uniquekeys.append(k) ``` `k` is the current grouping key, and `g` is an iterator that you can use to iterate over the group defined by that grouping key. In other words, the `groupby` iterator itself returns iterators. Here's an example of that, using clearer variable names: ``` from itertools import groupby things = [("animal", "bear"), ("animal", "duck"), ("plant", "cactus"), ("vehicle", "speed boat"), ("vehicle", "school bus")] for key, group in groupby(things, lambda x: x[0]): for thing in group: print "A %s is a %s." % (thing[1], key) print " " ``` This will give you the output: > A bear is a animal. > A duck is a animal. > > A cactus is a plant. > > A speed boat is a vehicle. > A school bus is a vehicle. In this example, `things` is a list of tuples where the first item in each tuple is the group the second item belongs to. The `groupby()` function takes two arguments: (1) the data to group and (2) the function to group it with. Here, `lambda x: x[0]` tells `groupby()` to use the first item in each tuple as the grouping key. In the above `for` statement, `groupby` returns three (key, group iterator) pairs - once for each unique key. You can use the returned iterator to iterate over each individual item in that group. Here's a slightly different example with the same data, using a list comprehension: ``` for key, group in groupby(things, lambda x: x[0]): listOfThings = " and ".join([thing[1] for thing in group]) print key + "s: " + listOfThings + "." ``` This will give you the output: > animals: bear and duck. > plants: cactus. > vehicles: speed boat and school bus.
How do I use Python's itertools.groupby()?
773
256
2008-08-03T18:27:09Z
37,252
24
2008-08-31T23:27:16Z
[ "python", "iteration" ]
I haven't been able to find an understandable explanation of how to actually use Python's `itertools.groupby()` function. What I'm trying to do is this: * Take a list - in this case, the children of an objectified `lxml` element * Divide it into groups based on some criteria * Then later iterate over each of these groups separately. I've reviewed [the documentation](https://docs.python.org/2/library/itertools.html), and [the examples](https://docs.python.org/2/library/itertools.html#itertools.groupby), but I've had trouble trying to apply them beyond a simple list of numbers. So, how do I use of `itertools.groupby()`? Is there another technique I should be using? Pointers to good "prerequisite" reading would also be appreciated.
A neato trick with groupby is to run length encoding in one line: ``` [(c,len(list(cgen))) for c,cgen in groupby(some_string)] ``` will give you a list of 2-tuples where the first element is the char and the 2nd is the number of repetitions.
How do I use Python's itertools.groupby()?
773
256
2008-08-03T18:27:09Z
14,443,477
15
2013-01-21T16:54:08Z
[ "python", "iteration" ]
I haven't been able to find an understandable explanation of how to actually use Python's `itertools.groupby()` function. What I'm trying to do is this: * Take a list - in this case, the children of an objectified `lxml` element * Divide it into groups based on some criteria * Then later iterate over each of these groups separately. I've reviewed [the documentation](https://docs.python.org/2/library/itertools.html), and [the examples](https://docs.python.org/2/library/itertools.html#itertools.groupby), but I've had trouble trying to apply them beyond a simple list of numbers. So, how do I use of `itertools.groupby()`? Is there another technique I should be using? Pointers to good "prerequisite" reading would also be appreciated.
Another example: ``` for key, igroup in itertools.groupby(xrange(12), lambda x: x // 5): print key, list(igroup) ``` results in ``` 0 [0, 1, 2, 3, 4] 1 [5, 6, 7, 8, 9] 2 [10, 11] ``` Note that igroup is an iterator (a sub-iterator as the documentation calls it). This is useful for chunking a generator: ``` def chunker(items, chunk_size): '''Group items in chunks of chunk_size''' for _key, group in itertools.groupby(enumerate(items), lambda x: x[0] // chunk_size): yield (g[1] for g in group) with open('file.txt') as fobj: for chunk in chunker(fobj): process(chunk) ``` Another example of groupby - when the keys are not sorted. In the following example, items in xx are grouped by values in yy. In this case, one set of zeros is output first, followed by a set of ones, followed again by a set of zeros. ``` xx = range(10) yy = [0, 0, 0, 1, 1, 1, 0, 0, 0, 0] for group in itertools.groupby(iter(xx), lambda x: yy[x]): print group[0], list(group[1]) ``` Produces: ``` 0 [0, 1, 2] 1 [3, 4, 5] 0 [6, 7, 8, 9] ```
How do I use Python's itertools.groupby()?
773
256
2008-08-03T18:27:09Z
16,427,674
8
2013-05-07T20:09:46Z
[ "python", "iteration" ]
I haven't been able to find an understandable explanation of how to actually use Python's `itertools.groupby()` function. What I'm trying to do is this: * Take a list - in this case, the children of an objectified `lxml` element * Divide it into groups based on some criteria * Then later iterate over each of these groups separately. I've reviewed [the documentation](https://docs.python.org/2/library/itertools.html), and [the examples](https://docs.python.org/2/library/itertools.html#itertools.groupby), but I've had trouble trying to apply them beyond a simple list of numbers. So, how do I use of `itertools.groupby()`? Is there another technique I should be using? Pointers to good "prerequisite" reading would also be appreciated.
I would like to give another example where groupby without sort is not working. Adapted from example by James Sulak ``` from itertools import groupby things = [("vehicle", "bear"), ("animal", "duck"), ("animal", "cactus"), ("vehicle", "speed boat"), ("vehicle", "school bus")] for key, group in groupby(things, lambda x: x[0]): for thing in group: print "A %s is a %s." % (thing[1], key) print " " ``` output is ``` A bear is a vehicle. A duck is a animal. A cactus is a animal. A speed boat is a vehicle. A school bus is a vehicle. ``` there are two groups with vehicule, whereas one could expect only one group
How do I use Python's itertools.groupby()?
773
256
2008-08-03T18:27:09Z
20,013,133
10
2013-11-16T00:39:31Z
[ "python", "iteration" ]
I haven't been able to find an understandable explanation of how to actually use Python's `itertools.groupby()` function. What I'm trying to do is this: * Take a list - in this case, the children of an objectified `lxml` element * Divide it into groups based on some criteria * Then later iterate over each of these groups separately. I've reviewed [the documentation](https://docs.python.org/2/library/itertools.html), and [the examples](https://docs.python.org/2/library/itertools.html#itertools.groupby), but I've had trouble trying to apply them beyond a simple list of numbers. So, how do I use of `itertools.groupby()`? Is there another technique I should be using? Pointers to good "prerequisite" reading would also be appreciated.
WARNING: The syntax list(groupby(...)) won't work the way that you intend. It seems to destroy the internal iterator objects, so using ``` for x in list(groupby(range(10))): print(list(x[1])) ``` will produce: ``` [] [] [] [] [] [] [] [] [] [9] ``` Instead, of list(groupby(...)), try [(k, list(g)) for k,g in groupby(...)], or if you use that syntax often, ``` def groupbylist(*args, **kwargs): return [(k, list(g)) for k, g in groupby(*args, **kwargs)] ``` and get access to the groupby functionality while avoiding those pesky (for small data) iterators all together.
Adding a Method to an Existing Object Instance
972
364
2008-08-04T02:17:51Z
982
14
2008-08-04T02:31:13Z
[ "python", "oop", "methods", "monkeypatching" ]
I've read that it is possible to add a method to an existing object (e.g. not in the class definition) in **Python**, I think this is called *Monkey Patching* (or in some cases *Duck Punching*). I understand that it's not always a good decision to do so. But, how might one do this? **UPDATE 8/04/2008 00:21:01 EST:** [That](http://stackoverflow.com/a/982) looks like a good answer John Downey, I tried it but it appears that it ends up being not a *true* method. Your example defines the new patch function with an argument of **`self`**, but if you write actual code that way, the now patched class method asks for an argument named `self` (it doesn't automagically recognize it as the object to which it is supposed to bind, which is what would happen if defined within the class definition), meaning you have to call **`class.patch(obj)`** instead of just **`class.patch()`** if you want the same functionality as a *true* method. **It looks like Python isn't really treating it as a method, but more just as a variable which happens to be a function** (and as such is callable). Is there any way to attach an actual method to a class? Oh, and Ryan, [that](http://pypi.python.org/pypi/monkey) isn't exactly what I was looking for (it isn't a builtin functionality), but it is quite cool nonetheless.
In Python monkey patching generally works by overwriting a class or functions signature with your own. Below is an example from the [Zope Wiki](http://wiki.zope.org/zope2/MonkeyPatch): ``` from SomeOtherProduct.SomeModule import SomeClass def speak(self): return "ook ook eee eee eee!" SomeClass.speak = speak ``` That code will overwrite/create a method called speak on the class. In Jeff Atwood's [recent post on monkey patching](http://www.codinghorror.com/blog/archives/001151.html). He shows an example in C# 3.0 which is the current language I use for work.
Adding a Method to an Existing Object Instance
972
364
2008-08-04T02:17:51Z
2,982
576
2008-08-06T00:33:35Z
[ "python", "oop", "methods", "monkeypatching" ]
I've read that it is possible to add a method to an existing object (e.g. not in the class definition) in **Python**, I think this is called *Monkey Patching* (or in some cases *Duck Punching*). I understand that it's not always a good decision to do so. But, how might one do this? **UPDATE 8/04/2008 00:21:01 EST:** [That](http://stackoverflow.com/a/982) looks like a good answer John Downey, I tried it but it appears that it ends up being not a *true* method. Your example defines the new patch function with an argument of **`self`**, but if you write actual code that way, the now patched class method asks for an argument named `self` (it doesn't automagically recognize it as the object to which it is supposed to bind, which is what would happen if defined within the class definition), meaning you have to call **`class.patch(obj)`** instead of just **`class.patch()`** if you want the same functionality as a *true* method. **It looks like Python isn't really treating it as a method, but more just as a variable which happens to be a function** (and as such is callable). Is there any way to attach an actual method to a class? Oh, and Ryan, [that](http://pypi.python.org/pypi/monkey) isn't exactly what I was looking for (it isn't a builtin functionality), but it is quite cool nonetheless.
In Python, there is a difference between functions and bound methods. ``` >>> def foo(): ... print "foo" ... >>> class A: ... def bar( self ): ... print "bar" ... >>> a = A() >>> foo <function foo at 0x00A98D70> >>> a.bar <bound method A.bar of <__main__.A instance at 0x00A9BC88>> >>> ``` Bound methods have been "bound" (how descriptive) to an instance, and that instance will be passed as the first argument whenever the method is called. Callables that are attributes of a class (as opposed to an instance) are still unbound, though, so you can modify the class definition whenever you want: ``` >>> def fooFighters( self ): ... print "fooFighters" ... >>> A.fooFighters = fooFighters >>> a2 = A() >>> a2.fooFighters <bound method A.fooFighters of <__main__.A instance at 0x00A9BEB8>> >>> a2.fooFighters() fooFighters ``` Previously defined instances are updated as well (as long as they haven't overridden the attribute themselves): ``` >>> a.fooFighters() fooFighters ``` The problem comes when you want to attach a method to a single instance: ``` >>> def barFighters( self ): ... print "barFighters" ... >>> a.barFighters = barFighters >>> a.barFighters() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: barFighters() takes exactly 1 argument (0 given) ``` The function is not automatically bound when it's attached directly to an instance: ``` >>> a.barFighters <function barFighters at 0x00A98EF0> ``` To bind it, we can use the [MethodType function in the types module](http://docs.python.org/library/types.html?highlight=methodtype#module-types): ``` >>> import types >>> a.barFighters = types.MethodType( barFighters, a ) >>> a.barFighters <bound method ?.barFighters of <__main__.A instance at 0x00A9BC88>> >>> a.barFighters() barFighters ``` This time other instances of the class have not been affected: ``` >>> a2.barFighters() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: A instance has no attribute 'barFighters' ``` More information can be found by reading about [descriptors](http://users.rcn.com/python/download/Descriptor.htm) and [metaclass](http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html) [programming](http://www.gnosis.cx/publish/programming/metaclass_2.html).
Adding a Method to an Existing Object Instance
972
364
2008-08-04T02:17:51Z
959,064
66
2009-06-06T05:31:38Z
[ "python", "oop", "methods", "monkeypatching" ]
I've read that it is possible to add a method to an existing object (e.g. not in the class definition) in **Python**, I think this is called *Monkey Patching* (or in some cases *Duck Punching*). I understand that it's not always a good decision to do so. But, how might one do this? **UPDATE 8/04/2008 00:21:01 EST:** [That](http://stackoverflow.com/a/982) looks like a good answer John Downey, I tried it but it appears that it ends up being not a *true* method. Your example defines the new patch function with an argument of **`self`**, but if you write actual code that way, the now patched class method asks for an argument named `self` (it doesn't automagically recognize it as the object to which it is supposed to bind, which is what would happen if defined within the class definition), meaning you have to call **`class.patch(obj)`** instead of just **`class.patch()`** if you want the same functionality as a *true* method. **It looks like Python isn't really treating it as a method, but more just as a variable which happens to be a function** (and as such is callable). Is there any way to attach an actual method to a class? Oh, and Ryan, [that](http://pypi.python.org/pypi/monkey) isn't exactly what I was looking for (it isn't a builtin functionality), but it is quite cool nonetheless.
Module **new** is deprecated since python 2.6 and removed in 3.0, use **types** see <http://docs.python.org/library/new.html> In the example below I've deliberately removed return value from `patch_me()` function. I think that giving return value may make one believe that patch returns a new object, which is not true - it modifies the incoming one. Probably this can facilitate a more disciplined use of monkeypatching. ``` import types class A(object):#but seems to work for old style objects too pass def patch_me(target): def method(target,x): print "x=",x print "called from", target target.method = types.MethodType(method,target) #add more if needed a = A() print a #out: <__main__.A object at 0x2b73ac88bfd0> patch_me(a) #patch instance a.method(5) #out: x= 5 #out: called from <__main__.A object at 0x2b73ac88bfd0> patch_me(A) A.method(6) #can patch class too #out: x= 6 #out: called from <class '__main__.A'> ```
Adding a Method to an Existing Object Instance
972
364
2008-08-04T02:17:51Z
8,961,717
25
2012-01-22T14:20:54Z
[ "python", "oop", "methods", "monkeypatching" ]
I've read that it is possible to add a method to an existing object (e.g. not in the class definition) in **Python**, I think this is called *Monkey Patching* (or in some cases *Duck Punching*). I understand that it's not always a good decision to do so. But, how might one do this? **UPDATE 8/04/2008 00:21:01 EST:** [That](http://stackoverflow.com/a/982) looks like a good answer John Downey, I tried it but it appears that it ends up being not a *true* method. Your example defines the new patch function with an argument of **`self`**, but if you write actual code that way, the now patched class method asks for an argument named `self` (it doesn't automagically recognize it as the object to which it is supposed to bind, which is what would happen if defined within the class definition), meaning you have to call **`class.patch(obj)`** instead of just **`class.patch()`** if you want the same functionality as a *true* method. **It looks like Python isn't really treating it as a method, but more just as a variable which happens to be a function** (and as such is callable). Is there any way to attach an actual method to a class? Oh, and Ryan, [that](http://pypi.python.org/pypi/monkey) isn't exactly what I was looking for (it isn't a builtin functionality), but it is quite cool nonetheless.
I think that the above answers missed the key point. Let's have a class with a method: ``` class A(object): def m(self): pass ``` Now, let's play with it in ipython: ``` In [2]: A.m Out[2]: <unbound method A.m> ``` Ok, so *m()* somehow becomes an unbound method of *A*. But is it really like that? ``` In [5]: A.__dict__['m'] Out[5]: <function m at 0xa66b8b4> ``` It turns out that *m()* is just a function, reference to which is added to *A* class dictionary - there's no magic. Then why *A.m* gives us an unbound method? It's because the dot is not translated to a simple dictionary lookup. It's de facto a call of A.\_\_class\_\_.\_\_getattribute\_\_(A, 'm'): ``` In [11]: class MetaA(type): ....: def __getattribute__(self, attr_name): ....: print str(self), '-', attr_name In [12]: class A(object): ....: __metaclass__ = MetaA In [23]: A.m <class '__main__.A'> - m <class '__main__.A'> - m ``` Now, I'm not sure out of the top of my head why the last line is printed twice, but still it's clear what's going on there. Now, what the default \_\_getattribute\_\_ does is that it checks if the attribute is a so-called [descriptor](http://docs.python.org/reference/datamodel.html#implementing-descriptors) or not, i.e. if it implements a special \_\_get\_\_ method. If it implements that method, then what is returned is the result of calling that \_\_get\_\_ method. Going back to the first version of our *A* class, this is what we have: ``` In [28]: A.__dict__['m'].__get__(None, A) Out[28]: <unbound method A.m> ``` And because Python functions implement the descriptor protocol, if they are called on behalf of an object, they bind themselves to that object in their \_\_get\_\_ method. Ok, so how to add a method to an existing object? Assuming you don't mind patching class, it's as simple as: ``` B.m = m ``` Then *B.m* "becomes" an unbound method, thanks to the descriptor magic. And if you want to add a method just to a single object, then you have to emulate the machinery yourself, by using types.MethodType: ``` b.m = types.MethodType(m, b) ``` By the way: ``` In [2]: A.m Out[2]: <unbound method A.m> In [59]: type(A.m) Out[59]: <type 'instancemethod'> In [60]: type(b.m) Out[60]: <type 'instancemethod'> In [61]: types.MethodType Out[61]: <type 'instancemethod'> ```
Adding a Method to an Existing Object Instance
972
364
2008-08-04T02:17:51Z
16,240,409
7
2013-04-26T15:47:35Z
[ "python", "oop", "methods", "monkeypatching" ]
I've read that it is possible to add a method to an existing object (e.g. not in the class definition) in **Python**, I think this is called *Monkey Patching* (or in some cases *Duck Punching*). I understand that it's not always a good decision to do so. But, how might one do this? **UPDATE 8/04/2008 00:21:01 EST:** [That](http://stackoverflow.com/a/982) looks like a good answer John Downey, I tried it but it appears that it ends up being not a *true* method. Your example defines the new patch function with an argument of **`self`**, but if you write actual code that way, the now patched class method asks for an argument named `self` (it doesn't automagically recognize it as the object to which it is supposed to bind, which is what would happen if defined within the class definition), meaning you have to call **`class.patch(obj)`** instead of just **`class.patch()`** if you want the same functionality as a *true* method. **It looks like Python isn't really treating it as a method, but more just as a variable which happens to be a function** (and as such is callable). Is there any way to attach an actual method to a class? Oh, and Ryan, [that](http://pypi.python.org/pypi/monkey) isn't exactly what I was looking for (it isn't a builtin functionality), but it is quite cool nonetheless.
There are at least two ways for attach a method to an instance without `types.MethodType`: ``` >>> class A: ... def m(self): ... print 'im m, invoked with: ', self >>> a = A() >>> a.m() im m, invoked with: <__main__.A instance at 0x973ec6c> >>> a.m <bound method A.m of <__main__.A instance at 0x973ec6c>> >>> >>> def foo(firstargument): ... print 'im foo, invoked with: ', firstargument >>> foo <function foo at 0x978548c> ``` 1: ``` >>> a.foo = foo.__get__(a, A) # or foo.__get__(a, type(a)) >>> a.foo() im foo, invoked with: <__main__.A instance at 0x973ec6c> >>> a.foo <bound method A.foo of <__main__.A instance at 0x973ec6c>> ``` 2: ``` >>> instancemethod = type(A.m) >>> instancemethod <type 'instancemethod'> >>> a.foo2 = instancemethod(foo, a, type(a)) >>> a.foo2() im foo, invoked with: <__main__.A instance at 0x973ec6c> >>> a.foo2 <bound method instance.foo of <__main__.A instance at 0x973ec6c>> ``` Useful links: [Data model - invoking descriptors](http://docs.python.org/2/reference/datamodel.html#invoking-descriptors) [Descriptor HowTo Guide - invoking descriptors](http://docs.python.org/2.7/howto/descriptor.html#invoking-descriptors)
Adding a Method to an Existing Object Instance
972
364
2008-08-04T02:17:51Z
28,060,251
10
2015-01-21T05:31:23Z
[ "python", "oop", "methods", "monkeypatching" ]
I've read that it is possible to add a method to an existing object (e.g. not in the class definition) in **Python**, I think this is called *Monkey Patching* (or in some cases *Duck Punching*). I understand that it's not always a good decision to do so. But, how might one do this? **UPDATE 8/04/2008 00:21:01 EST:** [That](http://stackoverflow.com/a/982) looks like a good answer John Downey, I tried it but it appears that it ends up being not a *true* method. Your example defines the new patch function with an argument of **`self`**, but if you write actual code that way, the now patched class method asks for an argument named `self` (it doesn't automagically recognize it as the object to which it is supposed to bind, which is what would happen if defined within the class definition), meaning you have to call **`class.patch(obj)`** instead of just **`class.patch()`** if you want the same functionality as a *true* method. **It looks like Python isn't really treating it as a method, but more just as a variable which happens to be a function** (and as such is callable). Is there any way to attach an actual method to a class? Oh, and Ryan, [that](http://pypi.python.org/pypi/monkey) isn't exactly what I was looking for (it isn't a builtin functionality), but it is quite cool nonetheless.
> # Adding a Method to an Existing Object Instance > > I've read that it is possible to add a method to an existing object (e.g. not in the class definition) in python, I think this is called Monkey Patching (or in some cases Duck Punching). I understand that it's not always a good decision to do so. **But, how might one do this?** ## Yes, it is possible. (But not recommended.) Since it's instructive, however, I'm going to show you three ways of doing this. Here's some setup code. We need a class definition. It could be imported, but it really doesn't matter. ``` class Foo(object): '''An empty class to demonstrate adding a method to an instance''' ``` Create an instance: ``` foo = Foo() ``` Create a method to add to it: ``` def sample_method(self, bar, baz): print(bar + baz) ``` ### Method one - types.MethodType First, import types, from which we'll get the method constructor: ``` import types ``` Now we add the method to the instance. To do this, we require the MethodType constructor from the `types` module (which we imported above). The argument signature for types.MethodType is `(function, instance, class)`: ``` foo.sample_method = types.MethodType(sample_method, foo, Foo) ``` and usage: ``` >>> foo.sample_method(1,2) 3 ``` ## Method two: lexical binding First, we create a wrapper function that binds the method to the instance: ``` def bind(instance, method): def binding_scope_fn(*args, **kwargs): return method(instance, *args, **kwargs) return binding_scope_fn ``` usage: ``` >>> foo.sample_method = bind(foo, sample_method) >>> foo.sample_method(1,2) 3 ``` ## Method three: functools.partial ``` >>> from functools import partial >>> foo.sample_method = partial(sample_method, foo) >>> foo.sample_method(1,2) 3 ``` This makes sense when you consider that bound methods are partial functions of the instance. ## Unbound function as an object attribute - why this doesn't work: If we try to add the sample\_method in the same way as we might add it to the class, it is unbound from the instance, and doesn't take the implicit self as the first argument. ``` >>> foo.sample_method = sample_method >>> foo.sample_method(1,2) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: sample_method() takes exactly 3 arguments (2 given) ``` We can make the unbound function work by explicitly passing the instance (or anything, since this method doesn't actually use the `self` argument variable), but it would not be consistent with the expected signature of other instances (if we're monkey-patching this instance): ``` >>> foo.sample_method(foo, 1, 2) 3 ``` --- # Disclaimer Note, just because this is possible doesn't make it recommended. In fact, I suggest that you not do this unless you have a really good reason. It is far better to define the correct method in the class definition or less preferably to monkey-patch the class directly, like this: ``` Foo.sample_method = sample_method ```
How do you express binary literals in Python?
1,476
251
2008-08-04T18:20:36Z
1,484
57
2008-08-04T18:34:45Z
[ "python", "syntax", "binary", "integer", "literals" ]
How do you express an integer as a binary number with Python literals? I was easily able to find the answer for hex: ``` >>> 0x12AF 4783 >>> 0x100 256 ``` and octal: ``` >>> 01267 695 >>> 0100 64 ``` **How do you use literals to express binary in Python?** --- ***Summary of Answers*** * Python 2.5 and earlier: can express binary using `int('01010101111',2)` but not with a literal. * Python 2.5 and earlier: there is *no way* to express binary literals. * Python 2.6 beta: You can do like so: `0b1100111` or `0B1100111`. * Python 2.6 beta: will also allow `0o27` or `0O27` (second character is the letter O) to represent an octal. * Python 3.0 beta: Same as 2.6, but will no longer allow the older `027` syntax for octals.
``` >>> print int('01010101111',2) 687 >>> print int('11111111',2) 255 ``` Another way.
How do you express binary literals in Python?
1,476
251
2008-08-04T18:20:36Z
13,107
204
2008-08-16T12:35:36Z
[ "python", "syntax", "binary", "integer", "literals" ]
How do you express an integer as a binary number with Python literals? I was easily able to find the answer for hex: ``` >>> 0x12AF 4783 >>> 0x100 256 ``` and octal: ``` >>> 01267 695 >>> 0100 64 ``` **How do you use literals to express binary in Python?** --- ***Summary of Answers*** * Python 2.5 and earlier: can express binary using `int('01010101111',2)` but not with a literal. * Python 2.5 and earlier: there is *no way* to express binary literals. * Python 2.6 beta: You can do like so: `0b1100111` or `0B1100111`. * Python 2.6 beta: will also allow `0o27` or `0O27` (second character is the letter O) to represent an octal. * Python 3.0 beta: Same as 2.6, but will no longer allow the older `027` syntax for octals.
For reference—*future* Python possibilities: Starting with Python 2.6 you can express binary literals using the prefix **0b** or **0B**: ``` >>> 0b101111 47 ``` You can also use the new **bin** function to get the binary representation of a number: ``` >>> bin(173) '0b10101101' ``` Development version of the documentation: [What's New in Python 2.6](http://docs.python.org/dev/whatsnew/2.6.html#pep-3127-integer-literal-support-and-syntax)
Any experiences with Protocol Buffers?
1,734
20
2008-08-05T00:12:55Z
1,780
8
2008-08-05T01:14:30Z
[ "python", "xml", "database", "protocol-buffers" ]
I was just looking through some information about Google's [protocol buffers](http://code.google.com/apis/protocolbuffers/) data interchange format. Has anyone played around with the code or even created a project around it? I'm currently using XML in a Python project for structured content created by hand in a text editor, and I was wondering what the general opinion was on Protocol Buffers as a user-facing input format. The speed and brevity benefits definitely seem to be there, but there are so many factors when it comes to actually generating and processing the data.
If you are looking for user facing interaction, stick with xml. It has more support, understanding, and general acceptance currently. If it's internal, I would say that protocol buffers are a great idea. Maybe in a few years as more tools come out to support protocol buffers, then start looking towards that for a public facing api. Until then... [JSON](http://en.wikipedia.org/wiki/JSON)?
Any experiences with Protocol Buffers?
1,734
20
2008-08-05T00:12:55Z
6,161
10
2008-08-08T17:12:24Z
[ "python", "xml", "database", "protocol-buffers" ]
I was just looking through some information about Google's [protocol buffers](http://code.google.com/apis/protocolbuffers/) data interchange format. Has anyone played around with the code or even created a project around it? I'm currently using XML in a Python project for structured content created by hand in a text editor, and I was wondering what the general opinion was on Protocol Buffers as a user-facing input format. The speed and brevity benefits definitely seem to be there, but there are so many factors when it comes to actually generating and processing the data.
Protocol buffers are intended to optimize communications between machines. They are really not intended for human interaction. Also, the format is binary, so it could not replace XML in that use case. I would also recommend [JSON](http://en.wikipedia.org/wiki/JSON) as being the most compact text-based format.
How do I make a menu that does not require the user to press [enter] to make a selection?
1,829
12
2008-08-05T02:39:23Z
1,840
8
2008-08-05T02:54:54Z
[ "python" ]
I've got a menu in Python. That part was easy. I'm using `raw_input()` to get the selection from the user. The problem is that `raw_input` (and input) require the user to press `Enter` after they make a selection. Is there any way to make the program act immediately upon a keystroke? Here's what I've got so far: ``` import sys print """Menu 1) Say Foo 2) Say Bar""" answer = raw_input("Make a selection> ") if "1" in answer: print "foo" elif "2" in answer: print "bar" ``` It would be great to have something like ``` print menu while lastKey = "": lastKey = check_for_recent_keystrokes() if "1" in lastKey: #do stuff... ```
**On Linux:** * set raw mode * select and read the keystroke * restore normal settings ``` import sys import select import termios import tty def getkey(): old_settings = termios.tcgetattr(sys.stdin) tty.setraw(sys.stdin.fileno()) select.select([sys.stdin], [], [], 0) answer = sys.stdin.read(1) termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings) return answer print """Menu 1) Say Foo 2) Say Bar""" answer=getkey() if "1" in answer: print "foo" elif "2" in answer: print "bar" ```
How to check what OS am I running on in Python?
1,854
270
2008-08-05T03:23:18Z
1,857
341
2008-08-05T03:27:03Z
[ "python" ]
What do I need to look at to see if I'm on Windows, Unix, etc?
``` >>> import os >>> print os.name posix >>> import platform >>> platform.system() 'Linux' >>> platform.release() '2.6.22-15-generic' ``` See: [platform — Access to underlying platform’s identifying data](https://docs.python.org/2/library/platform.html)
How to check what OS am I running on in Python?
1,854
270
2008-08-05T03:23:18Z
1,871
112
2008-08-05T03:57:22Z
[ "python" ]
What do I need to look at to see if I'm on Windows, Unix, etc?
Dang -- lbrandy beat me to the punch, but that doesn't mean I can't provide you with the system results for Vista! ``` >>> import os >>> os.name 'nt' >>> import platform >>> platform.system() 'Windows' >>> platform.release() 'Vista' ```
How to check what OS am I running on in Python?
1,854
270
2008-08-05T03:23:18Z
1,879
91
2008-08-05T04:13:53Z
[ "python" ]
What do I need to look at to see if I'm on Windows, Unix, etc?
For the record here's the results on Mac: ``` >>> import os >>> os.name 'posix' >>> import platform >>> platform.system() 'Darwin' >>> platform.release() '8.11.1' ```
How to check what OS am I running on in Python?
1,854
270
2008-08-05T03:23:18Z
28,426
30
2008-08-26T15:41:50Z
[ "python" ]
What do I need to look at to see if I'm on Windows, Unix, etc?
You can also use sys.platform if you already have imported sys and you don't want to import another module ``` >>> import sys >>> sys.platform 'linux2' ```
How to check what OS am I running on in Python?
1,854
270
2008-08-05T03:23:18Z
553,500
13
2009-02-16T14:43:18Z
[ "python" ]
What do I need to look at to see if I'm on Windows, Unix, etc?
I do this ``` import sys print sys.platform ``` Docs here : [sys.platform](http://docs.python.org/library/sys.html#sys.platform). Everything you need is probably in the sys module.
How to check what OS am I running on in Python?
1,854
270
2008-08-05T03:23:18Z
3,021,004
7
2010-06-11T07:37:56Z
[ "python" ]
What do I need to look at to see if I'm on Windows, Unix, etc?
I am using the WLST tool that comes with weblogic, and it doesn't implement the platform package. ``` wls:/offline> import os wls:/offline> print os.name java wls:/offline> import sys wls:/offline> print sys.platform 'java1.5.0_11' ``` Apart from patching the system *javaos.py* ([issue with os.system() on windows 2003 with jdk1.5](http://osdir.com/ml/lang.jython.devel/2006-08/msg00035.html)) (which I can't do, I have to use weblogic out of the box), this is what I use: ``` def iswindows(): os = java.lang.System.getProperty( "os.name" ) return "win" in os.lower() ```
How to check what OS am I running on in Python?
1,854
270
2008-08-05T03:23:18Z
6,477,354
7
2011-06-25T11:10:45Z
[ "python" ]
What do I need to look at to see if I'm on Windows, Unix, etc?
``` >>> import platform >>> platform.system() ```
How to check what OS am I running on in Python?
1,854
270
2008-08-05T03:23:18Z
14,477,954
15
2013-01-23T10:55:26Z
[ "python" ]
What do I need to look at to see if I'm on Windows, Unix, etc?
A comparison between the different methods, and what they return on different operating systems can be found here: [OS\_flavor\_name\_version](https://github.com/hpcugent/easybuild/wiki/OS_flavor_name_version) Methods that are compared: ``` import platform import sys def linux_distribution(): try: return platform.linux_distribution() except: return "N/A" print("""Python version: %s dist: %s linux_distribution: %s system: %s machine: %s platform: %s uname: %s version: %s mac_ver: %s """ % ( sys.version.split('\n'), str(platform.dist()), linux_distribution(), platform.system(), platform.machine(), platform.platform(), platform.uname(), platform.version(), platform.mac_ver(), )) ```
How to check what OS am I running on in Python?
1,854
270
2008-08-05T03:23:18Z
25,863,224
35
2014-09-16T07:42:41Z
[ "python" ]
What do I need to look at to see if I'm on Windows, Unix, etc?
Sample code to differentiate OS's using python: ``` from sys import platform as _platform if _platform == "linux" or _platform == "linux2": # linux elif _platform == "darwin": # MAC OS X elif _platform == "win32": # Windows ```
Python: what is the difference between (1,2,3) and [1,2,3], and when should I use each?
1,983
31
2008-08-05T07:18:55Z
1,987
19
2008-08-05T07:27:40Z
[ "python", "list", "tuples" ]
In many places, `(1,2,3)` and `[1,2,3]` can be used interchangeably. When should I use one or the other, and why?
The list [1,2,3] is dynamic and flexible but that flexibility comes at a speed cost. The tuple (1,2,3) is fixed (immutable) and therefore faster.
Python: what is the difference between (1,2,3) and [1,2,3], and when should I use each?
1,983
31
2008-08-05T07:18:55Z
2,277
26
2008-08-05T13:22:43Z
[ "python", "list", "tuples" ]
In many places, `(1,2,3)` and `[1,2,3]` can be used interchangeably. When should I use one or the other, and why?
From the [Python FAQ](http://www.python.org/doc/faq/general/#why-are-there-separate-tuple-and-list-data-types): > Lists and tuples, while similar in many respects, are generally used in fundamentally different ways. Tuples can be thought of as being similar to Pascal records or C structs; they're small collections of related data which may be of different types which are operated on as a group. For example, a Cartesian coordinate is appropriately represented as a tuple of two or three numbers. > > Lists, on the other hand, are more like arrays in other languages. They tend to hold a varying number of objects all of which have the same type and which are operated on one-by-one. Generally by convention you wouldn't choose a list or a tuple just based on its (im)mutability. You would choose a tuple for small collections of completely different pieces of data in which a full-blown class would be too heavyweight, and a list for collections of any reasonable size where you have a homogeneous set of data.
Python: what is the difference between (1,2,3) and [1,2,3], and when should I use each?
1,983
31
2008-08-05T07:18:55Z
4,595
10
2008-08-07T11:21:56Z
[ "python", "list", "tuples" ]
In many places, `(1,2,3)` and `[1,2,3]` can be used interchangeably. When should I use one or the other, and why?
Tuples are a quick\flexible way to create *composite* data-types. Lists are containers for, well, lists of objects. For example, you would use a List to store a list of student details in a class. Each student detail in that list may be a 3-tuple containing their roll number, name and test score. ``` `[(1,'Mark',86),(2,'John',34)...]` ``` Also, because tuples are immutable they can be used as keys in dictionaries.
Python: what is the difference between (1,2,3) and [1,2,3], and when should I use each?
1,983
31
2008-08-05T07:18:55Z
12,557
7
2008-08-15T18:00:37Z
[ "python", "list", "tuples" ]
In many places, `(1,2,3)` and `[1,2,3]` can be used interchangeably. When should I use one or the other, and why?
The notion of tuples are highly expressive: * Pragmatically, they are great for packing and unpacking values (`x,y=coord`). * In combination with dictionaries (hash tables), they allow forms of mapping that would otherwise require many levels of association. For example, consider marking that (x,y) has been found. ``` // PHP if (!isset($found[$x])) { $found[$x] = Array(); $found[$x][$y] = true; } else if (!isset($found[$x][$y])) { $found[$x][$y] = true; } # Python found[(x,y)] = True # parens added for clarity ``` * Lists should be used with the expectation of operations on its contents (hence the various mentions of immutability). One will want to pop, push, splice, slice, search, insert before, insert after, etc with a list. * Tuples should be a low-level representation of an object, where simple comparisons are made, or operations such as extracting the n'th element or n elements in a predictable fashion, such as the coordinates example given earlier. * Lastly, lists are not hashable, so the type of mapping done with dictionaries (hash tables in Perl, associative arrays in PHP) must be done with tuples. Here's a simple example of tuples and dictionaries, together at last: ``` """ couple is a tuple of two people doesLike is a dictionary mapping couples to True or False """ couple = "john", "jane" doesLike = dict() doesLike[couple] = True doesLike["jane", "john"] = False # unrequited love :'( ```
File size differences after copying a file to a server vía FTP
2,311
26
2008-08-05T13:40:47Z
2,316
14
2008-08-05T13:45:38Z
[ "php", "python", "ftp", "webserver" ]
I have created a PHP-script to update a webserver that is live inside a local directory. I'm migrating the script into Python. It works fine for the most part, but after a PUT command the size of the file appears to change. Thus, the size of the file is different from that of the file on the server. Once I download again the file from the FTP server, the only difference is the CR/LF mark. This annoys me because the same script is comparing the size of the files to update. Also, in case it means anything, the script works perfectly in PHP vía ftp\_put. ``` from ftplib import FTP ftpserver = "myserver" ftpuser = "myuser" ftppass = "mypwd" locfile = "g:/test/style.css" ftpfile = "/temp/style.css" try: ftp = FTP(ftpserver, ftpuser, ftppass) except: exit ("Cannot connect") f = open (locfile, "r") try: ftp.delete (ftpfile) except: pass # ftp.sendcmd ("TYPE I") # ftp.storlines("STOR %s" % ftpfile, f) ftp.storbinary("STOR %s" % ftpfile, f) f.close() ftp.dir (ftpfile) ftp.quit() ``` Any suggestions?
Do you need to open the locfile in binary using `rb`? ``` f = open (locfile, "rb") ```
How can I create a directly-executable cross-platform GUI app using Python?
2,933
171
2008-08-05T22:26:00Z
2,937
189
2008-08-05T22:34:25Z
[ "python", "user-interface", "deployment", "tkinter", "release-management" ]
Python works on multiple platforms and can be used for desktop and web applications, thus I conclude that there is some way to compile it into an executable for Mac, Windows and Linux. The problem being I have no idea where to start or how to write a GUI with it, can anybody shed some light on this and point me in the right direction please?
First you will need some GUI library with Python bindings and then (if you want) some program that will convert your python scripts into standalone executables. **Cross-platform GUI libraries with Python bindings (Windows, Linux, Mac)** Of course, there are many, but the most popular that I've seen in wild are: * [Tkinter](http://wiki.python.org/moin/TkInter) - based on [Tk GUI toolkit](http://www.tcl.tk/) (de-facto standard GUI library for python, free for commercial projects) * [WxPython](http://www.wxpython.org/) - based on [WxWidgets](http://www.wxwidgets.org/) (very popular, free for commercial projects) * [PyQt](http://www.riverbankcomputing.co.uk/news) - based on [Qt](http://trolltech.com/products/qt/) (also very popular and more stable than WxWidgets but costly license for commercial projects) Complete list is at <http://wiki.python.org/moin/GuiProgramming> **Single executable (Windows)** * [py2exe](http://www.py2exe.org/) - Probably the most popular out there ([PyInstaller](http://stackoverflow.com/questions/2933/an-executable-python-app/31859#31859) is also gaining in popularity) **Single executable (Linux)** * [Freeze](http://wiki.python.org/moin/Freeze) - works the same way like py2exe but targets Linux platform **Single executable (Mac)** * [py2app](https://pythonhosted.org/py2app/) - again, works like py2exe but targets Mac OS
How can I create a directly-executable cross-platform GUI app using Python?
2,933
171
2008-08-05T22:26:00Z
12,166
13
2008-08-15T11:56:02Z
[ "python", "user-interface", "deployment", "tkinter", "release-management" ]
Python works on multiple platforms and can be used for desktop and web applications, thus I conclude that there is some way to compile it into an executable for Mac, Windows and Linux. The problem being I have no idea where to start or how to write a GUI with it, can anybody shed some light on this and point me in the right direction please?
An alternative tool to py2exe is [bbfreeze](http://pypi.python.org/pypi/bbfreeze/) which generates executables for windows and linux. It's newer than py2exe and handles eggs quite well. I've found it magically works better without configuration for a wide variety of applications.
How can I create a directly-executable cross-platform GUI app using Python?
2,933
171
2008-08-05T22:26:00Z
31,859
39
2008-08-28T08:41:45Z
[ "python", "user-interface", "deployment", "tkinter", "release-management" ]
Python works on multiple platforms and can be used for desktop and web applications, thus I conclude that there is some way to compile it into an executable for Mac, Windows and Linux. The problem being I have no idea where to start or how to write a GUI with it, can anybody shed some light on this and point me in the right direction please?
Another system (not mentioned in the accepted answer yet) is PyInstaller, which worked for a PyQt project of mine when py2exe would not. I found it easier to use. <http://www.pyinstaller.org/> Pyinstaller is based on Gordon McMillan's Python Installer. Which is no longer available.
How can I create a directly-executable cross-platform GUI app using Python?
2,933
171
2008-08-05T22:26:00Z
265,570
7
2008-11-05T15:53:19Z
[ "python", "user-interface", "deployment", "tkinter", "release-management" ]
Python works on multiple platforms and can be used for desktop and web applications, thus I conclude that there is some way to compile it into an executable for Mac, Windows and Linux. The problem being I have no idea where to start or how to write a GUI with it, can anybody shed some light on this and point me in the right direction please?
There's also [PyGTK](http://pygtk.org/), which is basically a Python wrapper for the Gnome Toolkit. I've found it easier to wrap my mind around than Tkinter, coming from pretty much no knowledge of GUI programming previously. It works pretty well and has some good tutorials. Unfortunately there isn't an installer for Python 2.6 for Windows yet, and may not be for a while.
Calling a function of a module from a string with the function's name in Python
3,061
761
2008-08-06T03:36:08Z
3,071
925
2008-08-06T03:57:16Z
[ "python" ]
What is the best way to go about calling a function given a string with the function's name in a Python program. For example, let's say that I have a module `foo`, and I have a string whose contents are `"bar"`. What is the best way to go about calling `foo.bar()`? I need to get the return value of the function, which is why I don't just use `eval`. I figured out how to do it by using `eval` to define a temp function that returns the result of that function call, but I'm hoping that there is a more elegant way to do this.
Assuming module `foo` with method `bar`: ``` import foo methodToCall = getattr(foo, 'bar') result = methodToCall() ``` As far as that goes, lines 2 and 3 can be compressed to: ``` result = getattr(foo, 'bar')() ``` if that makes more sense for your use case. You can use `getattr` in this fashion on class instance bound methods, module-level methods, class methods... the list goes on.
Calling a function of a module from a string with the function's name in Python
3,061
761
2008-08-06T03:36:08Z
4,605
145
2008-08-07T11:35:23Z
[ "python" ]
What is the best way to go about calling a function given a string with the function's name in a Python program. For example, let's say that I have a module `foo`, and I have a string whose contents are `"bar"`. What is the best way to go about calling `foo.bar()`? I need to get the return value of the function, which is why I don't just use `eval`. I figured out how to do it by using `eval` to define a temp function that returns the result of that function call, but I'm hoping that there is a more elegant way to do this.
Patrick's solution is probably the cleanest. If you need to dynamically pick up the module as well, you can import it like: ``` m = __import__ ('foo') func = getattr(m,'bar') func() ```
Calling a function of a module from a string with the function's name in Python
3,061
761
2008-08-06T03:36:08Z
834,451
266
2009-05-07T12:45:13Z
[ "python" ]
What is the best way to go about calling a function given a string with the function's name in a Python program. For example, let's say that I have a module `foo`, and I have a string whose contents are `"bar"`. What is the best way to go about calling `foo.bar()`? I need to get the return value of the function, which is why I don't just use `eval`. I figured out how to do it by using `eval` to define a temp function that returns the result of that function call, but I'm hoping that there is a more elegant way to do this.
``` locals()["myfunction"]() ``` or ``` globals()["myfunction"]() ``` [locals](http://docs.python.org/library/functions.html#locals) returns a dictionary with a current local symbol table. [globals](http://docs.python.org/library/functions.html#globals) returns a dictionary with global symbol table.
Calling a function of a module from a string with the function's name in Python
3,061
761
2008-08-06T03:36:08Z
9,272,378
12
2012-02-14T05:55:36Z
[ "python" ]
What is the best way to go about calling a function given a string with the function's name in a Python program. For example, let's say that I have a module `foo`, and I have a string whose contents are `"bar"`. What is the best way to go about calling `foo.bar()`? I need to get the return value of the function, which is why I don't just use `eval`. I figured out how to do it by using `eval` to define a temp function that returns the result of that function call, but I'm hoping that there is a more elegant way to do this.
For what it's worth, if you needed to pass the function (or class) name and app name as a string, then you could do this: ``` myFnName = "MyFn" myAppName = "MyApp" app = sys.modules[myAppName] fn = getattr(app,myFnName) ```
Calling a function of a module from a string with the function's name in Python
3,061
761
2008-08-06T03:36:08Z
12,025,554
46
2012-08-19T09:40:43Z
[ "python" ]
What is the best way to go about calling a function given a string with the function's name in a Python program. For example, let's say that I have a module `foo`, and I have a string whose contents are `"bar"`. What is the best way to go about calling `foo.bar()`? I need to get the return value of the function, which is why I don't just use `eval`. I figured out how to do it by using `eval` to define a temp function that returns the result of that function call, but I'm hoping that there is a more elegant way to do this.
Just a simple contribution. If the class that we need to instance is in the same file, we can use something like this: ``` # Get class from globals and create an instance m = globals()['our_class']() # Get the function (from the instance) that we need to call func = getattr(m, 'function_name') # Call it func() ``` For example: ``` class A: def __init__(self): pass def sampleFunc(self, arg): print('you called sampleFunc({})'.format(arg)) m = globals()['A']() func = getattr(m, 'sampleFunc') func('sample arg') # Sample, all on one line getattr(globals()['A'](), 'sampleFunc')('sample arg') ``` And, if not a class: ``` def sampleFunc(arg): print('you called sampleFunc({})'.format(arg)) globals()['sampleFunc']('sample arg') ```
Calling a function of a module from a string with the function's name in Python
3,061
761
2008-08-06T03:36:08Z
14,072,943
8
2012-12-28T16:56:45Z
[ "python" ]
What is the best way to go about calling a function given a string with the function's name in a Python program. For example, let's say that I have a module `foo`, and I have a string whose contents are `"bar"`. What is the best way to go about calling `foo.bar()`? I need to get the return value of the function, which is why I don't just use `eval`. I figured out how to do it by using `eval` to define a temp function that returns the result of that function call, but I'm hoping that there is a more elegant way to do this.
none of what was suggested helped me. I did discover this though. ``` <object>.__getattribute__(<string name>)(<params>) ``` I am using python 2.66 Hope this helps
Calling a function of a module from a string with the function's name in Python
3,061
761
2008-08-06T03:36:08Z
19,393,328
39
2013-10-16T00:24:22Z
[ "python" ]
What is the best way to go about calling a function given a string with the function's name in a Python program. For example, let's say that I have a module `foo`, and I have a string whose contents are `"bar"`. What is the best way to go about calling `foo.bar()`? I need to get the return value of the function, which is why I don't just use `eval`. I figured out how to do it by using `eval` to define a temp function that returns the result of that function call, but I'm hoping that there is a more elegant way to do this.
Given a string, with a complete python path to a function, this is how I went about getting the result of said function: ``` import importlib function_string = 'mypackage.mymodule.myfunc' mod_name, func_name = function_string.rsplit('.',1) mod = importlib.import_module(mod_name) func = getattr(mod, func_name) result = func() ```
Calling a function of a module from a string with the function's name in Python
3,061
761
2008-08-06T03:36:08Z
22,959,509
17
2014-04-09T10:17:41Z
[ "python" ]
What is the best way to go about calling a function given a string with the function's name in a Python program. For example, let's say that I have a module `foo`, and I have a string whose contents are `"bar"`. What is the best way to go about calling `foo.bar()`? I need to get the return value of the function, which is why I don't just use `eval`. I figured out how to do it by using `eval` to define a temp function that returns the result of that function call, but I'm hoping that there is a more elegant way to do this.
The answer (I hope) no one ever wanted Eval like behavior ``` getattr(locals().get("foo") or globals().get("foo"), "bar")() ``` Why not add auto-importing ``` getattr( locals().get("foo") or globals().get("foo") or __import__("foo"), "bar")() ``` In case we have extra dictionaries we want to check ``` getattr(next((x for x in (f("foo") for f in [locals().get, globals().get, self.__dict__.get, __import__]) if x)), "bar")() ``` We need to go deeper ``` getattr(next((x for x in (f("foo") for f in ([locals().get, globals().get, self.__dict__.get] + [d.get for d in (list(dd.values()) for dd in [locals(),globals(),self.__dict__] if isinstance(dd,dict)) if isinstance(d,dict)] + [__import__])) if x)), "bar")() ```
How to sell Python to a client/boss/person with lots of cash
4,942
5
2008-08-07T16:43:21Z
4,978
11
2008-08-07T17:04:25Z
[ "php", "python", "ruby-on-rails", "ruby" ]
When asked to create system XYZ and you ask to do it in Python over PHP or Ruby, what are the main features you can mention when they require you to explain it?
This is one of those cases that really boil down to personal preference or situational details. If you're more comfortable and experienced with Python, then say so. Are they asking you to justify it because they're more comfortable with one of the other environments? After you're done, will the system be passed off to someone else for long-term maintenance? If they ask you to use a technology or language that you're not as familiar with, then make sure they know up-front that it's going to take you longer.
How do you set up Python scripts to work in Apache 2.0?
5,102
14
2008-08-07T18:24:12Z
5,129
12
2008-08-07T18:40:53Z
[ "python", "apache", "apache2" ]
I tried to follow a couple of googled up tutorials on setting up mod\_python, but failed every time. Do you have a good, step-by step, rock-solid howto? My dev box is OS X, production - Centos.
There are two main ways of running Python on Apache. The simplest would be to use CGI and write normal Python scripts while the second is using a web framework like Django or Pylons. Using CGI is straightforward. Make sure your Apache config file has a cgi-bin set up. If not, follow their documentation (<http://httpd.apache.org/docs/2.0/howto/cgi.html>). At that point all you need to do is place your Python scripts in the cgi-bin directory and the standard output will become the HTTP response. Refer to Python's documentation for further info (<https://docs.python.org/library/cgi.html>). If you want to use a web framework you'll need to setup mod\_python or FastCGI. These steps are dependent on which framework you want to use. Django provides clear instructions on how to setup mod\_python and Django with Apache (<http://www.djangoproject.com/documentation/modpython/>)
How do you set up Python scripts to work in Apache 2.0?
5,102
14
2008-08-07T18:24:12Z
5,165
8
2008-08-07T19:02:57Z
[ "python", "apache", "apache2" ]
I tried to follow a couple of googled up tutorials on setting up mod\_python, but failed every time. Do you have a good, step-by step, rock-solid howto? My dev box is OS X, production - Centos.
Yes, mod\_python is pretty confusing to set up. Here's how I did it. In httpd.conf: ``` LoadModule python_module modules/mod_python.so <Directory "/serverbase/htdocs/myapp"> AddHandler mod_python .py PythonHandler myapp PythonDebug On ``` and in your application directory: ``` $ /serverbase/htdocs/myapp$ ls -l total 16 -r-xr-xr-x 1 root sys 6484 May 21 15:54 myapp.py ``` Repeat the configuration for each python program you wish to have running under mod\_python.
Cross Platform, Language Agnostic GUI Markup Language?
5,313
11
2008-08-07T21:07:24Z
5,319
8
2008-08-07T21:10:27Z
[ "python", "user-interface", "markup" ]
I learned Swing back in the day but now I've moved to Python and want to make some apps with GUIs. I haven't had the time to learn a new GUI API so I've been using Jython, but I would prefer to use CPython. It would be great if I can have one simple markup that allows me to switch GUI libraries. It would be even better if I can use the same markup language across languages so I can quickly make GUIs for any language I'm using. Does anyone know of such a markup/library? I've seen markups like Glade and wxWidget's markup (I forget the name). They're partly what I'm looking for (making a GUI without coding it in a language) but they're intertwined with a specific library. And neither are really nice looking or friendly to human editting.
erm.. HTML? (trying to be funny here... while we wait for real answers..)
Convert Bytes to Floating Point Numbers in Python
5,415
21
2008-08-07T22:24:27Z
5,435
13
2008-08-07T22:35:48Z
[ "python", "floating-point" ]
I have a binary file that I have to parse and I'm using Python. Is there a way to take 4 bytes and convert it to a single precision floating point number?
You'll want the [struct](https://docs.python.org/3.4/library/struct.html) package.
Convert Bytes to Floating Point Numbers in Python
5,415
21
2008-08-07T22:24:27Z
73,281
32
2008-09-16T14:59:37Z
[ "python", "floating-point" ]
I have a binary file that I have to parse and I'm using Python. Is there a way to take 4 bytes and convert it to a single precision floating point number?
``` >>> import struct >>> struct.pack('f', 3.141592654) b'\xdb\x0fI@' >>> struct.unpack('f', b'\xdb\x0fI@') (3.1415927410125732,) >>> struct.pack('4f', 1.0, 2.0, 3.0, 4.0) '\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@' ```
Python, Unicode, and the Windows console
5,419
72
2008-08-07T22:26:58Z
5,430
24
2008-08-07T22:32:23Z
[ "python", "unicode" ]
When I try to print a Unicode string in a Windows console, I get a `UnicodeEncodeError: 'charmap' codec can't encode character ....` error. I assume this is because the Windows console does not accept Unicode-only characters. What's the best way around this? Is there any way I can make Python automatically print a `?` instead of failing in this situation? **Edit:** I'm using Python 2.5. --- **Note:** @LasseV.Karlsen answer with the checkmark is sort of outdated (from 2008). Please use the solutions/answers/suggestions below with care!! [@JFSebastian answer](http://stackoverflow.com/a/32176732/610569) is more relevant as of today (6 Jan 2016).
**Note:** This answer is sort of outdated (from 2008). Please use the solution below with care!! --- Here is a page that details the problem and a solution (search the page for the text *Wrapping sys.stdout into an instance*): [PrintFails - Python Wiki](http://wiki.python.org/moin/PrintFails) Here's a code excerpt from that page: ``` $ python -c 'import sys, codecs, locale; print sys.stdout.encoding; \ sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout); \ line = u"\u0411\n"; print type(line), len(line); \ sys.stdout.write(line); print line' UTF-8 <type 'unicode'> 2 Б Б $ python -c 'import sys, codecs, locale; print sys.stdout.encoding; \ sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout); \ line = u"\u0411\n"; print type(line), len(line); \ sys.stdout.write(line); print line' | cat None <type 'unicode'> 2 Б Б ``` There's some more information on that page, well worth a read.
Python, Unicode, and the Windows console
5,419
72
2008-08-07T22:26:58Z
2,013,263
7
2010-01-06T13:38:39Z
[ "python", "unicode" ]
When I try to print a Unicode string in a Windows console, I get a `UnicodeEncodeError: 'charmap' codec can't encode character ....` error. I assume this is because the Windows console does not accept Unicode-only characters. What's the best way around this? Is there any way I can make Python automatically print a `?` instead of failing in this situation? **Edit:** I'm using Python 2.5. --- **Note:** @LasseV.Karlsen answer with the checkmark is sort of outdated (from 2008). Please use the solutions/answers/suggestions below with care!! [@JFSebastian answer](http://stackoverflow.com/a/32176732/610569) is more relevant as of today (6 Jan 2016).
The below code will make Python output to console as UTF-8 even on Windows. The console will display the characters well on Windows 7 but on Windows XP it will not display them well, but at least it will work and most important you will have a consistent output from your script on all platforms. You'll be able to redirect the output to a file. Below code was tested with Python 2.6 on Windows. ``` #!/usr/bin/python # -*- coding: UTF-8 -*- import codecs, sys reload(sys) sys.setdefaultencoding('utf-8') print sys.getdefaultencoding() if sys.platform == 'win32': try: import win32console except: print "Python Win32 Extensions module is required.\n You can download it from https://sourceforge.net/projects/pywin32/ (x86 and x64 builds are available)\n" exit(-1) # win32console implementation of SetConsoleCP does not return a value # CP_UTF8 = 65001 win32console.SetConsoleCP(65001) if (win32console.GetConsoleCP() != 65001): raise Exception ("Cannot set console codepage to 65001 (UTF-8)") win32console.SetConsoleOutputCP(65001) if (win32console.GetConsoleOutputCP() != 65001): raise Exception ("Cannot set console output codepage to 65001 (UTF-8)") #import sys, codecs sys.stdout = codecs.getwriter('utf8')(sys.stdout) sys.stderr = codecs.getwriter('utf8')(sys.stderr) print "This is an Е乂αmp١ȅ testing Unicode support using Arabic, Latin, Cyrillic, Greek, Hebrew and CJK code points.\n" ```
Python, Unicode, and the Windows console
5,419
72
2008-08-07T22:26:58Z
4,637,795
19
2011-01-09T05:07:56Z
[ "python", "unicode" ]
When I try to print a Unicode string in a Windows console, I get a `UnicodeEncodeError: 'charmap' codec can't encode character ....` error. I assume this is because the Windows console does not accept Unicode-only characters. What's the best way around this? Is there any way I can make Python automatically print a `?` instead of failing in this situation? **Edit:** I'm using Python 2.5. --- **Note:** @LasseV.Karlsen answer with the checkmark is sort of outdated (from 2008). Please use the solutions/answers/suggestions below with care!! [@JFSebastian answer](http://stackoverflow.com/a/32176732/610569) is more relevant as of today (6 Jan 2016).
Despite the other plausible-sounding answers that suggest changing the code page to 65001, that [does not work](http://bugs.python.org/issue1602). (Also, changing the default encoding using `sys.setdefaultencoding` is [not a good idea](http://stackoverflow.com/questions/3578685/how-to-display-utf-8-in-windows-console/3580165#3580165).) See [this question](http://stackoverflow.com/questions/878972/windows-cmd-encoding-change-causes-python-crash/3259271) for details and code that does work.
Python, Unicode, and the Windows console
5,419
72
2008-08-07T22:26:58Z
10,667,978
10
2012-05-19T18:48:28Z
[ "python", "unicode" ]
When I try to print a Unicode string in a Windows console, I get a `UnicodeEncodeError: 'charmap' codec can't encode character ....` error. I assume this is because the Windows console does not accept Unicode-only characters. What's the best way around this? Is there any way I can make Python automatically print a `?` instead of failing in this situation? **Edit:** I'm using Python 2.5. --- **Note:** @LasseV.Karlsen answer with the checkmark is sort of outdated (from 2008). Please use the solutions/answers/suggestions below with care!! [@JFSebastian answer](http://stackoverflow.com/a/32176732/610569) is more relevant as of today (6 Jan 2016).
If you're not interested in getting a reliable representation of the bad character(s) you might use something like this (working with python >= 2.6, including 3.x): ``` from __future__ import print_function import sys def safeprint(s): try: print(s) except UnicodeEncodeError: if sys.version_info >= (3,): print(s.encode('utf8').decode(sys.stdout.encoding)) else: print(s.encode('utf8')) safeprint(u"\N{EM DASH}") ``` The bad character(s) in the string will be converted in a representation which is printable by the Windows console.
Python, Unicode, and the Windows console
5,419
72
2008-08-07T22:26:58Z
32,176,732
13
2015-08-24T07:35:32Z
[ "python", "unicode" ]
When I try to print a Unicode string in a Windows console, I get a `UnicodeEncodeError: 'charmap' codec can't encode character ....` error. I assume this is because the Windows console does not accept Unicode-only characters. What's the best way around this? Is there any way I can make Python automatically print a `?` instead of failing in this situation? **Edit:** I'm using Python 2.5. --- **Note:** @LasseV.Karlsen answer with the checkmark is sort of outdated (from 2008). Please use the solutions/answers/suggestions below with care!! [@JFSebastian answer](http://stackoverflow.com/a/32176732/610569) is more relevant as of today (6 Jan 2016).
**Update:** [Python 3.6](https://docs.python.org/3.6/whatsnew/3.6.html#pep-528-change-windows-console-encoding-to-utf-8) implements [PEP 528: Change Windows console encoding to UTF-8](https://www.python.org/dev/peps/pep-0528/): *the default console on Windows will now accept all Unicode characters.* Internally, it uses the same Unicode API as [the `win-unicode-console` package mentioned below](https://github.com/Drekin/win-unicode-console). `print(unicode_string)` should just work now. --- > I get a `UnicodeEncodeError: 'charmap' codec can't encode character...` error. The error means that Unicode characters that you are trying to print can't be represented using the current (`chcp`) console character encoding. The codepage is often 8-bit encoding such as `cp437` that can represent only ~0x100 characters from ~1M Unicode characters: ``` >>> u"\N{EURO SIGN}".encode('cp437') Traceback (most recent call last): ... UnicodeEncodeError: 'charmap' codec can't encode character '\u20ac' in position 0: character maps to ``` > I assume this is because the Windows console does not accept Unicode-only characters. What's the best way around this? Windows console does accept Unicode characters and it can even display them (BMP only) **if the corresponding font is configured**. `WriteConsoleW()` API should be used as suggested in [@Daira Hopwood's answer](http://stackoverflow.com/a/4637795/4279). It can be called transparently i.e., you don't need to and should not modify your scripts if you use [`win-unicode-console` package](https://github.com/Drekin/win-unicode-console): ``` T:\> py -mpip install win-unicode-console T:\> py -mrun your_script.py ``` See [What's the deal with Python 3.4, Unicode, different languages and Windows?](http://stackoverflow.com/a/30551552/4279) > Is there any way I can make Python > automatically print a `?` instead of failing in this situation? If it is enough to replace all unencodable characters with `?` in your case then you could set [`PYTHONIOENCODING` envvar](https://docs.python.org/3/using/cmdline.html#envvar-PYTHONIOENCODING): ``` T:\> set PYTHONIOENCODING=:replace T:\> python3 -c "print(u'[\N{EURO SIGN}]')" [?] ``` In Python 3.6+, the encoding specified by `PYTHONIOENCODING` envvar is ignored for interactive console buffers unless `PYTHONLEGACYWINDOWSIOENCODING` envvar is set to a non-empty string.
Get size of a file before downloading in Python
5,909
28
2008-08-08T13:35:19Z
5,935
16
2008-08-08T13:47:26Z
[ "python", "urllib" ]
I'm downloading an entire directory from a web server. It works OK, but I can't figure how to get the file size before download to compare if it was updated on the server or not. Can this be done as if I was downloading the file from a FTP server? ``` import urllib import re url = "http://www.someurl.com" # Download the page locally f = urllib.urlopen(url) html = f.read() f.close() f = open ("temp.htm", "w") f.write (html) f.close() # List only the .TXT / .ZIP files fnames = re.findall('^.*<a href="(\w+(?:\.txt|.zip)?)".*$', html, re.MULTILINE) for fname in fnames: print fname, "..." f = urllib.urlopen(url + "/" + fname) #### Here I want to check the filesize to download or not #### file = f.read() f.close() f = open (fname, "w") f.write (file) f.close() ``` --- @Jon: thank for your quick answer. It works, but the filesize on the web server is slightly less than the filesize of the downloaded file. Examples: ``` Local Size Server Size 2.223.533 2.115.516 664.603 662.121 ``` It has anything to do with the CR/LF conversion?
Using the returned-urllib-object method `info()`, you can get various information on the retrived document. Example of grabbing the current Google logo: ``` >>> import urllib >>> d = urllib.urlopen("http://www.google.co.uk/logos/olympics08_opening.gif") >>> print d.info() Content-Type: image/gif Last-Modified: Thu, 07 Aug 2008 16:20:19 GMT Expires: Sun, 17 Jan 2038 19:14:07 GMT Cache-Control: public Date: Fri, 08 Aug 2008 13:40:41 GMT Server: gws Content-Length: 20172 Connection: Close ``` It's a dict, so to get the size of the file, you do `urllibobject.info()['Content-Length']` ``` print f.info()['Content-Length'] ``` And to get the size of the local file (for comparison), you can use the os.stat() command: ``` os.stat("/the/local/file.zip").st_size ```
Get size of a file before downloading in Python
5,909
28
2008-08-08T13:35:19Z
5,985
19
2008-08-08T14:21:51Z
[ "python", "urllib" ]
I'm downloading an entire directory from a web server. It works OK, but I can't figure how to get the file size before download to compare if it was updated on the server or not. Can this be done as if I was downloading the file from a FTP server? ``` import urllib import re url = "http://www.someurl.com" # Download the page locally f = urllib.urlopen(url) html = f.read() f.close() f = open ("temp.htm", "w") f.write (html) f.close() # List only the .TXT / .ZIP files fnames = re.findall('^.*<a href="(\w+(?:\.txt|.zip)?)".*$', html, re.MULTILINE) for fname in fnames: print fname, "..." f = urllib.urlopen(url + "/" + fname) #### Here I want to check the filesize to download or not #### file = f.read() f.close() f = open (fname, "w") f.write (file) f.close() ``` --- @Jon: thank for your quick answer. It works, but the filesize on the web server is slightly less than the filesize of the downloaded file. Examples: ``` Local Size Server Size 2.223.533 2.115.516 664.603 662.121 ``` It has anything to do with the CR/LF conversion?
I have reproduced what you are seeing: ``` import urllib, os link = "http://python.org" print "opening url:", link site = urllib.urlopen(link) meta = site.info() print "Content-Length:", meta.getheaders("Content-Length")[0] f = open("out.txt", "r") print "File on disk:",len(f.read()) f.close() f = open("out.txt", "w") f.write(site.read()) site.close() f.close() f = open("out.txt", "r") print "File on disk after download:",len(f.read()) f.close() print "os.stat().st_size returns:", os.stat("out.txt").st_size ``` Outputs this: ``` opening url: http://python.org Content-Length: 16535 File on disk: 16535 File on disk after download: 16535 os.stat().st_size returns: 16861 ``` What am I doing wrong here? Is os.stat().st\_size not returning the correct size? --- Edit: OK, I figured out what the problem was: ``` import urllib, os link = "http://python.org" print "opening url:", link site = urllib.urlopen(link) meta = site.info() print "Content-Length:", meta.getheaders("Content-Length")[0] f = open("out.txt", "rb") print "File on disk:",len(f.read()) f.close() f = open("out.txt", "wb") f.write(site.read()) site.close() f.close() f = open("out.txt", "rb") print "File on disk after download:",len(f.read()) f.close() print "os.stat().st_size returns:", os.stat("out.txt").st_size ``` this outputs: ``` $ python test.py opening url: http://python.org Content-Length: 16535 File on disk: 16535 File on disk after download: 16535 os.stat().st_size returns: 16535 ``` Make sure you are opening both files for binary read/write. ``` // open for binary write open(filename, "wb") // open for binary read open(filename, "rb") ```
How to use Xpath in Python?
8,692
164
2008-08-12T11:28:36Z
8,699
74
2008-08-12T11:40:13Z
[ "python", "xml", "dom", "xpath", "nodes" ]
What is the library? Is there a full implementation? How is the library used? Where is its website?
The [lxml package](http://lxml.de/) supports xpath. It seems to work pretty well, although I've had some trouble with the self:: axis. There's also [Amara](http://pypi.python.org/pypi/Amara/1.1.6), but I haven't used it personally.
How to use Xpath in Python?
8,692
164
2008-08-12T11:28:36Z
10,846
7
2008-08-14T09:48:59Z
[ "python", "xml", "dom", "xpath", "nodes" ]
What is the library? Is there a full implementation? How is the library used? Where is its website?
The latest version of [elementtree](http://effbot.org/zone/element-xpath.htm) supports XPath pretty well. Not being an XPath expert I can't say for sure if the implementation is full but it has satisfied most of my needs when working in Python. I've also use lxml and PyXML and I find etree nice because it's a standard module. NOTE: I've since found lxml and for me it's definitely the best XML lib out there for Python. It does XPath nicely as well (though again perhaps not a full implementation).
How to use Xpath in Python?
8,692
164
2008-08-12T11:28:36Z
27,974
106
2008-08-26T13:06:39Z
[ "python", "xml", "dom", "xpath", "nodes" ]
What is the library? Is there a full implementation? How is the library used? Where is its website?
[libxml2](http://xmlsoft.org/python.html) has a number of advantages: 1. Compliance to the [spec](http://www.w3.org/TR/xpath) 2. Active development and a community participation 3. Speed. This is really a python wrapper around a C implementation. 4. Ubiquity. The libxml2 library is pervasive and thus well tested. Downsides include: 1. Compliance to the [spec](http://www.w3.org/TR/xpath). It's strict. Things like default namespace handling are easier in other libraries. 2. Use of native code. This can be a pain depending on your how your application is distributed / deployed. RPMs are available that ease some of this pain. 3. Manual resource handling. Note in the sample below the calls to freeDoc() and xpathFreeContext(). This is not very Pythonic. If you are doing simple path selection, stick with [ElementTree](http://effbot.org/zone/element-xpath.htm) ( which is included in Python 2.5 ). If you need full spec compliance or raw speed and can cope with the distribution of native code, go with libxml2. **Sample of libxml2 XPath Use** --- ``` import libxml2 doc = libxml2.parseFile("tst.xml") ctxt = doc.xpathNewContext() res = ctxt.xpathEval("//*") if len(res) != 2: print "xpath query: wrong node set size" sys.exit(1) if res[0].name != "doc" or res[1].name != "foo": print "xpath query: wrong node set value" sys.exit(1) doc.freeDoc() ctxt.xpathFreeContext() ``` **Sample of ElementTree XPath Use** --- ``` from elementtree.ElementTree import ElementTree mydoc = ElementTree(file='tst.xml') for e in mydoc.findall('/foo/bar'): print e.get('title').text ``` ---
How to use Xpath in Python?
8,692
164
2008-08-12T11:28:36Z
1,732,475
35
2009-11-13T23:11:17Z
[ "python", "xml", "dom", "xpath", "nodes" ]
What is the library? Is there a full implementation? How is the library used? Where is its website?
Use LXML. LXML uses the full power of libxml2 and libxslt, but wraps them in more "Pythonic" bindings than the Python bindings that are native to those libraries. As such, it gets the full XPath 1.0 implementation. Native ElemenTree supports a limited subset of XPath, although it may be good enough for your needs.
How to use Xpath in Python?
8,692
164
2008-08-12T11:28:36Z
2,122,709
23
2010-01-23T09:30:19Z
[ "python", "xml", "dom", "xpath", "nodes" ]
What is the library? Is there a full implementation? How is the library used? Where is its website?
Another option is [py-dom-xpath](http://code.google.com/p/py-dom-xpath/), it works seamlessly with minidom and is pure Python so works on appengine. ``` import xpath xpath.find('//item', doc) ```
How to use Xpath in Python?
8,692
164
2008-08-12T11:28:36Z
3,547,741
9
2010-08-23T13:00:01Z
[ "python", "xml", "dom", "xpath", "nodes" ]
What is the library? Is there a full implementation? How is the library used? Where is its website?
You can use: **PyXML**: ``` from xml.dom.ext.reader import Sax2 from xml import xpath doc = Sax2.FromXmlFile('foo.xml').documentElement for url in xpath.Evaluate('//@Url', doc): print url.value ``` **libxml2**: ``` import libxml2 doc = libxml2.parseFile('foo.xml') for url in doc.xpathEval('//@Url'): print url.content ```
How to use Xpath in Python?
8,692
164
2008-08-12T11:28:36Z
13,504,511
30
2012-11-22T01:05:52Z
[ "python", "xml", "dom", "xpath", "nodes" ]
What is the library? Is there a full implementation? How is the library used? Where is its website?
Sounds like an lxml advertisement in here. ;) ElementTree is included in the std library. Under 2.6 and below its xpath is pretty weak, but in [2.7 much improved](http://docs.python.org/2/library/xml.etree.elementtree.html#xpath-support): ``` import xml.etree.ElementTree as ET root = ET.parse(filename) result = '' for elem in root.findall('.//child/grandchild'): # How to make decisions based on attributes even in 2.6: if elem.attrib.get('name') == 'foo': result = elem.text break ```
Accessing mp3 Meta-Data with Python
8,948
81
2008-08-12T15:16:00Z
9,358
11
2008-08-13T00:44:26Z
[ "python", "mp3", "metadata" ]
What is the best way to retrieve mp3 metadata in python? I've seen a couple frameworks out there, but I'm unsure as to which would be the best to use.... Any ideas?
What you're after is the [ID3](http://id3-py.sourceforge.net/) module. It's very simple and will give you exactly what you need. Just copy the ID3.py file into your site-packages directory and you'll be able to do something like the following: ``` from ID3 import * try: id3info = ID3('file.mp3') print id3info # Change the tags id3info['TITLE'] = "Green Eggs and Ham" id3info['ARTIST'] = "Dr. Seuss" for k, v in id3info.items(): print k, ":", v except InvalidTagError, message: print "Invalid ID3 tag:", message ```
Accessing mp3 Meta-Data with Python
8,948
81
2008-08-12T15:16:00Z
10,845
25
2008-08-14T09:46:21Z
[ "python", "mp3", "metadata" ]
What is the best way to retrieve mp3 metadata in python? I've seen a couple frameworks out there, but I'm unsure as to which would be the best to use.... Any ideas?
I've used [mutagen](https://bitbucket.org/lazka/mutagen) to edit tags in media files before. The nice thing about mutagen is that it can handle other formats, such as mp4, FLAC etc. I've written several scripts with a lot of success using this API.
Accessing mp3 Meta-Data with Python
8,948
81
2008-08-12T15:16:00Z
102,285
75
2008-09-19T14:30:41Z
[ "python", "mp3", "metadata" ]
What is the best way to retrieve mp3 metadata in python? I've seen a couple frameworks out there, but I'm unsure as to which would be the best to use.... Any ideas?
I used [eyeD3](http://eyed3.nicfit.net/) the other day with a lot of success. I found that it could add artwork to the ID3 tag which the other modules I looked at couldn't. You'll have to download the tar and execute `python setup.py install` from the source folder. Relevant examples from the website are below. Reading the contents of an mp3 file containing either v1 or v2 tag info: ``` import eyeD3 tag = eyeD3.Tag() tag.link("/some/file.mp3") print tag.getArtist() print tag.getAlbum() print tag.getTitle() ``` Read an mp3 file (track length, bitrate, etc.) and access it's tag: ``` if eyeD3.isMp3File(f): audioFile = eyeD3.Mp3AudioFile(f) tag = audioFile.getTag() ``` Specific tag versions can be selected: ``` tag.link("/some/file.mp3", eyeD3.ID3_V2) tag.link("/some/file.mp3", eyeD3.ID3_V1) tag.link("/some/file.mp3", eyeD3.ID3_ANY_VERSION) # The default. ``` Or you can iterate over the raw frames: ``` tag = eyeD3.Tag() tag.link("/some/file.mp3") for frame in tag.frames: print frame ``` Once a tag is linked to a file it can be modified and saved: ``` tag.setArtist(u"Cro-Mags") tag.setAlbum(u"Age of Quarrel") tag.update() ``` If the tag linked in was v2 and you'd like to save it as v1: ``` tag.update(eyeD3.ID3_V1_1) ``` Read in a tag and remove it from the file: ``` tag.link("/some/file.mp3") tag.remove() tag.update() ``` Add a new tag: ``` tag = eyeD3.Tag() tag.link('/some/file.mp3') # no tag in this file, link returned False tag.header.setVersion(eyeD3.ID3_V2_3) tag.setArtist('Fugazi') tag.update() ```
Accessing mp3 Meta-Data with Python
8,948
81
2008-08-12T15:16:00Z
4,559,380
7
2010-12-30T01:40:52Z
[ "python", "mp3", "metadata" ]
What is the best way to retrieve mp3 metadata in python? I've seen a couple frameworks out there, but I'm unsure as to which would be the best to use.... Any ideas?
check this one out: <https://github.com/Ciantic/songdetails> Usage example: ``` >>> import songdetails >>> song = songdetails.scan("data/song.mp3") >>> print song.duration 0:03:12 ``` Saving changes: ``` >>> import songdetails >>> song = songdetails.scan("data/commit.mp3") >>> song.artist = "Great artist" >>> song.save() ```
How do I treat an integer as an array of bytes in Python?
10,123
8
2008-08-13T17:46:41Z
10,129
10
2008-08-13T17:56:34Z
[ "python" ]
I'm trying to decode the result of the Python os.wait() function. This returns, according to the Python docs: > a tuple containing its pid and exit status indication: a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the signal number is zero); the high bit of the low byte is set if a core file was produced. How do I decode the exit status indication (which is an integer) to obtain the high and low byte? To be specific, how do I implement the decode function used in the following code snippet: ``` (pid,status) = os.wait() (exitstatus, signum) = decode(status) ```
This will do what you want: ``` signum = status & 0xff exitstatus = (status & 0xff00) >> 8 ```
How do I treat an integer as an array of bytes in Python?
10,123
8
2008-08-13T17:46:41Z
10,213
10
2008-08-13T18:52:36Z
[ "python" ]
I'm trying to decode the result of the Python os.wait() function. This returns, according to the Python docs: > a tuple containing its pid and exit status indication: a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the signal number is zero); the high bit of the low byte is set if a core file was produced. How do I decode the exit status indication (which is an integer) to obtain the high and low byte? To be specific, how do I implement the decode function used in the following code snippet: ``` (pid,status) = os.wait() (exitstatus, signum) = decode(status) ```
To answer your general question, you can use [bit manipulation](http://en.wikipedia.org/wiki/Bit_twiddling) techniques: ``` pid, status = os.wait() exitstatus, signum = status & 0xFF, (status & 0xFF00) >> 8 ``` However, there are also [built-in functions](http://docs.python.org/lib/os-process.html#l2h-2780) for interpreting exit status values: ``` pid, status = os.wait() exitstatus, signum = os.WEXITSTATUS( status ), os.WTERMSIG( status ) ``` See also: * os.WCOREDUMP() * os.WIFCONTINUED() * os.WIFSTOPPED() * os.WIFSIGNALED() * os.WIFEXITED() * os.WSTOPSIG()
How should I unit test a code-generator?
11,060
18
2008-08-14T13:59:21Z
11,074
8
2008-08-14T14:04:25Z
[ "c++", "python", "unit-testing", "code-generation", "swig" ]
This is a difficult and open-ended question I know, but I thought I'd throw it to the floor and see if anyone had any interesting suggestions. I have developed a code-generator that takes our python interface to our C++ code (generated via SWIG) and generates code needed to expose this as WebServices. When I developed this code I did it using TDD, but I've found my tests to be brittle as hell. Because each test essentially wanted to verify that for a given bit of input code (which happens to be a C++ header) I'd get a given bit of outputted code I wrote a small engine that reads test definitions from XML input files and generates test cases from these expectations. The problem is I dread going in to modify the code at all. That and the fact that the unit tests themselves are a: complex, and b: brittle. So I'm trying to think of alternative approaches to this problem, and it strikes me I'm perhaps tackling it the wrong way. Maybe I need to focus more on the outcome, IE: does the code I generate actually run and do what I want it to, rather than, does the code look the way I want it to. Has anyone got any experiences of something similar to this they would care to share?
I started writing up a summary of my experience with my own code generator, then went back and re-read your question and found you had already touched upon the same issues yourself, focus on the execution results instead of the code layout/look. Problem is, this is hard to test, the generated code might not be suited to actually run in the environment of the unit test system, and how do you encode the expected results? I've found that you need to break down the code generator into smaller pieces and unit test those. Unit testing a full code generator is more like integration testing than unit testing if you ask me.
Can you check that an exception is thrown with doctest in Python?
12,592
28
2008-08-15T18:43:17Z
12,609
45
2008-08-15T19:04:13Z
[ "python", "doctest" ]
Is it possible to write a doctest unit test that will check that an exception is raised? For example, if I have a function `foo(x)` that is supposed to raise an exception if `x<0`, how would I write the doctest for that?
Yes. You can do it. The [doctest module documentation](https://docs.python.org/3/library/doctest.html) and Wikipedia has an [example](http://en.wikipedia.org/wiki/Doctest#Example_2%3a_doctests_embedded_in_a_README.txt_file) of it. ``` >>> x Traceback (most recent call last): ... NameError: name 'x' is not defined ```
Python version of PHP's stripslashes
13,454
9
2008-08-17T01:23:50Z
13,598
10
2008-08-17T12:15:13Z
[ "python", "string", "escaping" ]
I wrote a piece of code to convert PHP's striplashes into valid Python [backslash] escapes: ``` cleaned = stringwithslashes cleaned = cleaned.replace('\\n', '\n') cleaned = cleaned.replace('\\r', '\n') cleaned = cleaned.replace('\\', '') ``` How can I condense it?
Not totally sure this is what you want, but.. ``` cleaned = stringwithslashes.decode('string_escape') ```
Python Regular Expressions to implement string unescaping
13,791
10
2008-08-17T18:20:21Z
13,943
7
2008-08-17T21:36:32Z
[ "python", "regex", "backreference" ]
I'm trying to implement string unescaping with Python regex and backreferences, and it doesn't seem to want to work very well. I'm sure it's something I'm doing wrong but I can't figure out what... ``` >>> import re >>> mystring = r"This is \n a test \r" >>> p = re.compile( "\\\\(\\S)" ) >>> p.sub( "\\1", mystring ) 'This is n a test r' >>> p.sub( "\\\\\\1", mystring ) 'This is \\n a test \\r' >>> p.sub( "\\\\1", mystring ) 'This is \\1 a test \\1' ``` I'd like to replace \\[char] with \[char], but backreferences in Python don't appear to follow the same rules they do in every other implementation I've ever used. Could someone shed some light?
Isn't that what [Anders' second example](#13844) does? In 2.5 there's also a `string-escape` encoding you can apply: ``` >>> mystring = r"This is \n a test \r" >>> mystring.decode('string-escape') 'This is \n a test \r' >>> print mystring.decode('string-escape') This is a test >>> ```
Can you explain closures (as they relate to Python)?
13,857
56
2008-08-17T19:14:30Z
13,875
37
2008-08-17T19:32:33Z
[ "python", "functional-programming", "closures" ]
I've been reading a lot about closures and I think I understand them, but without clouding the picture for myself and others, I am hoping someone can explain closures as succinctly and clearly as possible. I'm looking for a simple explanation that might help me understand where and why I would want to use them.
It's simple: A function that references variables from a containing scope, potentially after flow-of-control has left that scope. That last bit is very useful: ``` >>> def makeConstantAdder(x): ... constant = x ... def adder(y): ... return y + constant ... return adder ... >>> f = makeConstantAdder(12) >>> f(3) 15 >>> g = makeConstantAdder(4) >>> g(3) 7 ``` Note that 12 and 4 have "disappeared" inside f and g, respectively, this feature is what make f and g proper closures.
Can you explain closures (as they relate to Python)?
13,857
56
2008-08-17T19:14:30Z
13,906
13
2008-08-17T20:25:18Z
[ "python", "functional-programming", "closures" ]
I've been reading a lot about closures and I think I understand them, but without clouding the picture for myself and others, I am hoping someone can explain closures as succinctly and clearly as possible. I'm looking for a simple explanation that might help me understand where and why I would want to use them.
I like [this rough, succinct definition](http://effbot.org/zone/closure.htm): > A function that can refer to environments that are no longer active. I'd add > A closure allows you to bind variables into a function *without passing them as parameters*. Decorators which accept parameters are a common use for closures. Closures are a common implementation mechanism for that sort of "function factory". I frequently choose to use closures in the [Strategy Pattern](http://c2.com/cgi/wiki?StrategyPattern) when the strategy is modified by data at run-time. In a language that allows anonymous block definition -- e.g., Ruby, C# -- closures can be used to implement (what amount to) novel new control structures. The lack of anonymous blocks is among [the limitations of closures in Python](http://ivan.truemesh.com/archives/000411.html).
Can you explain closures (as they relate to Python)?
13,857
56
2008-08-17T19:14:30Z
24,061
11
2008-08-23T07:43:18Z
[ "python", "functional-programming", "closures" ]
I've been reading a lot about closures and I think I understand them, but without clouding the picture for myself and others, I am hoping someone can explain closures as succinctly and clearly as possible. I'm looking for a simple explanation that might help me understand where and why I would want to use them.
To be honest, I understand closures perfectly well except I've never been clear about what exactly is the thing which is the "closure" and what's so "closure" about it. I recommend you give up looking for any logic behind the choice of term. Anyway, here's my explanation: ``` def foo(): x = 3 def bar(): print x x = 5 return bar bar = foo() bar() # print 5 ``` A key idea here is that the function object returned from foo retains a hook to the local var 'x' even though 'x' has gone out of scope and should be defunct. This hook is to the var itself, not just the value that var had at the time, so when bar is called, it prints 5, not 3. Also be clear that Python 2.x has limited closure: there's no way I can modify 'x' inside 'bar' because writing 'x = bla' would declare a local 'x' in bar, not assign to 'x' of foo. This is a side-effect of Python's assignment=declaration. To get around this, Python 3.0 introduces the nonlocal keyword: ``` def foo(): x = 3 def bar(): print x def ack(): nonlocal x x = 7 x = 5 return (bar, ack) bar, ack = foo() ack() # modify x of the call to foo bar() # print 7 ```
Can you explain closures (as they relate to Python)?
13,857
56
2008-08-17T19:14:30Z
141,426
60
2008-09-26T19:28:32Z
[ "python", "functional-programming", "closures" ]
I've been reading a lot about closures and I think I understand them, but without clouding the picture for myself and others, I am hoping someone can explain closures as succinctly and clearly as possible. I'm looking for a simple explanation that might help me understand where and why I would want to use them.
[Closure on closures](http://mrevelle.blogspot.com/2006/10/closure-on-closures.html) > Objects are data with methods > attached, closures are functions with > data attached. ``` def make_counter(): i = 0 def counter(): # counter() is a closure nonlocal i i += 1 return i return counter c1 = make_counter() c2 = make_counter() print (c1(), c1(), c2(), c2()) # -> 1 2 1 2 ```
Python Sound ("Bell")
13,941
34
2008-08-17T21:33:39Z
13,949
47
2008-08-17T21:46:02Z
[ "python", "osx", "audio", "terminal" ]
I'd like to have a python program alert me when it has completed its task by making a beep noise. Currently, I use `import os` and then use a command line speech program to say "Process complete." I much rather it be a simple "bell." I know that there's a function that can be used in Cocoa apps, NSBeep, but I don't think that has much anything to do with this. I've also tried `print(\a)` but that didn't work. I'm using a Mac, if you couldn't tell by my Cocoa comment, so that may help. Thanks!
Have you tried : ``` import sys sys.stdout.write('\a') sys.stdout.flush() ``` That works for me here on Mac OS 10.5 Actually, I think your original attempt works also with a little modification: ``` print('\a') ``` (You just need the single quotes around the character sequence).
Python Sound ("Bell")
13,941
34
2008-08-17T21:33:39Z
34,482
9
2008-08-29T15:47:05Z
[ "python", "osx", "audio", "terminal" ]
I'd like to have a python program alert me when it has completed its task by making a beep noise. Currently, I use `import os` and then use a command line speech program to say "Process complete." I much rather it be a simple "bell." I know that there's a function that can be used in Cocoa apps, NSBeep, but I don't think that has much anything to do with this. I've also tried `print(\a)` but that didn't work. I'm using a Mac, if you couldn't tell by my Cocoa comment, so that may help. Thanks!
If you have PyObjC (the Python - Objective-C bridge) installed or are running on OS X 10.5's system python (which ships with PyObjC), you can do ``` from AppKit import NSBeep NSBeep() ``` to play the system alert.
Is there a python module for regex matching in zip files
14,281
3
2008-08-18T07:41:09Z
14,320
8
2008-08-18T08:19:06Z
[ "python", "regex", "zip", "text-processing" ]
I have over a million text files compressed into 40 zip files. I also have a list of about 500 model names of phones. I want to find out the number of times a particular model was mentioned in the text files. Is there any python module which can do a regex match on the files without unzipping it. Is there a simple way to solve this problem without unzipping?
There's nothing that will automatically do what you want. However, there is a python zipfile module that will make this easy to do. Here's how to iterate over the lines in the file. ``` #!/usr/bin/python import zipfile f = zipfile.ZipFile('myfile.zip') for subfile in f.namelist(): print subfile data = f.read(subfile) for line in data.split('\n'): print line ```
Regex and unicode
14,389
21
2008-08-18T09:41:14Z
14,391
14
2008-08-18T09:43:10Z
[ "python", "regex", "unicode", "character-properties" ]
I have a script that parses the filenames of TV episodes (show.name.s01e02.avi for example), grabs the episode name (from the www.thetvdb.com API) and automatically renames them into something nicer (Show Name - [01x02].avi) The script works fine, that is until you try and use it on files that have Unicode show-names (something I never really thought about, since all the files I have are English, so mostly pretty-much all fall within `[a-zA-Z0-9'\-]`) How can I allow the regular expressions to match accented characters and the likes? Currently the regex's config section looks like.. ``` config['valid_filename_chars'] = """0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@£$%^&*()_+=-[]{}"'.,<>`~? """ config['valid_filename_chars_regex'] = re.escape(config['valid_filename_chars']) config['name_parse'] = [ # foo_[s01]_[e01] re.compile('''^([%s]+?)[ \._\-]\[[Ss]([0-9]+?)\]_\[[Ee]([0-9]+?)\]?[^\\/]*$'''% (config['valid_filename_chars_regex'])), # foo.1x09* re.compile('''^([%s]+?)[ \._\-]\[?([0-9]+)x([0-9]+)[^\\/]*$''' % (config['valid_filename_chars_regex'])), # foo.s01.e01, foo.s01_e01 re.compile('''^([%s]+?)[ \._\-][Ss]([0-9]+)[\.\- ]?[Ee]([0-9]+)[^\\/]*$''' % (config['valid_filename_chars_regex'])), # foo.103* re.compile('''^([%s]+)[ \._\-]([0-9]{1})([0-9]{2})[\._ -][^\\/]*$''' % (config['valid_filename_chars_regex'])), # foo.0103* re.compile('''^([%s]+)[ \._\-]([0-9]{2})([0-9]{2,3})[\._ -][^\\/]*$''' % (config['valid_filename_chars_regex'])), ] ```
Use a subrange of [\u0000-\uFFFF] for what you want. You can also use the re.UNICODE compile flag. [The docs](http://docs.python.org/lib/re-syntax.html) say that if UNICODE is set, \w will match the characters [0-9\_] plus whatever is classified as alphanumeric in the Unicode character properties database. See also <http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-05/2560.html>.
How do I validate xml against a DTD file in Python
15,798
27
2008-08-19T06:24:54Z
15,931
28
2008-08-19T09:39:56Z
[ "python", "xml", "validation", "dtd" ]
I need to validate an XML string (and not a file) against a DTD description file. How can that be done in `python`?
Another good option is [lxml's validation](http://lxml.de/validation.html) which I find quite pleasant to use. A simple example taken from the lxml site: ``` from StringIO import StringIO from lxml import etree dtd = etree.DTD(StringIO("""<!ELEMENT foo EMPTY>""")) root = etree.XML("<foo/>") print(dtd.validate(root)) # True root = etree.XML("<foo>bar</foo>") print(dtd.validate(root)) # False print(dtd.error_log.filter_from_errors()) # <string>:1:0:ERROR:VALID:DTD_NOT_EMPTY: Element foo was declared EMPTY this one has content ```
How do I validate xml against a DTD file in Python
15,798
27
2008-08-19T06:24:54Z
270,538
7
2008-11-06T22:17:48Z
[ "python", "xml", "validation", "dtd" ]
I need to validate an XML string (and not a file) against a DTD description file. How can that be done in `python`?
from the examples directory in the libxml2 python bindings: ``` #!/usr/bin/python -u import libxml2 import sys # Memory debug specific libxml2.debugMemory(1) dtd="""<!ELEMENT foo EMPTY>""" instance="""<?xml version="1.0"?> <foo></foo>""" dtd = libxml2.parseDTD(None, 'test.dtd') ctxt = libxml2.newValidCtxt() doc = libxml2.parseDoc(instance) ret = doc.validateDtd(ctxt, dtd) if ret != 1: print "error doing DTD validation" sys.exit(1) doc.freeDoc() dtd.freeDtd() del dtd del ctxt ```
Prototyping with Python code before compiling
16,067
18
2008-08-19T12:32:38Z
28,467
10
2008-08-26T15:58:08Z
[ "python", "swig", "ctypes", "prototyping", "python-sip" ]
I have been mulling over writing a peak fitting library for a while. I know Python fairly well and plan on implementing everything in Python to begin with but envisage that I may have to re-implement some core routines in a compiled language eventually. IIRC, one of Python's original remits was as a prototyping language, however Python is pretty liberal in allowing functions, functors, objects to be passed to functions and methods, whereas I suspect the same is not true of say C or Fortran. What should I know about designing functions/classes which I envisage will have to interface into the compiled language? And how much of these potential problems are dealt with by libraries such as cTypes, bgen, [SWIG](http://www.swig.org/), [Boost.Python](http://www.boost.org/doc/libs/1_35_0/libs/python/doc/index.html), [Cython](http://cython.org/) or [Python SIP](http://www.riverbankcomputing.co.uk/software/sip/intro)? For this particular use case, (a fitting library) I imagine allowing users to define mathematical functions (Guassian, Lorentzian etc.) as Python functions which can then to be passed an interpreted by the compiled code fitting library. Passing and returning arrays is also essential.
I haven't used SWIG or SIP, but I find writing Python wrappers with [boost.python](http://www.boost.org/doc/libs/1_35_0/libs/python/doc/index.html) to be very powerful and relatively easy to use. I'm not clear on what your requirements are for passing types between C/C++ and python, but you can do that easily by either exposing a C++ type to python, or by using a generic [boost::python::object](http://www.boost.org/doc/libs/1_35_0/libs/python/doc/v2/object.html) argument to your C++ API. You can also register converters to automatically convert python types to C++ types and vice versa. If you plan use boost.python, the [tutorial](http://www.boost.org/doc/libs/1_35_0/libs/python/doc/tutorial/doc/html/index.html) is a good place to start. I have implemented something somewhat similar to what you need. I have a C++ function that accepts a python function and an image as arguments, and applies the python function to each pixel in the image. ``` Image* unary(boost::python::object op, Image& im) { Image* out = new Image(im.width(), im.height(), im.channels()); for(unsigned int i=0; i<im.size(); i++) { (*out)[i] == extract<float>(op(im[i])); } return out; } ``` In this case, Image is a C++ object exposed to python (an image with float pixels), and op is a python defined function (or really any python object with a \_\_call\_\_ attribute). You can then use this function as follows (assuming unary is located in the called image that also contains Image and a load function): ``` import image im = image.load('somefile.tiff') double_im = image.unary(lambda x: 2.0*x, im) ``` As for using arrays with boost, I personally haven't done this, but I know the functionality to expose arrays to python using boost is available - [this](http://www.boost.org/doc/libs/1_35_0/libs/python/doc/v2/faq.html#question2) might be helpful.
Prototyping with Python code before compiling
16,067
18
2008-08-19T12:32:38Z
1,661,276
33
2009-11-02T13:16:20Z
[ "python", "swig", "ctypes", "prototyping", "python-sip" ]
I have been mulling over writing a peak fitting library for a while. I know Python fairly well and plan on implementing everything in Python to begin with but envisage that I may have to re-implement some core routines in a compiled language eventually. IIRC, one of Python's original remits was as a prototyping language, however Python is pretty liberal in allowing functions, functors, objects to be passed to functions and methods, whereas I suspect the same is not true of say C or Fortran. What should I know about designing functions/classes which I envisage will have to interface into the compiled language? And how much of these potential problems are dealt with by libraries such as cTypes, bgen, [SWIG](http://www.swig.org/), [Boost.Python](http://www.boost.org/doc/libs/1_35_0/libs/python/doc/index.html), [Cython](http://cython.org/) or [Python SIP](http://www.riverbankcomputing.co.uk/software/sip/intro)? For this particular use case, (a fitting library) I imagine allowing users to define mathematical functions (Guassian, Lorentzian etc.) as Python functions which can then to be passed an interpreted by the compiled code fitting library. Passing and returning arrays is also essential.
Finally a question that I can really put a value answer to :). I have investigated f2py, boost.python, swig, cython and pyrex for my work (PhD in optical measurement techniques). I used swig extensively, boost.python some and pyrex and cython a lot. I also used ctypes. This is my breakdown: **Disclaimer**: This is my personal experience. I am not involved with any of these projects. **swig:** does not play well with c++. It should, but name mangling problems in the linking step was a major headache for me on linux & Mac OS X. If you have C code and want it interfaced to python, it is a good solution. I wrapped the GTS for my needs and needed to write basically a C shared library which I could connect to. I would not recommend it. **Ctypes:** I wrote a libdc1394 (IEEE Camera library) wrapper using ctypes and it was a very straigtforward experience. You can find the code on <https://launchpad.net/pydc1394>. It is a lot of work to convert headers to python code, but then everything works reliably. This is a good way if you want to interface an external library. Ctypes is also in the stdlib of python, so everyone can use your code right away. This is also a good way to play around with a new lib in python quickly. I can recommend it to interface to external libs. **Boost.Python**: Very enjoyable. If you already have C++ code of your own that you want to use in python, go for this. It is very easy to translate c++ class structures into python class structures this way. I recommend it if you have c++ code that you need in python. **Pyrex/Cython:** Use Cython, not Pyrex. Period. Cython is more advanced and more enjoyable to use. Nowadays, I do everything with cython that i used to do with SWIG or Ctypes. It is also the best way if you have python code that runs too slow. The process is absolutely fantastic: you convert your python modules into cython modules, build them and keep profiling and optimizing like it still was python (no change of tools needed). You can then apply as much (or as little) C code mixed with your python code. This is by far faster then having to rewrite whole parts of your application in C; you only rewrite the inner loop. **Timings**: ctypes has the highest call overhead (~700ns), followed by boost.python (322ns), then directly by swig (290ns). Cython has the lowest call overhead (124ns) and the best feedback where it spends time on (cProfile support!). The numbers are from my box calling a trivial function that returns an integer from an interactive shell; module import overhead is therefore not timed, only function call overhead is. It is therefore easiest and most productive to get python code fast by profiling and using cython. **Summary**: For your problem, use Cython ;). I hope this rundown will be useful for some people. I'll gladly answer any remaining question. --- **Edit**: I forget to mention: for numerical purposes (that is, connection to NumPy) use Cython; they have support for it (because they basically develop cython for this purpose). So this should be another +1 for your decision.
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
6