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
Getting key with maximum value in dictionary?
268,272
302
2008-11-06T10:49:58Z
23,428,922
10
2014-05-02T13:07:23Z
[ "python", "dictionary", "max" ]
I have a `dictionary`: keys are strings, values are integers. Example: ``` stats = {'a':1000, 'b':3000, 'c': 100} ``` I'd like to get `'b'` as an answer, since it's the key with a higher value. I did the following, using an intermediate list with reversed key-value tuples: ``` inverse = [(value, key) for key, valu...
Given that more than one entry my have the max value. I would make a list of the keys that have the max value as their value. ``` >>> stats = {'a':1000, 'b':3000, 'c': 100, 'd':3000} >>> [key for key,val in stats.iteritems() if val == max(stats.values())] ['b', 'd'] ``` This will give you 'b' and any other max key as...
Getting key with maximum value in dictionary?
268,272
302
2008-11-06T10:49:58Z
35,256,685
11
2016-02-07T17:31:32Z
[ "python", "dictionary", "max" ]
I have a `dictionary`: keys are strings, values are integers. Example: ``` stats = {'a':1000, 'b':3000, 'c': 100} ``` I'd like to get `'b'` as an answer, since it's the key with a higher value. I did the following, using an intermediate list with reversed key-value tuples: ``` inverse = [(value, key) for key, valu...
If you need to know only a key with the max value you can do it without `iterkeys` or `iteritems` because iteration through a dictionary on Python is just an iteration through a dictionary keys. ``` ddd = {'a': 3, 'b': 1} max_key = max(ddd, key=lambda k: ddd[k]) ```
How to stop BaseHTTPServer.serve_forever() in a BaseHTTPRequestHandler subclass?
268,629
22
2008-11-06T13:10:54Z
268,660
15
2008-11-06T13:21:35Z
[ "python", "http", "basehttpserver" ]
I am running my `HTTPServer` in a separate thread (using the threading module which has no way to stop threads...) and want to stop serving requests when the main thread also shuts down. The Python documentation states that `BaseHTTPServer.HTTPServer` is a subclass of `SocketServer.TCPServer`, which supports a `shutdo...
I should start by saying that "I probably wouldn't do this myself, but I have in the past". The serve\_forever (from SocketServer.py) method looks like this: ``` def serve_forever(self): """Handle one request at a time until doomsday.""" while 1: self.handle_request() ``` You could replace (in subclas...
How to stop BaseHTTPServer.serve_forever() in a BaseHTTPRequestHandler subclass?
268,629
22
2008-11-06T13:10:54Z
268,686
15
2008-11-06T13:30:25Z
[ "python", "http", "basehttpserver" ]
I am running my `HTTPServer` in a separate thread (using the threading module which has no way to stop threads...) and want to stop serving requests when the main thread also shuts down. The Python documentation states that `BaseHTTPServer.HTTPServer` is a subclass of `SocketServer.TCPServer`, which supports a `shutdo...
In my python 2.6 installation, I can call it on the underlying TCPServer - it still there inside your `HTTPServer`: ``` TCPServer.shutdown >>> import BaseHTTPServer >>> h=BaseHTTPServer.HTTPServer(('',5555), BaseHTTPServer.BaseHTTPRequestHandler) >>> h.shutdown <bound method HTTPServer.shutdown of <BaseHTTPServer.HT...
How to stop BaseHTTPServer.serve_forever() in a BaseHTTPRequestHandler subclass?
268,629
22
2008-11-06T13:10:54Z
4,020,093
8
2010-10-26T01:38:35Z
[ "python", "http", "basehttpserver" ]
I am running my `HTTPServer` in a separate thread (using the threading module which has no way to stop threads...) and want to stop serving requests when the main thread also shuts down. The Python documentation states that `BaseHTTPServer.HTTPServer` is a subclass of `SocketServer.TCPServer`, which supports a `shutdo...
I think you can use `[serverName].socket.close()`
How to stop BaseHTTPServer.serve_forever() in a BaseHTTPRequestHandler subclass?
268,629
22
2008-11-06T13:10:54Z
22,493,362
7
2014-03-18T23:38:21Z
[ "python", "http", "basehttpserver" ]
I am running my `HTTPServer` in a separate thread (using the threading module which has no way to stop threads...) and want to stop serving requests when the main thread also shuts down. The Python documentation states that `BaseHTTPServer.HTTPServer` is a subclass of `SocketServer.TCPServer`, which supports a `shutdo...
In python 2.7, calling shutdown() works but only if you are serving via serve\_forever, because it uses async select and a polling loop. Running your own loop with handle\_request() ironically excludes this functionality because it implies a dumb blocking call. From SocketServer.py's BaseServer: ``` def serve_forever...
Is there a Python library function which attempts to guess the character-encoding of some bytes?
269,060
14
2008-11-06T15:18:20Z
269,105
19
2008-11-06T15:26:25Z
[ "python", "email", "character-encoding", "invalid-characters" ]
I'm writing some mail-processing software in Python that is encountering strange bytes in header fields. I suspect this is just malformed mail; the message itself claims to be us-ascii, so I don't think there is a true encoding, but I'd like to get out a unicode string approximating the original one without throwing a ...
You may be interested in [Universal Encoding Detector](http://pypi.python.org/pypi/chardet).
Is there a Python library function which attempts to guess the character-encoding of some bytes?
269,060
14
2008-11-06T15:18:20Z
269,276
15
2008-11-06T16:13:29Z
[ "python", "email", "character-encoding", "invalid-characters" ]
I'm writing some mail-processing software in Python that is encountering strange bytes in header fields. I suspect this is just malformed mail; the message itself claims to be us-ascii, so I don't think there is a true encoding, but I'd like to get out a unicode string approximating the original one without throwing a ...
+1 for the [chardet](http://web.archive.org/web/20110709171259/http://chardet.feedparser.org/docs/faq.html) module (suggested by [`@insin`](http://stackoverflow.com/questions/269060/is-there-a-python-library-function-which-attempts-to-guess-the-character-encoding/269105#269105)). It is not in the standard library, but...
Is there a Python library function which attempts to guess the character-encoding of some bytes?
269,060
14
2008-11-06T15:18:20Z
273,631
9
2008-11-07T21:03:20Z
[ "python", "email", "character-encoding", "invalid-characters" ]
I'm writing some mail-processing software in Python that is encountering strange bytes in header fields. I suspect this is just malformed mail; the message itself claims to be us-ascii, so I don't think there is a true encoding, but I'd like to get out a unicode string approximating the original one without throwing a ...
As far as I can tell, the standard library doesn't have a function, though it's not too difficult to write one as suggested above. I think the real thing I was looking for was a way to decode a string and guarantee that it wouldn't throw an exception. The errors parameter to string.decode does that. ``` def decode(s, ...
What mime-type should I return for a python string
269,292
3
2008-11-06T16:19:58Z
269,364
8
2008-11-06T16:38:35Z
[ "python", "http", "mime-types" ]
I have a web API that returns python dictionaries or lists as a response that I eval() in python scripts that use the API, for completness I wanted to set a proper content-type but not sure what would be best to use "text/x-python" or maybe "application/python", or something else? [edit] I'm also outputting JSON, I'm ...
I doubt there's an established MIME type. Have you considered using JSON instead, it is almost the same as a Python dict, and has a better established culture of tools and techniques.
Using Python to authenticate against raw username, hash, salt in DB created by ASP.NET roles/membership
269,713
6
2008-11-06T18:14:45Z
270,670
8
2008-11-06T22:57:12Z
[ "asp.net", "python", "hash", "passwords" ]
We have a current application where user login credentials are stored in a SQL Server DB. These are, basically, stored as a plain text username, a password hash, and an associated salt for this hash. These were all created by built in functions in ASP.NET's membership/role system. Here's a row for a user named 'joe' a...
It appears python is inserting a byte order marker when you convert a UTF16 string to binary. The .NET byte array contains no BOM, so I did some ghetto python that turns the UTF16 into hex, removes the first 4 characters, then decodes it to binary. There may be a better way to rip out the BOM, but this works for me! ...
How do I find the location of Python module sources?
269,795
261
2008-11-06T18:36:52Z
269,803
25
2008-11-06T18:39:52Z
[ "python", "module" ]
How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux? I'm trying to look for the source of the `datetime` module in particular, but I'm interested in a more general answer as well.
The `sys.path` list contains the list of directories which will be searched for modules at runtime: ``` python -v >>> import sys >>> sys.path ['', '/usr/local/lib/python25.zip', '/usr/local/lib/python2.5', ... ] ```
How do I find the location of Python module sources?
269,795
261
2008-11-06T18:36:52Z
269,806
136
2008-11-06T18:40:27Z
[ "python", "module" ]
How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux? I'm trying to look for the source of the `datetime` module in particular, but I'm interested in a more general answer as well.
Running `python -v` from the command line should tell you what is being imported and from where. This works for me on Windows and Mac OS X. ``` C:\>python -v # installing zipimport hook import zipimport # builtin # installed zipimport hook # C:\Python24\lib\site.pyc has bad mtime import site # from C:\Python24\lib\sit...
How do I find the location of Python module sources?
269,795
261
2008-11-06T18:36:52Z
269,810
25
2008-11-06T18:41:56Z
[ "python", "module" ]
How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux? I'm trying to look for the source of the `datetime` module in particular, but I'm interested in a more general answer as well.
`datetime` is a builtin module, so there is no (Python) source file. For modules coming from `.py` (or `.pyc`) files, you can use `mymodule.__file__`, e.g. ``` > import random > random.__file__ 'C:\\Python25\\lib\\random.pyc' ```
How do I find the location of Python module sources?
269,795
261
2008-11-06T18:36:52Z
269,825
211
2008-11-06T18:45:33Z
[ "python", "module" ]
How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux? I'm trying to look for the source of the `datetime` module in particular, but I'm interested in a more general answer as well.
For a pure python module you can find the source by looking at `themodule.__file__`. The datetime module, however, is written in C, and therefore `datetime.__file__` points to a .so file (there is no `datetime.__file__` on Windows), and therefore, you can't see the source. If you download a python source tarball and e...
How do I find the location of Python module sources?
269,795
261
2008-11-06T18:36:52Z
2,723,437
7
2010-04-27T17:22:07Z
[ "python", "module" ]
How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux? I'm trying to look for the source of the `datetime` module in particular, but I'm interested in a more general answer as well.
Check out this [nifty "cdp" command](http://chris-lamb.co.uk/2010/04/22/locating-source-any-python-module/) to cd to the directory containing the source for the indicated Python module: ``` cdp () { cd "$(python -c "import os.path as _, ${1}; \ print _.dirname(_.realpath(${1}.__file__[:-1]))" )" } ```
How do I find the location of Python module sources?
269,795
261
2008-11-06T18:36:52Z
5,089,930
10
2011-02-23T10:56:12Z
[ "python", "module" ]
How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux? I'm trying to look for the source of the `datetime` module in particular, but I'm interested in a more general answer as well.
New in Python 3.2, you can now use e.g. `code_info()` from the dis module: <http://docs.python.org/dev/whatsnew/3.2.html#dis>
How do I find the location of Python module sources?
269,795
261
2008-11-06T18:36:52Z
5,740,458
8
2011-04-21T06:39:13Z
[ "python", "module" ]
How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux? I'm trying to look for the source of the `datetime` module in particular, but I'm interested in a more general answer as well.
In the python interpreter you could import the particular module and then type help(module). This gives details such as Name, File, Module Docs, Description et al. Ex: ``` import os help(os) Help on module os: NAME os - OS routines for Mac, NT, or Posix depending on what system we're on. FILE /usr/lib/python2....
How do I find the location of Python module sources?
269,795
261
2008-11-06T18:36:52Z
13,888,157
77
2012-12-15T00:31:15Z
[ "python", "module" ]
How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux? I'm trying to look for the source of the `datetime` module in particular, but I'm interested in a more general answer as well.
I realize this answer is 4 years late, but the existing answers are misleading people. The right way to do this is never `__file__`, or trying to walk through `sys.path` and search for yourself, etc. (unless you need to be backward compatible beyond 2.1). It's the [`inspect`](http://docs.python.org/library/inspect.ht...
How do I find the location of Python module sources?
269,795
261
2008-11-06T18:36:52Z
16,370,057
17
2013-05-04T02:40:30Z
[ "python", "module" ]
How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux? I'm trying to look for the source of the `datetime` module in particular, but I'm interested in a more general answer as well.
from the standard library try [imp.find\_module](http://docs.python.org/2/library/imp.html#imp.find_module) ``` >>> import imp >>> imp.find_module('fontTools') (None, 'C:\\Python27\\lib\\site-packages\\FontTools\\fontTools', ('', '', 5)) >>> imp.find_module('datetime') (None, 'datetime', ('', '', 6)) ```
How do I find the location of Python module sources?
269,795
261
2008-11-06T18:36:52Z
32,784,452
9
2015-09-25T14:27:58Z
[ "python", "module" ]
How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux? I'm trying to look for the source of the `datetime` module in particular, but I'm interested in a more general answer as well.
If you're using pip to install your modules, just `pip show $module` the location is returned.
Tkinter: invoke event in main loop
270,648
14
2008-11-06T22:49:44Z
276,069
21
2008-11-09T16:26:28Z
[ "python", "user-interface", "communication", "tkinter" ]
How do you invoke a tkinter `event` from a separate object? I'm looking for something like wxWidgets `wx.CallAfter`. For example, If I create an object, and pass to it my `Tk` root instance, and then try to call a method of that root window from my object, my app locks up. The best I can come up with is to use the th...
To answer your specific question of "How do you invoke a TkInter event from a separate object", use the `event_generate` command. It allows you to inject events into the event queue of the root window. Combined with Tk's powerful virtual event mechanism it becomes a handy message passing mechanism. For example: ``` f...
How do I determine all of my IP addresses when I have multiple NICs?
270,745
24
2008-11-06T23:20:28Z
274,644
30
2008-11-08T11:43:25Z
[ "python", "sockets", "ip-address" ]
I have multiple Network Interface Cards on my computer, each with its own IP address. When I use `gethostbyname(gethostname())` from Python's (built-in) `socket` module, it will only return one of them. How do I get the others?
Use the [`netifaces`](http://alastairs-place.net/netifaces/) module. Because networking is complex, using netifaces can be a little tricky, but here's how to do what you want: ``` >>> import netifaces >>> netifaces.interfaces() ['lo', 'eth0'] >>> netifaces.ifaddresses('eth0') {17: [{'broadcast': 'ff:ff:ff:ff:ff:ff', '...
Efficiently updating database using SQLAlchemy ORM
270,879
62
2008-11-07T00:24:04Z
278,606
99
2008-11-10T17:40:42Z
[ "python", "orm", "sqlalchemy" ]
I'm starting a new application and looking at using an ORM -- in particular, SQLAlchemy. Say I've got a column 'foo' in my database and I want to increment it. In straight sqlite, this is easy: ``` db = sqlite3.connect('mydata.sqlitedb') cur = db.cursor() cur.execute('update table stuff set foo = foo + 1') ``` I fig...
SQLAlchemy's ORM is meant to be used together with the SQL layer, not hide it. But you do have to keep one or two things in mind when using the ORM and plain SQL in the same transaction. Basically, from one side, ORM data modifications will only hit the database when you flush the changes from your session. From the ot...
Efficiently updating database using SQLAlchemy ORM
270,879
62
2008-11-07T00:24:04Z
4,540,110
45
2010-12-27T16:28:03Z
[ "python", "orm", "sqlalchemy" ]
I'm starting a new application and looking at using an ORM -- in particular, SQLAlchemy. Say I've got a column 'foo' in my database and I want to increment it. In straight sqlite, this is easy: ``` db = sqlite3.connect('mydata.sqlitedb') cur = db.cursor() cur.execute('update table stuff set foo = foo + 1') ``` I fig...
``` session.query(Clients).filter(Clients.id == client_id_list).update({'status': status}) session.commit() ``` Try this =)
Django - How to do tuple unpacking in a template 'for' loop
271,077
41
2008-11-07T02:40:20Z
271,128
50
2008-11-07T03:11:51Z
[ "python", "django", "templates", "tuples", "iterable-unpacking" ]
In my views.py, I'm building a list of two-tuples, where the second item in the tuple is another list, like this: ``` [ Product_Type_1, [ product_1, product_2 ], Product_Type_2, [ product_3, product_4 ]] ``` In plain old Python, I could iteration the list like this: ``` for product_type, products in list: prin...
it would be best if you construct your data like {note the '(' and ')' can be exchanged for '[' and ']' repectively, one being for tuples, one for lists} ``` [ (Product_Type_1, ( product_1, product_2 )), (Product_Type_2, ( product_3, product_4 )) ] ``` and have the template do this: ``` {% for product_type, produ...
Django - How to do tuple unpacking in a template 'for' loop
271,077
41
2008-11-07T02:40:20Z
4,756,748
48
2011-01-21T08:23:38Z
[ "python", "django", "templates", "tuples", "iterable-unpacking" ]
In my views.py, I'm building a list of two-tuples, where the second item in the tuple is another list, like this: ``` [ Product_Type_1, [ product_1, product_2 ], Product_Type_2, [ product_3, product_4 ]] ``` In plain old Python, I could iteration the list like this: ``` for product_type, products in list: prin...
Another way is as follows. If one has a list of tuples say ``` mylst = [(a, b, c), (x, y, z), (l, m, n)], ``` then one can unpack this list in the template file in the following manner. In my case I had a list of tuples which contained the URL, title, and summary of a document. ``` {\% for item in mylst \%} ...
How does one add default (hidden) values to form templates in Django?
271,244
7
2008-11-07T04:27:14Z
271,303
8
2008-11-07T05:26:25Z
[ "python", "django", "django-templates", "django-urls" ]
Given a Django.db models class: ``` class P(models.Model): type = models.ForeignKey(Type) # Type is another models.Model class name = models.CharField() ``` where one wishes to create a new P with a specified type, i.e. how does one make "type" to be a default, hidden field (from the user), where type is given ...
The widget `django.forms.widgets.HiddenInput` will render your field as hidden. In most cases, I think you'll find that any hidden form value could also be specified as a url parameter instead. In other words: ``` <form action="new/{{your_hidden_value}}" method="post"> .... </form> ``` and in urls.py: ``` ^/new/(?P...
Linking languages
271,488
15
2008-11-07T08:07:10Z
271,590
9
2008-11-07T09:14:32Z
[ "java", "c++", "python", "ruby", "perl" ]
I asked [a question](http://stackoverflow.com/questions/269417/which-language-should-i-use) earlier about which language to use for an AI prototype. The consensus seemed to be that if I want it to be fast, I need to use a language like Java or C++, but that Python / Perl / Ruby would be good for the interface bits. So...
First, a meta comment: I would highly recommend coding the entire thing in a high-level language, profiling like mad, and optimizing only where profiling shows it's necessary. First optimize the algorithm, then the code, then think about bringing in the heavy iron. Having an optimum algorithm and clean code will make t...
Linking languages
271,488
15
2008-11-07T08:07:10Z
271,642
14
2008-11-07T09:46:13Z
[ "java", "c++", "python", "ruby", "perl" ]
I asked [a question](http://stackoverflow.com/questions/269417/which-language-should-i-use) earlier about which language to use for an AI prototype. The consensus seemed to be that if I want it to be fast, I need to use a language like Java or C++, but that Python / Perl / Ruby would be good for the interface bits. So...
[Boost.Python](http://www.boost.org/doc/libs/1_36_0/libs/python/doc/tutorial/doc/html/index.html) provides an easy way to turn C++ code into Python modules. It's rather mature and works well in my experience. For example, the inevitable Hello World... ``` char const* greet() { return "hello, world"; } ``` can be e...
Interactive console using Pydev in Eclipse?
271,625
36
2008-11-07T09:34:27Z
340,875
29
2008-12-04T15:02:58Z
[ "python", "debugging", "console", "pydev", "interactive" ]
I'm debugging my Python code in Eclipse using the Pydev plugin. I'm able to open a Pydev console and it gives me two options: "Console for currently active editor" and "Python console". However none of them is useful to inspect current variable status after a breakpoint. For example, the code stopped at a breakpoint a...
This feature is documented here: <http://pydev.org/manual_adv_debug_console.html>
Interactive console using Pydev in Eclipse?
271,625
36
2008-11-07T09:34:27Z
2,117,923
13
2010-01-22T14:38:10Z
[ "python", "debugging", "console", "pydev", "interactive" ]
I'm debugging my Python code in Eclipse using the Pydev plugin. I'm able to open a Pydev console and it gives me two options: "Console for currently active editor" and "Python console". However none of them is useful to inspect current variable status after a breakpoint. For example, the code stopped at a breakpoint a...
The console that opens in the debug perspective is in fact interactive, although it took me a while to realize it. You need to hit return twice after typing something and then it gets evaluated. More info on the Pydev site here: <http://pydev.org/manual_adv_debug_console.html>
how to tell if a string is base64 or not
271,657
6
2008-11-07T09:54:34Z
271,705
7
2008-11-07T10:24:32Z
[ "python", "jython", "base64", "mime" ]
I have many emails coming in from different sources. they all have attachments, many of them have attachment names in chinese, so these names are converted to base64 by their email clients. When I receive these emails, I wish to decode the name. but there are other names which are not base64. How can I differentiate w...
@gnud, @edg - Unless I misunderstand, he's asking about the filename, not the file content @setori - the Content-Trasfer-Encoding is telling you how the CONTENT of the file is encoded, not the "filename". I'm not an expert, but this part here in the filename is telling him about the characters that follow: =?gb2312?B...
how to tell if a string is base64 or not
271,657
6
2008-11-07T09:54:34Z
271,720
21
2008-11-07T10:35:59Z
[ "python", "jython", "base64", "mime" ]
I have many emails coming in from different sources. they all have attachments, many of them have attachment names in chinese, so these names are converted to base64 by their email clients. When I receive these emails, I wish to decode the name. but there are other names which are not base64. How can I differentiate w...
The header value tells you this: ``` =?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?= "=?" introduces an encoded value "gb2312" denotes the character encoding of the original value "B" denotes that B-encoding (equal to Base64) was used (the alternative is "Q", which refers to something close to quoted-printab...
how to tell if a string is base64 or not
271,657
6
2008-11-07T09:54:34Z
271,832
12
2008-11-07T11:38:38Z
[ "python", "jython", "base64", "mime" ]
I have many emails coming in from different sources. they all have attachments, many of them have attachment names in chinese, so these names are converted to base64 by their email clients. When I receive these emails, I wish to decode the name. but there are other names which are not base64. How can I differentiate w...
> Please note both `Content-Transfer-Encoding` have base64 Not relevant in this case, the `Content-Transfer-Encoding` only applies to the body payload, not to the headers. ``` =?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?= ``` That's an **RFC2047**-encoded header atom. The stdlib function to decode it is `email.header.decode...
How should I stress test / load test a client server application?
271,825
12
2008-11-07T11:35:00Z
271,839
8
2008-11-07T11:44:40Z
[ "python", "database", "client-server", "load-testing", "stress-testing" ]
I develop a client-server style, database based system and I need to devise a way to stress / load test the system. Customers inevitably want to know such things as: • How many clients can a server support? • How many concurrent searches can a server support? • How much data can we store in the database? â...
**Test 1**: Connect and Disconnect clients like mad, to see how well you handle the init and end of sessions, and just how much your server will survive under spikes, also while doing this measure how many clients fail to connect. That is very important **Test 2**: Connect clients and keep them logged on for say a wee...
How to scan a webpage and get images and youtube embeds?
271,855
2
2008-11-07T11:55:41Z
271,860
7
2008-11-07T11:58:27Z
[ "python", "web-applications", "screen-scraping" ]
I am building a web app where I need to get all the images and any flash videos that are embedded (e.g. youtube) on a given URL. I'm using Python. I've googled, but have not found any good information about this (probably because I don't know what this is called to search for), does anyone have any experience with thi...
[BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) is a great screen-scraping library. Use urllib2 to fetch the page, and BeautifulSoup to parse it apart. Here's a code sample from their docs: ``` import urllib2 from BeautifulSoup import BeautifulSoup page = urllib2.urlopen("http://www.icc-ccs.org/prc/pir...
Generating a WSDL using Python and SOAPpy
273,002
11
2008-11-07T18:05:08Z
276,994
8
2008-11-10T03:25:11Z
[ "python", "soap", "wsdl", "soappy", "zsi" ]
First of all, I will admit I am a novice to web services, although I'm familiar with HTML and basic web stuff. I created a quick-and-dirty web service using Python that calls a stored procedure in a MySQL database, that simply returns a BIGINT value. I want to return this value in the web service, and I want to generat...
When I tried to write Python web service last year, I ended up using [ZSI-2.0](http://pywebsvcs.sourceforge.net/) (which is something like heir of SOAPpy) and a [paper available on its web](http://pywebsvcs.sourceforge.net/holger.pdf). Basically I wrote my WSDL file by hand and then used ZSI stuff to generate stubs fo...
How to check if a directory exists and create it if necessary?
273,192
1,739
2008-11-07T18:56:45Z
273,206
10
2008-11-07T19:00:01Z
[ "python", "exception", "directory" ]
What is the most elegant way to check if the directory a file is going to be written to exists, and if not, create the directory using Python? Here is what I tried: ``` filename = "/my/directory/filename.txt" dir = os.path.dirname(filename) try: os.stat(dir) except: os.mkdir(dir) f = file(filename) ``...
Try the [`os.path.exists`](https://docs.python.org/2/library/os.path.html#os.path.exists) function ``` if not os.path.exists(dir): os.mkdir(dir) ```
How to check if a directory exists and create it if necessary?
273,192
1,739
2008-11-07T18:56:45Z
273,208
40
2008-11-07T19:01:25Z
[ "python", "exception", "directory" ]
What is the most elegant way to check if the directory a file is going to be written to exists, and if not, create the directory using Python? Here is what I tried: ``` filename = "/my/directory/filename.txt" dir = os.path.dirname(filename) try: os.stat(dir) except: os.mkdir(dir) f = file(filename) ``...
Check out [os.makedirs](https://docs.python.org/3/library/os.html#os.makedirs): (It makes sure the complete path exists.) To handle the fact the directory might exist, catch OSError. ``` import os try: os.makedirs('./path/to/somewhere') except OSError: pass ```
How to check if a directory exists and create it if necessary?
273,192
1,739
2008-11-07T18:56:45Z
273,227
2,049
2008-11-07T19:06:07Z
[ "python", "exception", "directory" ]
What is the most elegant way to check if the directory a file is going to be written to exists, and if not, create the directory using Python? Here is what I tried: ``` filename = "/my/directory/filename.txt" dir = os.path.dirname(filename) try: os.stat(dir) except: os.mkdir(dir) f = file(filename) ``...
I see two answers with good qualities, each with a small flaw, so I will give my take on it: Try [`os.path.exists`](https://docs.python.org/2/library/os.path.html#os.path.exists), and consider [`os.makedirs`](https://docs.python.org/2/library/os.html#os.makedirs) for the creation. ``` if not os.path.exists(directory)...
How to check if a directory exists and create it if necessary?
273,192
1,739
2008-11-07T18:56:45Z
273,679
17
2008-11-07T21:23:03Z
[ "python", "exception", "directory" ]
What is the most elegant way to check if the directory a file is going to be written to exists, and if not, create the directory using Python? Here is what I tried: ``` filename = "/my/directory/filename.txt" dir = os.path.dirname(filename) try: os.stat(dir) except: os.mkdir(dir) f = file(filename) ``...
I have put the following down. It's not totally foolproof though. ``` import os dirname = 'create/me' try: os.makedirs(dirname) except OSError: if os.path.exists(dirname): # We are nearly safe pass else: # There was an error on creation, so make sure we know about it raise...
How to check if a directory exists and create it if necessary?
273,192
1,739
2008-11-07T18:56:45Z
444,023
63
2009-01-14T17:57:32Z
[ "python", "exception", "directory" ]
What is the most elegant way to check if the directory a file is going to be written to exists, and if not, create the directory using Python? Here is what I tried: ``` filename = "/my/directory/filename.txt" dir = os.path.dirname(filename) try: os.stat(dir) except: os.mkdir(dir) f = file(filename) ``...
I would personally recommend that you use `os.path.isdir()` to test instead of `os.path.exists()`. ``` >>> os.path.exists('/tmp/dirname') True >>> os.path.exists('/tmp/dirname/filename.etc') True >>> os.path.isdir('/tmp/dirname/filename.etc') False >>> os.path.isdir('/tmp/fakedirname') False ``` If you have: ``` >>>...
How to check if a directory exists and create it if necessary?
273,192
1,739
2008-11-07T18:56:45Z
5,032,238
434
2011-02-17T17:17:25Z
[ "python", "exception", "directory" ]
What is the most elegant way to check if the directory a file is going to be written to exists, and if not, create the directory using Python? Here is what I tried: ``` filename = "/my/directory/filename.txt" dir = os.path.dirname(filename) try: os.stat(dir) except: os.mkdir(dir) f = file(filename) ``...
Using try except and the right error code from errno module gets rid of the race condition and is cross-platform: ``` import os import errno def make_sure_path_exists(path): try: os.makedirs(path) except OSError as exception: if exception.errno != errno.EEXIST: raise ``` In other ...
How to check if a directory exists and create it if necessary?
273,192
1,739
2008-11-07T18:56:45Z
14,364,249
327
2013-01-16T17:31:19Z
[ "python", "exception", "directory" ]
What is the most elegant way to check if the directory a file is going to be written to exists, and if not, create the directory using Python? Here is what I tried: ``` filename = "/my/directory/filename.txt" dir = os.path.dirname(filename) try: os.stat(dir) except: os.mkdir(dir) f = file(filename) ``...
### Python 2.7: While a naive solution may first use [`os.path.isdir`](https://docs.python.org/2/library/os.path.html#os.path.isdir "os.path.isdir") followed by [`os.makedirs`](https://docs.python.org/2/library/os.html#os.makedirs "os.makedirs"), the solution below reverses the order of the two operations. In doing so...
How to check if a directory exists and create it if necessary?
273,192
1,739
2008-11-07T18:56:45Z
28,100,757
15
2015-01-22T23:49:18Z
[ "python", "exception", "directory" ]
What is the most elegant way to check if the directory a file is going to be written to exists, and if not, create the directory using Python? Here is what I tried: ``` filename = "/my/directory/filename.txt" dir = os.path.dirname(filename) try: os.stat(dir) except: os.mkdir(dir) f = file(filename) ``...
# Insights on the specifics of this situation You give a particular file at a certain path and you pull the directory from the file path. Then after making sure you have the directory, you attempt to open a file for reading. To comment on this code: > ``` > filename = "/my/directory/filename.txt" > dir = os.path.dirn...
How to check if a directory exists and create it if necessary?
273,192
1,739
2008-11-07T18:56:45Z
28,997,083
7
2015-03-11T20:50:01Z
[ "python", "exception", "directory" ]
What is the most elegant way to check if the directory a file is going to be written to exists, and if not, create the directory using Python? Here is what I tried: ``` filename = "/my/directory/filename.txt" dir = os.path.dirname(filename) try: os.stat(dir) except: os.mkdir(dir) f = file(filename) ``...
In Python 3.4 you can also use the [brand new `pathlib` module](https://docs.python.org/3/library/pathlib.html): ``` from pathlib import Path path = Path("/my/directory/filename.txt") try: if not path.parent.exists(): path.parent.mkdir(parents=True) except OSError: # handle error; you can also catch sp...
Python 3.0 and language evolution
273,524
13
2008-11-07T20:23:14Z
273,571
16
2008-11-07T20:37:22Z
[ "python", "programming-languages", "python-3.x" ]
Python 3.0 breaks backwards compatibility with previous versions and splits the language into two paths (at least temporarily). Do you know of any other language that went through such a major design phase while in maturity? Also, do you believe that this is how programming languages should evolve or is the price to p...
The only language I can think of to attempt such a mid-stream change would be Perl. Of course, Python is beating Perl to that particular finish line by releasing first. It should be noted, however, that Perl's changes are much more extensive than Python's and likely will be harder to detangle. (There's a price for Per...
Python 3.0 and language evolution
273,524
13
2008-11-07T20:23:14Z
273,576
9
2008-11-07T20:37:50Z
[ "python", "programming-languages", "python-3.x" ]
Python 3.0 breaks backwards compatibility with previous versions and splits the language into two paths (at least temporarily). Do you know of any other language that went through such a major design phase while in maturity? Also, do you believe that this is how programming languages should evolve or is the price to p...
The python team has worked very hard to make the lack of backward compatibility as painless as possible, to the point where the 2.6 release of python was created with a mind towards a painless upgrade process. Once you have upgraded to 2.6 there are scripts that you can run that will move you to 3.0 without issue.
Python 3.0 and language evolution
273,524
13
2008-11-07T20:23:14Z
273,661
7
2008-11-07T21:17:04Z
[ "python", "programming-languages", "python-3.x" ]
Python 3.0 breaks backwards compatibility with previous versions and splits the language into two paths (at least temporarily). Do you know of any other language that went through such a major design phase while in maturity? Also, do you believe that this is how programming languages should evolve or is the price to p...
It's worth mentioning that backward compatibility incurs costs of its own. In some cases it's almost impossible to evolve a language in the ideal way if 100% backward compatibility is required. Java's implementation of generics (which erases type information at compile-time in order to be backwardly-compatible) is a go...
Python 3.0 and language evolution
273,524
13
2008-11-07T20:23:14Z
273,688
13
2008-11-07T21:25:59Z
[ "python", "programming-languages", "python-3.x" ]
Python 3.0 breaks backwards compatibility with previous versions and splits the language into two paths (at least temporarily). Do you know of any other language that went through such a major design phase while in maturity? Also, do you believe that this is how programming languages should evolve or is the price to p...
The price of insisting on near-absolute backwards compatibility is just too high. Spend two minutes programming in C++ if you want to see why.
python, basic question on loops
273,612
2
2008-11-07T20:55:33Z
273,618
13
2008-11-07T20:58:56Z
[ "python", "loops" ]
It's a really basic question but i can't think at the second. How do i set up a loop that asks each time the function inside runs whether to do it again. So it runs it then says something like; "loop again? y/n"
``` while True: func() answer = raw_input( "Loop again? " ) if answer != 'y': break ```
Is there a cross-platform way of getting information from Python's OSError?
273,698
31
2008-11-07T21:30:18Z
273,872
48
2008-11-07T22:39:59Z
[ "python", "exception", "cross-platform" ]
On a simple directory creation operation for example, I can make an OSError like this: (Ubuntu Linux) ``` >>> import os >>> os.mkdir('foo') >>> os.mkdir('foo') Traceback (most recent call last): File "<stdin>", line 1, in <module> OSError: [Errno 17] File exists: 'foo' ``` Now I can catch that error like this: ``...
The `errno` attribute on the error should be the same on all platforms. You will get `WindowsError` exceptions on Windows, but since this is a subclass of OSError the same "`except OSError:`" block will catch it. Windows does have its own error codes, and these are accessible as `.winerror`, but the `.errno` attribute ...
How do I resize an image using PIL and maintain its aspect ratio?
273,946
196
2008-11-07T23:08:04Z
273,962
246
2008-11-07T23:15:37Z
[ "python", "image", "python-imaging-library", "thumbnails" ]
Is there an obvious way to do this that I'm missing? I'm just trying to make thumbnails.
Define a maximum size. Then, compute a resize ratio by taking `min(maxwidth/width, maxheight/height)`. The proper size is `oldsize*ratio`. There is of course also a library method to do this: the method `Image.thumbnail`. Below is an (edited) example from the [PIL documentation](http://effbot.org/imagingbook/introd...
How do I resize an image using PIL and maintain its aspect ratio?
273,946
196
2008-11-07T23:08:04Z
364,789
9
2008-12-13T03:43:00Z
[ "python", "image", "python-imaging-library", "thumbnails" ]
Is there an obvious way to do this that I'm missing? I'm just trying to make thumbnails.
If you are trying to maintain the same aspect ratio, then wouldn't you resize by some percentage of the original size? For example, half the original size ``` half = 0.5 out = im.resize( [int(half * s) for s in im.size] ) ```
How do I resize an image using PIL and maintain its aspect ratio?
273,946
196
2008-11-07T23:08:04Z
451,580
77
2009-01-16T19:12:07Z
[ "python", "image", "python-imaging-library", "thumbnails" ]
Is there an obvious way to do this that I'm missing? I'm just trying to make thumbnails.
This script will resize an image (somepic.jpg) using PIL (Python Imaging Library) to a width of 300 pixels and a height proportional to the new width. It does this by determining what percentage 300 pixels is of the original width (img.size[0]) and then multiplying the original height (img.size[1]) by that percentage. ...
How do I resize an image using PIL and maintain its aspect ratio?
273,946
196
2008-11-07T23:08:04Z
940,368
39
2009-06-02T16:03:07Z
[ "python", "image", "python-imaging-library", "thumbnails" ]
Is there an obvious way to do this that I'm missing? I'm just trying to make thumbnails.
I also recommend using PIL's thumbnail method, because it removes all the ratio hassles from you. One important hint, though: Replace ``` im.thumbnail(size) ``` with ``` im.thumbnail(size,Image.ANTIALIAS) ``` by default, PIL uses the Image.NEAREST filter for resizing which results in good performance, but poor qua...
How do I resize an image using PIL and maintain its aspect ratio?
273,946
196
2008-11-07T23:08:04Z
12,718,182
16
2012-10-03T23:11:39Z
[ "python", "image", "python-imaging-library", "thumbnails" ]
Is there an obvious way to do this that I'm missing? I'm just trying to make thumbnails.
PIL already has the option to crop an image ``` img = ImageOps.fit(img, size, Image.ANTIALIAS) ```
How to copy a file in Python with a progress bar?
274,493
8
2008-11-08T07:21:53Z
274,497
14
2008-11-08T07:28:43Z
[ "python", "file-io" ]
When copying large files using `shutil.copy()`, you get no indication of how the operation is progressing.. I have put together something that works - it uses a simple ProgressBar class (which simple returns a simple ASCII progress bar, as a string), and a loop of `open().read()` and `.write()` to do the actual copyin...
Two things: * I would make the default block size a *lot* larger than 512. I would start with 16384 and perhaps more. * For modularity, it might be better to have the `copy_with_prog` function not output the progress bar itself, but call a callback function so the caller can decide how to display the progress. Perhap...
How can I remove (chomp) a newline in Python?
275,018
959
2008-11-08T18:25:24Z
275,025
963
2008-11-08T18:31:53Z
[ "python", "newline" ]
What is the Python equivalent of Perl's `chomp` function, which removes the last character of a value?
Try the [rstrip](http://docs.python.org/2/library/stdtypes.html#str.rstrip) method. ``` >>> 'test string\n'.rstrip() 'test string' ``` Note that Python's rstrip method strips *all* kinds of trailing whitespace by default, not just one newline as Perl does with chomp. To strip only newlines: ``` >>> 'test string \n\n...
How can I remove (chomp) a newline in Python?
275,018
959
2008-11-08T18:25:24Z
275,401
100
2008-11-09T00:11:21Z
[ "python", "newline" ]
What is the Python equivalent of Perl's `chomp` function, which removes the last character of a value?
The canonical way to strip end-of-line (EOL) characters is to use the string rstrip() method removing any trailing \r or \n. Here are examples for Mac, Windows, and Unix EOL characters. ``` >>> 'Mac EOL\r'.rstrip('\r\n') 'Mac EOL' >>> 'Windows EOL\r\n'.rstrip('\r\n') 'Windows EOL' >>> 'Unix EOL\n'.rstrip('\r\n') 'Unix...
How can I remove (chomp) a newline in Python?
275,018
959
2008-11-08T18:25:24Z
275,659
113
2008-11-09T05:52:43Z
[ "python", "newline" ]
What is the Python equivalent of Perl's `chomp` function, which removes the last character of a value?
And I would say the "pythonic" way to get lines without trailing newline characters is splitlines(). ``` >>> text = "line 1\nline 2\r\nline 3\nline 4" >>> text.splitlines() ['line 1', 'line 2', 'line 3', 'line 4'] ```
How can I remove (chomp) a newline in Python?
275,018
959
2008-11-08T18:25:24Z
326,279
86
2008-11-28T17:31:34Z
[ "python", "newline" ]
What is the Python equivalent of Perl's `chomp` function, which removes the last character of a value?
Note that rstrip doesn't act exactly like Perl's chomp() because it doesn't modify the string. That is, in Perl: ``` $x="a\n"; chomp $x ``` results in `$x` being `"a"`. but in Python: ``` x="a\n" x.rstrip() ``` will mean that the value of `x` is **still** `"a\n"`. Even `x=x.rstrip()` doesn't always give the same...
How can I remove (chomp) a newline in Python?
275,018
959
2008-11-08T18:25:24Z
1,077,495
12
2009-07-03T01:49:19Z
[ "python", "newline" ]
What is the Python equivalent of Perl's `chomp` function, which removes the last character of a value?
I don't program in Python, but I came across an [FAQ](http://www.python.org/doc/faq/programming/#is-there-an-equivalent-to-perl-s-chomp-for-removing-trailing-newlines-from-strings) at python.org advocating S.rstrip("\r\n") for python 2.2 or later.
How can I remove (chomp) a newline in Python?
275,018
959
2008-11-08T18:25:24Z
2,396,894
39
2010-03-07T16:07:27Z
[ "python", "newline" ]
What is the Python equivalent of Perl's `chomp` function, which removes the last character of a value?
I might use something like this: ``` import os s = s.rstrip(os.linesep) ``` I think the problem with `rstrip("\n")` is that you'll probably want to make sure the line separator is portable. (some antiquated systems are rumored to use `"\r\n"`). The other gotcha is that `rstrip` will strip out repeated whitespace. Hop...
How can I remove (chomp) a newline in Python?
275,018
959
2008-11-08T18:25:24Z
5,764,202
14
2011-04-23T12:42:25Z
[ "python", "newline" ]
What is the Python equivalent of Perl's `chomp` function, which removes the last character of a value?
rstrip doesn't do the same thing as chomp, on so many levels. Read <http://perldoc.perl.org/functions/chomp.html> and see that chomp is very complex indeed. However, my main point is that chomp removes at most 1 line ending, whereas rstrip will remove as many as it can. Here you can see rstrip removing all the newlin...
How can I remove (chomp) a newline in Python?
275,018
959
2008-11-08T18:25:24Z
5,803,510
17
2011-04-27T11:43:20Z
[ "python", "newline" ]
What is the Python equivalent of Perl's `chomp` function, which removes the last character of a value?
Careful with `"foo".rstrip(os.linesep)`: That will only chomp the newline characters for the platform where your Python is being executed. Imagine you're chimping the lines of a Windows file under Linux, for instance: ``` $ python Python 2.7.1 (r271:86832, Mar 18 2011, 09:09:48) [GCC 4.5.0 20100604 [gcc-4_5-branch re...
How can I remove (chomp) a newline in Python?
275,018
959
2008-11-08T18:25:24Z
8,327,143
7
2011-11-30T14:04:19Z
[ "python", "newline" ]
What is the Python equivalent of Perl's `chomp` function, which removes the last character of a value?
workaround solution for special case: if the newline character is the last character (as is the case with most file inputs), then for any element in the collection you can index as follows: ``` foobar= foobar[:-1] ``` to slice out your newline character.
How can I remove (chomp) a newline in Python?
275,018
959
2008-11-08T18:25:24Z
9,507,807
15
2012-02-29T22:40:11Z
[ "python", "newline" ]
What is the Python equivalent of Perl's `chomp` function, which removes the last character of a value?
``` "line 1\nline 2\r\n...".replace('\n', '').replace('\r', '') >>> 'line 1line 2...' ``` or you could always get geekier with regexps :) have fun!
How can I remove (chomp) a newline in Python?
275,018
959
2008-11-08T18:25:24Z
16,527,062
35
2013-05-13T16:41:22Z
[ "python", "newline" ]
What is the Python equivalent of Perl's `chomp` function, which removes the last character of a value?
You may use `line = line.rstrip('\n')`. This will strip all newlines from the end of the string, not just one.
How can I remove (chomp) a newline in Python?
275,018
959
2008-11-08T18:25:24Z
19,531,239
16
2013-10-23T01:32:11Z
[ "python", "newline" ]
What is the Python equivalent of Perl's `chomp` function, which removes the last character of a value?
An [example in Python's documentation](http://docs.python.org/2/library/stdtypes.html#file.next) simply uses `line.strip()`. Perl's `chomp` function removes one linebreak sequence from the end of a string only if it's actually there. Here is how I plan to do that in Python, if `process` is conceptually the function t...
How can I remove (chomp) a newline in Python?
275,018
959
2008-11-08T18:25:24Z
21,242,117
8
2014-01-20T19:07:03Z
[ "python", "newline" ]
What is the Python equivalent of Perl's `chomp` function, which removes the last character of a value?
``` import re r_unwanted = re.compile("[\n\t\r]") r_unwanted.sub("", your_text) ```
How can I remove (chomp) a newline in Python?
275,018
959
2008-11-08T18:25:24Z
27,054,136
15
2014-11-21T04:29:07Z
[ "python", "newline" ]
What is the Python equivalent of Perl's `chomp` function, which removes the last character of a value?
you can use strip: ``` line = line.strip() ``` demo: ``` >>> "\n\n hello world \n\n".strip() 'hello world' ```
How can I remove (chomp) a newline in Python?
275,018
959
2008-11-08T18:25:24Z
28,937,424
25
2015-03-09T08:02:55Z
[ "python", "newline" ]
What is the Python equivalent of Perl's `chomp` function, which removes the last character of a value?
``` s = s.rstrip() ``` will remove all newlines at the end of the string `s`. The assignment is needed because `rstrip` returns a new string instead of modifying the original string.
How do I perform HTML decoding/encoding using Python/Django?
275,174
91
2008-11-08T20:44:30Z
275,246
89
2008-11-08T21:40:37Z
[ "python", "django", "html-encode" ]
I have a string that is html encoded: ``` &lt;img class=&quot;size-medium wp-image-113&quot; style=&quot;margin-left: 15px;&quot; title=&quot;su1&quot; src=&quot;http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg&quot; alt=&quot;&quot; width=&quot;300&quot; height=&quot;194&quot; /&gt; ``` I want to ...
Given the Django use case, there are two answers to this. Here is its `django.utils.html.escape` function, for reference: ``` def escape(html): """Returns the given HTML with ampersands, quotes and carets encoded.""" return mark_safe(force_unicode(html).replace('&', '&amp;').replace('<', '&l t;').replace('>', ...
How do I perform HTML decoding/encoding using Python/Django?
275,174
91
2008-11-08T20:44:30Z
275,463
20
2008-11-09T01:15:21Z
[ "python", "django", "html-encode" ]
I have a string that is html encoded: ``` &lt;img class=&quot;size-medium wp-image-113&quot; style=&quot;margin-left: 15px;&quot; title=&quot;su1&quot; src=&quot;http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg&quot; alt=&quot;&quot; width=&quot;300&quot; height=&quot;194&quot; /&gt; ``` I want to ...
Use daniel's solution if the set of encoded characters is relatively restricted. Otherwise, use one of the numerous HTML-parsing libraries. I like BeautifulSoup because it can handle malformed XML/HTML : <http://www.crummy.com/software/BeautifulSoup/> for your question, there's an example in their [documentation](ht...
How do I perform HTML decoding/encoding using Python/Django?
275,174
91
2008-11-08T20:44:30Z
312,538
8
2008-11-23T13:50:40Z
[ "python", "django", "html-encode" ]
I have a string that is html encoded: ``` &lt;img class=&quot;size-medium wp-image-113&quot; style=&quot;margin-left: 15px;&quot; title=&quot;su1&quot; src=&quot;http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg&quot; alt=&quot;&quot; width=&quot;300&quot; height=&quot;194&quot; /&gt; ``` I want to ...
See at the bottom of this [page at Python wiki](http://wiki.python.org/moin/EscapingHtml), there are at least 2 options to "unescape" html.
How do I perform HTML decoding/encoding using Python/Django?
275,174
91
2008-11-08T20:44:30Z
449,169
75
2009-01-16T01:12:53Z
[ "python", "django", "html-encode" ]
I have a string that is html encoded: ``` &lt;img class=&quot;size-medium wp-image-113&quot; style=&quot;margin-left: 15px;&quot; title=&quot;su1&quot; src=&quot;http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg&quot; alt=&quot;&quot; width=&quot;300&quot; height=&quot;194&quot; /&gt; ``` I want to ...
For html encoding, there's **cgi.escape** from the standard library: ``` >> help(cgi.escape) cgi.escape = escape(s, quote=None) Replace special characters "&", "<" and ">" to HTML-safe sequences. If the optional flag quote is true, the quotation mark character (") is also translated. ``` For html decoding...
How do I perform HTML decoding/encoding using Python/Django?
275,174
91
2008-11-08T20:44:30Z
7,088,472
70
2011-08-17T05:51:23Z
[ "python", "django", "html-encode" ]
I have a string that is html encoded: ``` &lt;img class=&quot;size-medium wp-image-113&quot; style=&quot;margin-left: 15px;&quot; title=&quot;su1&quot; src=&quot;http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg&quot; alt=&quot;&quot; width=&quot;300&quot; height=&quot;194&quot; /&gt; ``` I want to ...
With the standard library: * HTML Escape ``` try: from html import escape # python 3.x except ImportError: from cgi import escape # python 2.x print(escape("<")) ``` * HTML Unescape ``` try: from html import unescape # python 3.4+ except ImportError: try: from ht...
Python ctypes and function calls
275,207
7
2008-11-08T21:11:25Z
275,460
7
2008-11-09T01:06:14Z
[ "python", "c", "assembly", "ctypes", "x86-64" ]
My friend produced a small proof-of-concept assembler that worked on x86. I decided to port it for x86\_64 as well, but I immediately hit a problem. I wrote a small piece of program in C, then compiled and objdumped the code. After that I inserted it to my python script, therefore the x86\_64 code is correct: ``` fro...
As [vincent](http://stackoverflow.com/questions/275207/python-ctypes-and-function-calls#275333) mentioned, this is due to the allocated page being marked as non executable. Newer processors support this [functionality](http://en.wikipedia.org/wiki/NX_bit), and its used as an added layer of security by OS's which suppor...
How do you get a thumbnail of a movie using IMDbPy?
275,683
6
2008-11-09T06:39:52Z
275,774
10
2008-11-09T09:34:46Z
[ "python", "imdb", "imdbpy" ]
Using [IMDbPy](http://imdbpy.sourceforge.net) it is painfully easy to access movies from the IMDB site: ``` import imdb access = imdb.IMDb() movie = access.get_movie(3242) # random ID print "title: %s year: %s" % (movie['title'], movie['year']) ``` However I see no way to get the picture or thumbnail of the movie c...
**Note:** * Not every movie has a cover url. (The random ID in your example doesn't.) * Make sure you're using an up-to-date version of IMDbPy. (IMDb changes, and IMDbPy with it.) ... ``` import imdb access = imdb.IMDb() movie = access.get_movie(1132626) print "title: %s year: %s" % (movie['title'], movie['year'])...
What's the difference between all of the os.popen() methods?
275,756
7
2008-11-09T08:50:12Z
275,758
9
2008-11-09T08:53:58Z
[ "python", "subprocess", "popen" ]
I was looking at the [Python documentation](http://www.python.org/doc/2.5.2/lib/module-popen2.html) and saw that there are 4-5 different versions of popen(), e.g. os.popen(), os.popen2(), etc. Apart from the fact that some include *stderr* while others don't, what are the differences between them and when would you us...
popen2 doesn't capture standard error, popen3 does capture standard error and gives a unique file handle for it. Finally, popen4 captures standard error but includes it in the same file object as standard output.
What's the difference between all of the os.popen() methods?
275,756
7
2008-11-09T08:50:12Z
275,817
14
2008-11-09T10:44:40Z
[ "python", "subprocess", "popen" ]
I was looking at the [Python documentation](http://www.python.org/doc/2.5.2/lib/module-popen2.html) and saw that there are 4-5 different versions of popen(), e.g. os.popen(), os.popen2(), etc. Apart from the fact that some include *stderr* while others don't, what are the differences between them and when would you us...
I would recommend to use the `subprocess` module which has all the features that these functions have and more.
What's the difference between all of the os.popen() methods?
275,756
7
2008-11-09T08:50:12Z
275,894
12
2008-11-09T13:06:46Z
[ "python", "subprocess", "popen" ]
I was looking at the [Python documentation](http://www.python.org/doc/2.5.2/lib/module-popen2.html) and saw that there are 4-5 different versions of popen(), e.g. os.popen(), os.popen2(), etc. Apart from the fact that some include *stderr* while others don't, what are the differences between them and when would you us...
Jason has it right. To summarize in a way that's easier to see: * os.popen() -> stdout * os.popen2() -> (stdin, stdout) * os.popen3() -> (stdin, stdout, stderr) * os.popen4() -> (stdin, stdout\_and\_stderr)
How to get current CPU and RAM usage in Python?
276,052
150
2008-11-09T16:04:50Z
276,934
7
2008-11-10T02:38:51Z
[ "python", "system", "cpu", "status", "ram" ]
What's your preferred way of getting current system status (current CPU, RAM, free disk space, etc.) in Python? Bonus points for \*nix and Windows platforms. There seems to be a few possible ways of extracting that from my search: 1. Using a library such as [PSI](http://www.psychofx.com/psi/trac/wiki/) (that currentl...
Here's something I put together a while ago, it's windows only but may help you get part of what you need done. Derived from: "for sys available mem" <http://msdn2.microsoft.com/en-us/library/aa455130.aspx> "individual process information and python script examples" <http://www.microsoft.com/technet/scriptcenter/scri...
How to get current CPU and RAM usage in Python?
276,052
150
2008-11-09T16:04:50Z
2,468,983
196
2010-03-18T10:24:30Z
[ "python", "system", "cpu", "status", "ram" ]
What's your preferred way of getting current system status (current CPU, RAM, free disk space, etc.) in Python? Bonus points for \*nix and Windows platforms. There seems to be a few possible ways of extracting that from my search: 1. Using a library such as [PSI](http://www.psychofx.com/psi/trac/wiki/) (that currentl...
[The psutil library](https://pypi.python.org/pypi/psutil) will give you some system information (CPU / Memory usage) on a variety of platforms: > psutil is a module providing an interface for retrieving information on running processes and system utilization (CPU, memory) in a portable way by using Python, implementin...
WCF and Python
276,184
20
2008-11-09T17:41:15Z
707,911
7
2009-04-02T00:56:04Z
[ "python", "wcf" ]
Is there any example code of a [cpython](http://www.python.org/) (not IronPython) client which can call Windows Communication Foundation (WCF) service?
WCF needs to expose functionality through a communication protocol. I think the most commonly used protocol is probably SOAP over HTTP. Let's assume that's what you're using then. Take a look at [this chapter in Dive Into Python](http://www.diveintopython.net/soap_web_services/index.html). It will show you how to make...
WCF and Python
276,184
20
2008-11-09T17:41:15Z
3,865,315
16
2010-10-05T15:42:35Z
[ "python", "wcf" ]
Is there any example code of a [cpython](http://www.python.org/) (not IronPython) client which can call Windows Communication Foundation (WCF) service?
I used [suds](/questions/tagged/suds "show questions tagged 'suds'"). ``` from suds.client import Client print "Connecting to Service..." wsdl = "http://serviceurl.com/service.svc?WSDL" client = Client(wsdl) result = client.service.Method(variable1, variable2) print result ``` That should get you started. I'm able t...
What's a cross platform way to play a sound file in python?
276,266
17
2008-11-09T18:28:42Z
277,274
12
2008-11-10T07:21:59Z
[ "python", "cross-platform", "audio" ]
I tried playing a .wav file using pyaudio. It works great on windows, but doesn't work in Ubuntu when another device is using sound. > The error is "IOError: [Errorno > Invalid output device (no default > output device)] -9996 Is there another library I could try to use? Another method?
You can use [wxPython](http://wxpython.org/) ``` sound = wx.Sound('sound.wav') sound.Play(wx.SOUND_SYNC) ``` or ``` sound.Play(wx.SOUND_ASYNC) ``` [Here](http://svn.wxwidgets.org/viewvc/wx/wxPython/tags/wxPy-2.8.9.1/wxPython/demo/Sound.py?view=markup) is an example from the wxPython demo.
CPU Usage Per Process in Python
276,281
14
2008-11-09T18:35:14Z
276,295
23
2008-11-09T18:44:10Z
[ "python", "monitoring", "cpu-usage" ]
Is it possible for me to see the amount of processor usage (% of maximum) that the current, python, app is using? Scenario: My host will allow me to run my app as long as it does not consume more then X% of the CPU power, so I would like it to 'keep an eye on itself' and slowdown. So how can I know how much CPU the ap...
``` >>> import os >>> os.times() (1.296875, 0.765625, 0.0, 0.0, 0.0) >>> print os.times.__doc__ times() -> (utime, stime, cutime, cstime, elapsed_time) Return a tuple of floating point numbers indicating process times. ``` From the (2.5) manual: > times( ) > > Return a 5-tuple of floating point numbers indicating ac...
CPU Usage Per Process in Python
276,281
14
2008-11-09T18:35:14Z
6,265,475
12
2011-06-07T12:55:38Z
[ "python", "monitoring", "cpu-usage" ]
Is it possible for me to see the amount of processor usage (% of maximum) that the current, python, app is using? Scenario: My host will allow me to run my app as long as it does not consume more then X% of the CPU power, so I would like it to 'keep an eye on itself' and slowdown. So how can I know how much CPU the ap...
By using [psutil](http://code.google.com/p/psutil): ``` >>> import psutil >>> p = psutil.Process() >>> p.cpu_times() cputimes(user=0.06, system=0.03) >>> p.cpu_percent(interval=1) 0.0 >>> ```
Syntax error whenever I put Python code inside a Django template
276,345
2
2008-11-09T19:24:41Z
276,372
7
2008-11-09T19:44:06Z
[ "python", "django", "templates", "django-templates" ]
I'm trying to do the following in my Django template: ``` {% for embed in embeds %} {% embed2 = embed.replace("&lt;", "<") %} {{embed2}}<br /> {% endfor %} ``` However, I always get an invalid block or some syntax error when I do anything like that (by that I mean {% %} code inside a loop). Py...
I am quite sure that Django templates does not support that. For your replace operation I would look into different filters. You really should try to keep as much logic as you can in your views and not in the templates.
Can you achieve a case insensitive 'unique' constraint in Sqlite3 (with Django)?
276,656
11
2008-11-09T23:20:13Z
471,066
8
2009-01-22T22:18:21Z
[ "python", "django", "sqlite", "django-models" ]
So let's say I'm using Python 2.5's built-in default sqlite3 and I have a Django model class with the following code: ``` class SomeEntity(models.Model): some_field = models.CharField(max_length=50, db_index=True, unique=True) ``` I've got the admin interface setup and everything appears to be working fine except...
Yes this can easily be done by adding a unique index to the table with the following command: CREATE UNIQUE INDEX uidxName ON mytable (myfield COLLATE NOCASE) If you need case insensitivity for nonASCII letters, you will need to register your own COLLATION with commands similar to the following: The following exampl...
Exposing a C++ API to Python
276,761
34
2008-11-10T00:34:50Z
277,306
19
2008-11-10T07:41:53Z
[ "c++", "python", "boost", "swig" ]
I'm currently working on a project were I had to wrap the C++ classes with Python to be able to script the program. So my specific experience also involved embedding the Python interpreter in our program. The alternatives I tried were: * Boost.Python I liked the cleaner API produced by Boost.Python, but the fact t...
I've used both (for the same project): Boost is better integrated with the STL, and especially C++ exceptions. Also, its memory management mechanism (which tries to bridge C++ memory management and Python GC) is way more flexible than SWIG's. However, SWIG has *much* better documentation, no external dependencies, and ...
Exposing a C++ API to Python
276,761
34
2008-11-10T00:34:50Z
288,689
18
2008-11-13T23:03:19Z
[ "c++", "python", "boost", "swig" ]
I'm currently working on a project were I had to wrap the C++ classes with Python to be able to script the program. So my specific experience also involved embedding the Python interpreter in our program. The alternatives I tried were: * Boost.Python I liked the cleaner API produced by Boost.Python, but the fact t...
I've used [Robin](http://code.google.com/p/robin/) with great success. **Great** integration with C++ types, and creates a single .cpp file to compile and include in your shared object.
How to expose std::vector<int> as a Python list using SWIG?
276,769
14
2008-11-10T00:38:59Z
277,687
14
2008-11-10T11:44:15Z
[ "c++", "python", "stl", "swig" ]
I'm trying to expose this function to Python using SWIG: ``` std::vector<int> get_match_stats(); ``` And I want SWIG to generate wrapping code for Python so I can see it as a list of integers. Adding this to the .i file: ``` %include "typemaps.i" %include "std_vector.i" namespace std { %template(IntVector) vecto...
``` %template(IntVector) vector<int>; ```
Is there a good Python GUI shell?
277,170
12
2008-11-10T06:02:59Z
277,234
7
2008-11-10T06:49:18Z
[ "python", "shell", "user-interface" ]
I saw this the other day (scroll *all the way* down to see some of the clever stuff): > <http://www.mono-project.com/docs/tools+libraries/tools/repl/> And wondered whether something like this exists for Python. So, is there a good Python GUI shell that can do stuff like that C# shell can do? Edit: Here are links to...
Have you looked at [ipython](http://ipython.scipy.org/moin/)? It's not quite as "gui". No smileys, sorry. ;-) It is a pretty good interactive shell for python though. edit: I see you revised your question to emphasize the importance **GUI**. In that case, IPython wouldn't be a good match. Might as well save you anoth...
Is there a good Python GUI shell?
277,170
12
2008-11-10T06:02:59Z
277,531
13
2008-11-10T10:23:00Z
[ "python", "shell", "user-interface" ]
I saw this the other day (scroll *all the way* down to see some of the clever stuff): > <http://www.mono-project.com/docs/tools+libraries/tools/repl/> And wondered whether something like this exists for Python. So, is there a good Python GUI shell that can do stuff like that C# shell can do? Edit: Here are links to...
One project I'm aware of that provides similar features (inline plotting, customisable rendering) is [Reinteract](http://fishsoup.net/software/reinteract/). Another (though possibly a bit heavyweight for general usage) is [SAGE](http://www.sagemath.org/) which provides functionality for web-based [notebooks](http://www...
Python Argument Binders
277,922
39
2008-11-10T14:01:22Z
277,932
55
2008-11-10T14:06:47Z
[ "python" ]
How can I bind arguments to a Python method to store a nullary functor for later invocation? Similar to C++'s `boost::bind`.
[`functools.partial`](http://docs.python.org/2/library/functools.html#functools.partial) returns a callable wrapping a function with some or all of the arguments frozen. ``` import sys import functools print_hello = functools.partial(sys.stdout.write, "Hello world\n") print_hello() ``` ``` Hello world ``` The abov...
Python Argument Binders
277,922
39
2008-11-10T14:01:22Z
277,933
20
2008-11-10T14:07:14Z
[ "python" ]
How can I bind arguments to a Python method to store a nullary functor for later invocation? Similar to C++'s `boost::bind`.
I'm not overly familiar with boost::bind, but the `partial` function from `functools` may be a good start: ``` >>> from functools import partial >>> def f(a, b): ... return a+b >>> p = partial(f, 1, 2) >>> p() 3 >>> p2 = partial(f, 1) >>> p2(7) 8 ```