instruction
stringlengths
12
148
input
stringlengths
16
30.2k
output
stringlengths
11
27.3k
Convert a Unicode string to a string in Python (containing extra symbols)
How do you convert a Unicode string (containing extra characters like £ $, etc.) into a Python string?
title = u"Klüft skräms inför på fédéral électoral große" import unicodedata unicodedata.normalize('NFKD', title).encode('ascii','ignore') 'Kluft skrams infor pa federal electoral groe'
Where's my JSON data in my incoming Django request?
I'm trying to process incoming JSON/Ajax requests with Django/Python. request.is_ajax() is True on the request, but I have no idea where the payload is with the JSON data. request.POST.dir contains this: ['__class__', '__cmp__', '__contains__', '__copy__', '__deepcopy__', '__delattr__', '__delitem__', '__dict__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__str__', '__weakref__', '_assert_mutable', '_encoding', '_get_encoding', '_mutable', '_set_encoding', 'appendlist', 'clear', 'copy', 'encoding', 'fromkeys', 'get', 'getlist', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'lists', 'pop', 'popitem', 'setdefault', 'setlist', 'setlistdefault', 'update', 'urlencode', 'values'] There are apparently no keys in the request post keys. When I look at the POST in Firebug, there is JSON data being sent up in the request.
If you are posting JSON to Django, I think you want request.body (request.raw_post_data on Django < 1.4). This will give you the raw JSON data sent via the post. From there you can process it further. Here is an example using JavaScript, jQuery, jquery-json and Django. JavaScript: var myEvent = {id: calEvent.id, start: calEvent.start, end: calEvent.end, allDay: calEvent.allDay }; $.ajax({ url: '/event/save-json/', type: 'POST', contentType: 'application/json; charset=utf-8', data: $.toJSON(myEvent), dataType: 'text', success: function(result) { alert(result.Result); } }); Django: def save_events_json(request): if request.is_ajax(): if request.method == 'POST': print 'Raw Data: "%s"' % request.body return HttpResponse("OK") Django < 1.4: def save_events_json(request): if request.is_ajax(): if request.method == 'POST': print 'Raw Data: "%s"' % request.raw_post_data return HttpResponse("OK")
Using numpy to build an array of all combinations of two arrays
I'm trying to run over the parameters space of a 6 parameter function to study it's numerical behavior before trying to do anything complex with it so I'm searching for a efficient way to do this. My function takes float values given a 6-dim numpy array as input. What I tried to do initially was this: First I created a function that takes 2 arrays and generate an array with all combinations of values from the two arrays from numpy import * def comb(a,b): c = [] for i in a: for j in b: c.append(r_[i,j]) return c Then I used reduce() to apply that to m copies of the same array: def combs(a,m): return reduce(comb,[a]*m) And then I evaluate my function like this: values = combs(np.arange(0,1,0.1),6) for val in values: print F(val) This works but it's waaaay too slow. I know the space of parameters is huge, but this shouldn't be so slow. I have only sampled 106 (a million) points in this example and it took more than 15 seconds just to create the array values. Do you know any more efficient way of doing this with numpy? I can modify the way the function F takes it's arguments if it's necessary.
Here's a pure-numpy implementation. It's ca. 5× faster than using itertools. import numpy as np def cartesian(arrays, out=None): """ Generate a cartesian product of input arrays. Parameters ---------- arrays : list of array-like 1-D arrays to form the cartesian product of. out : ndarray Array to place the cartesian product in. Returns ------- out : ndarray 2-D array of shape (M, len(arrays)) containing cartesian products formed of input arrays. Examples -------- >>> cartesian(([1, 2, 3], [4, 5], [6, 7])) array([[1, 4, 6], [1, 4, 7], [1, 5, 6], [1, 5, 7], [2, 4, 6], [2, 4, 7], [2, 5, 6], [2, 5, 7], [3, 4, 6], [3, 4, 7], [3, 5, 6], [3, 5, 7]]) """ arrays = [np.asarray(x) for x in arrays] dtype = arrays[0].dtype n = np.prod([x.size for x in arrays]) if out is None: out = np.zeros([n, len(arrays)], dtype=dtype) m = n / arrays[0].size out[:,0] = np.repeat(arrays[0], m) if arrays[1:]: cartesian(arrays[1:], out=out[0:m,1:]) for j in xrange(1, arrays[0].size): out[j*m:(j+1)*m,1:] = out[0:m,1:] return out
how do I use CommaSeparatedIntegerField in django?
There is almost no documentation for it here: http://docs.djangoproject.com/en/dev/ref/models/fields/#commaseparatedintegerfield Maybe someone could, by example, show me how to populate a CommaSeparatedIntegerField in Django? -thanks.
Looking at the source for django... class CommaSeparatedIntegerField(CharField): def formfield(self, **kwargs): defaults = { 'form_class': forms.RegexField, 'regex': '^[\d,]+$', 'max_length': self.max_length, 'error_messages': { 'invalid': _(u'Enter only digits separated by commas.'), } } defaults.update(kwargs) return super(CommaSeparatedIntegerField, self).formfield(**defaults) Check out that regex validator. Looks like as long as you give it a list of integers and commas, django won't complain. You can define it just like a charfield basically: class Foo(models.Model): int_list = models.CommaSeparatedIntegerField(max_length=200) And populate it like this: f = Foo(int_list="1,2,3,4,5")
Django and urls.py: How do I HttpResponseRedirect via a named url?
I'm writing a member-based web application, and I need to be able to redirect the page after login. I want to use the named url from my urls.py script in my views.py file for the login application, but I can't for the life of me figure out what to do. What I have is this: def login(request): if request.session.has_key('user'): if request.session['user'] is not None: return HttpResponseRedirect('/path/to/page.html') What I want to accomplish is something like: def login(request): if request.session.has_key('user'): if request.session['user'] is not None: return HttpResponseRedirect url pageName I get syntax errors when I execute this, any ideas?
You need to use the reverse() utils function. from django.core.urlresolvers import reverse def myview(request): return HttpResponseRedirect(reverse('arch-summary', args=[1945])) Where args satisfies all the arguments in your url's regular expression. You can also supply named args by passing a dictionary.
Decoding HTML entities with Python
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out what I am doing wrong. Take for example: "U.S. Adviser&#8217;s Blunt Memo on Iraq: Time &#8216;to Go Home&#8217;" I've tried BeautifulSoup, decode('iso-8859-1'), and django.utils.encoding's smart_str without any success.
Actually what you have are not HTML entities. There are THREE varieties of those &.....; thingies -- for example &#160; &#xa0; &nbsp; all mean U+00A0 NO-BREAK SPACE. &#160; (the type you have) is a "numeric character reference" (decimal). &#xa0; is a "numeric character reference" (hexadecimal). &nbsp; is an entity. Further reading: http://htmlhelp.com/reference/html40/entities/ Here you will find code for Python2.x that does all three in one scan through the input: http://effbot.org/zone/re-sub.htm#unescape-html
No module named _sqlite3
I am trying to run a Django app on my VPS running Debian 5. When I run a demo app, it comes back with this error: File "/usr/local/lib/python2.5/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/usr/local/lib/python2.5/site-packages/django/db/backends/sqlite3/base.py", line 30, in <module> raise ImproperlyConfigured, "Error loading %s: %s" % (module, exc) ImproperlyConfigured: Error loading either pysqlite2 or sqlite3 modules (tried in that order): No module named _sqlite3 Looking at the Python install, it gives the same error: Python 2.5.2 (r252:60911, May 12 2009, 07:46:31) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sqlite3 Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python2.5/sqlite3/__init__.py", line 24, in <module> from dbapi2 import * File "/usr/local/lib/python2.5/sqlite3/dbapi2.py", line 27, in <module> from _sqlite3 import * ImportError: No module named _sqlite3 >>> Reading on the web, I learn that Python 2.5 should come with all the necessary SQLite wrappers included. Do I need to reinstall Python, or is there another way to get this module up and running?
I had the same problem (building python2.5 from source on Ubuntu Lucid), and import sqlite3 threw this same exception. I've installed libsqlite3-dev from the package manager, recompiled python2.5, and then the import worked.
Python: high precision time.sleep
can you tell me how can I get a high precision sleep-function in Python2.6 on Win32 and on Linux?
You can use floating-point numbers in sleep(): The argument may be a floating point number to indicate a more precise sleep time. So time.sleep(0.5) will sleep for half a second. In practice, however, it's unlikely that you will get much more than millisecond precision with sleep because operating systems usually only support millisecond sleeps and because very short amounts of time quickly get unreliable.
What is the most compatible way to install python modules on a Mac?
I'm starting to learn python and loving it. I work on a Mac mainly as well as Linux. I'm finding that on Linux (Ubuntu 9.04 mostly) when I install a python module using apt-get it works fine. I can import it with no trouble. On the Mac, I'm used to using Macports to install all the Unixy stuff. However, I'm finding that most of the python modules I install with it are not being seen by python. I've spent some time playing around with PATH settings and using python_select . Nothing has really worked and at this point I'm not really understanding, instead I'm just poking around. I get the impression that Macports isn't universally loved for managing python modules. I'd like to start fresh using a more "accepted" (if that's the right word) approach. So, I was wondering, what is the method that Mac python developers use to manage their modules? Bonus questions: Do you use Apple's python, or some other version? Do you compile everything from source or is there a package manger that works well (Fink?). Any tips or suggestions here are greatly appreciated. Thanks for your time. :)
The most popular way to manage python packages (if you're not using your system package manager) is to use setuptools and easy_install. It is probably already installed on your system. Use it like this: easy_install django easy_install uses the Python Package Index which is an amazing resource for python developers. Have a look around to see what packages are available. A better option is pip, which is gaining traction, as it attempts to fix a lot of the problems associated with easy_install. Pip uses the same package repository as easy_install, it just works better. Really the only time use need to use easy_install is for this command: easy_install pip After that, use: pip install django At some point you will probably want to learn a bit about virtualenv. If you do a lot of python development on projects with conflicting package requirements, virtualenv is a godsend. It will allow you to have completely different versions of various packages, and switch between them easily depending your needs. Regarding which python to use, sticking with Apple's python will give you the least headaches, but If you need a newer version (Leopard is 2.5.1 I believe), I would go with the macports python 2.6.
What user do python scripts run as in windows?
I'm trying to have python delete some directories and I get access errors on them. I think its that the python user account doesn't have rights? WindowsError: [Error 5] Access is denied: 'path' is what I get when I run the script. I've tried shutil.rmtree os.remove os.rmdir they all return the same error.
We've had issues removing files and directories on Windows, even if we had just copied them, if they were set to 'readonly'. shutil.rmtree() offers you sort of exception handlers to handle this situation. You call it and provide an exception handler like this: import errno, os, stat, shutil def handleRemoveReadonly(func, path, exc): excvalue = exc[1] if func in (os.rmdir, os.remove) and excvalue.errno == errno.EACCES: os.chmod(path, stat.S_IRWXU| stat.S_IRWXG| stat.S_IRWXO) # 0777 func(path) else: raise shutil.rmtree(filename, ignore_errors=False, onerror=handleRemoveReadonly) You might want to try that.
How to get environment from a subprocess in Python
I want to call a process via a python program, however, this process need some specific environment variables that are set by another process. How can I get the first process environment variables to pass them to the second? This is what the program look like: import subprocess subprocess.call(['proc1']) # this set env. variables for proc2 subprocess.call(['proc2']) # this must have env. variables set by proc1 to work but the to process don't share the same environment. Note that these programs aren't mine (the first is big and ugly .bat file and the second a proprietary soft) so I can't modify them (ok, I can extract all that I need from the .bat but it's very combersome). N.B.: I am using Windows, but I prefer a cross-platform solution (but my problem wouldn't happen on a Unix-like ...)
Here's an example of how you can extract environment variables from a batch or cmd file without creating a wrapper script. Enjoy. from __future__ import print_function import sys import subprocess import itertools def validate_pair(ob): try: if not (len(ob) == 2): print("Unexpected result:", ob, file=sys.stderr) raise ValueError except: return False return True def consume(iter): try: while True: next(iter) except StopIteration: pass def get_environment_from_batch_command(env_cmd, initial=None): """ Take a command (either a single command or list of arguments) and return the environment created after running that command. Note that if the command must be a batch file or .cmd file, or the changes to the environment will not be captured. If initial is supplied, it is used as the initial environment passed to the child process. """ if not isinstance(env_cmd, (list, tuple)): env_cmd = [env_cmd] # construct the command that will alter the environment env_cmd = subprocess.list2cmdline(env_cmd) # create a tag so we can tell in the output when the proc is done tag = 'Done running command' # construct a cmd.exe command to do accomplish this cmd = 'cmd.exe /s /c "{env_cmd} && echo "{tag}" && set"'.format(**vars()) # launch the process proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, env=initial) # parse the output sent to stdout lines = proc.stdout # consume whatever output occurs until the tag is reached consume(itertools.takewhile(lambda l: tag not in l, lines)) # define a way to handle each KEY=VALUE line handle_line = lambda l: l.rstrip().split('=',1) # parse key/values into pairs pairs = map(handle_line, lines) # make sure the pairs are valid valid_pairs = filter(validate_pair, pairs) # construct a dictionary of the pairs result = dict(valid_pairs) # let the process finish proc.communicate() return result So to answer your question, you would create a .py file that does the following: env = get_environment_from_batch_command('proc1') subprocess.Popen('proc2', env=env)
oauth google using python
i am fairly new to programming for web. and i want to start from scratch here. i tried to search the net but ended up completely confused. now what i want to learn is how to authenticate a google account through a python script. can anyone please provide me with a code fragment or any example. thanks a lot in advance.
I spent a whole day on coding this, after several failed attempts over the past few weeks. This only gets you as far as the first step, but it does so without any external libraries. And yes, I know it's close to two years after the OP, but from what I could see it still needed to be done. #!/usr/bin/python 'demo Google OAuth' import sys, os, urllib, urllib2, time, httplib import hmac, hashlib, random, re, base64 PARAMETERS = { 'oauth_consumer_key': os.getenv('OAUTH_CONSUMER_KEY') or 'anonymous', 'oauth_signature_method': 'HMAC-SHA1', 'oauth_signature': '', 'oauth_timestamp': os.getenv('OAUTH_TIMESTAMP') or '%d' % time.time(), 'oauth_nonce': os.getenv('OAUTH_NONCE') or '%x' % random.getrandbits(64), 'oauth_version': '1.0', 'oauth_callback': os.getenv('OAUTH_CALLBACK') or 'callback', } SCOPE = {'scope': 'https://www.google.com/calendar/feeds/'} SECRET = os.getenv('OAUTH_CONSUMER_SECRET') or 'anonymous' def google_oauth(): 'OAuthGetRequestToken, OAuthAuthorizeToken, OAuthGetAccessToken' request_token = get_request_token() return request_token def get_request_token(): 'ask Google for a request token' url = 'https://www.google.com/accounts/OAuthGetRequestToken' token_secret = '' # we don't have a token secret yet PARAMETERS['oauth_signature'] = sign('&'.join((SECRET, token_secret)), '&'.join(map(urlencode, ('GET', url, parameters('signing'))))) body = urllib.urlencode(SCOPE) request = urllib2.Request(url + '?' + body) request.add_header('Authorization', 'OAuth ' + parameters('header')) opener = urllib2.build_opener(urllib2.HTTPSHandler(debuglevel = 1)) response = opener.open(request) reply = response.read() response.close() return reply def byte_encode(match): 'for use with re.sub' return '%%%02X' % ord(match.group()) def urlencode(string): "unreserved = ALPHA, DIGIT, '-', '.', '_', '~'" return re.sub(re.compile('[^0-9A-Za-z._~-]'), byte_encode, string.encode('utf8')) def sign(secret, text): print >>sys.stderr, 'signature base string: "%s", secret: %s' % ( repr(text), repr(secret)) digest = hmac.new(secret, text, hashlib.sha1).digest() return urlencode(base64.encodestring(digest).rstrip()) def base64string(hexstring): recoded = urlencode(base64.encodestring(hexstring.decode('hex')).rstrip()) print >>sys.stderr, 'recoded:', recoded return recoded def parameters(format): if format == 'header': formatted = ', '.join(['%s="%s"' % (key, value) for key, value in PARAMETERS.items()]) elif format == 'signing': formatted = '&'.join(sorted(['%s=%s' % (key, urlencode(value.encode('utf8'))) for key, value in (PARAMETERS.items() + SCOPE.items()) if key not in ['oauth_signature']])) #print >>sys.stderr, format, formatted return formatted def hmac_sha1_test(): 'from tools.ietf.org/html/rfc2202' assert sign('\x0b' * 20, 'Hi There') == base64string( 'b617318655057264e28bc0b6fb378c8ef146be00') assert sign('Jefe', 'what do ya want for nothing?') == base64string( 'effcdf6ae5eb2fa2d27416d5f184df9c259a7c79') assert sign('\xaa' * 20, '\xdd' * 50) == base64string( '125d7342b9ac11cd91a39af48aa17b4f63f175d3') # last test from http://oauth.net/core/1.0/#rfc.section.9.1.1, app. A.5.2 assert sign('kd94hf93k423kf44&pfkkdhi9sl3r4s00', 'GET&http%3A%2F%2Fphotos.example.net%2Fphotos&file%3Dvacation.jpg%26' + \ 'oauth_consumer_key%3Ddpf43f3p2l4k3l03%26oauth_nonce%3D' + \ 'kllo9940pd9333jh%26oauth_signature_method%3DHMAC-SHA1%26' + \ 'oauth_timestamp%3D1191242096%26oauth_token%3Dnnch734d00sl2jdk%26' + \ 'oauth_version%3D1.0%26size%3Doriginal') == urlencode( 'tR3+Ty81lMeYAr/Fid0kMTYa/WM=') return True if __name__ == '__main__': command = os.path.splitext(os.path.basename(sys.argv[0]))[0] print eval(command)(*sys.argv[1:]) Save it as google_oauth.py, and you can link to it like so: ln -s google_oauth.py hmac_sha1_test.py to test any of the subroutines. Combined with the use of environment variables, you can compare your results with those of Google's OAuth Playground (other folks here provided the link) and see where you are going wrong. I found many problems with the script that way; there may well be many more. But if you invoke ./google_oauth.py, you should see something like this: jcomeau@intrepid:~/rentacoder/marchie$ ./google_oauth.py signature base string: "'GET&https%3A%2F%2Fwww.google.com%2Faccounts%2FOAuthGetRequestToken&oauth_callback%3Dcallback%26oauth_consumer_key%3Danonymous%26oauth_nonce%3Da64720fda018906b%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1302253695%26oauth_version%3D1.0%26scope%3Dhttps%253A%252F%252Fwww.google.com%252Fcalendar%252Ffeeds%252F'", secret: 'anonymous&' send: 'GET /accounts/OAuthGetRequestToken?scope=https%3A%2F%2Fwww.google.com%2Fcalendar%2Ffeeds%2F HTTP/1.1\r\nAccept-Encoding: identity\r\nHost: www.google.com\r\nConnection: close\r\nAuthorization: OAuth oauth_nonce="a64720fda018906b", oauth_timestamp="1302253695", oauth_consumer_key="anonymous", oauth_signature_method="HMAC-SHA1", oauth_version="1.0", oauth_signature="LSJxopFXWN71sTSIBIkNeGgsOjc%3D", oauth_callback="callback"\r\nUser-Agent: Python-urllib/2.6\r\n\r\n' reply: 'HTTP/1.1 200 OK\r\n' header: Content-Type: text/plain; charset=UTF-8 header: Date: Fri, 08 Apr 2011 09:08:20 GMT header: Expires: Fri, 08 Apr 2011 09:08:20 GMT header: Cache-Control: private, max-age=0 header: X-Content-Type-Options: nosniff header: X-XSS-Protection: 1; mode=block header: Content-Length: 118 header: Server: GSE header: Connection: close oauth_token=4%2FfvSIWW9WBHXa_CjInpOf4FdNYhCj&oauth_token_secret=qhB1EGIKjL1pG9POF2ZOcQk3&oauth_callback_confirmed=true
How might I remove duplicate lines from a file?
I have a file with one column. How to delete repeated lines in a file?
On Unix/Linux, use the uniq command, as per David Locke's answer, or sort, as per William Pursell's comment. If you need a Python script: lines_seen = set() # holds lines already seen outfile = open(outfilename, "w") for line in open(infilename, "r"): if line not in lines_seen: # not a duplicate outfile.write(line) lines_seen.add(line) outfile.close() Update: The sort/uniq combination will remove duplicates but return a file with the lines sorted, which may or may not be what you want. The Python script above won't reorder lines, but just drop duplicates. Of course, to get the script above to sort as well, just leave out the outfile.write(line) and instead, immediately after the loop, do outfile.writelines(sorted(lines_seen)).
Ubuntu + virtualenv = a mess? virtualenv hates dist-packages, wants site-packages
Can someone please explain to me what is going on with python in ubuntu 9.04? I'm trying to spin up virtualenv, and the --no-site-packages flag seems to do nothing with ubuntu. I installed virtualenv 1.3.3 with easy_install (which I've upgraded to setuptools 0.6c9) and everything seems to be installed to /usr/local/lib/python2.6/dist-packages I assume that when installing a package using apt-get, it's placed in /usr/lib/python2.6/dist-packages/ ? The issue is, there is a /usr/local/lib/python2.6/site-packages as well that just sits there being empty. It would seem (by looking at the path in a virtualenv) that this is the folder virtualenv uses as backup. Thus even thought I omit --no-site-packages, I cant access my local systems packages from any of my virtualenv's. So my questions are: How do I get virtualenv to point to one of the dist-packages? Which dist-packages should I point it to? /usr/lib/python2.6/dist-packages or /usr/local/lib/python2.6/dist-packages/ What is the point of /usr/lib/python2.6/site-packages? There's nothing in there! Is it first come first serve on the path? If I have a newer version of package XYZ installed in /usr/local/lib/python2.6/dist-packages/ and and older one (from ubuntu repos/apt-get) in /usr/lib/python2.6/dist-packages, which one gets imported when I import xyz? I'm assuming this is based on the path list, yes? Why the hell is this so confusing? Is there something I'm missing here? Where is it defined that easy_install should install to /usr/local/lib/python2.6/dist-packages? Will this affect pip as well? Thanks to anyone who can clear this up!
I believe Mike Orr's answer from the virtual-env mailing list seems to be the best. Note the OP published this question in both places. Original content of mail: Years ago Debian created /usr/local/lib/pythonVERSION/site-packages, and compiled the Python binary to include it in the default search path. Ubuntu followed Debian's lead as it normally does. The Python developers did not like this because you'd get interference with a locally-installed /usr/local/bin/python using the same site-packages directory. Ubuntu finally decided to abandon site-packages and use dist-packages instead, a name which they invented so it wouldn't interfere with anything. The loing story is out there somewhere if you google it, somewhere in the Python bug tracker or distutils SIG or such. The system works, at least if you use the Ubuntu virtualenv package. Some people have had problems using a locally-installed virtualenv on Ubuntu because the magic sys.path entries weren't being added or something. I'm not sure about --no-site-packages because I never use that option: I run PIL and mysqldb from the Ubuntu packages because it can be hard to compile their C dependencies sometimes. (Need the right header files, Python is ignoring the header files, etc.) So Ubuntu Python packages go into /usr/lib/pythonVERSION/dist-packages. Or that python-support directory for some reason. Locally-installed Python packages go into /usr/local/lib/pythonVERSION/dist-packages by default. Whenever I install an Ubuntu 9.04 system I run: $ sudo apt-get install python-setuptools (6.0c9) $ sudo apt-get install python-virtualenv (1.3.3) $ sudo easy_install pip $ sudo pip install virtualenvwrapper The virtualenvs work fine this way, although I haven't tried --no-site-packages. I'm trying to spin up virtualenv, and the --no-site-packages flag seems to do nothing with ubuntu. I installed virtualenv 1.3.3 with easy_install (which I've upgraded to setuptools 0.6c9) These versions are both in Ubuntu 9.04, so you're making it harder on yourself by installing them locally. and everything seems to be installed to /usr/local/lib/python2.6/dist-packages Yes I assume that when installing a package using apt-get, it's placed in / usr/lib/python2.6/dist-packages/ ? Yes Is it first come first serve on the path? If I have a newer version of package XYZ installed in /usr/local/lib/python2.6/dist- packages/ and and older one (from ubuntu repos/apt-get) in /usr/lib/ python2.6/dist-packages, which one gets imported when I import xyz? I'm assuming this is based on the path list, yes? sys.path is scanned in order. The only funny thing is that .pth eggs get put earlier or later in the path than some people expect. But if you're using pip for everything it can do (i.e. except to install pip itself, precompiled eggs, and a snapshot of a local directory that's a copy rather than an egg link), you won't have many .pth eggs anyway. Why the hell is this so confusing? Is there something I'm missing here? It's not well documented. I figured it out by scanning the web. Will this affect pip as well? Yes, pip will automatically install to /usr/local/lib/pythonVERSION/site-packages. Use "pip install -E $VIRTUAL_ENV packagename" to install into a virtualenv.
Django newbie deployment question - ImportError: Could not import settings 'settings'
The app runs fine using django internal server however when I use apache + mod_python I get the below error File "/usr/local/lib/python2.6/dist-packages/django/conf/__init__.py", line 75, in __init__ raise ImportError, "Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e) ImportError: Could not import settings 'settings' (Is it on sys.path? Does it have syntax errors?): No module named settings Here is the needed information 1) Project directory: /root/djangoprojects/mysite 2) directory listing of /root/djangoprojects/mysite ls -ltr total 28 -rw-r--r-- 1 root root 546 Aug 1 08:34 manage.py -rw-r--r-- 1 root root 0 Aug 1 08:34 __init__.py -rw-r--r-- 1 root root 136 Aug 1 08:35 __init__.pyc -rw-r--r-- 1 root root 2773 Aug 1 08:39 settings.py -rw-r--r-- 1 root root 1660 Aug 1 08:53 settings.pyc drwxr-xr-x 2 root root 4096 Aug 1 09:04 polls -rw-r--r-- 1 root root 581 Aug 1 10:06 urls.py -rw-r--r-- 1 root root 314 Aug 1 10:07 urls.pyc 3) App directory : /root/djangoprojects/mysite/polls 4) directory listing of /root/djangoprojects/mysite/polls ls -ltr total 20 -rw-r--r-- 1 root root 514 Aug 1 08:53 tests.py -rw-r--r-- 1 root root 57 Aug 1 08:53 models.py -rw-r--r-- 1 root root 0 Aug 1 08:53 __init__.py -rw-r--r-- 1 root root 128 Aug 1 09:02 views.py -rw-r--r-- 1 root root 375 Aug 1 09:04 views.pyc -rw-r--r-- 1 root root 132 Aug 1 09:04 __init__.pyc 5) Anywhere in the filesystem running import django in python interpreter works fine 6) content of httpd.conf <Location "/mysite"> SetHandler python-program PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE settings PythonOption django.root /mysite PythonPath "['/root/djangoprojects/', '/root/djangoprojects/mysite','/root/djangoprojects/mysite/polls', '/var/www'] + sys.path" PythonDebug On </Location> 7) PYTHONPATH variable is set to echo $PYTHONPATH /root/djangoprojects/mysite 8) DJANGO_SETTINGS_MODULE is set to echo $DJANGO_SETTINGS_MODULE mysite.settings 9) content of sys.path is import sys >>> sys.path ['', '/root/djangoprojects/mysite', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/lib-dynload', '/usr/lib/python2.6/dist-packages', '/usr/local/lib/python2.6/dist-packages'] How do I add settings location to sys.path such that it persistent across sessions ? I have read umpteen no of post with people having the same issue it and I have tried a lot completely beats me as to what I need to do. Looking for some help. Thanks in advance Ankur Gupta
Your apache configuration should look like this: <Location "/mysite"> SetHandler python-program PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE mysite.settings PythonOption django.root /mysite PythonPath "['/root/djangoprojects/', '/root/djangoprojects/mysite','/root/djangoprojects/mysite/polls', '/var/www'] + sys.path" PythonDebug On </Location> Note that the sole difference is the "mysite.settings". Don't forget to restart apache once the config has changed (apache2ctl restart). See http://docs.djangoproject.com/en/dev/howto/deployment/modpython/ for more info.
Is it safe to replace a self object by another object of the same type in a method?
I would like to replace an object instance by another instance inside a method like this: class A: def method1(self): self = func(self) The object is retrieved from a database.
It is unlikely that replacing the 'self' variable will accomplish whatever you're trying to do, that couldn't just be accomplished by storing the result of func(self) in a different variable. 'self' is effectively a local variable only defined for the duration of the method call, used to pass in the instance of the class which is being operated upon. Replacing self will not actually replace references to the original instance of the class held by other objects, nor will it create a lasting reference to the new instance which was assigned to it.
Python: sorting a dictionary of lists
Still learning python (finally!) and can't quite wrap my head around this one yet. What I want to do is sort a dictionary of lists by value using the third item in the list. It's easy enough sorting a dictionary by value when the value is just a single number or string, but this list thing has me baffled. Example: myDict = { 'item1' : [ 7, 1, 9], 'item2' : [8, 2, 3], 'item3' : [ 9, 3, 11 ] } I want to be able to iterate through the dictionary in order of the third value in each list, in this case 9, 3, 11. Thanks much for any help!
Here is one way to do this: >>> sorted(myDict.items(), key=lambda e: e[1][2]) [('item2', [8, 2, 3]), ('item1', [7, 1, 9]), ('item3', [9, 3, 11])] The key argument of the sorted function lets you derive a sorting key for each element of the list. To iterate over the keys/values in this list, you can use something like: >>> for key, value in sorted(myDict.items(), key=lambda e: e[1][2]): ... print key, value ... item2 [8, 2, 3] item1 [7, 1, 9] item3 [9, 3, 11]
How do I forbid easy_install from zipping eggs?
What must I put into distutils.cfg to prevent easy_install from ever installing a zipped egg? The compression is a nice thought, but I like to be able to grep through and debug that code. I pulled in some dependencies with python setup.py develop . A closer look reveals that also accepts the --always-unzip flag. It would just be nice to set that as default.
the option is zip-ok, so put the following in your distutils.cfg: [easy_install] # i don't like having zipped files. zip_ok = 0
python's sum() and non-integer values
Is there a simple and quick way to use sum() with non-integer values? So I can use it like this: class Foo(object): def __init__(self,bar) self.bar=bar mylist=[Foo(3),Foo(34),Foo(63),200] result=sum(mylist) # result should be 300 I tried overriding __add__ and __int__ etc, but I don't have found a solution yet EDIT: The solution is to implement: def __radd__(self, other): return other + self.bar as Will suggested in his post. But as always, all roads lead to Rome, but I think this is the best solution since I don't need __add__ in my class
Its a bit tricky - the sum() function takes the start and adds it to the next and so on You need to implement the __radd__ method: class T: def __init__(self,x): self.x = x def __radd__(self, other): return other + self.x test = (T(1),T(2),T(3),200) print sum(test)
Multiple versions of Python on OS X Leopard
I currently have multiple versions of Python installed on my Mac, the one that came with it, a version I downloaded recently from python.org, an older version used to run Zope locally and another version that Appengine is using. It's kind of a mess. Any recommendations of using one version of python to rule them all? How would I go about deleted older versions and linking all of my apps to a single install. Any Mac specific gotchas I should know about? Is this a dumb idea?
There's nothing inherently wrong with having multiple versions of Python around. Sometimes it's a necessity when using applications with version dependencies. Probably the biggest issue is dealing with site-package dependencies which may vary from app to app. Tools like virtualenv can help there. One thing you should not do is attempt to remove the Apple-supplied Python in /System/Library/Frameworks and linked to from /usr/bin/python. (Note the recent discussion of multiple versions here.)
Can I redirect the stdout in python into some sort of string buffer?
I'm using python's ftplib to write a small FTP client, but some of the functions in the package don't return string output, but print to stdout. I want to redirect stdout to an object which I'll be able to read the output from. I know stdout can be redirected into any regular file with: stdout = open("file", "a") But I prefer a method that doesn't uses the local drive. I'm looking for something like the BufferedReader in Java that can be used to wrap a buffer into a stream.
from cStringIO import StringIO import sys old_stdout = sys.stdout sys.stdout = mystdout = StringIO() # blah blah lots of code ... sys.stdout = old_stdout # examine mystdout.getvalue()
How do I do database transactions with psycopg2/python db api?
Im fiddling with psycopg2 , and while there's a .commit() and .rollback() there's no .begin() or similar to start a transaction , or so it seems ? I'd expect to be able to do db.begin() # possible even set the isolation level here curs = db.cursor() cursor.execute('select etc... for update') ... cursor.execute('update ... etc.') db.commit(); So, how do transactions work with psycopg2 ? How would I set/change the isolation level ?
Use db.set_isolation_level(n), assuming db is your connection object. As Federico wrote here, the meaning of n is: 0 -> autocommit 1 -> read committed 2 -> serialized (but not officially supported by pg) 3 -> serialized As documented here, psycopg2.extensions gives you symbolic constants for the purpose: Setting transaction isolation levels ==================================== psycopg2 connection objects hold informations about the PostgreSQL `transaction isolation level`_. The current transaction level can be read from the `.isolation_level` attribute. The default isolation level is ``READ COMMITTED``. A different isolation level con be set through the `.set_isolation_level()` method. The level can be set to one of the following constants, defined in `psycopg2.extensions`: `ISOLATION_LEVEL_AUTOCOMMIT` No transaction is started when command are issued and no `.commit()`/`.rollback()` is required. Some PostgreSQL command such as ``CREATE DATABASE`` can't run into a transaction: to run such command use `.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)`. `ISOLATION_LEVEL_READ_COMMITTED` This is the default value. A new transaction is started at the first `.execute()` command on a cursor and at each new `.execute()` after a `.commit()` or a `.rollback()`. The transaction runs in the PostgreSQL ``READ COMMITTED`` isolation level. `ISOLATION_LEVEL_SERIALIZABLE` Transactions are run at a ``SERIALIZABLE`` isolation level. .. _transaction isolation level: http://www.postgresql.org/docs/8.1/static/transaction-iso.html
java and python equivalent of php's foreach($array as $key => $value)
In php, one can handle a list of state names and their abbreviations with an associative array like this: <?php $stateArray = array( "ALABAMA"=>"AL", "ALASKA"=>"AK", // etc... "WYOMING"=>"WY" ); foreach ($stateArray as $stateName => $stateAbbreviation){ print "The abbreviation for $stateName is $stateAbbreviation.\n\n"; } ?> Output (with key order preserved): The abbreviation for ALABAMA is AL. The abbreviation for ALASKA is AK. The abbreviation for WYOMING is WY. EDIT: Note that the order of array elements is preserved in the output of the php version. The Java implementation, using a HashMap, does not guarantee the order of elements. Nor does the dictionary in Python. How is this done in java and python? I only find approaches that supply the value, given the key, like python's: stateDict = { "ALASKA": "AK", "WYOMING": "WY", } for key in stateDict: value = stateDict[key] EDIT: based on the answers, this was my solution in python, # a list of two-tuples stateList = [ ('ALABAMA', 'AL'), ('ALASKA', 'AK'), ('WISCONSIN', 'WI'), ('WYOMING', 'WY'), ] for name, abbreviation in stateList: print name, abbreviation Output: ALABAMA AL ALASKA AK WISCONSIN WI WYOMING WY Which is exactly what was required.
in Python: for key, value in stateDict.items(): # .iteritems() in Python 2.x print "The abbreviation for %s is %s." % (key, value) in Java: Map<String,String> stateDict; for (Map.Entry<String,String> e : stateDict.entrySet()) System.out.println("The abbreviation for " + e.getKey() + " is " + e.getValue() + ".");
Barchart with vertical labels in python/matplotlib
I'm using matplotlib to generate a (vertical) barchart. The problem is my labels are rather long. Is there any way to display them vertically, either in the bar or above it or below it?
Do you mean something like this: >>> from matplotlib import * >>> plot(xrange(10)) >>> yticks(xrange(10), rotation='vertical') ? In general, to show any text in matplotlib with a vertical orientation, you can add the keyword rotation='vertical'. For further options, you can look at help(matplotlib.pyplot.text) The yticks function plots the ticks on the y axis; I am not sure whether you originally meant this or the ylabel function, but the procedure is alwasy the same, you have to add rotation='vertical' Maybe you can also find useful the options 'verticalalignment' and 'horizontalalignment', which allows you to define how to align the text with respect to the ticks or the other elements.
signals or triggers in SQLAlchemy
does SQLAlchemy have something similar to Django's signal concept? Basically, I'd like to trigger a few functions when I pre-save or post-save some entity objects. Thanks. Edit: I JUST want equivalent of django-signals in SQLAlchemy.
I think you are looking for `ORM Events'. You can find documentation here: http://docs.sqlalchemy.org/en/latest/orm/events.html
Should I Start With Python 3.0?
Recently I decided to expand my programming horizons and learn the python programming language. While I have used python a little bit for classes in college and for a project or two at work I am by no means an expert. My question is as follows: should I bother with the 2.x releases or should I jump straight to 3.0? I am leaning towards 3.0 since I will be programming applications more for personal/learning use, but I wanted to see if there were any good arguments against it before I began.
Absolutely not 3.0 - 3.1 is out and is stabler, better, faster in every respect; it makes absolutely no sense to start with 3.0 at this time, if you want to take up the 3 series it should on all accounts be 3.1. As for 2.6 vs 3.1, 3.1 is a better language (especially because some cruft was removed that had accumulated over the years but has to stay in 2.* for backwards compatibility) but all the rest of the ecosystem (from extensions to tools, from books to collective knowledge) is still very much in favor of 2.6 -- if you don't care about being able to use (e.g.) certain GUIs or scientific extensions, deploy on App Engine, script Windows with COM, have a spiffy third party IDE, and so on, 3.1 is advisable, but if you care about such things, still 2.* for now.
GIL in Python 3.1
Does anybody knows fate of Global Interpreter Lock in Python 3.1 against C++ multithreading integration
GIL is still there in CPython 3.1; the Unladen Swallow projects aims (among many other performance boosts) to eventually remove it, but it's still a way from its goals, and is working on 2.6 first with the intent of eventually porting to 3.x for whatever x will be current by the time the 2.y version is considered to be done. For now, multiprocessing (instead of threading) remains the way of choice for using multiple cores in CPython (IronPython and Jython are fine too, but they don't support Python 3 currently, nor do they make C++ integration all that easy either;-).
How to write native newline character to a file descriptor in Python?
The os.write function can be used to writes bytes into a file descriptor (not file object). If I execute os.write(fd, '\n'), only the LF character will be written into the file, even on Windows. I would like to have CRLF in the file on Windows and only LF in Linux. What is the best way to achieve this? I'm using Python 2.6, but I'm also wondering if Python 3 has a different solution.
Use this import os os.write(fd, os.linesep)
Trying to import module with the same name as a built-in module causes an import error
I have a module that conflicts with a built-in module. For example, a myapp.email module defined in myapp/email.py. I can reference myapp.email anywhere in my code without issue. However, I need to reference the built-in email module from my email module. # myapp/email.py from email import message_from_string It only finds itself, and therefore raises an ImportError, since myapp.email doesn't have a message_from_string method. import email causes the same issue when I try email.message_from_string. Is there any native support to do this in Python, or am I stuck with renaming my "email" module to something more specific?
You will want to read about Absolute and Relative Imports which addresses this very problem. Use: from __future__ import absolute_import Using that, any unadorned package name will always refer to the top level package. You will then need to use relative imports (from .email import ...) to access your own package.
Checking email with Python
I am interested to trigger a certain action upon receiving an email from specific address with specific subject. In order to be able to do so I need to implement monitoring of my mailbox, checking every incoming mail (in particular, i use gmail). what is the easiest way to do that? Thank you, Sasha
Gmail provides the ability to connect over POP, which you can turn on in the gmail settings panel. Python can make connections over POP pretty easily: import poplib from email import parser pop_conn = poplib.POP3_SSL('pop.gmail.com') pop_conn.user('username') pop_conn.pass_('password') #Get messages from server: messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)] # Concat message pieces: messages = ["\n".join(mssg[1]) for mssg in messages] #Parse message intom an email object: messages = [parser.Parser().parsestr(mssg) for mssg in messages] for message in messages: print message['subject'] pop_conn.quit() You would just need to run this script as a cron job. Not sure what platform you're on so YMMV as to how that's done.
Inserting the same value multiple times when formatting a string
I have a string of this form s='arbit' string='%s hello world %s hello world %s' %(s,s,s) All the %s in string have the same value (i.e. s). Is there a better way of writing this? (Rather than listing out s three times)
You can use advanced string formatting, available in Python 2.6 and Python 3.x: incoming = 'arbit' result = '{0} hello world {0} hello world {0}'.format(incoming)
multiprocess or threading in python?
I have a python application that grabs a collection of data and for each piece of data in that collection it performs a task. The task takes some time to complete as there is a delay involved. Because of this delay, I don't want each piece of data to perform the task subsequently, I want them to all happen in parallel. Should I be using multiprocess? or threading for this operation? I attempted to use threading but had some trouble, often some of the tasks would never actually fire.
If you are truly compute bound, using the multiprocessing module is probably the lightest weight solution (in terms of both memory consumption and implementation difficulty.) If you are I/O bound, using the threading module will usually give you good results. Make sure that you use thread safe storage (like the Queue) to hand data to your threads. Or else hand them a single piece of data that is unique to them when they are spawned. PyPy is focused on performance. It has a number of features that can help with compute-bound processing. They also have support for Software Transactional Memory, although that is not yet production quality. The promise is that you can use simpler parallel or concurrent mechanisms than multiprocessing (which has some awkward requirements.) Stackless Python is also a nice idea. Stackless has portability issues as indicated above. Unladen Swallow was promising, but is now defunct. Pyston is another (unfinished) Python implementation focusing on speed. It is taking an approach different to PyPy, which may yield better (or just different) speedups.
Substitutions inside links in reST / Sphinx
I am using Sphinx to document a webservice that will be deployed in different servers. The documentation is full of URL examples for the user to click and they should just work. My problem is that the host, port and deployment root will vary and the documentation will have to be re-generated for every deployment. I tried defining substitutions like this: |base_url|/path .. |base_url| replace:: http://localhost:8080 But the generated HTML is not what I want (doesn't include "/path" in the generated link): <a href="http://localhost:8080">http://localhost:8080</a>/path Does anybody know how to work around this?
New in Sphinx v1.0: sphinx.ext.extlinks – Markup to shorten external links http://sphinx.pocoo.org/ext/extlinks.html The extension adds one new config value: extlinks This config value must be a dictionary of external sites, mapping unique short alias names to a base URL and a prefix. For example, to create an alias for the above mentioned issues, you would add extlinks = {'issue': ('http://bitbucket.org/birkenfeld/sphinx/issue/%s', 'issue ')} Now, you can use the alias name as a new role, e.g. :issue:`123`. This then inserts a link to http://bitbucket.org/birkenfeld/sphinx/issue/123. As you can see, the target given in the role is substituted in the base URL in the place of %s. The link caption depends on the second item in the tuple, the prefix: If the prefix is None, the link caption is the full URL. If the prefix is the empty string, the link caption is the partial URL given in the role content (123 in this case.) If the prefix is a non-empty string, the link caption is the partial URL, prepended by the prefix – in the above example, the link caption would be issue 123. You can also use the usual “explicit title” syntax supported by other roles that generate links, i.e. :issue:`this issue <123>`. In this case, the prefix is not relevant.
Compare object instances for equality by their attributes in Python
What is the best way to compare two instances of some object for equality in Python? I'd like to be able to do something like Example: doc1 = ErrorDocument(path='/folder',title='Page') doc2 = ErrorDocument(path='/folder',title='Page') if doc1 == doc2: # this should be True #do something EDIT: To further clarify the question. I'd like to compare by attribute values, and to make a more generic solution than def __eq__(self, other): return self.path == other.path and self.title == other.title Should the __eq__() method look something like this? def __eq__(self, other): # Is the other instance of the same object # Loop through __dict__ and compare values to attributes of other
As usual with Python, it's kiss : class Test(object): def __init__(self, attr1, attr2): self.attr1 = attr1 self.attr2 = attr2 def __str__(self): return str(self.__dict__) def __eq__(self, other): return self.__dict__ == other.__dict__ t1 = Test("foo", 42) t2 = Test("foo", 42) t3 = Test("bar", 42) print t1, t2, t3 print t1 == t2 print t2 == t3 It outputs: {'attr2': 42, 'attr1': 'foo'} {'attr2': 42, 'attr1': 'foo'} {'attr2': 42, 'attr1': 'bar'} True False N.B : be aware that before Python 3.0, you are more likely to use __cmp__ instead of __eq__, working the same way.
Change one character in a string in Python?
What is the easiest way in Python to replace a character in a string like: text = "abcdefg"; text[1] = "Z"; ^
Don't modify strings. Work with them as lists; turn them into strings only when needed. >>> s = list("Hello zorld") >>> s ['H', 'e', 'l', 'l', 'o', ' ', 'z', 'o', 'r', 'l', 'd'] >>> s[6] = 'W' >>> s ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'] >>> "".join(s) 'Hello World' Python strings are immutable (i.e. they can't be modified). There are a lot of reasons for this. Use lists until you have no choice, only then turn them into strings.
subprocess: deleting child processes in Windows
On Windows, subprocess.Popen.terminate calls win32's TerminalProcess. However, the behavior I see is that child processes of the process I am trying to terminate are still running. Why is that? How do I ensure all child processes started by the process are killed?
By using psutil: import psutil, os def kill_proc_tree(pid, including_parent=True): parent = psutil.Process(pid) children = parent.children(recursive=True) for child in children: child.kill() psutil.wait_procs(children, timeout=5) if including_parent: parent.kill() parent.wait(5) me = os.getpid() kill_proc_tree(me)
Python Multiprocessing Exit Elegantly How?
import multiprocessing import time class testM(multiprocessing.Process): def __init__(self): multiprocessing.Process.__init__(self) self.exit = False def run(self): while not self.exit: pass print "You exited!" return def shutdown(self): self.exit = True print "SHUTDOWN initiated" def dostuff(self): print "haha", self.exit a = testM() a.start() time.sleep(3) a.shutdown() time.sleep(3) print a.is_alive() a.dostuff() exit() I am just wondering how come the code above doesn't really print "you exited". What am I doing wrong? if so, may someone point me out the correct way to exit gracefully? (I am not referring to process.terminate or kill)
The reason you are not seeing this happen is because you are not communicating with the subprocess. You are trying to use a local variable (local to the parent process) to signal to the child that it should shutdown. Take a look at the information on synchonization primatives. You need to setup a signal of some sort that can be referenced in both processes. Once you have this you should be able to flick the switch in the parent process and wait for the child to die. Try the following code: import multiprocessing import time class MyProcess(multiprocessing.Process): def __init__(self, ): multiprocessing.Process.__init__(self) self.exit = multiprocessing.Event() def run(self): while not self.exit.is_set(): pass print "You exited!" def shutdown(self): print "Shutdown initiated" self.exit.set() if __name__ == "__main__": process = MyProcess() process.start() print "Waiting for a while" time.sleep(3) process.shutdown() time.sleep(3) print "Child process state: %d" % process.is_alive()
How do I remove packages installed with Python's easy_install?
Python's easy_install makes installing new packages extremely convenient. However, as far as I can tell, it doesn't implement the other common features of a dependency manager - listing and removing installed packages. What is the best way of finding out what's installed, and what is the preferred way of removing installed packages? Are there any files that need to be updated if I remove packages manually (e.g. by rm /usr/local/lib/python2.6/dist-packages/my_installed_pkg.egg or similar)?
pip, an alternative to setuptools/easy_install, provides an "uninstall" command. Install pip according to the installation instructions: $ wget https://bootstrap.pypa.io/get-pip.py $ python get-pip.py Then you can use pip uninstall to remove packages installed with easy_install
No Multiline Lambda in Python: Why not?
I've heard it said that multiline lambdas can't be added in Python because they would clash syntactically with the other syntax constructs in Python. I was thinking about this on the bus today and realized I couldn't think of a single Python construct that multiline lambdas clash with. Given that I know the language pretty well, this surprised me. Now, I'm sure Guido had a reason for not including multiline lambdas in the language, but out of curiosity: what's a situation where including a multiline lambda would be ambiguous? Is what I've heard true, or is there some other reason that Python doesn't allow multiline lambdas?
Guido van Rossum (the inventor of Python) answers this exact question himself in an old blog post. Basically, he admits that it's theoretically possible, but that any proposed solution would be un-Pythonic: "But the complexity of any proposed solution for this puzzle is immense, to me: it requires the parser (or more precisely, the lexer) to be able to switch back and forth between indent-sensitive and indent-insensitive modes, keeping a stack of previous modes and indentation level. Technically that can all be solved (there's already a stack of indentation levels that could be generalized). But none of that takes away my gut feeling that it is all an elaborate Rube Goldberg contraption."
Python Dictionary to URL Parameters
I am trying to convert a Python dictionary to a string for use as URL parameters. I am sure that there is a better, more Pythonic way of doing this. What is it? x = "" for key, val in {'a':'A', 'b':'B'}.items(): x += "%s=%s&" %(key,val) x = x[:-1]
Use urllib.urlencode(). It takes a dictionary of key-value pairs, and converts it into a form suitable for a URL (e.g., key1=val1&key2=val2). If you are using Python3, use urllib.parse.urlencode() If you want to make a URL with repetitive params such as: p=1&p=2&p=3 you have two options: >>> import urllib >>> a = (('p',1),('p',2), ('p', 3)) >>> urllib.urlencode(a) 'p=1&p=2&p=3' or if you want to make a url with repetitive params: >>> urllib.urlencode({'p': [1, 2, 3]}, doseq=True) 'p=1&p=2&p=3'
PYTHON: Converting list of tuples into a dictionary
I'm looking for a way to convert list of tuples which looks like this: [(1,4),(2,4),(3,4),(4,15),(5,15),(6,23),(7,23),(8,23),(9,15),(10,23),(11,15),(12,15)] into a dictionary, where key:value pair looks like this: {4:[1,2,3] ,15:[4,5,9,11,12], 23:[6,7,8,10]} Second element from a tuple becomes a dictionary key. First tuple element is assigned to that key. Can you show me how that can be done?
>>> from collections import defaultdict >>> l= [(1,4),(2,4),(3,4),(4,15),(5,15),(6,23),(7,23),(8,23),(9,15),(10,23),(11,15),(12,15)] >>> d= defaultdict( list ) >>> for v, k in l: ... d[k].append(v) ... >>> d defaultdict(<type 'list'>, {23: [6, 7, 8, 10], 4: [1, 2, 3], 15: [4, 5, 9, 11, 12]}) >>> [ {k:d[k]} for k in sorted(d) ] [{4: [1, 2, 3]}, {15: [4, 5, 9, 11, 12]}, {23: [6, 7, 8, 10]}]
What is the simplest way to SSH using Python?
How can I simply SSH to a remote server from a local Python (3.0) script, supply a login/password, execute a command and print the output to the Python console? I would rather not use any large external library or install anything on the remote server.
You can code it yourself using Paramiko, as suggested above. Alternatively, you can look into Fabric, a python application for doing all the things you asked about: Fabric is a Python library and command-line tool designed to streamline deploying applications or performing system administration tasks via the SSH protocol. It provides tools for running arbitrary shell commands (either as a normal login user, or via sudo), uploading and downloading files, and so forth. I think this fits your needs. It is also not a large library and requires no server installation, although it does have dependencies on paramiko and pycrypt that require installation on the client. The app used to be here. It can now be found here. * The official, canonical repository is git.fabfile.org * The official Github mirror is GitHub/bitprophet/fabric There are several good articles on it, though you should be careful because it has changed in the last six months: Deploying Django with Fabric Tools of the Modern Python Hacker: Virtualenv, Fabric and Pip Simple & Easy Deployment with Fabric and Virtualenv Later: Fabric no longer requires paramiko to install: $ pip install fabric Downloading/unpacking fabric Downloading Fabric-1.4.2.tar.gz (182Kb): 182Kb downloaded Running setup.py egg_info for package fabric warning: no previously-included files matching '*' found under directory 'docs/_build' warning: no files found matching 'fabfile.py' Downloading/unpacking ssh>=1.7.14 (from fabric) Downloading ssh-1.7.14.tar.gz (794Kb): 794Kb downloaded Running setup.py egg_info for package ssh Downloading/unpacking pycrypto>=2.1,!=2.4 (from ssh>=1.7.14->fabric) Downloading pycrypto-2.6.tar.gz (443Kb): 443Kb downloaded Running setup.py egg_info for package pycrypto Installing collected packages: fabric, ssh, pycrypto Running setup.py install for fabric warning: no previously-included files matching '*' found under directory 'docs/_build' warning: no files found matching 'fabfile.py' Installing fab script to /home/hbrown/.virtualenvs/fabric-test/bin Running setup.py install for ssh Running setup.py install for pycrypto ... Successfully installed fabric ssh pycrypto Cleaning up... This is mostly cosmetic, however: ssh is a fork of paramiko, the maintainer for both libraries is the same (Jeff Forcier, also the author of Fabric), and the maintainer has plans to reunite paramiko and ssh under the name paramiko. (This correction via pbanka.)
How to roll my own pypi?
I would like to run my own internal pypi server, for egg distribution within my organization. I have found a few projects, such as: http://pypi.python.org/pypi/EggBasket/ http://plone.org/products/plonesoftwarecenter As I understand it, pypi.python.org uses software called Cheese Shop. My questions: Why can't I use cheeseshop itself? (I can't find it, not sure it exists) How do other people solve this problem? (Currently we use blush svn to distribute eggs) *edit: This seems canonical http://wiki.python.org/moin/PyPiImplementations. Still, I'm interested in feedback.
The source to Cheese Shop can be downloaded from https://bitbucket.org/pypa/pypi/src. There is also an example, from the page you linked to, of using Apache as a "dumb" Python package repository: # Mount pypi repositories into URI space Alias /pypi /var/pypi # /pypi/dev: Redirect for unknown packages (fallback to pypi) RewriteCond /var/pypi/dev/$1 !-d RewriteCond /var/pypi/dev/$1 !-f RewriteRule ^/pypi/dev/([^/]+)/?$ http://pypi.python.org/pypi/$1/ [R,L] RewriteCond /var/pypi/dev/$1/$2 !-f RewriteRule ^/pypi/dev/([^/]+)/([^/]+)$ http://pypi.python.org/pypi/$1/$2 [R,L] # /pypi/stable: Redirect for unknown packages (fallback to pypi) RewriteCond /var/pypi/stable/$1 !-d RewriteCond /var/pypi/stable/$1 !-f RewriteRule ^/pypi/stable/([^/]+)/?$ http://pypi.python.org/pypi/$1/ [R,L] RewriteCond /var/pypi/stable/$1/$2 !-f RewriteRule ^/pypi/stable/([^/]+)/([^/]+)$ http://pypi.python.org/pypi/$1/$2 [R,L]
Python: remove dictionary from list
If I have a list of dictionaries, say: [{'id': 1, 'name': 'paul'}, {'id': 2, 'name': 'john'}] and I would like to remove the dictionary with id of 2 (or name john), what is the most efficient way to go about this programmatically (that is to say, I don't know the index of the entry in the list so it can't simply be popped).
thelist[:] = [d for d in thelist if d.get('id') != 2] Edit: as some doubts have been expressed in a comment about the performance of this code (some based on misunderstanding Python's performance characteristics, some on assuming beyond the given specs that there is exactly one dict in the list with a value of 2 for key 'id'), I wish to offer reassurance on this point. On an old Linux box, measuring this code: $ python -mtimeit -s"lod=[{'id':i, 'name':'nam%s'%i} for i in range(99)]; import random" "thelist=list(lod); random.shuffle(thelist); thelist[:] = [d for d in thelist if d.get('id') != 2]" 10000 loops, best of 3: 82.3 usec per loop of which about 57 microseconds for the random.shuffle (needed to ensure that the element to remove is not ALWAYS at the same spot;-) and 0.65 microseconds for the initial copy (whoever worries about performance impact of shallow copies of Python lists is most obviously out to lunch;-), needed to avoid altering the original list in the loop (so each leg of the loop does have something to delete;-). When it is known that there is exactly one item to remove, it's possible to locate and remove it even more expeditiously: $ python -mtimeit -s"lod=[{'id':i, 'name':'nam%s'%i} for i in range(99)]; import random" "thelist=list(lod); random.shuffle(thelist); where=(i for i,d in enumerate(thelist) if d.get('id')==2).next(); del thelist[where]" 10000 loops, best of 3: 72.8 usec per loop (use the next builtin rather than the .next method if you're on Python 2.6 or better, of course) -- but this code breaks down if the number of dicts that satisfy the removal condition is not exactly one. Generalizing this, we have: $ python -mtimeit -s"lod=[{'id':i, 'name':'nam%s'%i} for i in range(33)]*3; import random" "thelist=list(lod); where=[i for i,d in enumerate(thelist) if d.get('id')==2]; where.reverse()" "for i in where: del thelist[i]" 10000 loops, best of 3: 23.7 usec per loop where the shuffling can be removed because there are already three equispaced dicts to remove, as we know. And the listcomp, unchanged, fares well: $ python -mtimeit -s"lod=[{'id':i, 'name':'nam%s'%i} for i in range(33)]*3; import random" "thelist=list(lod); thelist[:] = [d for d in thelist if d.get('id') != 2]" 10000 loops, best of 3: 23.8 usec per loop totally neck and neck, with even just 3 elements of 99 to be removed. With longer lists and more repetitions, this holds even more of course: $ python -mtimeit -s"lod=[{'id':i, 'name':'nam%s'%i} for i in range(33)]*133; import random" "thelist=list(lod); where=[i for i,d in enumerate(thelist) if d.get('id')==2]; where.reverse()" "for i in where: del thelist[i]" 1000 loops, best of 3: 1.11 msec per loop $ python -mtimeit -s"lod=[{'id':i, 'name':'nam%s'%i} for i in range(33)]*133; import random" "thelist=list(lod); thelist[:] = [d for d in thelist if d.get('id') != 2]" 1000 loops, best of 3: 998 usec per loop All in all, it's obviously not worth deploying the subtlety of making and reversing the list of indices to remove, vs the perfectly simple and obvious list comprehension, to possibly gain 100 nanoseconds in one small case -- and lose 113 microseconds in a larger one;-). Avoiding or criticizing simple, straightforward, and perfectly performance-adequate solutions (like list comprehensions for this general class of "remove some items from a list" problems) is a particularly nasty example of Knuth's and Hoare's well-known thesis that "premature optimization is the root of all evil in programming"!-)
Execute python code inside browser without Jython
Is there a way to execute python code in a browser, other than using Jython and an applet? The execution does not have to deal with anything related to graphics. For example, just sum all the digits of a binary 1Gb file (chosen by the browser user) and then return the result to the server. I am aware that python can be executed remotely outside a browser, but my requirement is to be done inside a browser. For sure, I take for granted the user will keep the right to execute or not, and will be asked to do so, and all this security stuff... but that is not my question.
The Pyjamas project has a compiler called pyjs which turns Python code into Javascript.
Compiling python modules whith DEBUG defined on MSVC
Python rather stupidly has a pragma directive in its include files that forces a link against python26_d.lib when the DEBUG preprocessor variable is defined. This is a problem because the python installer doesn't come with python26_d.lib! So I can't build applications in msvc in debug mode. If i temporarily #undef DEBUG for just one file I get many complaints about inconsistent DLL linkage. If I change the pragma in pythons include file I get undefined references to various debug functions. I have tried compiling my own version of python but its somehow different enough from the python that gets distributed that I can't use my modules with apps built with the vanilla version of python Can anyone give me any advice on how to get round this? Thanks
From python list As a workaround to the situation, try to copy the file python26.dll to python26_d.dll. (I'm not sure this will work; you say you are building a SWIG library in debug mode, and it's possible that SWIG will try to use features of the Python debugging version. If that's the case, you'll have no choice but to use the debugging version of Python.) Edit: From comments: You should also edit pyconfig.h and comment out the line "#define Py_DEBUG" (line 374)
How do I see stdout when running Django tests?
When I run tests with ./manage.py test, whatever I send to the standard output through print doesn't show. When tests fail, I see an "stdout" block per failed test, so I guess Django traps it (but doesn't show it when tests pass).
Checked TEST_RUNNER in settings.py, it's using a project-specific runner that calls out to Nose. Nose has the -s option to stop it from capturing stdout, but if I run: ./manage.py test -s manage.py captures it first and throws a "no such option" error. The help for manage.py doesn't mention this, but I found that if I run: ./manage.py test -- -s it ignores the -s and lets me capture it on the custom runner's side, passing it to Nose without a problem.
Comma separated lists in django templates
If fruits is the list ['apples', 'oranges', 'pears'], is there a quick way using django template tags to produce "apples, oranges, and pears"? I know it's not difficult to do this using a loop and {% if counter.last %} statements, but because I'm going to use this repeatedly I think I'm going to have to learn how to write custom tags filters, and I don't want to reinvent the wheel if it's already been done. As an extension, my attempts to drop the Oxford Comma (ie return "apples, oranges and pears") are even messier.
First choice: use the existing join template tag. http://docs.djangoproject.com/en/dev/ref/templates/builtins/#join Here's their example {{ value|join:" // " }} Second choice: do it in the view. fruits_text = ", ".join( fruits ) Provide fruits_text to the template for rendering.
What does % do to strings in Python?
I have failed to find documentation for the operator % as it is used on strings in Python. Does someone know where that documentation is?
It's the string formatting operator. Read up on string formatting in Python. format % values Creates a string where format specifies a format and values are the values to be filled in.
Is it necessary or useful to inherit from python's object in Python 3.x?
In older python version when you create a class in python, it can inherit from object which is as far I understand a special built-in python element that allow your object to be a new-style object. What about newer version (> 3.0 and 2.6)? I googled about the class object but I get so much result (for an obvious reasons). Any hint? Thank!
You don't need to inherit from object to have new style in python 3. All classes are new-style.
Asynchronous method call in Python?
I was wondering if there's any library for asynchronous method calls in Python. It would be great if you could do something like @async def longComputation(): <code> token = longComputation() token.registerCallback(callback_function) # alternative, polling while not token.finished(): doSomethingElse() if token.finished(): result = token.result() Or to call a non-async routine asynchronously def longComputation() <code> token = asynccall(longComputation()) It would be great to have a more refined strategy as native in the language core. Was this considered?
What about something like import threading thr = threading.Thread(target=foo, args=(), kwargs={}) thr.start() # will run "foo" .... thr.is_alive() # will return whether foo is running currently .... thr.join() # will wait till "foo" is done See the docs at https://docs.python.org/2/library/threading.html#module-threading for more details; this code should work for python 3 as well.
Copy constructor in python
Is there a copy constructor in python ? If not what would I do to achieve something similar ? The situation is that I am using a library and I have extended one of the classes there with extra functionality and I want to be able to convert the objects I get from the library to instances of my own class.
I think you want the copy module import copy x = copy.copy(y) # make a shallow copy of y x = copy.deepcopy(y) # make a deep copy of y you can control copying in much the same way as you control pickle.
Multiple blocks of same name in Jinja2
In Jinja2, I have a base template like this: <title>{% block title %}{% endblock %} - example.com</title> [...] <h1> {% block title %}{% endblock %} - example.com </h1> Jinja2, then, fails with the following message: lines = [self.message, ' ' + location] : block 'title' defined twice It must be now evident as to what I am trying to do - to have the same title in two places: the TITLE tag and the H1 tag, but the part of the title is actually provided by other derived templates. How does one typically achieve this?
As documented here, defining a block creates a macro with the name of the block in the special "self" object: <title>{% block title %}{% endblock %} - example.com</title> [...] <h1> {{ self.title() }} - example.com </h1>
Beautiful Soup cannot find a CSS class if the object has other classes, too
if a page has <div class="class1"> and <p class="class1">, then soup.findAll(True, 'class1') will find them both. If it has <p class="class1 class2">, though, it will not be found. How do I find all objects with a certain class, regardless of whether they have other classes, too?
Unfortunately, BeautifulSoup treats this as a class with a space in it 'class1 class2' rather than two classes ['class1','class2']. A workaround is to use a regular expression to search for the class instead of a string. This works: soup.findAll(True, {'class': re.compile(r'\bclass1\b')})
curses-like library for cross-platform console app in python
I'm looking into developing a console application in python which should be able to run under Windows as well as Linux. For this, I'd really like to use a high-level console library like curses. However, as far as I know, curses is not available on Windows. What other options do I have? Unfortunately, using cygwin under Windows is not an option... Thanks for your help!
There is a wcurses. I've never tried it but it may meet your needs. It sounds like it doesn't have full curses compatibility, but may be close enough. Also it might not be using the DOS terminal, but opening a GUI window and drawing monospaced text inside. Other windows text mode options are: The console module; wconio -- based on Borland's C conio library. I believe both are windows only.
convert string to dict using list comprehension in python
I have came across this problem a few times and can't seem to figure out a simple solution. Say I have a string string = "a=0 b=1 c=3" I want to convert that into a dictionary with a, b and c being the key and 0, 1, and 3 being their respective values (converted to int). Obviously I can do this: list = string.split() dic = {} for entry in list: key, val = entry.split('=') dic[key] = int(val) But I don't really like that for loop, It seems so simple that you should be able to convert it to some sort of list comprehension expression. And that works for slightly simpler cases where the val can be a string. dic = dict([entry.split('=') for entry in list]) However, I need to convert val to an int on the fly and doing something like this is syntactically incorrect. dic = dict([[entry[0], int(entry[1])] for entry.split('=') in list]) So my question is: is there a way to eliminate the for loop using list comprehension? If not, is there some built in python method that will do that for me?
Do you mean this? >>> dict( (n,int(v)) for n,v in (a.split('=') for a in string.split() ) ) {'a': 0, 'c': 3, 'b': 1}
Python List Comprehension Vs. Map
Is there a reason to prefer using map() over list comprehension or vice versa? Is one generally more effecient or generally considered more pythonic than the other?
map may be microscopically faster in some cases (when you're NOT making a lambda for the purpose, but using the same function in map and a listcomp). List comprehensions may be faster in other cases and most (not all) pythonistas consider them more direct and clearer. An example of the tiny speed advantage of map when using exactly the same function: $ python -mtimeit -s'xs=range(10)' 'map(hex, xs)' 100000 loops, best of 3: 4.86 usec per loop $ python -mtimeit -s'xs=range(10)' '[hex(x) for x in xs]' 100000 loops, best of 3: 5.58 usec per loop An example of how performance comparison gets completely reversed when map needs a lambda: $ python -mtimeit -s'xs=range(10)' 'map(lambda x: x+2, xs)' 100000 loops, best of 3: 4.24 usec per loop $ python -mtimeit -s'xs=range(10)' '[x+2 for x in xs]' 100000 loops, best of 3: 2.32 usec per loop
Is this a good or bad 'simulation' for Monty Hall? How come?
Through trying to explain the Monty Hall problem to a friend during class yesterday, we ended up coding it in Python to prove that if you always swap, you will win 2/3 times. We came up with this: import random as r #iterations = int(raw_input("How many iterations? >> ")) iterations = 100000 doors = ["goat", "goat", "car"] wins = 0.0 losses = 0.0 for i in range(iterations): n = r.randrange(0,3) choice = doors[n] if n == 0: #print "You chose door 1." #print "Monty opens door 2. There is a goat behind this door." #print "You swapped to door 3." wins += 1 #print "You won a " + doors[2] + "\n" elif n == 1: #print "You chose door 2." #print "Monty opens door 1. There is a goat behind this door." #print "You swapped to door 3." wins += 1 #print "You won a " + doors[2] + "\n" elif n == 2: #print "You chose door 3." #print "Monty opens door 2. There is a goat behind this door." #print "You swapped to door 1." losses += 1 #print "You won a " + doors[0] + "\n" else: print "You screwed up" percentage = (wins/iterations) * 100 print "Wins: " + str(wins) print "Losses: " + str(losses) print "You won " + str(percentage) + "% of the time" My friend thought this was a good way of going about it (and is a good simulation for it), but I have my doubts and concerns. Is it actually random enough? The problem I have with it is that the all choices are kind of hard coded in. Is this a good or bad 'simulation' for the Monty Hall problem? How come? Can you come up with a better version?
Your solution is fine, but if you want a stricter simulation of the problem as posed (and somewhat higher-quality Python;-), try: import random iterations = 100000 doors = ["goat"] * 2 + ["car"] change_wins = 0 change_loses = 0 for i in xrange(iterations): random.shuffle(doors) # you pick door n: n = random.randrange(3) # monty picks door k, k!=n and doors[k]!="car" sequence = range(3) random.shuffle(sequence) for k in sequence: if k == n or doors[k] == "car": continue # now if you change, you lose iff doors[n]=="car" if doors[n] == "car": change_loses += 1 else: change_wins += 1 print "Changing has %s wins and %s losses" % (change_wins, change_loses) perc = (100.0 * change_wins) / (change_wins + change_loses) print "IOW, by changing you win %.1f%% of the time" % perc a typical output is: Changing has 66721 wins and 33279 losses IOW, by changing you win 66.7% of the time
Coroutines for game design?
I've heard that coroutines are a good way to structure games (e.g., PEP 342: "Coroutines are a natural way of expressing many algorithms, such as simulations, games...") but I'm having a hard time wrapping my head around how this would actually be done. I see from this article that coroutines can represent states in a state machine which transition to each other using a scheduler, but it's not clear to me how this applies to a game where the game state is changing based on moves from multiple players. Is there any simple example of a game written using coroutines available? Or can someone offer a sketch of how it might be done?
Coroutines allow for creating large amounts of very-lightweight "microthreads" with cooperative multitasking (i.e. microthreads suspending themselves willfully to allow other microthreads to run). Read up in Dave Beazley's article on this subject. Now, it's obvious how such microthreads can be useful for game programming. Consider a realtime strategy game, where you have dozens of units - each with a mind of its own. It may be a convenient abstraction for each unit's AI to run as such a microthread in your simulated multitasking environment. This is just one example, I'm sure there are more. The "coroutine game programming" search on Google seems to bring up interesting results.
Removing all non-numeric characters from string in Python
How do we remove all non-numeric characters from a string in Python?
>>> import re >>> re.sub("[^0-9]", "", "sdkjh987978asd098as0980a98sd") '987978098098098'
Simple python/Regex problem: Removing all new lines from a file
I'm becoming acquainted with python and am creating problems in order to help myself learn the ins and outs of the language. My next problem comes as follows: I have copied and pasted a huge slew of text from the internet, but the copy and paste added several new lines to break up the huge string. I wish to programatically remove all of these and return the string into a giant blob of characters. This is obviously a job for regex (I think), and parsing through the file and removing all instances of the newline character sounds like it would work, but it doesn't seem to be going over all that well for me. Is there an easy way to go about this? It seems rather simple.
The two main alternatives: read everything in as a single string and remove newlines: clean = open('thefile.txt').read().replace('\n', '') or, read line by line, removing the newline that ends each line, and join it up again: clean = ''.join(l[:-1] for l in open('thefile.txt')) The former alternative is probably faster, but, as always, I strongly recommend you MEASURE speed (e.g., use python -mtimeit) in cases of your specific interest, rather than just assuming you know how performance will be. REs are probably slower, but, again: don't guess, MEASURE! So here are some numbers for a specific text file on my laptop: $ python -mtimeit -s"import re" "re.sub('\n','',open('AV1611Bible.txt').read())" 10 loops, best of 3: 53.9 msec per loop $ python -mtimeit "''.join(l[:-1] for l in open('AV1611Bible.txt'))" 10 loops, best of 3: 51.3 msec per loop $ python -mtimeit "open('AV1611Bible.txt').read().replace('\n', '')" 10 loops, best of 3: 35.1 msec per loop The file is a version of the KJ Bible, downloaded and unzipped from here (I do think it's important to run such measurements on one easily fetched file, so others can easily reproduce them!). Of course, a few milliseconds more or less on a file of 4.3 MB, 34,000 lines, may not matter much to you one way or another; but as the fastest approach is also the simplest one (far from an unusual occurrence, especially in Python;-), I think that's a pretty good recommendation.
Alter namespace prefixing with ElementTree in Python
By default, when you call ElementTree.parse(someXMLfile) the Python ElementTree library prefixes every parsed node with it's namespace URI in Clark's Notation: {http://example.org/namespace/spec}mynode This makes accessing specific nodes by name a huge pain later in the code. I've read through the docs on ElementTree and namespaces and it looks like the iterparse() function should allow me to alter the way the parser prefixes namespaces, but for the life of me I can't actually make it change the prefix. It seems like that may happen in the background before the ns-start event even fires as in this example: for event, elem in iterparse(source): if event == "start-ns": namespaces.append(elem) elif event == "end-ns": namespaces.pop() else: ... How do I make it change the prefixing behavior and what is the proper thing to return when the function ends?
You don't specifically need to use iterparse. Instead, the following script: from cStringIO import StringIO import xml.etree.ElementTree as ET NS_MAP = { 'http://www.red-dove.com/ns/abc' : 'rdc', 'http://www.adobe.com/2006/mxml' : 'mx', 'http://www.red-dove.com/ns/def' : 'oth', } DATA = '''<?xml version="1.0" encoding="utf-8"?> <rdc:container xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:rdc="http://www.red-dove.com/ns/abc" xmlns:oth="http://www.red-dove.com/ns/def"> <mx:Style> <oth:style1/> </mx:Style> <mx:Style> <oth:style2/> </mx:Style> <mx:Style> <oth:style3/> </mx:Style> </rdc:container>''' tree = ET.parse(StringIO(DATA)) some_node = tree.getroot().getchildren()[1] print ET.fixtag(some_node.tag, NS_MAP) some_node = some_node.getchildren()[0] print ET.fixtag(some_node.tag, NS_MAP) produces ('mx:Style', None) ('oth:style2', None) Which shows how you can access the fully-qualified tag names of individual nodes in a parsed tree. You should be able to adapt this to your specific needs.
AttributeError: 'module' object has no attribute
I have two python modules: a.py import b def hello(): print "hello" print "a.py" print hello() print b.hi() b.py import a def hi(): print "hi" When I run a.py, I get: AttributeError: 'module' object has no attribute 'hi' What does the error mean? How do I fix it?
You have mutual top-level imports, which is almost always a bad idea. If you really must have mutual imports in Python, the way to do it is to import them within a function: # In b.py: def cause_a_to_do_something(): import a a.do_something() Now a.py can safely do import b without causing problems. (At first glance it might appear that cause_a_to_do_something() would be hugely inefficient because it does an import every time you call it, but in fact the import work only gets done the first time. The second and subsequent times you import a module, it's a quick operation.)
Python Class vs. Module Attributes
I'm interested in hearing some discussion about class attributes in Python. For example, what is a good use case for class attributes? For the most part, I can not come up with a case where a class attribute is preferable to using a module level attribute. If this is true, then why have them around? The problem I have with them, is that it is almost too easy to clobber a class attribute value by mistake, and then your "global" value has turned into a local instance attribute. Feel free to comment on how you would handle the following situations: Constant values used by a class and/or sub-classes. This may include "magic number" dictionary keys or list indexes that will never change, but possible need one-time initialization. Default class attribute, that in rare occasions updated for a special instance of the class. Global data structure used to represent an internal state of a class shared between all instances. A class that initializes a number of default attributes, not influenced by constructor arguments. Some Related Posts: Difference Between Class and Instance Attributes
#4: I never use class attributes to initialize default instance attributes (the ones you normally put in __init__). For example: class Obj(object): def __init__(self): self.users = 0 and never: class Obj(object): users = 0 Why? Because it's inconsistent: it doesn't do what you want when you assign anything but an invariant object: class Obj(object): users = [] causes the users list to be shared across all objects, which in this case isn't wanted. It's confusing to split these into class attributes and assignments in __init__ depending on their type, so I always put them all in __init__, which I find clearer anyway. As for the rest, I generally put class-specific values inside the class. This isn't so much because globals are "evil"--they're not so big a deal as in some languages, because they're still scoped to the module, unless the module itself is too big--but if external code wants to access them, it's handy to have all of the relevant values in one place. For example, in module.py: class Obj(object): class Exception(Exception): pass ... and then: from module import Obj try: o = Obj() o.go() except o.Exception: print "error" Aside from allowing subclasses to change the value (which isn't always wanted anyway), it means I don't have to laboriously import exception names and a bunch of other stuff needed to use Obj. "from module import Obj, ObjException, ..." gets tiresome quickly.
How to enumerate an object's properties in Python?
I C# we do it through reflection. In Javascript it is simple as: for(var propertyName in objectName) var currentPropertyValue = objectName[propertyName]; How to do it in Python?
for property, value in vars(theObject).iteritems(): print property, ": ", value Be aware that in some rare cases there's a __slots__ property, such classes often have no __dict__.
Printing Python version in output
How can I print version number for the current Python installation in the output?
Try import sys print(sys.version) This prints the full version information string. If you only want the python version number, then Bastien Léonard's solution is the best. You might want to examine the full string and see if you need it or portions of it.
PIL Image.resize() not resizing the picture
I have some strange problem with PIL not resizing the image. def handle_uploaded_image(i, u): # resize image from PIL import Image img = Image.open(i) if img.mode not in ('L', 'RGB'): img = img.convert('RGB') width, height = img.size if width == height: img.thumbnail(settings.THUMB_SIZE, Image.ANTIALIAS) elif width > height: ratio = floor(width / height) newwidth = ratio * 150 newwidthhalf = floor(newwidth / 2) img.resize((newwidth, 150), Image.ANTIALIAS) box = 1 img.crop((newwidthhalf, 0, 150, 150)) elif height > width: ratio = floor(height / width) newheight = ratio * 150 newheighthalf = floor(newheight / 2) img.resize((150, newheight), image.ANTIALIAS) box = 1 img.crop((0, newheighthalf, 150, 150)) path = '/'.join([settings.MEDIA_ROOT, 'users', u.username, 'mugshotv2.jpg']) img.save(path, format='JPEG') This code runs without any errors and produces me image named mugshotv2.jpg in correct folder, but it does not resize it. It does something to it, because the size of the picture drops from 120 kb to 20 kb, but the dimensions remain the same. Perhaps you can also suggest way to crop images into squares with less code. I kinda thought that Image.thumbnail does it, but what it did was that it scaled my image to 150 px by its width, leaving height 100px. Alan.
resize() returns a resized copy of an image. It doesn't modify the original. The correct way to use it is: img = img.resize((150, newheight), image.ANTIALIAS) source I think what you are looking for is the ImageOps.fit function. From PIL docs: ImageOps.fit(image, size, method, bleed, centering) => image Returns a sized and cropped version of the image, cropped to the requested aspect ratio and size. The size argument is the requested output size in pixels, given as a (width, height) tuple.
Is there an object unique identifier in Python
This would be similar to the java.lang.Object.hashcode() method. I need to store objects I have no control over in a set, and make sure that only if two objects are actually the same object (not contain the same values) will the values be overwritten.
id(x) will do the trick for you. But I'm curious, what's wrong about the set of objects (which does combine objects by value)? For your particular problem I would probably keep the set of ids or of wrapper objects. A wrapper object will contain one reference and compare by x==y <==> x.ref is y.ref. It's also worth noting that Python objects have a hash function as well. This function is necessary to put an object into a set or dictionary. It is supposed to sometimes collide for different objects, though good implementations of hash try to make it less likely.
Distributing my python scripts as jars with jython?
I have been a python programmer for almost 2 years and I am used to writing small scripts to automate some repetitive tasks I had to do at office. Now, apparently my colleagues noticed this and they want those scripts too. Some of them have macs, some windows, I made these on windows. I investigated the possibility of using py2exe or even py2app to make natives of my script, but they never satisfied me.. I came to know that all of them have JVM on their systems, so can I give them one single executable jar file of my script using something like jython may be? How feasible is this... I mean, I had no idea how to write scripts for jython, neither did I care about it when I wrote them... what kind of problems will it give?
The best current techniques for distributing your Python files in a jar are detailed in this article on Jython's wiki: http://wiki.python.org/jython/JythonFaq/DistributingJythonScripts For your case, I think you would want to take the jython.jar file that you get when you install Jython and zip the Jython Lib directory into it, then zip your .py files in, and then add a __run__.py file with your startup logic (this file is treated specially by Jython and will be the file executed when you call the jar with "java -jar"). This process is definitely more complicated then in ought to be, and so we (the Jython developers) need to come up with a nice tool that will automate these tasks, but for now these are the best methods. Below I'm copying the recipe at the bottom of the above article (modified slightly to fit your problem description) to give you a sense of the solution. Create the basic jar: $ cd $JYTHON_HOME $ cp jython.jar jythonlib.jar $ zip -r jythonlib.jar Lib Add other modules to the jar: $ cd $MY_APP_DIRECTORY $ cp $JYTHON_HOME/jythonlib.jar myapp.jar $ zip myapp.jar Lib/showobjs.py # Add path to additional jar file. $ jar ufm myapp.jar othermanifest.mf Add the __run__.py module: # Copy or rename your start-up script, removing the "__name__ == '__main__'" check. $ cp mymainscript.py __run__.py # Add your start-up script (__run__.py) to the jar. $ zip myapp.jar __run__.py # Add path to main jar to the CLASSPATH environment variable. $ export CLASSPATH=/path/to/my/app/myapp.jar:$CLASSPATH On MS Windows, that last line, setting the CLASSPATH environment variable, would look something like this: set CLASSPATH=C:\path\to\my\app\myapp.jar;%CLASSPATH% Or, again on MS Windows, use the Control Panel and the System properties to set the CLASSPATH environment variable. Run the application: $ java -jar myapp.jar mymainscript.py arg1 arg2 Or, if you have added your start-up script to the jar, use one of the following: $ java org.python.util.jython -jar myapp.jar arg1 arg2 $ java -cp myapp.jar org.python.util.jython -jar myapp.jar arg1 arg2 $ java -jar myapp.jar -jar myapp.jar arg1 arg2 The double -jar is kind of annoying, so if you want to avoid that and get the more pleasing: $ java -jar myapp.jar arg1 You'll have to do a bit more work until we get something like this into a future Jython [Update: JarRunner is part of Jython 2.5.1]. Here is some Java code that looks for the __run__.py automatically, and runs it. Note that this is my first try at this class. Let me know if it needs improvement! package org.python.util; import org.python.core.imp; import org.python.core.PySystemState; public class JarRunner { public static void run(String[] args) { final String runner = "__run__"; String[] argv = new String[args.length + 1]; argv[0] = runner; System.arraycopy(args, 0, argv, 1, args.length); PySystemState.initialize(PySystemState.getBaseProperties(), null, argv); imp.load(runner); } public static void main(String[] args) { run(args); } } I put this code into the org.python.util package, since that's where it would go if we decide to include it in a future Jython. To compile it, you'll need to put jython.jar (or your myapp.jar) into the classpath like: $ javac -classpath myapp.jar org/python/util/JarRunner.java Then you'll need to add JarRunner.class to your jar (the class file will need to be in org/python/util/JarRunner.class) calling jar on the "org" directory will get the whole path into your jar. $ jar uf org Add this to a file that you will use to update the manifest, a good name is manifest.txt: Main-Class: org.python.util.JarRunner Then update the jar's manifest: $ jar ufm myapp.jar manifest.txt Now you should be able to run your app like this: $ java -jar myapp.jar
Why does subprocess.Popen() with shell=True work differently on Linux vs Windows?
When using subprocess.Popen(args, shell=True) to run "gcc --version" (just as an example), on Windows we get this: >>> from subprocess import Popen >>> Popen(['gcc', '--version'], shell=True) gcc (GCC) 3.4.5 (mingw-vista special r3) ... So it's nicely printing out the version as I expect. But on Linux we get this: >>> from subprocess import Popen >>> Popen(['gcc', '--version'], shell=True) gcc: no input files Because gcc hasn't received the --version option. The docs don't specify exactly what should happen to the args under Windows, but it does say, on Unix, "If args is a sequence, the first item specifies the command string, and any additional items will be treated as additional shell arguments." IMHO the Windows way is better, because it allows you to treat Popen(arglist) calls the same as Popen(arglist, shell=True) ones. Why the difference between Windows and Linux here?
Actually on Windows, it does use cmd.exe when shell=True - it prepends cmd.exe /c (it actually looks up the COMSPEC environment variable but defaults to cmd.exe if not present) to the shell arguments. (On Windows 95/98 it uses the intermediate w9xpopen program to actually launch the command). So the strange implementation is actually the UNIX one, which does the following (where each space separates a different argument): /bin/sh -c gcc --version It looks like the correct implementation (at least on Linux) would be: /bin/sh -c "gcc --version" gcc --version Since this would set the command string from the quoted parameters, and pass the other parameters successfully. From the sh man page section for -c: Read commands from the command_string operand instead of from the standard input. Special parameter 0 will be set from the command_name operand and the positional parameters ($1, $2, etc.) set from the remaining argument operands. This patch seems to fairly simply do the trick: --- subprocess.py.orig 2009-04-19 04:43:42.000000000 +0200 +++ subprocess.py 2009-08-10 13:08:48.000000000 +0200 @@ -990,7 +990,7 @@ args = list(args) if shell: - args = ["/bin/sh", "-c"] + args + args = ["/bin/sh", "-c"] + [" ".join(args)] + args if executable is None: executable = args[0]
Is there an easy way to pickle a python function (or otherwise serialize its code)?
I'm trying to transfer a transfer a function across a network connection (using asyncore). Is there an easy way to serialize a python function (one that, in this case at least, will have no side affects) for transfer like this? I would ideally like to have a pair of functions similar to these: def transmit(func): obj = pickle.dumps(func) [send obj across the network] def receive(): [receive obj from the network] func = pickle.loads(s) func()
You could serialise the function bytecode and then reconstruct it on the caller. The marshal module can be used to serialise code objects, which can then be reassembled into a function. ie: import marshal def foo(x): return x*x code_string = marshal.dumps(foo.func_code) Then in the remote process (after transferring code_string): import marshal, types code = marshal.loads(code_string) func = types.FunctionType(code, globals(), "some_func_name") func(10) # gives 100 A few caveats: marshal's format (any python bytecode for that matter) may not be compatable between major python versions. Will only work for cpython implementation. If the function references globals (including imported modules, other functions etc) that you need to pick up, you'll need to serialise these too, or recreate them on the remote side. My example just gives it the remote process's global namespace. You'll probably need to do a bit more to support more complex cases, like closures or generator functions.
Reimport a module in python while interactive
I know it can be done, but I never remember how. How can you reimport a module in python? The scenario is as follows: I import a module interactively and tinker with it, but then I face an error. I fix the error in the .py file and then I want to reimport the fixed module without quitting python. How can I do it ?
This should work: reload(my.module) From the Python docs Reload a previously imported module. The argument must be a module object, so it must have been successfully imported before. This is useful if you have edited the module source file using an external editor and want to try out the new version without leaving the Python interpreter.
Fastest way to convert a dict's keys & values from `unicode` to `str`?
I'm receiving a dict from one "layer" of code upon which some calculations/modifications are performed before passing it onto another "layer". The original dict's keys & "string" values are unicode, but the layer they're being passed onto only accepts str. This is going to be called often, so I'd like to know what would be the fastest way to convert something like: { u'spam': u'eggs', u'foo': True, u'bar': { u'baz': 97 } } ...to: { 'spam': 'eggs', 'foo': True, 'bar': { 'baz': 97 } } ...bearing in mind the non-"string" values need to stay as their original type. Any thoughts?
DATA = { u'spam': u'eggs', u'foo': frozenset([u'Gah!']), u'bar': { u'baz': 97 }, u'list': [u'list', (True, u'Maybe'), set([u'and', u'a', u'set', 1])]} def convert(data): if isinstance(data, basestring): return str(data) elif isinstance(data, collections.Mapping): return dict(map(convert, data.iteritems())) elif isinstance(data, collections.Iterable): return type(data)(map(convert, data)) else: return data print DATA print convert(DATA) # Prints: # {u'list': [u'list', (True, u'Maybe'), set([u'and', u'a', u'set', 1])], u'foo': frozenset([u'Gah!']), u'bar': {u'baz': 97}, u'spam': u'eggs'} # {'bar': {'baz': 97}, 'foo': frozenset(['Gah!']), 'list': ['list', (True, 'Maybe'), set(['and', 'a', 'set', 1])], 'spam': 'eggs'} Assumptions: You've imported the collections module and can make use of the abstract base classes it provides You're happy to convert using the default encoding (use data.encode('utf-8') rather than str(data) if you need an explicit encoding). If you need to support other container types, hopefully it's obvious how to follow the pattern and add cases for them.
Can Python's optparse display the default value of an option?
Is there a way to make Python's optparse print the default value of an option or flag when showing the help with --help?
Try using the %default string placeholder: # This example taken from http://docs.python.org/library/optparse.html#generating-help parser.add_option("-m", "--mode", default="intermediate", help="interaction mode: novice, intermediate, " "or expert [default: %default]")
How do you dynamically hide form fields in Django?
I am making a profile form in Django. There are a lot of optional extra profile fields but I would only like to show two at a time. How do I hide or remove the fields I do not want to show dynamically? Here is what I have so far: class UserProfileForm(forms.ModelForm): extra_fields = ('field1', 'field2', 'field3') extra_field_total = 2 class Meta: model = UserProfile def __init__(self, *args, **kwargs): extra_field_count = 0 for key, field in self.base_fields.iteritems(): if key in self.extra_fields: if extra_field_count < self.extra_field_total: extra_field_count += 1 else: # do something here to hide or remove field super(UserProfileForm, self).__init__(*args, **kwargs)
I think I found my answer. First I tried: field.widget = field.hidden_widget which didn't work. The correct way happens to be: field.widget = field.hidden_widget()
Django - Getting last object created, simultaneous filters
Apologies, I am completely new to Django and Python. I have 2 questions. First, how would I go about getting the last object created (or highest pk) in a list of objects? For example, I know that I could use the following to get the first object: list = List.objects.all()[0] Is there a way to get the length of List.objects? I've tried List.objects.length but to no avail. Second, is it possible to create simultaneous filters or combine lists? Here is an example: def findNumber(request, number) phone_list = Numbers.objects.filter(cell=number) I want something like the above, but more like: def findNumber(request, number) phone_list = Numbers.objects.filter(cell=number or home_phone=number) What is the correct syntax, if any?
I haven't tried this yet, but I'd look at the latest() operator on QuerySets: latest(field_name=None) Returns the latest object in the table, by date, using the field_name provided as the date field. This example returns the latest Entry in the table, according to the pub_date field: Entry.objects.latest('pub_date') If your model's Meta specifies get_latest_by, you can leave off the field_name argument to latest(). Django will use the field specified in get_latest_by by default. Like get(), latest() raises DoesNotExist if an object doesn't exist with the given parameters. Note latest() exists purely for convenience and readability. And the model docs on get_latest_by: get_latest_by Options.get_latest_by The name of a DateField or DateTimeField in the model. This specifies the default field to use in your model Manager's latest method. Example: get_latest_by = "order_date" See the docs for latest() for more. Edit: Wade has a good answer on Q() operator.
Iterate over pairs in a list (circular fashion) in Python
The problem is easy, I want to iterate over each element of the list and the next one in pairs (wrapping the last one with the first). I've thought about two unpythonic ways of doing it: def pairs(lst): n = len(lst) for i in range(n): yield lst[i],lst[(i+1)%n] and: def pairs(lst): return zip(lst,lst[1:]+[lst[0]]) expected output: >>> for i in pairs(range(10)): print i (0, 1) (1, 2) (2, 3) (3, 4) (4, 5) (5, 6) (6, 7) (7, 8) (8, 9) (9, 0) >>> any suggestions about a more pythonic way of doing this? maybe there is a predefined function out there I haven't heard about? also a more general n-fold (with triplets, quartets, etc. instead of pairs) version could be interesting.
def pairs(lst): i = iter(lst) first = prev = item = i.next() for item in i: yield prev, item prev = item yield item, first Works on any non-empty sequence, no indexing required.
python: slow timeit() function
When I run the code below outside of timeit(), it appears to complete instantaneously. However when I run it within the timeit() function, it takes much longer. Why? >>> import timeit >>> t = timeit.Timer("3**4**5") >>> t.timeit() 16.55522028637718 Using: Python 3.1 (x86) - AMD Athlon 64 X2 - WinXP (32 bit)
The timeit() function runs the code many times (default one million) and takes an average of the timings. To run the code only once, do this: t.timeit(1) but that will give you skewed results - it repeats for good reason. To get the per-loop time having let it repeat, divide the result by the number of loops. Use a smaller value for the number of repeats if one million is too many: count = 1000 print t.timeit(count) / count
python datetime strptime wildcard
I want to parse dates like these into a datetime object: December 12th, 2008 January 1st, 2009 The following will work for the first date: datetime.strptime("December 12th, 2008", "%B %dth, %Y") but will fail for the second because of the suffix to the day number ('st'). So, is there an undocumented wildcard character in strptime? Or a better approach altogether?
Try using the dateutil.parser module. import dateutil.parser date1 = dateutil.parser.parse("December 12th, 2008") date2 = dateutil.parser.parse("January 1st, 2009") Additional documentation can be found here: http://labix.org/python-dateutil
django Datefield to Unix timestamp
Hello In a model I have a such field: mydate = models.DateField() now a javascript graph function requires unix timestamp such as "1196550000000", how can I return the unix timestamp of my mydate input. Thanks
I know another answer was accepted a while ago, but this question appears high on Google's search results, so I will add another answer. If you are working at the template level, you can use the U parameter to the date filter, e.g.: {{ mydate|date:"U" }} Note that it will be based upon the TIMEZONE in your settings.py.
How can I use Emacs Flymake mode for python with pyflakes and pylint checking code?
For checking code in python mode I use flymake with pyflakes Also I want check code style (pep8) with pylint (description on the same page with pyflakes) This solutions work. But I can't configure flymake for work with pyflakes and pylint together. How can I do it?
Well, flymake is just looking for a executable command thats output lines in a predefined format. You can make a shell script for example that will call successively all the checkers you want... You must also make sure that your script ends by returning errorlevel 0. So this is an example: This is what I've done in a "pycheckers" script: #!/bin/bash epylint "$1" 2>/dev/null pyflakes "$1" pep8 --ignore=E221,E701,E202 --repeat "$1" true For the emacs lisp part: (when (load "flymake" t) (defun flymake-pyflakes-init () (let* ((temp-file (flymake-init-create-temp-buffer-copy 'flymake-create-temp-inplace)) (local-file (file-relative-name temp-file (file-name-directory buffer-file-name)))) (list "pycheckers" (list local-file)))) (add-to-list 'flymake-allowed-file-name-masks '("\\.py\\'" flymake-pyflakes-init)))
Python : Assert that variable is instance method?
How can one check if a variable is an instance method or not? I'm using python 2.5. Something like this: class Test: def method(self): pass assert is_instance_method(Test().method)
inspect.ismethod is what you want to find out if you definitely have a method, rather than just something you can call. import inspect def foo(): pass class Test(object): def method(self): pass print inspect.ismethod(foo) # False print inspect.ismethod(Test) # False print inspect.ismethod(Test.method) # True print inspect.ismethod(Test().method) # True print callable(foo) # True print callable(Test) # True print callable(Test.method) # True print callable(Test().method) # True callable is true if the argument if the argument is a method, a function (including lambdas), an instance with __call__ or a class. Methods have different properties than functions (like im_class and im_self). So you want assert inspect.ismethod(Test().method)
OS locale support for use in Python
The following Python code works on my Windows machine (Python 2.5.4), but doesn't on my Debian machine (Python 2.5.0). I'm guessing it's OS dependent. import locale locale.setlocale( locale.LC_ALL, 'English_United States.1252' ) I receive the following error: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.5/locale.py", line 476, in setlocale return _setlocale(category, locale) locale.Error: unsupported locale setting Questions: Is it OS dependent? How can I find the supported locale list within Python? How can I match between Windows locales and Debian locales?
It is OS dependent. To get the list of local available you can use locale -a in a shell I think the local you want is something like Windows-1252
Python: import a file from a subdirectory
I have a file called tester.py, located on /project. /project has a subdirectory called lib, with a file called BoxTime.py: /project/tester.py /project/lib/BoxTime.py I want to import BoxTime from tester. I have tried this: import lib.BoxTime Which resulted: Traceback (most recent call last): File "./tester.py", line 3, in <module> import lib.BoxTime ImportError: No module named lib.BoxTime Any ideas how to import BoxTime from the subdirectory? EDIT The __init__.py was the problem, but don't forget to refer to BoxTime as lib.BoxTime, or use: import lib.BoxTime as BT ... BT.bt_function()
Take a look at the Packages documentation (Section 6.4) here: http://docs.python.org/tutorial/modules.html In short, you need to put a blank file named __init__.py in the "lib" directory.
Python nonlocal statement
What does the Python nonlocal statement do (in Python 3.0 and later)? There's no documentation on the official Python website and help("nonlocal") does not work, either.
Compare this, without using nonlocal: x = 0 def outer(): x = 1 def inner(): x = 2 print("inner:", x) inner() print("outer:", x) outer() print("global:", x) # inner: 2 # outer: 1 # global: 0 To this, using nonlocal, where inner()'s x is now also outer()'s x: x = 0 def outer(): x = 1 def inner(): nonlocal x x = 2 print("inner:", x) inner() print("outer:", x) outer() print("global:", x) # inner: 2 # outer: 2 # global: 0 If we were to use global, it would bind x to the properly "global" value: x = 0 def outer(): x = 1 def inner(): global x x = 2 print("inner:", x) inner() print("outer:", x) outer() print("global:", x) # inner: 2 # outer: 1 # global: 2
Python decorators in classes
Can one write sth like: class Test(object): def _decorator(self, foo): foo() @self._decorator def bar(self): pass This fails: self in @self is unknown I also tried: @Test._decorator(self) which also fails: Test unknown If would like to temp. change some instance variables in the decorator and the run the decorated method, before changing them back. Thanks.
Would something like this do what you need? class Test(object): def _decorator(foo): def magic( self ) : print "start magic" foo( self ) print "end magic" return magic @_decorator def bar( self ) : print "normal call" test = Test() test.bar() This avoids the call to self to access the decorator and leaves it hidden in the class namespace as a regular method. >>> import stackoverflow >>> test = stackoverflow.Test() >>> test.bar() start magic normal call end magic >>> edited to answer question in comments: How to use the hidden decorator in another class class Test(object): def _decorator(foo): def magic( self ) : print "start magic" foo( self ) print "end magic" return magic @_decorator def bar( self ) : print "normal call" _decorator = staticmethod( _decorator ) class TestB( Test ): @Test._decorator def bar( self ): print "override bar in" super( TestB, self ).bar() print "override bar out" print "Normal:" test = Test() test.bar() print print "Inherited:" b = TestB() b.bar() print
Mechanize and BeautifulSoup for PHP?
I was wondering if there was anything similar like Mechanize or BeautifulSoup for PHP?
SimpleTest provides you with similar functionality: http://www.simpletest.org/en/browser_documentation.html
How to run Python egg files directly without installing them?
Is it possible to run Python egg files directly as you can run jar files with Java? For example, with Java you might dos something like: $ java -jar jar-file
A python egg is a "a single-file importable distribution format". Which is typically a python package. You can import the package in the egg as long as you know it's name and it's in your path. You can execute a package using the "-m" option and the package name. However, python packages generally do not do anything when executed, and you may get an error. The -c option can be used to run code. (See http://docs.python.org/using/cmdline.html for details on command line options) > python -m sphinx sphinx is a package and cannot be directly executed > python -c "import <package in an egg>; <function>();" > python -c "import sphinx; print sphinx.package_dir" C:\Python26\lib\site-packages\sphinx-0.6.1-py2.6.egg\sphinx
Python: Check if a string represents an int, Without using Try/Except?
Is there any way to tell whether a string represents an integer (e.g., '3', '-17' but not '3.14' or 'asfasfas') Without using a try/except mechanism? is_int('3.14') = False is_int('-7') = True
with positive integers you could use .isdigit: >>> '16'.isdigit() True it doesn't work with negative integers though. suppose you could try the following: >>> s = '-17' >>> s.startswith('-') and s[1:].isdigit() True it won't work with '16.0' format, which is similar to int casting in this sense. edit: def check_int(s): if s[0] in ('-', '+'): return s[1:].isdigit() return s.isdigit()
Does PHP have an equivalent to Python's list comprehension syntax?
Python has syntactically sweet list comprehensions: S = [x**2 for x in range(10)] print S; [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] In PHP I would need to do some looping: $output = array(); $Nums = range(0,9); foreach ($Nums as $num) { $out[] = $num*=$num; } print_r($out); to get: Array ( [0] => 0 [1] => 1 [2] => 4 [3] => 9 [4] => 16 [5] => 25 [6] => 36 [7] => 49 [8] => 64 [9] => 81 ) Is there anyway to get a similar list comprehension syntax in PHP? Is there anyway to do it with any of the new features in PHP 5.3? Thanks!
Maybe something like this? $out=array_map(function($x) {return $x*$x;}, range(0, 9)) This will work in PHP 5.3+, in an older version you'd have to define the callback for array_map separately function sq($x) {return $x*$x;} $out=array_map('sq', range(0, 9));
What's the best way to do literate programming in Python on Windows?
I've been playing with various ways of doing literate programming in Python. I like noweb, but I have two main problems with it: first, it is hard to build on Windows, where I spend about half my development time; and second, it requires me to indent each chunk of code as it will be in the final program --- which I don't necessarily know when I write it. I don't want to use Leo, because I'm very attached to Emacs. Is there a good literate programming tool that: Runs on Windows Allows me to set the indentation of the chunks when they're used, not when they're written Still lets me work in Emacs Thanks! Correction: noweb does allow me to indent later --- I misread the paper I found on it. By default, notangle preserves whitespace and maintains indentation when expanding chunks. It can therefore be used with languages like Miranda and Haskell, in which indentation is significant That leaves me with only the "Runs on Windows" problem.
I have written Pweave http://mpastell.com/pweave, that is aimed for dynamic report generation and uses noweb syntax. It is a pure python script so it also runs on Windows. It doesn't fix your indent problem, but maybe you can modify it for that, the code is really quite simple.
How can I force division to be floating point in Python? Division keeps rounding down to 0
I have two integer values a and b, but I need their ratio in floating point. I know that a<b and I want to calculate a/b, so if I use integer division I'll always get 0 with a remainder of a. How can I force c to be a floating point number in Python in the following? c = a / b
You can cast to float by doing c = a / float(b). If the numerator or denominator is a float, then the result will be also. A caveat: as commenters have pointed out, this won't work if b might be something other than an integer or floating-point number (or a string representing one). If you might be dealing with other types (such as complex numbers) you'll need to either check for those or use a different method.
Python: Possible to share in-memory data between 2 separate processes
I have an xmlrpc server using Twisted. The server has a huge amount of data stored in-memory. Is it possible to have a secondary, separate xmlrpc server running which can access the object in-memory in the first server? So, serverA starts up and creates an object. serverB starts up and can read from the object in serverA. * EDIT * The data to be shared is a list of 1 million tuples.
Without some deep and dark rewriting of the Python core runtime (to allow forcing of an allocator that uses a given segment of shared memory and ensures compatible addresses between disparate processes) there is no way to "share objects in memory" in any general sense. That list will hold a million addresses of tuples, each tuple made up of addresses of all of its items, and each of these addresses will have be assigned by pymalloc in a way that inevitably varies among processes and spreads all over the heap. On just about every system except Windows, it's possible to spawn a subprocess that has essentially read-only access to objects in the parent process's space... as long as the parent process doesn't alter those objects, either. That's obtained with a call to os.fork(), that in practice "snapshots" all of the memory space of the current process and starts another simultaneous process on the copy/snapshot. On all modern operating systems, this is actually very fast thanks to a "copy on write" approach: the pages of virtual memory that are not altered by either process after the fork are not really copied (access to the same pages is instead shared); as soon as either process modifies any bit in a previously shared page, poof, that page is copied, and the page table modified, so the modifying process now has its own copy while the other process still sees the original one. This extremely limited form of sharing can still be a lifesaver in some cases (although it's extremely limited: remember for example that adding a reference to a shared object counts as "altering" that object, due to reference counts, and so will force a page copy!)... except on Windows, of course, where it's not available. With this single exception (which I don't think will cover your use case), sharing of object graphs that include references/pointers to other objects is basically unfeasible -- and just about any objects set of interest in modern languages (including Python) falls under this classification. In extreme (but sufficiently simple) cases one can obtain sharing by renouncing the native memory representation of such object graphs. For example, a list of a million tuples each with sixteen floats could actually be represented as a single block of 128 MB of shared memory -- all the 16M floats in double-precision IEEE representation laid end to end -- with a little shim on top to "make it look like" you're addressing things in the normal way (and, of course, the not-so-little-after-all shim would also have to take care of the extremely hairy inter-process synchronization problems that are certain to arise;-). It only gets hairier and more complicated from there. Modern approaches to concurrency are more and more disdaining shared-anything approaches in favor of shared-nothing ones, where tasks communicate by message passing (even in multi-core systems using threading and shared address spaces, the synchronization issues and the performance hits the HW incurs in terms of caching, pipeline stalls, etc, when large areas of memory are actively modified by multiple cores at once, are pushing people away). For example, the multiprocessing module in Python's standard library relies mostly on pickling and sending objects back and forth, not on sharing memory (surely not in a R/W way!-). I realize this is not welcome news to the OP, but if he does need to put multiple processors to work, he'd better think in terms of having anything they must share reside in places where they can be accessed and modified by message passing -- a database, a memcache cluster, a dedicated process that does nothing but keep those data in memory and send and receive them on request, and other such message-passing-centric architectures.
Calling a base class's classmethod in Python
Consider the following code: class Base(object): @classmethod def do(cls, a): print cls, a class Derived(Base): @classmethod def do(cls, a): print 'In derived!' # Base.do(cls, a) -- can't pass `cls` Base.do(a) if __name__ == '__main__': d = Derived() d.do('hello') > $ python play.py > In derived! > <class '__main__.Base'> msg From Derived.do, how do I call Base.do? I would normally use super or even the base class name directly if this is a normal object method, but apparently I can't find a way to call the classmethod in the base class. In the above example, Base.do(a) prints Base class instead of Derived class.
super(Derived, cls).do(a) EDIT: Oh, wait a minute... it's not clear exactly what you're asking. This is how you would invoke the code in the base class's version of the method, from the derived class.
Scale an image in GTK
In GTK, how can I scale an image? Right now I load images with PIL and scale them beforehand, but is there a way to do it with GTK?
Load the image from a file using gtk.gdk.Pixbuf for that: import gtk pixbuf = gtk.gdk.pixbuf_new_from_file('/path/to/the/image.png') then scale it: pixbuf = pixbuf.scale_simple(width, height, gtk.gdk.INTERP_BILINEAR) Then, if you want use it in a gtk.Image, crate the widget and set the image from the pixbuf. image = gkt.Image() image.set_from_pixbuf(pixbuf) Or maybe in a direct way: image = gtk.image_new_from_pixbuf(pixbuf)
Unusual Speed Difference between Python and C++
I recently wrote a short algorithm to calculate happy numbers in python. The program allows you to pick an upper bound and it will determine all the happy numbers below it. For a speed comparison I decided to make the most direct translation of the algorithm I knew of from python to c++. Surprisingly, the c++ version runs significantly slower than the python version. Accurate speed tests between the execution times for discovering the first 10,000 happy numbers indicate the python program runs on average in 0.59 seconds and the c++ version runs on average in 8.5 seconds. I would attribute this speed difference to the fact that I had to write helper functions for parts of the calculations (for example determining if an element is in a list/array/vector) in the c++ version which were already built in to the python language. Firstly, is this the true reason for such an absurd speed difference, and secondly, how can I change the c++ version to execute more quickly than the python version (the way it should be in my opinion). The two pieces of code, with speed testing are here: Python Version, C++ Version. Thanks for the help. #include <iostream> #include <vector> #include <string> #include <ctime> #include <windows.h> using namespace std; bool inVector(int inQuestion, vector<int> known); int sum(vector<int> given); int pow(int given, int power); void calcMain(int upperBound); int main() { while(true) { int upperBound; cout << "Pick an upper bound: "; cin >> upperBound; long start, end; start = GetTickCount(); calcMain(upperBound); end = GetTickCount(); double seconds = (double)(end-start) / 1000.0; cout << seconds << " seconds." << endl << endl; } return 0; } void calcMain(int upperBound) { vector<int> known; for(int i = 0; i <= upperBound; i++) { bool next = false; int current = i; vector<int> history; while(!next) { char* buffer = new char[10]; itoa(current, buffer, 10); string digits = buffer; delete buffer; vector<int> squares; for(int j = 0; j < digits.size(); j++) { char charDigit = digits[j]; int digit = atoi(&charDigit); int square = pow(digit, 2); squares.push_back(square); } int squaresum = sum(squares); current = squaresum; if(inVector(current, history)) { next = true; if(current == 1) { known.push_back(i); //cout << i << "\t"; } } history.push_back(current); } } //cout << "\n\n"; } bool inVector(int inQuestion, vector<int> known) { for(vector<int>::iterator it = known.begin(); it != known.end(); it++) if(*it == inQuestion) return true; return false; } int sum(vector<int> given) { int sum = 0; for(vector<int>::iterator it = given.begin(); it != given.end(); it++) sum += *it; return sum; } int pow(int given, int power) { int original = given; int current = given; for(int i = 0; i < power-1; i++) current *= original; return current; } #!/usr/bin/env python import timeit upperBound = 0 def calcMain(): known = [] for i in range(0,upperBound+1): next = False current = i history = [] while not next: digits = str(current) squares = [pow(int(digit), 2) for digit in digits] squaresum = sum(squares) current = squaresum if current in history: next = True if current == 1: known.append(i) ##print i, "\t", history.append(current) ##print "\nend" while True: upperBound = input("Pick an upper bound: ") result = timeit.Timer(calcMain).timeit(1) print result, "seconds.\n"
For 100000 elements, the Python code took 6.9 seconds while the C++ originally took above 37 seconds. I did some basic optimizations on your code and managed to get the C++ code above 100 times faster than the Python implementation. It now does 100000 elements in 0.06 seconds. That is 617 times faster than the original C++ code. The most important thing is to compile in Release mode, with all optimizations. This code is literally orders of magnitude slower in Debug mode. Next, I will explain the optimizations I did. Moved all vector declarations outside of the loop; replaced them by a clear() operation, which is much faster than calling the constructor. Replaced the call to pow(value, 2) by a multiplication : value * value. Instead of having a squares vector and calling sum on it, I sum the values in-place using just an integer. Avoided all string operations, which are very slow compared to integer operations. For instance, it is possible to compute the squares of each digit by repeatedly dividing by 10 and fetching the modulus 10 of the resulting value, instead of converting the value to a string and then each character back to int. Avoided all vector copies, first by replacing passing by value with passing by reference, and finally by eliminating the helper functions completely. Eliminated a few temporary variables. And probably many small details I forgot. Compare your code and mine side-by-side to see exactly what I did. It may be possible to optimize the code even more by using pre-allocated arrays instead of vectors, but this would be a bit more work and I'll leave it as an exercise to the reader. :P Here's the optimized code : #include <iostream> #include <vector> #include <string> #include <ctime> #include <algorithm> #include <windows.h> using namespace std; void calcMain(int upperBound, vector<int>& known); int main() { while(true) { vector<int> results; int upperBound; cout << "Pick an upper bound: "; cin >> upperBound; long start, end; start = GetTickCount(); calcMain(upperBound, results); end = GetTickCount(); for (size_t i = 0; i < results.size(); ++i) { cout << results[i] << ", "; } cout << endl; double seconds = (double)(end-start) / 1000.0; cout << seconds << " seconds." << endl << endl; } return 0; } void calcMain(int upperBound, vector<int>& known) { vector<int> history; for(int i = 0; i <= upperBound; i++) { int current = i; history.clear(); while(true) { int temp = current; int sum = 0; while (temp > 0) { sum += (temp % 10) * (temp % 10); temp /= 10; } current = sum; if(find(history.begin(), history.end(), current) != history.end()) { if(current == 1) { known.push_back(i); } break; } history.push_back(current); } } }
Python standard library to POST multipart/form-data encoded data
I would like to POST multipart/form-data encoded data. I have found an external module that does it: http://atlee.ca/software/poster/index.html however I would rather avoid this dependency. Is there a way to do this using the standard libraries? thanks
The standard library does not currently support that. There is cookbook recipe that includes a fairly short piece of code that you just may want to copy, though, along with long discussions of alternatives.
Python - how to refer to relative paths of resources when working with code repository
We are working with a code repository which is deployed both to windows and linux, sometimes on different directories. How should one of the modules inside the project refer to one of the non-python resources in the project (CSV file, etc.)? If we do something like thefile=open('test.csv') or thefile=open('../somedirectory/test.csv') It will work only when the script is run from one specific directory, or a subset of the directories. What I would like to do is something like: path=getBasePathOfProject()+'/somedirectory/test.csv' thefile=open(path) Is this the right way? Is it possible? Thanks
Try to use a filename relative to the current files path. Example for './my_file': fn = os.path.join(os.path.dirname(__file__), 'my_file')
How to remove two chars from the beginning of a line
I'm a complete Python noob. How can I remove two characters from the beginning of each line in a file? I was trying something like this: #!/Python26/ import re f = open('M:/file.txt') lines=f.readlines() i=0; for line in lines: line = line.strip() #do something here
You were off to a good start. Try this in your loop: for line in lines: line = line[2:] # do something here The [2:] is called "slice" syntax, it essentially says "give me the part of this sequence which begins at index 2 and continues to the end (since no end point was specified after the colon).
Resize a figure automatically in matplotlib
Is there a way to automatically resize a figure to properly fit contained plots in a matplotlib/pylab image? I'm creating heatmap (sub)plots that differ in aspect ratio according to the data used. I realise I could calculate the aspect ratio and manually set it, but surely there's an easier way?
Use bbox_inches='tight' import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm X = 10*np.random.rand(5,3) fig = plt.figure(figsize=(15,5),facecolor='w') ax = fig.add_subplot(111) ax.imshow(X, cmap=cm.jet) plt.savefig("image.png",bbox_inches='tight',dpi=100) ...only works when saving images though, not showing them.