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, value in stats.items()] print max(inverse)[1] ``` Is that one the better (or even more elegant) approach?
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 well.
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, value in stats.items()] print max(inverse)[1] ``` Is that one the better (or even more elegant) approach?
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 `shutdown` method, but it is missing in `HTTPServer`. The whole `BaseHTTPServer` module has very little documentation :(
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 subclass) `while 1` with `while self.should_be_running`, and modify that value from a different thread. Something like: ``` def stop_serving_forever(self): """Stop handling requests""" self.should_be_running = 0 # Make a fake request to the server, to really force it to stop. # Otherwise it will just stop on the next request. # (Exercise for the reader.) self.make_a_fake_request_to_myself() ``` Edit: I dug up the actual code I used at the time: ``` class StoppableRPCServer(SimpleXMLRPCServer.SimpleXMLRPCServer): stopped = False allow_reuse_address = True def __init__(self, *args, **kw): SimpleXMLRPCServer.SimpleXMLRPCServer.__init__(self, *args, **kw) self.register_function(lambda: 'OK', 'ping') def serve_forever(self): while not self.stopped: self.handle_request() def force_stop(self): self.server_close() self.stopped = True self.create_dummy_request() def create_dummy_request(self): server = xmlrpclib.Server('http://%s:%s' % self.server_address) server.ping() ```
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 `shutdown` method, but it is missing in `HTTPServer`. The whole `BaseHTTPServer` module has very little documentation :(
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.HTTPServer instance at 0x0100D800>> >>> ```
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 `shutdown` method, but it is missing in `HTTPServer`. The whole `BaseHTTPServer` module has very little documentation :(
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 `shutdown` method, but it is missing in `HTTPServer`. The whole `BaseHTTPServer` module has very little documentation :(
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(self, poll_interval=0.5): """Handle one request at a time until shutdown. Polls for shutdown every poll_interval seconds. Ignores self.timeout. If you need to do periodic tasks, do them in another thread. """ self.__is_shut_down.clear() try: while not self.__shutdown_request: # XXX: Consider using another file descriptor or # connecting to the socket to wake this up instead of # polling. Polling reduces our responsiveness to a # shutdown request and wastes cpu at all other times. r, w, e = select.select([self], [], [], poll_interval) if self in r: self._handle_request_noblock() finally: self.__shutdown_request = False self.__is_shut_down.set() ``` Heres part of my code for doing a blocking shutdown from another thread, using an event to wait for completion: ``` class MockWebServerFixture(object): def start_webserver(self): """ start the web server on a new thread """ self._webserver_died = threading.Event() self._webserver_thread = threading.Thread( target=self._run_webserver_thread) self._webserver_thread.start() def _run_webserver_thread(self): self.webserver.serve_forever() self._webserver_died.set() def _kill_webserver(self): if not self._webserver_thread: return self.webserver.shutdown() # wait for thread to die for a bit, then give up raising an exception. if not self._webserver_died.wait(5): raise ValueError("couldn't kill webserver") ```
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 `UnicodeDecodeError` . So, I'm looking for a function that takes a `str` and optionally some hints and does its darndest to give me back a `unicode`. I could write one of course, but if such a function exists its author has probably thought a bit deeper about the best way to go about this. I also know that Python's design prefers explicit to implicit and that the standard library is designed to avoid implicit magic in decoding text. I just want to explicitly say "go ahead and guess".
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 `UnicodeDecodeError` . So, I'm looking for a function that takes a `str` and optionally some hints and does its darndest to give me back a `unicode`. I could write one of course, but if such a function exists its author has probably thought a bit deeper about the best way to go about this. I also know that Python's design prefers explicit to implicit and that the standard library is designed to avoid implicit magic in decoding text. I just want to explicitly say "go ahead and guess".
+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 you can easily install it with the following command: ``` $ pip install chardet ``` [Example](http://web.archive.org/web/20111003070626/http://chardet.feedparser.org/): ``` >>> import chardet >>> import urllib >>> detect = lambda url: chardet.detect(urllib.urlopen(url).read()) >>> detect('http://stackoverflow.com') {'confidence': 0.85663169917190185, 'encoding': 'ISO-8859-2'} >>> detect('http://stackoverflow.com/questions/269060/is-there-a-python-lib') {'confidence': 0.98999999999999999, 'encoding': 'utf-8'} ``` See [Installing Pip](http://guide.python-distribute.org/installation.html#installing-pip) if you don't have one.
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 `UnicodeDecodeError` . So, I'm looking for a function that takes a `str` and optionally some hints and does its darndest to give me back a `unicode`. I could write one of course, but if such a function exists its author has probably thought a bit deeper about the best way to go about this. I also know that Python's design prefers explicit to implicit and that the standard library is designed to avoid implicit magic in decoding text. I just want to explicitly say "go ahead and guess".
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, encodings=('ascii', 'utf8', 'latin1')): for encoding in encodings: try: return s.decode(encoding) except UnicodeDecodeError: pass return s.decode('ascii', 'ignore') ```
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 doing Python as an option mainly for internal use.[/edit]
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' and a password of 'password': > joe,kDP0Py2QwEdJYtUX9cJABg==,OJF6H4KdxFLgLu+oTDNFodCEfMA= I've dumped this stuff into a CSV file and I'm attempting to get it into a usable format for Django which stores its passwords in this format: [algo]$[salt]$[hash] Where the salt is a plain string and the hash is the hex digest of an SHA1 hash. So far I've been able to ascertain that ASP is storing these hashes and salts in a base64 format. Those values above decode into binary strings. We've used reflector to glean how ASP authenticates against these values: ``` internal string EncodePassword(string pass, int passwordFormat, string salt) { if (passwordFormat == 0) { return pass; } byte[] bytes = Encoding.Unicode.GetBytes(pass); byte[] src = Convert.FromBase64String(salt); byte[] dst = new byte[src.Length + bytes.Length]; byte[] inArray = null; Buffer.BlockCopy(src, 0, dst, 0, src.Length); Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length); if (passwordFormat == 1) { HashAlgorithm algorithm = HashAlgorithm.Create(Membership.HashAlgorithmType); if ((algorithm == null) && Membership.IsHashAlgorithmFromMembershipConfig) { RuntimeConfig.GetAppConfig().Membership.ThrowHashAlgorithmException(); } inArray = algorithm.ComputeHash(dst); } else { inArray = this.EncryptPassword(dst); } return Convert.ToBase64String(inArray); } ``` Eseentially, pulls in the salt from the DB and b64 decodes it into a binary representation. It does a "GetBytes" on the raw password and then it concatinates them, salt first. It then runs the SHA1 algorithm on this new string, base64 encodes it, and compares it against the value stored in the database. I've attempted to write some code to try and reproduce these hashes in Python and I'm failing. I won't be able to use them in Django until I can figure out how this translates over. Here's how I'm testing: ``` import hashlib from base64 import b64decode, b64encode b64salt = "kDP0Py2QwEdJYtUX9cJABg==" b64hash = "OJF6H4KdxFLgLu+oTDNFodCEfMA=" binsalt = b64decode(b64salt) password_string = 'password' m1 = hashlib.sha1() # Pass in salt m1.update(binsalt) # Pass in password m1.update(password_string) # B64 encode the binary digest if b64encode(m1.digest()) == b64hash: print "Logged in!" else: print "Didn't match" print b64hash print b64encode(m1.digest()) ``` I'm wondering if anyone can see any flaws in my approach or can suggest an alternate method. Perhaps you can take the algorithms above and the known password and salt above and produce the hash on your system?
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! Here's one that passes: ``` import hashlib from base64 import b64decode, b64encode def utf16tobin(s): return s.encode('hex')[4:].decode('hex') b64salt = "kDP0Py2QwEdJYtUX9cJABg==" b64hash = "OJF6H4KdxFLgLu+oTDNFodCEfMA=" binsalt = b64decode(b64salt) password_string = 'password'.encode("utf16") password_string = utf16tobin(password_string) m1 = hashlib.sha1() # Pass in salt m1.update(binsalt + password_string) # Pass in password # B64 encode the binary digest if b64encode(m1.digest()) == b64hash: print "Logged in!" else: print "Didn't match" print b64hash print b64encode(m1.digest()) ```
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\site.py # wrote C:\Python24\lib\site.pyc # C:\Python24\lib\os.pyc has bad mtime import os # from C:\Python24\lib\os.py # wrote C:\Python24\lib\os.pyc import nt # builtin # C:\Python24\lib\ntpath.pyc has bad mtime ... ``` I'm not sure what those bad mtime's are on my install!
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 extract it, the modules' code can be found in the **Modules** subdirectory. For example, if you want to find the datetime code for python 2.6, you can look at ``` Python-2.6/Modules/datetimemodule.c ``` You can also find the latest Mercurial version on the web at <https://hg.python.org/cpython/file/tip/Modules/_datetimemodule.c>
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.6/os.py MODULE DOCS http://docs.python.org/library/os DESCRIPTION This exports: - all functions from posix, nt, os2, or ce, e.g. unlink, stat, etc. - os.path is one of the modules posixpath, or ntpath - os.name is 'posix', 'nt', 'os2', 'ce' or 'riscos' ``` et al
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.html) module—in particular, `getfile` or `getsourcefile`. Unless you want to learn and implement the rules (which are documented, but painful, for CPython 2.x, and not documented at all for other implementations, or 3.x) for mapping `.pyc` to `.py` files; dealing with .zip archives, eggs, and module packages; trying different ways to get the path to `.so`/`.pyd` files that don't support `__file__`; figuring out what Jython/IronPython/PyPy do; etc. In which case, go for it. Meanwhile, every Python version's source from 2.0+ is available online at `http://hg.python.org/cpython/file/X.Y/` (e.g., [2.7](http://hg.python.org/cpython/file/2.7/) or [3.3](http://hg.python.org/cpython/file/3.3/)). So, once you discover that `inspect.getfile(datetime)` is a `.so` or `.pyd` file like `/usr/local/lib/python2.7/lib-dynload/datetime.so`, you can look it up inside the Modules directory. Strictly speaking, there's no way to be sure of which file defines which module, but nearly all of them are either `foo.c` or `foomodule.c`, so it shouldn't be hard to guess that [datetimemodule.c](http://hg.python.org/cpython/file/2.7/Modules/datetimemodule.c) is what you want.
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 the `after` method and check the status from my separate object, but that seems wasteful.
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: ``` from tkinter import * def doFoo(*args): print("Hello, world") root = Tk() root.bind("<<Foo>>", doFoo) # some time later, inject the "<<Foo>>" virtual event at the # tail of the event queue root.event_generate("<<Foo>>", when="tail") ``` Note that the `event_generate` call will return immediately. It's not clear if that's what you want or not. Generally speaking you don't want an event based program to block waiting for a response to a specific event because it will *freeze the GUI*. I'm not sure if this solves your problem though; without seeing your code I'm not sure what your real problem is. I can, for example, access methods of root in the constructor of an object where the root is passed in without the app locking up. This tells me there's something else going on in your code. Here's an example of successfully accessing methods on a root window from some other object: ``` from tkinter import * class myClass: def __init__(self, root): print("root background is %s" % root.cget("background")) root = Tk() newObj = myClass(root) ```
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', 'addr': '00:11:2f:32:63:45'}], 2: [{'broadcast': '10.0.0.255', 'netmask': '255.255.255.0', 'addr': '10.0.0.2'}], 10: [{'netmask': 'ffff:ffff:ffff:ffff::', 'addr': 'fe80::211:2fff:fe32:6345%eth0'}]} >>> for interface in netifaces.interfaces(): ... print netifaces.ifaddresses(interface)[netifaces.AF_INET] ... [{'peer': '127.0.0.1', 'netmask': '255.0.0.0', 'addr': '127.0.0.1'}] [{'broadcast': '10.0.0.255', 'netmask': '255.255.255.0', 'addr': '10.0.0.2'}] >>> for interface in netifaces.interfaces(): ... for link in netifaces.ifaddresses(interface)[netifaces.AF_INET]: ... print link['addr'] ... 127.0.0.1 10.0.0.2 ``` This can be made a little more readable like this: ``` from netifaces import interfaces, ifaddresses, AF_INET def ip4_addresses(): ip_list = [] for interface in interfaces(): for link in ifaddresses(interface)[AF_INET]: ip_list.append(link['addr']) return ip_list ``` If you want IPv6 addresses, use `AF_INET6` instead of `AF_INET`. If you're wondering why `netifaces` uses lists and dictionaries all over the place, it's because a single computer can have multiple NICs, and each NIC can have multiple addresses, and each address has its own set of options.
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 figured out the SQLAlchemy SQL-builder equivalent: ``` engine = sqlalchemy.create_engine('sqlite:///mydata.sqlitedb') md = sqlalchemy.MetaData(engine) table = sqlalchemy.Table('stuff', md, autoload=True) upd = table.update(values={table.c.foo:table.c.foo+1}) engine.execute(upd) ``` This is slightly slower, but there's not much in it. Here's my best guess for a SQLAlchemy ORM approach: ``` # snip definition of Stuff class made using declarative_base # snip creation of session object for c in session.query(Stuff): c.foo = c.foo + 1 session.flush() session.commit() ``` This does the right thing, but it takes just under fifty times as long as the other two approaches. I presume that's because it has to bring all the data into memory before it can work with it. Is there any way to generate the efficient SQL using SQLAlchemy's ORM? Or using any other python ORM? Or should I just go back to writing the SQL by hand?
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 other side, SQL data manipulation statements don't affect the objects that are in your session. So if you say ``` for c in session.query(Stuff).all(): c.foo = c.foo+1 session.commit() ``` it will do what it says, go fetch all the objects from the database, modify all the objects and then when it's time to flush the changes to the database, update the rows one by one. Instead you should do this: ``` session.execute(update(stuff_table, values={stuff_table.c.foo: stuff_table.c.foo + 1})) session.commit() ``` This will execute as one query as you would expect, and because atleast the default session configuration expires all data in the session on commit you don't have any stale data issues. In the almost-released 0.5 series you could also use this method for updating: ``` session.query(Stuff).update({Stuff.foo: Stuff.foo + 1}) session.commit() ``` That will basically run the same SQL statement as the previous snippet, but also select the changed rows and expire any stale data in the session. If you know you aren't using any session data after the update you could also add synchronize\_session=False to the update statement and get rid of that select.
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 figured out the SQLAlchemy SQL-builder equivalent: ``` engine = sqlalchemy.create_engine('sqlite:///mydata.sqlitedb') md = sqlalchemy.MetaData(engine) table = sqlalchemy.Table('stuff', md, autoload=True) upd = table.update(values={table.c.foo:table.c.foo+1}) engine.execute(upd) ``` This is slightly slower, but there's not much in it. Here's my best guess for a SQLAlchemy ORM approach: ``` # snip definition of Stuff class made using declarative_base # snip creation of session object for c in session.query(Stuff): c.foo = c.foo + 1 session.flush() session.commit() ``` This does the right thing, but it takes just under fifty times as long as the other two approaches. I presume that's because it has to bring all the data into memory before it can work with it. Is there any way to generate the efficient SQL using SQLAlchemy's ORM? Or using any other python ORM? Or should I just go back to writing the SQL by hand?
``` 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: print product_type for product in products: print product ``` I can't seem to do the same thing in my Django template: ``` {% for product_type, products in product_list %} print product_type {% for product in products %} print product {% endfor %} {% endfor %} ``` I get this error from Django: **Caught an exception while rendering: zip argument #2 must support iteration** Of course, there is some HTML markup in the template, not print statements. Is tuple unpacking not supported in the Django template language? Or am I going about this the wrong way? All I am trying to do is display a simple hierarchy of objects - there are several product types, each with several products (in models.py, Product has a foreign key to Product\_type, a simple one-to-many relationship). Obviously, I am quite new to Django, so any input would be appreciated.
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, products in product_type_list %} {{ product_type }} {% for product in products %} {{ product }} {% endfor %} {% endfor %} ``` the way tuples/lists are unpacked in for loops is based on the item returned by the list iterator. each iteration only one item was returned. the first time around the loop, Product\_Type\_1, the second your list of products...
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: print product_type for product in products: print product ``` I can't seem to do the same thing in my Django template: ``` {% for product_type, products in product_list %} print product_type {% for product in products %} print product {% endfor %} {% endfor %} ``` I get this error from Django: **Caught an exception while rendering: zip argument #2 must support iteration** Of course, there is some HTML markup in the template, not print statements. Is tuple unpacking not supported in the Django template language? Or am I going about this the wrong way? All I am trying to do is display a simple hierarchy of objects - there are several product types, each with several products (in models.py, Product has a foreign key to Product\_type, a simple one-to-many relationship). Obviously, I am quite new to Django, so any input would be appreciated.
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 \%} {{ item.0 }} {{ item.1}} {{ item.2 }} {\% endfor \%} ```
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 likeso: ``` http://x.y/P/new?type=3 ``` So that in the form no "type" field will appear, but when the P is saved, its type will have id 3 (i.e. Type.objects.get(pk=3)). Secondarily, how does one (& is it possible) specify a "default" type in the url, via urls.py, when using generic Django views, viz. ``` urlpatterns = ('django.generic.views.create_update', url(r'^/new$', 'create_object', { 'model': P }, name='new_P'), ) ``` I found that terribly difficult to describe, which may be part of the problem. :) Input is much appreciated!
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<hidden_value>\w+)/ ``` I prefer this technique myself because I only really find myself needing hidden form fields when I need to track the primary key of a model instance - in which case an "edit/pkey" url serves the purposes of both initiating the edit/returning the form, and receiving the POST on save.
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, this leads me on to another question. How easy is it to link these languages together? And which combination works best? So, if I wanted to have a Ruby CGI-type program calling C++ or Java AI functions, is that easy to do? Any pointers for where I look for information on doing that kind of thing? Or would a different combination be better? My main experience with writing web applications started with C++ CGI and then moved on to Java servlets (about 10 years ago) and then after a long gap away from programming I did some PHP. But I've not had experience of writing a web application in a scripting language which then calls out to a compiled language for the speed-critical bits. So any advice will be welcome!
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 things much easier when/if you need to reimplement in a lower-level language. Speaking for Python, [IronPython](http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython)/C# is probably the easiest optimization path. CPython with C++ is doable, but I find C a lot easier to handle (but not all that easy, being C). Two tools that ease this are [cython](http://cython.org/)/[pyrex](http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/) (for C) and [shedskin](http://shed-skin.blogspot.com/) (for C++). These compile Python into C/C++, and from there you can access C/C++ libraries without too much ado. I've never used jython, but I hear that the jython/Java optimization path isn't all that bad.
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, this leads me on to another question. How easy is it to link these languages together? And which combination works best? So, if I wanted to have a Ruby CGI-type program calling C++ or Java AI functions, is that easy to do? Any pointers for where I look for information on doing that kind of thing? Or would a different combination be better? My main experience with writing web applications started with C++ CGI and then moved on to Java servlets (about 10 years ago) and then after a long gap away from programming I did some PHP. But I've not had experience of writing a web application in a scripting language which then calls out to a compiled language for the speed-critical bits. So any advice will be welcome!
[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 exposed to Python by writing a Boost.Python wrapper: ``` #include <boost/python.hpp> BOOST_PYTHON_MODULE(hello_ext) { using namespace boost::python; def("greet", greet); } ``` That's it. We're done. We can now build this as a shared library. The resulting DLL is now visible to Python. Here's a sample Python session: ``` >>> import hello_ext >>> print hello.greet() hello, world ``` (example taken from boost.org)
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 and I want to inspect an "action" variable using the console. However my variables are not available. How can I do things like "dir(action)", etc? (even if it is not using a console).
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 and I want to inspect an "action" variable using the console. However my variables are not available. How can I do things like "dir(action)", etc? (even if it is not using a console).
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 whether a string is base64 or not, using the **jython** programming language? Ie. First attachment: ``` ------=_NextPart_000_0091_01C940CC.EF5AC860 Content-Type: application/vnd.ms-excel; name="Copy of Book1.xls" Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename="Copy of Book1.xls" ``` second attachment: ``` ------=_NextPart_000_0091_01C940CC.EF5AC860 Content-Type: application/vnd.ms-excel; name="=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?=" Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename="=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?=" ``` Please note both "**Content-Transfer-Encoding**" have base64
@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? I'm looking for the documentation in the RFCs... Ah! here it is: <http://tools.ietf.org/html/rfc2047> The RFC says: ***Generally, an "encoded-word" is a sequence of printable ASCII characters that begins with "=?", ends with "?=", and has two "?"s in between.*** Something else to look at is the code in SharpMimeTools, a MIME parser (in C#) that I use in my [bug tracking](http://ifdefined.com/bugtrackernet.html) app, [BugTracker.NET](http://ifdefined.com/bugtrackernet.html)
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 whether a string is base64 or not, using the **jython** programming language? Ie. First attachment: ``` ------=_NextPart_000_0091_01C940CC.EF5AC860 Content-Type: application/vnd.ms-excel; name="Copy of Book1.xls" Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename="Copy of Book1.xls" ``` second attachment: ``` ------=_NextPart_000_0091_01C940CC.EF5AC860 Content-Type: application/vnd.ms-excel; name="=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?=" Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename="=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?=" ``` Please note both "**Content-Transfer-Encoding**" have base64
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-printable) "?" functions as a separator "uLG..." is the actual value, encoded using the encoding specified before "?=" ends the encoded value ``` So splitting on "?" actually gets you this (JSON notation) ``` ["=", "gb2312", "B", "uLGxvmhlbrixsb5nLnhscw==", "="] ``` In the resulting array, if "B" is on position 2, you face a base-64 encoded string on position 3. Once you decoded it, be sure to pay attention to the encoding on position 1, probably it would be best to convert the whole thing to UTF-8 using that info.
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 whether a string is base64 or not, using the **jython** programming language? Ie. First attachment: ``` ------=_NextPart_000_0091_01C940CC.EF5AC860 Content-Type: application/vnd.ms-excel; name="Copy of Book1.xls" Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename="Copy of Book1.xls" ``` second attachment: ``` ------=_NextPart_000_0091_01C940CC.EF5AC860 Content-Type: application/vnd.ms-excel; name="=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?=" Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename="=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?=" ``` Please note both "**Content-Transfer-Encoding**" have base64
> 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_header`. It still needs a little post-processing to interpret the outcome of that function though: ``` import email.header x= '=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?=' try: name= u''.join([ unicode(b, e or 'ascii') for b, e in email.header.decode_header(x) ]) except email.Errors.HeaderParseError: pass # leave name as it was ``` However... ``` Content-Type: application/vnd.ms-excel; name="=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?=" ``` This is simply wrong. What mailer created it? RFC2047 encoding can only happen in atoms, and a quoted-string is not an atom. RFC2047 §5 explicitly denies this: > * An 'encoded-word' MUST NOT appear within a 'quoted-string'. The accepted way to encode parameter headers when long string or Unicode characters are present is **RFC2231**, which is a whole new bag of hurt. But you should be using a standard mail-parsing library which will cope with that for you. So, you could detect the `'=?'` in filename parameters if you want, and try to decode it via RFC2047. However, the strictly-speaking-correct thing to do is to take the mailer at its word and really call the file `=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?=`!
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? • Etc. Key to all these questions is response time. We need to be able to measure how response time and performance degrades as new load is introduced so that we could for example, produce some kind of pretty graph we could throw at clients to give them an idea what kind of performance to expect with a given hardware configuration. Right now we just put out fingers in the air and make educated guesses based on what we already know about the system from experience. As the product is put under more demanding conditions, this is proving to be inadequate for our needs going forward though. I've been given the task of devising a method to get such answers in a meaningful way. I realise that this is not a question that anyone can answer definitively but I'm looking for suggestions about how people have gone about doing such work on their own systems. One thing to note is that we have full access to our client API via the Python language (courtesy of SWIG) which is a lot easier to work with than C++ for this kind of work. So there we go, I throw this to the floor: really interested to see what ideas you guys can come up with!
**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 week, doing random actions [(FuzzTest)](http://en.wikipedia.org/wiki/Fuzz_testing). Time the round-trip of each action. Also keep record of the order of actions, because this way your "clients" will find loopholes in your usecases (very important, and VERY hard to test rationally). **Test 3 & 4**: Determine major use cases for your system, and write up scripts that do these tasks. Then run several clients doing same task(test 3), and also several clients doing different tasks(test 4). **Series:** Now the other dimension you need here is amount of clients. A nice series would be: 5,10,50,100,500,1000,5000,10000,... This way you can get data for each series of tests with different work loads. Also congrats on SWIGing your clients api to Python! That is a great way to get things ready. Note: [IBM has a sample of fuzz testing on Java](http://www.ibm.com/developerworks/java/library/j-fuzztest.html), which is unrealted to your case, but will help you design a good fuzztest for your system
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 this and knows how it can be done? I'd love to see some code examples if there are any available. Thanks!
[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/piracyreport.php") soup = BeautifulSoup(page) for incident in soup('td', width="90%"): where, linebreak, what = incident.contents[:3] print where.strip() print what.strip() print ```
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 generate a WSDL that I can give our web developers. I might add that the stored procedure only returns one value. Here's some example code: ``` #!/usr/bin/python import SOAPpy import MySQLdb def getNEXTVAL(): cursor = db.cursor() cursor.execute( "CALL my_stored_procedure()" ) # Returns a number result=cursor.fetchall() for record in result: return record[0] db=MySQLdb.connect(host="localhost", user="myuser", passwd="********", db="testing") server = SOAPpy.SOAPServer(("10.1.22.29", 8080)) server.registerFunction(getNEXTVAL) server.serve_forever() ``` I want to generate a WSDL that I can give to the web folks, and I'm wondering if it's possible to have SOAPpy just generate one for me. Is this possible?
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 for my client and server code. I wouldn't describe the experience as pleasant, but the application did work.
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) ``` Somehow, I missed `os.path.exists` (thanks kanja, Blair, and Douglas). This is what I have now: ``` def ensure_dir(f): d = os.path.dirname(f) if not os.path.exists(d): os.makedirs(d) ``` Is there a flag for "open", that makes this happen automatically?
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) ``` Somehow, I missed `os.path.exists` (thanks kanja, Blair, and Douglas). This is what I have now: ``` def ensure_dir(f): d = os.path.dirname(f) if not os.path.exists(d): os.makedirs(d) ``` Is there a flag for "open", that makes this happen automatically?
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) ``` Somehow, I missed `os.path.exists` (thanks kanja, Blair, and Douglas). This is what I have now: ``` def ensure_dir(f): d = os.path.dirname(f) if not os.path.exists(d): os.makedirs(d) ``` Is there a flag for "open", that makes this happen automatically?
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): os.makedirs(directory) ``` As noted in comments and elsewhere, there's a race condition - if the directory is created between the `os.path.exists` and the `os.makedirs` calls, the `os.makedirs` will fail with an `OSError`. Unfortunately, blanket-catching `OSError` and continuing is not foolproof, as it will ignore a failure to create the directory due to other factors, such as insufficient permissions, full disk, etc. One option would be to trap the `OSError` and examine the embedded error code, if one knew what's what (on my OS, 13 seems to indicate that permission is denied, and 17 that the file exists - it's not clear that that's even remotely portable, but is explored in [Is there a cross-platform way of getting information from Python’s OSError](http://stackoverflow.com/questions/273698/is-there-a-cross-platform-way-of-getting-information-from-pythons-oserror)). Alternatively, there could be a second `os.path.exists`, but suppose another created the directory after the first check, then removed it before the second one - we could still be fooled. Depending on the application, the danger of concurrent operations may be more or less than the danger posed by other factors such as file permissions. The developer would have to know more about the particular application being developed and its expected environment before choosing an implementation.
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) ``` Somehow, I missed `os.path.exists` (thanks kanja, Blair, and Douglas). This is what I have now: ``` def ensure_dir(f): d = os.path.dirname(f) if not os.path.exists(d): os.makedirs(d) ``` Is there a flag for "open", that makes this happen automatically?
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 ``` Now as I say, this is not really foolproof, because we have the possiblity of failing to create the directory, and another process creating it during that period.
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) ``` Somehow, I missed `os.path.exists` (thanks kanja, Blair, and Douglas). This is what I have now: ``` def ensure_dir(f): d = os.path.dirname(f) if not os.path.exists(d): os.makedirs(d) ``` Is there a flag for "open", that makes this happen automatically?
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: ``` >>> dir = raw_input(":: ") ``` And a foolish user input: ``` :: /tmp/dirname/filename.etc ``` ... You're going to end up with a directory named `filename.etc` when you pass that argument to `os.makedirs()` if you test with `os.path.exists()`.
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) ``` Somehow, I missed `os.path.exists` (thanks kanja, Blair, and Douglas). This is what I have now: ``` def ensure_dir(f): d = os.path.dirname(f) if not os.path.exists(d): os.makedirs(d) ``` Is there a flag for "open", that makes this happen automatically?
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 words, we try to create the directories, but if they already exist we ignore the error. On the other hand, any other error gets reported. For example, if you create dir 'a' beforehand and remove all permissions from it, you will get an OSError raised with errno.EACCES (Permission denied, error 13).
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) ``` Somehow, I missed `os.path.exists` (thanks kanja, Blair, and Douglas). This is what I have now: ``` def ensure_dir(f): d = os.path.dirname(f) if not os.path.exists(d): os.makedirs(d) ``` Is there a flag for "open", that makes this happen automatically?
### 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, it handles the possible race condition and also disambiguates files from directories: ``` try: os.makedirs(path) except OSError: if not os.path.isdir(path): raise ``` Capturing the exception and using `errno` is *not* so useful because `OSError: [Errno 17] File exists` is raised for both files and directories. ### Python 3.2+: ``` os.makedirs(path, exist_ok=True) ``` If using Python 3.2+, an optional [`exist_ok`](https://docs.python.org/3/library/os.html#os.makedirs "os.makedirs") parameter is available, with a default value of `False`. It does not exist in Python 2.x up to 2.7. One can therefore simply specify `exist_ok=True` in Python 3.2+ to avoid raising an exception if the directory already exists. As such, there is, no need for manual exception handling as with Python 2.7. With regard to the directory's `chmod` *mode*, please refer to the documentation.
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) ``` Somehow, I missed `os.path.exists` (thanks kanja, Blair, and Douglas). This is what I have now: ``` def ensure_dir(f): d = os.path.dirname(f) if not os.path.exists(d): os.makedirs(d) ``` Is there a flag for "open", that makes this happen automatically?
# 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.dirname(filename) > ``` We want to avoid overwriting the builtin function, `dir`. Also, `filepath` or perhaps `fullfilepath` is probably a better semantic name than `filename` so this would be better written: ``` import os filepath = '/my/directory/filename.txt' directory = os.path.dirname(filepath) ``` Your end goal is to open this file, you initially state, for writing, but you're essentially approaching this goal (based on your code) like this, which opens the file for **reading**: > ``` > if not os.path.exists(directory): > os.makedirs(directory) > f = file(filename) > ``` ## Assuming opening for reading Why would you make a directory for a file that you expect to be there and be able to read? Just attempt to open the file. ``` with open(filepath) as my_file: do_stuff(my_file) ``` If the directory or file isn't there, you'll get an `IOError` with an associated error number: `errno.ENOENT` will point to the correct error number regardless of your platform. You can catch it if you want, for example: ``` import errno try: with open(filepath) as my_file: do_stuff(my_file) except IOError as error: if error.errno == errno.ENOENT: print 'ignoring error because directory or file is not there' else: raise ``` ## Assuming we're opening for writing This is *probably* what you're wanting. In this case, we probably aren't facing any race conditions. So just do as you were, but note that for writing, you need to open with the `w` mode (or `a` to append). It's also a Python best practice to use the context manager for opening files. ``` import os if not os.path.exists(directory): os.makedirs(directory) with open(filepath, 'w') as my_file: do_stuff(my_file) ``` However, say we have several Python processes that attempt to put all their data into the same directory. Then we may have contention over creation of the directory. In that case it's best to wrap the `makedirs` call in a try-except block. ``` import os import errno if not os.path.exists(directory): try: os.makedirs(directory) except OSError as error: if error.errno != errno.EEXIST: raise with open(filepath, 'w') as my_file: do_stuff(my_file) ```
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) ``` Somehow, I missed `os.path.exists` (thanks kanja, Blair, and Douglas). This is what I have now: ``` def ensure_dir(f): d = os.path.dirname(f) if not os.path.exists(d): os.makedirs(d) ``` Is there a flag for "open", that makes this happen automatically?
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 specific errors like # FileExistsError and so on. ```
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 pay simply too high?
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 Perl's "There's More Than One Way To Do It" philosophy.) There are examples like the changes from version to version of .NET-based languages (ironic, considering the whole point of .NET was supposed to be API stability and cross-platform compatibility). However, I would hardly call those languages "mature"; it's always been more of a design-on-the-go, build-the-plane-as-we-fly approach to things. Or, as I tend to think of it, most languages come from either "organic growth" or "engineered construction." Perl is the perfect example of organic growth; it started as a fancy text processing tool ala awk/sed and grew into a full language. Python, on the other hand, is much more engineered. Spend a bit of time wandering around the extensive whitepapers on their website to see the extensive debate that goes into every even minor change to the language's syntax and implementation. The idea of making these sorts of far-reaching changes is somewhat new to programming languages because programming languages themselves have changed in nature. It used to be that programming methodologies changed only when a new processor came out that had a new instruction set. The early languages tended to either be so low-level and married to assembly language (e.g. C) or so utterly dynamic in nature (Forth, Lisp) that such a mid-stream change wouldn't even come up as a consideration. As to whether or not the changes are good ones, I'm not sure. I tend to have faith in the people guiding Python's development, however; the changes in the language thus far have been largely for the better. I think in the days to come the Global Interpreter Lock will prove more central than syntax changes. Though the new multiprocessor library might alleviate most of that.
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 pay simply too high?
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 pay simply too high?
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 good example of how implementing features with 100% backward compatibility can result in a sub-optimal language feature. So loosely speaking, it can come down to a choice between a poorly implemented new feature that's backwardly compatible, or a nicely implemented new feature that's not. In many cases, the latter is a better choice, particularly if there are tools that can automatically translate incompatible code.
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 pay simply too high?
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: ``` >>> import os >>> os.mkdir('foo') >>> try: ... os.mkdir('foo') ... except OSError, e: ... print e.args ... (17, 'File exists') ``` Is there a cross-platform way that I can know that that the 17 or the 'File Exists' will always mean the same thing so that I can act differently depending on the situation? (This came up [during another question](http://stackoverflow.com/questions/273192/python-best-way-to-create-directory-if-it-doesnt-exist-for-file-write).)
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 should still be present, and usable in a cross-platform way. Symbolic names for the various error codes can be found in the `errno` module. For example, ``` import os, errno try: os.mkdir('test') except OSError, e: if e.errno == errno.EEXIST: # Do something ``` You can also perform the reverse lookup (to find out what code you should be using) with `errno.errorcode`. That is: ``` >>> errno.errorcode[17] 'EEXIST' ```
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/introduction.htm). ``` import os, sys import Image size = 128, 128 for infile in sys.argv[1:]: outfile = os.path.splitext(infile)[0] + ".thumbnail" if infile != outfile: try: im = Image.open(infile) im.thumbnail(size, Image.ANTIALIAS) im.save(outfile, "JPEG") except IOError: print "cannot create thumbnail for '%s'" % infile ```
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. Change "basewidth" to any other number to change the default width of your images. ``` import PIL from PIL import Image basewidth = 300 img = Image.open('somepic.jpg') wpercent = (basewidth/float(img.size[0])) hsize = int((float(img.size[1])*float(wpercent))) img = img.resize((basewidth,hsize), PIL.Image.ANTIALIAS) img.save('sompic.jpg') ```
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 quality.
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 copying. It displays the progress bar using `sys.stdout.write("\r%s\r" % (the_progress_bar))` which is a little hackish, but it works. You can see the code (in context) [on github here](http://github.com/dbr/checktveps/tree/1be8f4445fbf766eba25f98f78ec52e955571608/autoPathTv.py#L64-153) Is there any built-in module that will do this better? Is there any improvements that can be made to this code?
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. Perhaps something like this: ``` def copy_with_prog(src, dest, callback = None): while True: # copy loop stuff if callback: callback(pos, total) prog = ProgressBar(...) copy_with_prog(src, dest, lambda pos, total: prog.update(pos, total)) ```
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'.rstrip('\n') 'test string ' ``` There is also the `lstrip` and `strip` methods. ``` >>> s = " \n abc def " >>> s.strip() 'abc def' >>> s.rstrip() ' \n abc def' >>> s.lstrip() 'abc def ' >>> ```
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 EOL' ``` Using '\r\n' as the parameter to rstrip means that it will strip out any trailing combination of '\r' or '\n'. That's why it works in all three cases above. This nuance matters in rare cases. For example, I once had to process a text file which contained an HL7 message. The HL7 standard requires a trailing '\r' as its EOL character. The Windows machine on which I was using this message had appended its own '\r\n' EOL character. Therefore, the end of each line looked like '\r\r\n'. Using rstrip('\r\n') would have taken off the entire '\r\r\n' which is not what I wanted. In that case, I simply sliced off the last two characters instead. Note that unlike Perl's `chomp` function, this will strip all specified characters at the end of the string, not just one: ``` >>> "Hello\n\n\n".rstrip("\n") "Hello" ```
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 result, as it strips all whitespace from the end of the string, not just one newline at most.
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. Hopefully `os.linesep` will contain the right characters. the above works for me.
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 newlines: ``` >>> 'foo\n\n'.rstrip(os.linesep) 'foo' ``` A much closer approximation of typical Perl chomp usage can be accomplished with re.sub, like this: ``` >>> re.sub(os.linesep + r'\Z','','foo\n\n') 'foo\n' ```
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 revision 160292]] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os, sys >>> sys.platform 'linux2' >>> "foo\r\n".rstrip(os.linesep) 'foo\r' >>> ``` Use `"foo".rstrip("\r\n")` instead, as Mike says above.
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 that I need in order to do something useful to each line from this file: ``` import os sep_pos = -len(os.linesep) with open("file.txt") as f: for line in f: if line[sep_pos:] == os.linesep: line = line[:sep_pos] process(line) ```
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 change that to: ``` <img class="size-medium wp-image-113" style="margin-left: 15px;" title="su1" src="http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg" alt="" width="300" height="194" /> ``` I want this to register as HTML so that it is rendered as an image by the browser instead of being displayed as text. I've found how to do this in C# but not in in Python. Can someone help me out? Thanks. Edit: Someone asked why my strings are stored like that. It's because I am using a web-scraping tool that "scans" a web-page and gets certain content from it. The tool (BeautifulSoup) returns the string in that format. ### Related * [Convert XML/HTML Entities into Unicode String in Python](http://stackoverflow.com/questions/57708/convert-xml-html-entities-into-unicode-string-in-python)
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('>', '&gt;').replace('"', '&quot;').replace("'", '&#39;')) ``` To reverse this, the Cheetah function described in Jake's answer should work, but is missing the single-quote. This version includes an updated tuple, with the order of replacement reversed to avoid symmetric problems: ``` def html_decode(s): """ Returns the ASCII decoded version of the given HTML string. This does NOT remove normal HTML tags like <p>. """ htmlCodes = ( ("'", '&#39;'), ('"', '&quot;'), ('>', '&gt;'), ('<', '&lt;'), ('&', '&amp;') ) for code in htmlCodes: s = s.replace(code[1], code[0]) return s unescaped = html_decode(my_string) ``` This, however, is not a general solution; it is only appropriate for strings encoded with `django.utils.html.escape`. More generally, it is a good idea to stick with the standard library: ``` # Python 2.x: import HTMLParser html_parser = HTMLParser.HTMLParser() unescaped = html_parser.unescape(my_string) # Python 3.x: import html.parser html_parser = html.parser.HTMLParser() unescaped = html_parser.unescape(my_string) ``` As a suggestion: it may make more sense to store the HTML unescaped in your database. It'd be worth looking into getting unescaped results back from BeautifulSoup if possible, and avoiding this process altogether. With Django, escaping only occurs during template rendering; so to prevent escaping you just tell the templating engine not to escape your string. To do that, use one of these options in your template: ``` {{ context_var|safe }} {% autoescape off %} {{ context_var }} {% endautoescape %} ```
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 change that to: ``` <img class="size-medium wp-image-113" style="margin-left: 15px;" title="su1" src="http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg" alt="" width="300" height="194" /> ``` I want this to register as HTML so that it is rendered as an image by the browser instead of being displayed as text. I've found how to do this in C# but not in in Python. Can someone help me out? Thanks. Edit: Someone asked why my strings are stored like that. It's because I am using a web-scraping tool that "scans" a web-page and gets certain content from it. The tool (BeautifulSoup) returns the string in that format. ### Related * [Convert XML/HTML Entities into Unicode String in Python](http://stackoverflow.com/questions/57708/convert-xml-html-entities-into-unicode-string-in-python)
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](http://www.crummy.com/software/BeautifulSoup/documentation.html) ``` from BeautifulSoup import BeautifulStoneSoup BeautifulStoneSoup("Sacr&eacute; bl&#101;u!", convertEntities=BeautifulStoneSoup.HTML_ENTITIES).contents[0] # u'Sacr\xe9 bleu!' ```
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 change that to: ``` <img class="size-medium wp-image-113" style="margin-left: 15px;" title="su1" src="http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg" alt="" width="300" height="194" /> ``` I want this to register as HTML so that it is rendered as an image by the browser instead of being displayed as text. I've found how to do this in C# but not in in Python. Can someone help me out? Thanks. Edit: Someone asked why my strings are stored like that. It's because I am using a web-scraping tool that "scans" a web-page and gets certain content from it. The tool (BeautifulSoup) returns the string in that format. ### Related * [Convert XML/HTML Entities into Unicode String in Python](http://stackoverflow.com/questions/57708/convert-xml-html-entities-into-unicode-string-in-python)
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 change that to: ``` <img class="size-medium wp-image-113" style="margin-left: 15px;" title="su1" src="http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg" alt="" width="300" height="194" /> ``` I want this to register as HTML so that it is rendered as an image by the browser instead of being displayed as text. I've found how to do this in C# but not in in Python. Can someone help me out? Thanks. Edit: Someone asked why my strings are stored like that. It's because I am using a web-scraping tool that "scans" a web-page and gets certain content from it. The tool (BeautifulSoup) returns the string in that format. ### Related * [Convert XML/HTML Entities into Unicode String in Python](http://stackoverflow.com/questions/57708/convert-xml-html-entities-into-unicode-string-in-python)
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, I use the following: ``` import re from htmlentitydefs import name2codepoint # for some reason, python 2.5.2 doesn't have this one (apostrophe) name2codepoint['#39'] = 39 def unescape(s): "unescape HTML code refs; c.f. http://wiki.python.org/moin/EscapingHtml" return re.sub('&(%s);' % '|'.join(name2codepoint), lambda m: unichr(name2codepoint[m.group(1)]), s) ``` For anything more complicated, I use BeautifulSoup.
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 change that to: ``` <img class="size-medium wp-image-113" style="margin-left: 15px;" title="su1" src="http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg" alt="" width="300" height="194" /> ``` I want this to register as HTML so that it is rendered as an image by the browser instead of being displayed as text. I've found how to do this in C# but not in in Python. Can someone help me out? Thanks. Edit: Someone asked why my strings are stored like that. It's because I am using a web-scraping tool that "scans" a web-page and gets certain content from it. The tool (BeautifulSoup) returns the string in that format. ### Related * [Convert XML/HTML Entities into Unicode String in Python](http://stackoverflow.com/questions/57708/convert-xml-html-entities-into-unicode-string-in-python)
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 html.parser import HTMLParser # python 3.x (<3.4) except ImportError: from HTMLParser import HTMLParser # python 2.x unescape = HTMLParser().unescape print(unescape("&gt;")) ```
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: ``` from ctypes import cast, CFUNCTYPE, c_char_p, c_long buffer = ''.join(map(chr, [ #0000000000000000 <add>: 0x55, # push %rbp 0x48, 0x89, 0xe5, # mov %rsp,%rbp 0x48, 0x89, 0x7d, 0xf8, # mov %rdi,-0x8(%rbp) 0x48, 0x8b, 0x45, 0xf8, # mov -0x8(%rbp),%rax 0x48, 0x83, 0xc0, 0x0a, # add $0xa,%rax 0xc9, # leaveq 0xc3, # retq ])) fptr = cast(c_char_p(buffer), CFUNCTYPE(c_long, c_long)) print fptr(1234) ``` Now, why does this script keeps doing segmentation fault whenever I run it? I have yet a question about mprotect and no execution flag. It is said to protect against most basic security exploits like buffer overruns. But what is the real reason it's in use? You could just keep on writing until you hit the .text, then inject your instructions into a nice, PROT\_EXEC -area. Unless, of course, you use a write protection in .text But then, why have that PROT\_EXEC everywhere anyway? Wouldn't it just help tremendously that your .text section is write protected?
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 support it. The idea is to protect against certain buffer overflow attacks. Eg. A common attack is to overflow a stack variable, rewriting the return address to point to code you have inserted. With a non-executable stack this now only produces a segfault, rather than control of the process. Similar attacks also exist for heap memory. To get around it, you need to alter the protection. This can only be performed on page aligned memory, so you'll probably need to change your code to something like the below: ``` libc = CDLL('libc.so') # Some constants PROT_READ = 1 PROT_WRITE = 2 PROT_EXEC = 4 def executable_code(buffer): """Return a pointer to a page-aligned executable buffer filled in with the data of the string provided. The pointer should be freed with libc.free() when finished""" buf = c_char_p(buffer) size = len(buffer) # Need to align to a page boundary, so use valloc addr = libc.valloc(size) addr = c_void_p(addr) if 0 == addr: raise Exception("Failed to allocate memory") memmove(addr, buf, size) if 0 != libc.mprotect(addr, len(buffer), PROT_READ | PROT_WRITE | PROT_EXEC): raise Exception("Failed to set protection on buffer") return addr code_ptr = executable_code(buffer) fptr = cast(code_ptr, CFUNCTYPE(c_long, c_long)) print fptr(1234) libc.free(code_ptr) ``` Note: It may be a good idea to unset the executable flag before freeing the page. Most C libraries don't actually return the memory to the OS when done, but keep it in their own pool. This could mean they will reuse the page elsewhere without clearing the EXEC bit, bypassing the security benefit. Also note that this is fairly non-portable. I've tested it on linux, but not on any other OS. It won't work on windows, buy may do on other unixes (BSD, OsX?).
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 cover. Suggestions?
**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']) print "Cover url: %s" % movie['cover url'] ``` If for some reason you can't use the above, you can always use something like BeautifulSoup to get the cover url. ``` from BeautifulSoup import BeautifulSoup import imdb access = imdb.IMDb() movie = access.get_movie(1132626) page = urllib2.urlopen(access.get_imdbURL(movie)) soup = BeautifulSoup(page) cover_div = soup.find(attrs={"class" : "photo"}) cover_url = (photo_div.find('img'))['src'] print "Cover url: %s" % cover_url ```
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 use each one? The documentation didn't really explain it very well.
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 use each one? The documentation didn't really explain it very well.
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 use each one? The documentation didn't really explain it very well.
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 currently seems not actively developed and not supported on multiple platform) or something like [pystatgrab](http://www.i-scream.org/pystatgrab/) (again no activity since 2007 it seems and no support for Windows). 2. Using platform specific code such as using a `os.popen("ps")` or similar for the \*nix systems and `MEMORYSTATUS` in `ctypes.windll.kernel32` (see [this recipe on ActiveState](http://code.activestate.com/recipes/511491/)) for the Windows platform. One could put a Python class together with all those code snippets. It's not that those methods are bad but is there already a well-supported, multi-platform way of doing the same thing?
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/scripts/default.mspx?mfr=true> NOTE: the WMI interface/process is also available for performing similar tasks I'm not using it here because the current method covers my needs, but if someday it's needed to extend or improve this, then may want to investigate the WMI tools a vailable. WMI for python: <http://tgolden.sc.sabren.com/python/wmi.html> The code: ``` ''' Monitor window processes 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/scripts/default.mspx?mfr=true NOTE: the WMI interface/process is also available for performing similar tasks I'm not using it here because the current method covers my needs, but if someday it's needed to extend or improve this module, then may want to investigate the WMI tools available. WMI for python: http://tgolden.sc.sabren.com/python/wmi.html ''' __revision__ = 3 import win32com.client from ctypes import * from ctypes.wintypes import * import pythoncom import pywintypes import datetime class MEMORYSTATUS(Structure): _fields_ = [ ('dwLength', DWORD), ('dwMemoryLoad', DWORD), ('dwTotalPhys', DWORD), ('dwAvailPhys', DWORD), ('dwTotalPageFile', DWORD), ('dwAvailPageFile', DWORD), ('dwTotalVirtual', DWORD), ('dwAvailVirtual', DWORD), ] def winmem(): x = MEMORYSTATUS() # create the structure windll.kernel32.GlobalMemoryStatus(byref(x)) # from cytypes.wintypes return x class process_stats: '''process_stats is able to provide counters of (all?) the items available in perfmon. Refer to the self.supported_types keys for the currently supported 'Performance Objects' To add logging support for other data you can derive the necessary data from perfmon: --------- perfmon can be run from windows 'run' menu by entering 'perfmon' and enter. Clicking on the '+' will open the 'add counters' menu, From the 'Add Counters' dialog, the 'Performance object' is the self.support_types key. --> Where spaces are removed and symbols are entered as text (Ex. # == Number, % == Percent) For the items you wish to log add the proper attribute name in the list in the self.supported_types dictionary, keyed by the 'Performance Object' name as mentioned above. --------- NOTE: The 'NETFramework_NETCLRMemory' key does not seem to log dotnet 2.0 properly. Initially the python implementation was derived from: http://www.microsoft.com/technet/scriptcenter/scripts/default.mspx?mfr=true ''' def __init__(self,process_name_list=[],perf_object_list=[],filter_list=[]): '''process_names_list == the list of all processes to log (if empty log all) perf_object_list == list of process counters to log filter_list == list of text to filter print_results == boolean, output to stdout ''' pythoncom.CoInitialize() # Needed when run by the same process in a thread self.process_name_list = process_name_list self.perf_object_list = perf_object_list self.filter_list = filter_list self.win32_perf_base = 'Win32_PerfFormattedData_' # Define new datatypes here! self.supported_types = { 'NETFramework_NETCLRMemory': [ 'Name', 'NumberTotalCommittedBytes', 'NumberTotalReservedBytes', 'NumberInducedGC', 'NumberGen0Collections', 'NumberGen1Collections', 'NumberGen2Collections', 'PromotedMemoryFromGen0', 'PromotedMemoryFromGen1', 'PercentTimeInGC', 'LargeObjectHeapSize' ], 'PerfProc_Process': [ 'Name', 'PrivateBytes', 'ElapsedTime', 'IDProcess',# pid 'Caption', 'CreatingProcessID', 'Description', 'IODataBytesPersec', 'IODataOperationsPersec', 'IOOtherBytesPersec', 'IOOtherOperationsPersec', 'IOReadBytesPersec', 'IOReadOperationsPersec', 'IOWriteBytesPersec', 'IOWriteOperationsPersec' ] } def get_pid_stats(self, pid): this_proc_dict = {} pythoncom.CoInitialize() # Needed when run by the same process in a thread if not self.perf_object_list: perf_object_list = self.supported_types.keys() for counter_type in perf_object_list: strComputer = "." objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator") objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2") query_str = '''Select * from %s%s''' % (self.win32_perf_base,counter_type) colItems = objSWbemServices.ExecQuery(query_str) # "Select * from Win32_PerfFormattedData_PerfProc_Process")# changed from Win32_Thread if len(colItems) > 0: for objItem in colItems: if hasattr(objItem, 'IDProcess') and pid == objItem.IDProcess: for attribute in self.supported_types[counter_type]: eval_str = 'objItem.%s' % (attribute) this_proc_dict[attribute] = eval(eval_str) this_proc_dict['TimeStamp'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.') + str(datetime.datetime.now().microsecond)[:3] break return this_proc_dict def get_stats(self): ''' Show process stats for all processes in given list, if none given return all processes If filter list is defined return only the items that match or contained in the list Returns a list of result dictionaries ''' pythoncom.CoInitialize() # Needed when run by the same process in a thread proc_results_list = [] if not self.perf_object_list: perf_object_list = self.supported_types.keys() for counter_type in perf_object_list: strComputer = "." objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator") objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2") query_str = '''Select * from %s%s''' % (self.win32_perf_base,counter_type) colItems = objSWbemServices.ExecQuery(query_str) # "Select * from Win32_PerfFormattedData_PerfProc_Process")# changed from Win32_Thread try: if len(colItems) > 0: for objItem in colItems: found_flag = False this_proc_dict = {} if not self.process_name_list: found_flag = True else: # Check if process name is in the process name list, allow print if it is for proc_name in self.process_name_list: obj_name = objItem.Name if proc_name.lower() in obj_name.lower(): # will log if contains name found_flag = True break if found_flag: for attribute in self.supported_types[counter_type]: eval_str = 'objItem.%s' % (attribute) this_proc_dict[attribute] = eval(eval_str) this_proc_dict['TimeStamp'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.') + str(datetime.datetime.now().microsecond)[:3] proc_results_list.append(this_proc_dict) except pywintypes.com_error, err_msg: # Ignore and continue (proc_mem_logger calls this function once per second) continue return proc_results_list def get_sys_stats(): ''' Returns a dictionary of the system stats''' pythoncom.CoInitialize() # Needed when run by the same process in a thread x = winmem() sys_dict = { 'dwAvailPhys': x.dwAvailPhys, 'dwAvailVirtual':x.dwAvailVirtual } return sys_dict if __name__ == '__main__': # This area used for testing only sys_dict = get_sys_stats() stats_processor = process_stats(process_name_list=['process2watch'],perf_object_list=[],filter_list=[]) proc_results = stats_processor.get_stats() for result_dict in proc_results: print result_dict import os this_pid = os.getpid() this_proc_results = stats_processor.get_pid_stats(this_pid) print 'this proc results:' print this_proc_results ``` <http://monkut.webfactional.com/blog/archive/2009/1/21/windows-process-memory-logging-python>
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 currently seems not actively developed and not supported on multiple platform) or something like [pystatgrab](http://www.i-scream.org/pystatgrab/) (again no activity since 2007 it seems and no support for Windows). 2. Using platform specific code such as using a `os.popen("ps")` or similar for the \*nix systems and `MEMORYSTATUS` in `ctypes.windll.kernel32` (see [this recipe on ActiveState](http://code.activestate.com/recipes/511491/)) for the Windows platform. One could put a Python class together with all those code snippets. It's not that those methods are bad but is there already a well-supported, multi-platform way of doing the same thing?
[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, implementing many functionalities offered by tools like ps, top and Windows task manager. > > It currently supports Linux, Windows, OSX, Sun Solaris, FreeBSD, OpenBSD and NetBSD, both 32-bit and 64-bit architectures, with Python versions from 2.6 to 3.5 (users of Python 2.4 and 2.5 may use 2.1.3 version).
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 SOAP calls. I know of no unified way of calling a WCF service in Python, regardless of communication protocol.
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 to connect to exposed services from WCF and a RESTful layer. There needs to be some data massaging to help do what you need, especially if you need to bind to several namespaces.
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 app is using? Target platform is \*nix, however I would like to do it on a Win host also.
``` >>> 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 accumulated (processor or other) times, in seconds. The items are: user time, system time, children's user time, children's system time, and elapsed real time since a fixed point in the past, in that order. See the Unix manual page times(2) or the corresponding Windows Platform API documentation. Availability: Macintosh, Unix, Windows.
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 app is using? Target platform is \*nix, however I would like to do it on a Win host also.
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). Python doesn't have {} to signify "scope" so I think this might be my problem? Am I formatting my code wrong? Edit: the exact error is: `Invalid block tag: 'embed2'` Edit2: Since someone said what I'm doing is not supported by Django templates, I rewrote the code, putting the logic in the view. I now have: ``` embed_list = [] for embed in embeds: embed_list[len(embed_list):] = [embed.replace("&lt;", "<")] #this is line 35 return render_to_response("scanvideos.html", { "embed_list" :embed_list }) ``` However, I now get an error: `'NoneType' object is not callable" on line 35`.
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 that I can create two SomeEntity records, one with some\_field='some value' and one with some\_field='Some Value' because the unique constraint on some\_field appears to be case sensitive. Is there some way to force sqlite to perform a case *in*sensitive comparison when checking for uniqueness? I can't seem to find an option for this in Django's docs and I'm wondering if there's something that I can do directly to sqlite to get it to behave the way I want. :-)
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 example shows a custom collation that sorts “the wrong way”: ``` import sqlite3 def collate_reverse(string1, string2): return -cmp(string1, string2) con = sqlite3.connect(":memory:") con.create_collation("reverse", collate_reverse) cur = con.cursor() cur.execute("create table test(x)") cur.executemany("insert into test(x) values (?)", [("a",), ("b",)]) cur.execute("select x from test order by x collate reverse") for row in cur: print row con.close() ``` Additional python documentation for sqlite3 shown [here](http://docs.python.org/library/sqlite3.html)
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 that it would have required that users install an additional dependency made us switch to SWIG. * SWIG SWIG's main advantage for us was that it doesn't require end users to install it to use the final program. What have you used to do this, and what has been your experience with it?
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 if you get the library wrapped in SWIG for Python you're more than half-way there to getting a Java/Perl/Ruby wrapper as well. I don't think there's a clear-cut choice: for smaller projects, I'd go with Boost.Python again, for larger long-lived projects, the extra investment in SWIG is worth it.
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 that it would have required that users install an additional dependency made us switch to SWIG. * SWIG SWIG's main advantage for us was that it doesn't require end users to install it to use the final program. What have you used to do this, and what has been your experience with it?
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) vector<int>; } ``` I'm running `SWIG Version 1.3.36` and calling swig with `-Wall` and I get no warnings. I'm able to get access to a list but I get a bunch of warnings when compiling with `-Wall` (with `g++ (GCC) 4.2.4` ) the generated C++ code that say: ``` warning: dereferencing type-punned pointer will break strict-aliasing rules ``` Am I exposing the function correctly? If so, what does the warning mean? --- These are the lines before the offending line in the same function: ``` SWIGINTERN PyObject *_wrap_IntVector_erase__SWIG_0(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; std::vector *arg1 = (std::vector *) 0 ; std::vector::iterator arg2 ; std::vector::iterator result; void *argp1 = 0 ; int res1 = 0 ; swig::PySwigIterator *iter2 = 0 ; int res2 ; PyObject * obj0 = 0 ; PyObject * obj1 = 0 ; if (!PyArg_ParseTuple(args,(char *)"OO:IntVector_erase",&obj0,&obj1)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_std__vectorT_int_std__allocatorT_int_t_t, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "IntVector_erase" "', argument " "1"" of type '" "std::vector *""'"); } arg1 = reinterpret_cast * >(argp1); ``` And this is the offending line: ``` res2 = SWIG_ConvertPtr(obj1, SWIG_as_voidptrptr(&iter2), swig::PySwigIterator::descriptor(), 0); ``` More code follows that. The warning generated when compiling with g++ 4.2.4 is: ``` swig_iss_wrap.cxx: In function ‘PyObject* _wrap_IntVector_erase__SWIG_0(PyObject*, PyObject*)’: swig_iss_wrap.cxx:5885: warning: dereferencing type-punned pointer will break strict-aliasing rules ```
``` %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 screenshots from the article, showing what I'm interested in doing. An example of the type of things I'm interested: <http://www.mono-project.com/archived/images/7/75/GSharpPlot.png> They are able to add hooks to produce GUI elements like the plot, or even do silly things like: <http://www.mono-project.com/archived/images/b/bf/GSharpRenderHandler.png> I don't think this is possible with any of the console shells I've tried (the regular python shell, ipython). Edit: I'm not looking for an IDE. If you look at the link, you'll get an idea of what I want.
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 another blind alley: I went looking at DrPython hoping it would be similar to PLT's DrScheme, which looks comparable to example you've linked too. Unfortunately DrPython isn't all that much like DrScheme.
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 screenshots from the article, showing what I'm interested in doing. An example of the type of things I'm interested: <http://www.mono-project.com/archived/images/7/75/GSharpPlot.png> They are able to add hooks to produce GUI elements like the plot, or even do silly things like: <http://www.mono-project.com/archived/images/b/bf/GSharpRenderHandler.png> I don't think this is possible with any of the console shells I've tried (the regular python shell, ipython). Edit: I'm not looking for an IDE. If you look at the link, you'll get an idea of what I want.
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.sagenb.org). These aren't quite shells - they're designed more as a mathematical notebook (so for instance, you can modify an earlier result and have the change propogate to later calculations), but they're close to what you're looking for, and could probably be modified to be used as such.
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 above usage is equivalent to the following `lambda`. ``` print_hello = lambda *a, **kw: sys.stdout.write("Hello world\n", *a, **kw) ```
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 ```