title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
How do I keep Python print from adding newlines or spaces?
255,147
169
2008-10-31T22:33:21Z
255,154
147
2008-10-31T22:35:49Z
[ "python", "printing", "formatting", "python-2.x" ]
In python, if I say ``` print 'h' ``` I get the letter h and a newline. If I say ``` print 'h', ``` I get the letter h and no newline. If I say ``` print 'h', print 'm', ``` I get the letter h, a space, and the letter m. How can I prevent Python from printing the space? The print statements are different iterations of the same loop so I can't just use the + operator.
You can use: ``` sys.stdout.write('h') sys.stdout.write('m') ```
How do I keep Python print from adding newlines or spaces?
255,147
169
2008-10-31T22:33:21Z
255,172
186
2008-10-31T22:44:14Z
[ "python", "printing", "formatting", "python-2.x" ]
In python, if I say ``` print 'h' ``` I get the letter h and a newline. If I say ``` print 'h', ``` I get the letter h and no newline. If I say ``` print 'h', print 'm', ``` I get the letter h, a space, and the letter m. How can I prevent Python from printing the space? The print statements are different iterations of the same loop so I can't just use the + operator.
Just a comment. In [Python 3](http://docs.python.org/dev/3.0/whatsnew/3.0.html), you will use ``` print('h', end='') ``` to suppress the endline terminator, and ``` print('a', 'b', 'c', sep='') ``` to suppress the whitespace separator between items.
How do I keep Python print from adding newlines or spaces?
255,147
169
2008-10-31T22:33:21Z
255,199
33
2008-10-31T22:53:52Z
[ "python", "printing", "formatting", "python-2.x" ]
In python, if I say ``` print 'h' ``` I get the letter h and a newline. If I say ``` print 'h', ``` I get the letter h and no newline. If I say ``` print 'h', print 'm', ``` I get the letter h, a space, and the letter m. How can I prevent Python from printing the space? The print statements are different iterations of the same loop so I can't just use the + operator.
Greg is right-- you can use sys.stdout.write Perhaps, though, you should consider refactoring your algorithm to accumulate a list of <whatevers> and then ``` lst = ['h', 'm'] print "".join(lst) ```
How do I keep Python print from adding newlines or spaces?
255,147
169
2008-10-31T22:33:21Z
255,306
18
2008-11-01T00:21:28Z
[ "python", "printing", "formatting", "python-2.x" ]
In python, if I say ``` print 'h' ``` I get the letter h and a newline. If I say ``` print 'h', ``` I get the letter h and no newline. If I say ``` print 'h', print 'm', ``` I get the letter h, a space, and the letter m. How can I prevent Python from printing the space? The print statements are different iterations of the same loop so I can't just use the + operator.
``` Python 2.5.2 (r252:60911, Sep 27 2008, 07:03:14) [GCC 4.3.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> print "hello",; print "there" hello there >>> print "hello",; sys.stdout.softspace=False; print "there" hellothere ``` But really, you should use `sys.stdout.write` directly.
How do I keep Python print from adding newlines or spaces?
255,147
169
2008-10-31T22:33:21Z
255,336
13
2008-11-01T00:43:51Z
[ "python", "printing", "formatting", "python-2.x" ]
In python, if I say ``` print 'h' ``` I get the letter h and a newline. If I say ``` print 'h', ``` I get the letter h and no newline. If I say ``` print 'h', print 'm', ``` I get the letter h, a space, and the letter m. How can I prevent Python from printing the space? The print statements are different iterations of the same loop so I can't just use the + operator.
For completeness, one other way is to clear the softspace value after performing the write. ``` import sys print "hello", sys.stdout.softspace=0 print "world", print "!" ``` prints `helloworld !` Using stdout.write() is probably more convenient for most cases though.
How do I keep Python print from adding newlines or spaces?
255,147
169
2008-10-31T22:33:21Z
410,850
15
2009-01-04T11:27:42Z
[ "python", "printing", "formatting", "python-2.x" ]
In python, if I say ``` print 'h' ``` I get the letter h and a newline. If I say ``` print 'h', ``` I get the letter h and no newline. If I say ``` print 'h', print 'm', ``` I get the letter h, a space, and the letter m. How can I prevent Python from printing the space? The print statements are different iterations of the same loop so I can't just use the + operator.
Or use a `+`, i.e.: ``` >>> print 'me'+'no'+'likee'+'spacees'+'pls' menolikeespaceespls ``` Just make sure all are concatenate-able objects.
How do I keep Python print from adding newlines or spaces?
255,147
169
2008-10-31T22:33:21Z
1,036,396
8
2009-06-24T04:26:03Z
[ "python", "printing", "formatting", "python-2.x" ]
In python, if I say ``` print 'h' ``` I get the letter h and a newline. If I say ``` print 'h', ``` I get the letter h and no newline. If I say ``` print 'h', print 'm', ``` I get the letter h, a space, and the letter m. How can I prevent Python from printing the space? The print statements are different iterations of the same loop so I can't just use the + operator.
Regain control of your console! Simply: ``` from __past__ import printf ``` where `__past__.py` contains: ``` import sys def printf(fmt, *varargs): sys.stdout.write(fmt % varargs) ``` then: ``` >>> printf("Hello, world!\n") Hello, world! >>> printf("%d %d %d\n", 0, 1, 42) 0 1 42 >>> printf('a'); printf('b'); printf('c'); printf('\n') abc >>> ``` Bonus extra: If you don't like `print >> f, ...`, you can extending this caper to fprintf(f, ...).
How do I keep Python print from adding newlines or spaces?
255,147
169
2008-10-31T22:33:21Z
20,677,875
11
2013-12-19T09:32:40Z
[ "python", "printing", "formatting", "python-2.x" ]
In python, if I say ``` print 'h' ``` I get the letter h and a newline. If I say ``` print 'h', ``` I get the letter h and no newline. If I say ``` print 'h', print 'm', ``` I get the letter h, a space, and the letter m. How can I prevent Python from printing the space? The print statements are different iterations of the same loop so I can't just use the + operator.
This may look stupid, but seems to be the simplest: ``` print 'h', print '\bm' ```
Python re.findall with groupdicts
255,332
8
2008-11-01T00:41:54Z
255,344
19
2008-11-01T00:52:19Z
[ "python", "regex" ]
I kind of wish that there were a version of `re.findall` that returned `groupdict`s instead of just `group`s. Am I missing some simple way to accomplish the same result? (Does anybody know of a reason that this function doesn't exist?)
You could use the finditer() function. This will give you a sequence of match objects, so you can get the groupdict for each with: ``` [m.groupdict() for m in regex.finditer(search_string)] ```
Determine if a named parameter was passed
255,429
10
2008-11-01T02:23:27Z
255,580
7
2008-11-01T06:17:54Z
[ "python", "default-value", "named-parameters" ]
I would like to know if it is possible to determine if a function parameter with a default value was passed in Python. For example, how does dict.pop work? ``` >>> {}.pop('test') Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'pop(): dictionary is empty' >>> {}.pop('test',None) >>> {}.pop('test',3) 3 >>> {}.pop('test',NotImplemented) NotImplemented ``` How does the pop method determine that the first time a default return value was not passed? Is this something that can only be done in C? Thanks
The convention is often to use `arg=None` and use ``` def foo(arg=None): if arg is None: arg = "default value" # other stuff # ... ``` to check if it was passed or not. Allowing the user to pass `None`, which would be interpreted as if the argument was *not* passed.
Browser-based application or stand-alone GUI app?
255,476
22
2008-11-01T03:25:09Z
255,481
10
2008-11-01T03:29:53Z
[ "python", "user-interface", "browser" ]
I'm sure this has been asked before, but I can't find it. What are the benefits/limitations of using a browser-based interface for a stand-alone application vs. using a normal GUI framework? I'm working on a Python program currently implement with wxPython for the GUI. The application is simply user-entry forms and dialogs. I am considering moving to PyQt because of the widgets it has (for future expansion), then I realized I could probably just use a browser to do much of the same stuff. The application currently doesn't require Internet access, though it's a possibility in the future. I was thinking of using [Karrigell](http://karrigell.sourceforge.net/) for the web framework if I go browser-based. --- **Edit** For clarification, as of right now the application would be browser-based, not web-based. All the information would be stored locally on the client computer; no server calls would need to be made and no Internet access required (it may come later though). It would simply be a browser GUI instead of a wxPython/PyQt GUI. Hope that makes sense.
The obvious advantages to browser-based: * you can present the same UI regardless of platform * you can upgrade the application easily, and all users have the same version of the app running * you know the environment that your application will be running in (the server hardware/OS) which makes for easier testing and support compared to the multitude of operating system/hardware configurations that a GUI app will be installed on. And for GUI based: * some applications (e.g.: image editing) arguably work better in a native GUI application * doesn't require network access Also see my comments on [this question](http://stackoverflow.com/questions/115501/is-ruby-any-good-for-gui-development#115638): > Cross-platform GUIs are an age-old problem. Qt, GTK, wxWindows, Java AWT, Java Swing, XUL -- they all suffer from the same problem: the resulting GUI doesn't look native on every platform. Worse still, every platform has a slightly different look and **feel**, so even if you were somehow able to get a toolkit that looked native on every platform, you'd have to somehow code your app to feel native on each platform. > > It comes down to a decision: do you want to minimise development effort and have a GUI that doesn't look and feel quite right on each platform, or do you want to maximise the user experience? If you choose the second option, you'll need to develop a common backend and a custom UI for each platform. *[edit: or use a web application.]* Another thought I just had: you also need to consider the kind of data that your application manipulates and where it is stored, and how the users will feel about that. People are obviously okay having their facebook profile data stored on a webserver, but they might feel differently if you're writing a finance application like MYOB and you want to store all their personal financial details on your server. You might be able to get that to work, but it would require a lot of effort to implement the required security and to assure the userbase that their data is safe. In that situation you might decide that the overall effort is lower if you go with a native GUI app.
Browser-based application or stand-alone GUI app?
255,476
22
2008-11-01T03:25:09Z
255,508
10
2008-11-01T03:53:47Z
[ "python", "user-interface", "browser" ]
I'm sure this has been asked before, but I can't find it. What are the benefits/limitations of using a browser-based interface for a stand-alone application vs. using a normal GUI framework? I'm working on a Python program currently implement with wxPython for the GUI. The application is simply user-entry forms and dialogs. I am considering moving to PyQt because of the widgets it has (for future expansion), then I realized I could probably just use a browser to do much of the same stuff. The application currently doesn't require Internet access, though it's a possibility in the future. I was thinking of using [Karrigell](http://karrigell.sourceforge.net/) for the web framework if I go browser-based. --- **Edit** For clarification, as of right now the application would be browser-based, not web-based. All the information would be stored locally on the client computer; no server calls would need to be made and no Internet access required (it may come later though). It would simply be a browser GUI instead of a wxPython/PyQt GUI. Hope that makes sense.
Let's pretend for a moment that the development/deployment/maintenance effort/cost is equal and we look at it from the application user's perspective: *Which UI is the user going to find more useful?* in terms of * Ease of use * Responsiveness * Familiar navigation/usage patterns * Most like other tools/applications in use on the platform (ie, native) I understand that "useful" is subjective. I personally would never use (as a user, not developer) a web interface again if I could get away with it. I ***hate*** them. There are some applications that just don't make sense to develop as browser based apps. From a development perspective * No two browsers available today render *exactly* the same. * Even with Ajax, javascript and dynamic, responsive interfaces are non-trivial to implement/debug. There are many, many standalone GUI applications that are just terrible, no argument. Development/deployment and maintenance for a multi-platform GUI is non-trivial. Developing good user-interfaces is hard, period. The reality is that I've made my living over the last 10 years developing mostly web based applications, because they're faster to develop, easier to deploy and provide enough utility that people will use them if they have to. I don't believe that most users would use a web interface if given an alternative. IMNSHO
How to implement Google Suggest in your own web application (e.g. using Python)
255,700
9
2008-11-01T15:50:30Z
255,705
7
2008-11-01T15:58:31Z
[ "python", "autocomplete", "autosuggest" ]
In my website, users have the possibility to store links. During typing the internet address into the designated field I would like to display a suggest/autocomplete box similar to Google Suggest or the Chrome Omnibar. Example: User is typing as URL: ``` http://www.sta ``` Suggestions which would be displayed: ``` http://www.staples.com http://www.starbucks.com http://www.stackoverflow.com ``` How can I achieve this while not reinventing the wheel? :)
You could try with <http://google.com/complete/search?output=toolbar&q=keyword> and then parse the xml result.
Which exception should I raise on bad/illegal argument combinations in Python?
256,222
235
2008-11-01T23:02:36Z
256,235
9
2008-11-01T23:17:40Z
[ "python", "exception", "arguments" ]
I was wondering about the best practices for indicating invalid argument combinations in Python. I've come across a few situations where you have a function like so: ``` def import_to_orm(name, save=False, recurse=False): """ :param name: Name of some external entity to import. :param save: Save the ORM object before returning. :param recurse: Attempt to import associated objects as well. Because you need the original object to have a key to relate to, save must be `True` for recurse to be `True`. :raise BadValueError: If `recurse and not save`. :return: The ORM object. """ pass ``` The only annoyance with this is that every package has its own, usually slightly differing `BadValueError`. I know that in Java there exists `java.lang.IllegalArgumentException` -- is it well understood that everybody will be creating their own `BadValueError`s in Python or is there another, preferred method?
I've mostly just seen the builtin `ValueError` used in this situation.
Which exception should I raise on bad/illegal argument combinations in Python?
256,222
235
2008-11-01T23:02:36Z
256,236
40
2008-11-01T23:17:49Z
[ "python", "exception", "arguments" ]
I was wondering about the best practices for indicating invalid argument combinations in Python. I've come across a few situations where you have a function like so: ``` def import_to_orm(name, save=False, recurse=False): """ :param name: Name of some external entity to import. :param save: Save the ORM object before returning. :param recurse: Attempt to import associated objects as well. Because you need the original object to have a key to relate to, save must be `True` for recurse to be `True`. :raise BadValueError: If `recurse and not save`. :return: The ORM object. """ pass ``` The only annoyance with this is that every package has its own, usually slightly differing `BadValueError`. I know that in Java there exists `java.lang.IllegalArgumentException` -- is it well understood that everybody will be creating their own `BadValueError`s in Python or is there another, preferred method?
I would inherit from `ValueError` ``` class IllegalArgumentError(ValueError): pass ``` It is sometimes better to create your own exceptions, but inherit from a built-in one, which is as close to what you want as possible. If you need to catch that specific error, it is helpful to have a name.
Which exception should I raise on bad/illegal argument combinations in Python?
256,222
235
2008-11-01T23:02:36Z
256,260
243
2008-11-01T23:37:31Z
[ "python", "exception", "arguments" ]
I was wondering about the best practices for indicating invalid argument combinations in Python. I've come across a few situations where you have a function like so: ``` def import_to_orm(name, save=False, recurse=False): """ :param name: Name of some external entity to import. :param save: Save the ORM object before returning. :param recurse: Attempt to import associated objects as well. Because you need the original object to have a key to relate to, save must be `True` for recurse to be `True`. :raise BadValueError: If `recurse and not save`. :return: The ORM object. """ pass ``` The only annoyance with this is that every package has its own, usually slightly differing `BadValueError`. I know that in Java there exists `java.lang.IllegalArgumentException` -- is it well understood that everybody will be creating their own `BadValueError`s in Python or is there another, preferred method?
I would just raise [ValueError](https://docs.python.org/2/library/exceptions.html#exceptions.ValueError), unless you need a more specific exception.. ``` def import_to_orm(name, save=False, recurse=False): if recurse and not save: raise ValueError("save must be True if recurse is True") ``` There's really no point in doing `class BadValueError(ValueError):pass` - your custom class is identical in use to [ValueError](https://docs.python.org/2/library/exceptions.html#exceptions.ValueError), so why not use that?
Python packages and egg-info directories
256,417
52
2008-11-02T02:26:20Z
256,614
46
2008-11-02T06:40:26Z
[ "python", "setuptools", "egg" ]
Can someone explain how egg-info directories are tied to their respective modules? For example, I have the following: ``` /usr/local/lib/python2.5/site-packages/quodlibet/ /usr/local/lib/python2.5/site-packages/quodlibet-2.0.egg-info/ ``` I'm assuming the egg-info directory is to make the corresponding module visible to setuptools (easy\_install), right? If so, how does setuptools tie the egg-info directory to the module directory? Assuming that I'm on the right track, and for the sake of example... If I wanted to make an existing package of mine visible to setuptools, could I just symlink the module directory and the egg-info directory to the site-packages directory? I would have just tried this myself, but I'm not sure how to test if the package is visible to setuptools. Bonus points if you can also tell me how to test this :) The main reason I'm trying to understand all this is because I would like to symlink some of my modules into site-packages so that I can make changes to them and have the changes visible to the scripts that use them without having to reinstall the egg from PyPI after each change.
The .egg-info directories get only created if --single-version-externally-managed was used to install the egg. "Normally", installing an egg would create a single directory (or zip file), containing both the code and the metadata. pkg\_resources (which is the library that reads the metadata) has a function `require` which can be used to request a specific version of the package. For "old-style", regular imports, easy\_install hacks a .pth file to get the egg directory onto sys.path. For --single-version-externally-managed, this hacking is not necessary, because there will only be a single version installed (by the system's pacakging infrastructure, e.g. rpm or dpkg). The egg-info is still included, for applications that use `require` (or any of the other pkg\_resources binding mechanisms). If you want to install a package by hard-linking, I recommend to use "setup.py develop". This is a command from setuptools which doesn't actually install the egg, but makes it available site-wide. To do so, it creates an egg-link file so that pkg\_resources can find it, and it manipulates a .pth file, so that regular import can find it.
Putting a pyCurl XML server response into a variable (Python)
256,564
3
2008-11-02T05:38:48Z
2,351,363
12
2010-02-28T14:42:24Z
[ "python", "xml", "pycurl" ]
I'm a Python novice, trying to use pyCurl. The project I am working on is creating a Python wrapper for the twitpic.com API (<http://twitpic.com/api.do>). For reference purposes, check out the code (<http://pastebin.com/f4c498b6e>) and the error I'm getting (<http://pastebin.com/mff11d31>). Pay special attention to line 27 of the code, which contains "xml = server.perform()". After researching my problem, I discovered that unlike I had previously thought, .perform() does not return the xml response from twitpic.com, but None, when the upload succeeds (duh!). After looking at the error output further, it seems to me like the xml input that I want stuffed into the "xml" variable is instead being printed to ether standard output or standard error (not sure which). I'm sure there is an easy way to do this, but I cannot seem to think of it at the moment. If you have any tips that could point me in the right direction, I'd be very appreciative. Thanks in advance.
Using a StringIO would be much cleaner, no point in using a dummy class like that if all you want is the response data... Something like this would suffice: ``` import pycurl import cStringIO response = cStringIO.StringIO() c = pycurl.Curl() c.setopt(c.URL, 'http://www.turnkeylinux.org') c.setopt(c.WRITEFUNCTION, response.write) c.perform() c.close() print response.getvalue() ```
Message Box in Python
257,398
6
2008-11-02T21:22:30Z
257,403
11
2008-11-02T21:26:54Z
[ "python", "user-controls", "user-interface" ]
Is there a UI library to create a message box or input box in python?
Your best bet is the tkMessageBox module, which should work on all systems (as Python will typically come with Tkinter). If you can restrict yourself to a specific operating system, better choices might be available.
Download image file from the HTML page source using python?
257,409
33
2008-11-02T21:31:00Z
257,412
8
2008-11-02T21:33:53Z
[ "python", "screen-scraping" ]
I am writing a scraper that downloads all the image files from a HTML page and saves them to a specific folder. all the images are the part of the HTML page.
You have to download the page and parse html document, find your image with regex and download it.. You can use urllib2 for downloading and Beautiful Soup for parsing html file.
Download image file from the HTML page source using python?
257,409
33
2008-11-02T21:31:00Z
258,511
69
2008-11-03T12:40:27Z
[ "python", "screen-scraping" ]
I am writing a scraper that downloads all the image files from a HTML page and saves them to a specific folder. all the images are the part of the HTML page.
Here is some code to download all the images from the supplied URL, and save them in the specified output folder. You can modify it to your own needs. ``` """ dumpimages.py Downloads all the images on the supplied URL, and saves them to the specified output file ("/test/" by default) Usage: python dumpimages.py http://example.com/ [output] """ from BeautifulSoup import BeautifulSoup as bs import urlparse from urllib2 import urlopen from urllib import urlretrieve import os import sys def main(url, out_folder="/test/"): """Downloads all the images at 'url' to /test/""" soup = bs(urlopen(url)) parsed = list(urlparse.urlparse(url)) for image in soup.findAll("img"): print "Image: %(src)s" % image filename = image["src"].split("/")[-1] parsed[2] = image["src"] outpath = os.path.join(out_folder, filename) if image["src"].lower().startswith("http"): urlretrieve(image["src"], outpath) else: urlretrieve(urlparse.urlunparse(parsed), outpath) def _usage(): print "usage: python dumpimages.py http://example.com [outpath]" if __name__ == "__main__": url = sys.argv[-1] out_folder = "/test/" if not url.lower().startswith("http"): out_folder = sys.argv[-1] url = sys.argv[-2] if not url.lower().startswith("http"): _usage() sys.exit(-1) main(url, out_folder) ``` **Edit:** You can specify the output folder now.
Download image file from the HTML page source using python?
257,409
33
2008-11-02T21:31:00Z
2,448,326
8
2010-03-15T15:35:20Z
[ "python", "screen-scraping" ]
I am writing a scraper that downloads all the image files from a HTML page and saves them to a specific folder. all the images are the part of the HTML page.
And this is function for download one image: ``` def download_photo(self, img_url, filename): file_path = "%s%s" % (DOWNLOADED_IMAGE_PATH, filename) downloaded_image = file(file_path, "wb") image_on_web = urllib.urlopen(img_url) while True: buf = image_on_web.read(65536) if len(buf) == 0: break downloaded_image.write(buf) downloaded_image.close() image_on_web.close() return file_path ```
Download image file from the HTML page source using python?
257,409
33
2008-11-02T21:31:00Z
4,200,547
9
2010-11-17T00:49:24Z
[ "python", "screen-scraping" ]
I am writing a scraper that downloads all the image files from a HTML page and saves them to a specific folder. all the images are the part of the HTML page.
Ryan's solution is good, but fails if the image source URLs are absolute URLs or anything that doesn't give a good result when simply concatenated to the main page URL. urljoin recognizes absolute vs. relative URLs, so replace the loop in the middle with: ``` for image in soup.findAll("img"): print "Image: %(src)s" % image image_url = urlparse.urljoin(url, image['src']) filename = image["src"].split("/")[-1] outpath = os.path.join(out_folder, filename) urlretrieve(image_url, outpath) ```
What's the difference between scgi and wsgi?
257,481
10
2008-11-02T22:22:25Z
257,511
7
2008-11-02T22:39:23Z
[ "python", "wsgi", "scgi" ]
What's the difference between these two? Which is better/faster/reliable?
They are both specifications for plugging a web application into a web server. One glaring difference is that WSGI comes from the Python world, and I believe there are no non-python implementations. **Specifications are generally not comparable based on better/faster/reliable.** Only their implementations are comparable, and I am sure you will find good implementations of both specifications. Perhaps [read](http://en.wikipedia.org/wiki/SCGI) and [read](http://en.wikipedia.org/wiki/WSGI).
What's the difference between scgi and wsgi?
257,481
10
2008-11-02T22:22:25Z
257,642
21
2008-11-03T00:28:52Z
[ "python", "wsgi", "scgi" ]
What's the difference between these two? Which is better/faster/reliable?
SCGI is a language-neutral means of connecting a front-end web server and a web application. WSGI is a Python-specific interface standard for web applications. Though they both have roots in CGI, they're rather different in scope and you could indeed quite reasonably use both at once, for example having a mod\_scgi on the webserver talk to a WSGI app run as an SCGI server. There are multiple library implementations that will run WSGI applications as SCGI servers for you (eg. wsgitools, cherrypy). They are both 'reliable', in as much as you can consider a specification reliable as opposed to a particular implementation. These days you would probably write your application as a WSGI callable, and consider the question of deployment separately. Maybe an Apache+mod\_wsgi (embedded) interface might be a *bit* faster than an Apache+mod\_scgi+(SCGI wrapper lib), but in all likelihood it's not going to be *hugely* different. More valuable is the ability to run the application on a variety of servers, platforms and connection standards.
Python MySQL Statement returning Error
257,563
2
2008-11-02T23:26:35Z
257,614
9
2008-11-03T00:02:17Z
[ "python", "sql" ]
hey, I'm very new to all this so please excuse stupidity :) ``` import os import MySQLdb import time db = MySQLdb.connect(host="localhost", user="root", passwd="********", db="workspace") cursor = db.cursor() tailoutputfile = os.popen('tail -f syslog.log') while 1: x = tailoutputfile.readline() if len(x)==0: break y = x.split() if y[2] == 'BAD': timestring = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())) cursor.execute("INSERT INTO releases (date, cat, name) values (timestring, y[4], y[7]") if y[2] == 'GOOD': print y[4] + '\t' + y[7] ``` so i run the program and this is the error message I am getting ``` user@machine:~/$ python reader.py Traceback (most recent call last): File "reader.py", line 17, in ? cursor.execute("INSERT INTO releases (date, cat, name) values (timestring, y[4], y[7]") File "/usr/lib/python2.4/site-packages/MySQLdb/cursors.py", line 163, in execute self.errorhandler(self, exc, value) File "/usr/lib/python2.4/site-packages/MySQLdb/connections.py", line 35, in defaulterrorhandler raise errorclass, errorvalue _mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '[4], y[7]' at line 1") user@machine:~/$ ``` So i'm assuming that the error is obviously coming from the SQL Statement ``` cursor.execute("INSERT INTO releases (date, cat, name) values (timestring, y[4], y[7]") ``` Here is an example of what y[4] and y[7] will look like. ``` YES Mail.Sent.To.User:[email protected]:23.17 ``` Is this error happening because I should be escaping those values before I try and Insert them into the Database? Or am I completely missing the point?? Any help would be appreciated! thanks in advance.
As pointed out, you're failing to copy the Python variable values into the query, only their names, which mean nothing to MySQL. However the direct string concatenation option: ``` cursor.execute("INSERT INTO releases (date, cat, name) VALUES ('%s', '%s', '%s')" % (timestring, y[4], y[7])) ``` is dangerous and should never be used. If those strings have out-of-bounds characters like ' or \ in, you've got an SQL injection leading to possible security compromise. Maybe in your particular app that can never happen, but it's still a very bad practice, which beginners' SQL tutorials really need to stop using. The solution using MySQLdb is to let the DBAPI layer take care of inserting and escaping parameter values into SQL for you, instead of trying to % it yourself: ``` cursor.execute('INSERT INTO releases (date, cat, name) VALUES (%s, %s, %s)', (timestring, y[4], y[7])) ```
How can I make a fake "active session" for gconf?
257,658
9
2008-11-03T00:45:10Z
260,731
8
2008-11-04T03:07:40Z
[ "python", "ubuntu", "gconf", "intrepid" ]
I've automated my Ubuntu installation - I've got Python code that runs automatically (after a clean install, but before the first user login - it's in a temporary /etc/init.d/ script) that sets up everything from Apache & its configuration to my personal Gnome preferences. It's the latter that's giving me trouble. This worked fine in Ubuntu 8.04 (Hardy), but when I use this with 8.10 (Intrepid), the first time I try to access gconf, I get this exception: Failed to contact configuration server; some possible causes are that you need to enable TCP/IP networking for ORBit, or you have stale NFS locks due to a system crash. See <http://www.gnome.org/projects/gconf/> for information. (Details - 1: **Not running within active session**) Yes, right, there's no Gnome session when this is running, because the user hasn't logged in yet - however, this worked before; this appears to be new with Intrepid's Gnome (2.24?). Short of modifying the gconf's XML files directly, is there a way to make some sort of proxy Gnome session? Or, any other suggestions? (More details: this is python code that runs as root, but setuid's & setgid's to be me before setting my preferences using the "gconf" module from the python-gconf package.)
I can reproduce this by installing GConf 2.24 on my machine. GConf 2.22 works fine, but 2.24 breaks it. GConf is failing to launch because D-Bus is not running. Manually spawning D-Bus and the GConf daemon makes this work again. I tried to spawn the D-Bus session bus by doing the following: ``` import dbus dummy_bus = dbus.SessionBus() ``` ...but got this: ``` dbus.exceptions.DBusException: org.freedesktop.DBus.Error.Spawn.ExecFailed: dbus-launch failed to autolaunch D-Bus session: Autolaunch error: X11 initialization failed. ``` Weird. Looks like it doesn't like to come up if X isn't running. To work around that, start dbus-launch manually (IIRC use the [os.system()](http://www.python.org/doc/2.5.2/lib/os-process.html) call): ``` $ dbus-launch DBUS_SESSION_BUS_ADDRESS=unix:abstract=/tmp/dbus-eAmT3q94u0,guid=c250f62d3c4739dcc9a12d48490fc268 DBUS_SESSION_BUS_PID=15836 ``` You'll need to parse the output somehow and inject them into environment variables (you'll probably want to use [os.putenv](http://www.python.org/doc/2.5.2/lib/os-procinfo.html)). For my testing, I just used the shell, and set the environment vars manually with `export DBUS_SESSION_BUS_ADDRESS=blahblah...`, etc. Next, you need to launch `gconftool-2 --spawn` with those environment variables you received from `dbus-launch`. This will launch the GConf daemon. If the D-Bus environment vars are not set, the daemon will not launch. Then, run your GConf code. Provided you set the D-Bus session bus environment variables for your own script, you will now be able to communicate with the GConf daemon. I know it's complicated. `gconftool-2` provides a `--direct` option that enables you to set GConf variables without needing to communicate with the server, but I haven't been able to find an equivalent option for the Python bindings (short of outputting XML manually). *Edit:* For future reference, if anybody wants to run `dbus-launch` from within a normal `bash` script (as opposed to a Python script, as this thread is discussing), it is quite easy to retrieve the session bus address for use within the script: ``` #!/bin/bash eval `dbus-launch --sh-syntax` export DBUS_SESSION_BUS_ADDRESS export DBUS_SESSION_BUS_PID do_other_stuff_here ```
Why are Exceptions iterable?
258,228
11
2008-11-03T09:46:03Z
258,930
11
2008-11-03T15:08:02Z
[ "python", "exception" ]
I have been bitten by something unexpected recently. I wanted to make something like that: ``` try : thing.merge(iterable) # this is an iterable so I add it to the list except TypeError : thing.append(iterable) # this is not iterable, so I add it ``` Well, It was working fine until I passed an object inheriting from Exception which was supposed to be added. Unfortunetly, an Exception is iterable. The following code does not raise any `TypeError`: ``` for x in Exception() : print 1 ``` Does anybody know why?
Note that what is happening is not related to any kind of implicit string conversion etc, but because the Exception class implements \_\_getitem\_\_(), and uses it to return the values in the args tuple (ex.args). You can see this by the fact that you get the whole string as your first and only item in the iteration, rather than the character-by-character result you'd get if you iterate over the string. This surprised me too, but thinking about it, I'm guessing it is for backwards compatability reasons. Python used to ([pre-1.5](http://www.python.org/doc/essays/stdexceptions.html)) lack the current class hierarchy of exceptions. Instead, strings were thrown, with (usually) a tuple argument for any details that should be passed to the handling block. ie: ``` try: raise "something failed", (42, "some other details") except "something failed", args: errCode, msg = args print "something failed. error code %d: %s" % (errCode, msg) ``` It looks like this behavior was put in to avoid breaking pre-1.5 code expecting a tuple of arguments, rather than a non-iterable exception object. There are a couple of examples of this with IOError in the Fatal Breakage section of the above [link](http://www.python.org/doc/essays/stdexceptions.html) String exceptions have been depecated for a while, and are going away in Python 3. I've now checked how Python 3 handles exception objects, and it looks like they are no longer iterable there: ``` >>> list(Exception("test")) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'Exception' object is not iterable ``` [Edit] Checked python3's behaviour
Django models - how to filter number of ForeignKey objects
258,296
33
2008-11-03T10:38:54Z
6,205,303
90
2011-06-01T17:30:34Z
[ "python", "django", "database-design" ]
I have a models `A` and `B`, that are like this: ``` class A(models.Model): title = models.CharField(max_length=20) (...) class B(models.Model): date = models.DateTimeField(auto_now_add=True) (...) a = models.ForeignKey(A) ``` Now I have some `A` and `B` objects, and I'd like to get a query that selects all `A` objects that have less then 2 `B` pointing at them. A is something like a pool thing, and users (the B) join pool. if there's only 1 or 0 joined, the pool shouldn't be displayed at all. Is it possible with such model design? Or should I modify that a bit?
The question and selected answer are from 2008 and since then this functionality has been integrated into the django framework. Since this is a top google hit for "django filter foreign key count" I'd like to add an easier solution with a recent django version using [Aggregation](https://docs.djangoproject.com/en/dev/topics/db/aggregation/ "Aggregation"). ``` from django.db.models import Count cats = A.objects.annotate(num_b=Count('b')).filter(num_b__lt=2) ``` In my case I had to take this concept a step further. My "B" object had a boolean field called is\_available, and I only wanted to return A objects who had more than 0 B objects with is\_available set to True. ``` A.objects.filter(B__is_available=True).annotate(num_b=Count('b')).filter(num_b__gt=0).order_by('-num_items') ```
Python filter/remove URLs from a list
258,390
5
2008-11-03T11:34:18Z
258,415
21
2008-11-03T11:45:47Z
[ "python", "url", "list", "filter" ]
I have a text file of URLs, about 14000. Below is a couple of examples: <http://www.domainname.com/pagename?CONTENT_ITEM_ID=100&param2=123> <http://www.domainname.com/images?IMAGE_ID=10> <http://www.domainname.com/pagename?CONTENT_ITEM_ID=101&param2=123> <http://www.domainname.com/images?IMAGE_ID=11> <http://www.domainname.com/pagename?CONTENT_ITEM_ID=102&param2=123> I have loaded the text file into a Python list and I am trying to get all the URLs with CONTENT\_ITEM\_ID separated off into a list of their own. What would be the best way to do this in Python? Cheers
Here's another alternative to Graeme's, using the newer list comprehension syntax: ``` list2= [line for line in file if 'CONTENT_ITEM_ID' in line] ``` Which you prefer is a matter of taste!
Slicing URL with Python
258,746
8
2008-11-03T14:22:13Z
259,159
14
2008-11-03T16:25:13Z
[ "python", "url", "string" ]
I am working with a huge list of URL's. Just a quick question I have trying to slice a part of the URL out, see below: ``` http://www.domainname.com/page?CONTENT_ITEM_ID=1234&param2&param3 ``` How could I slice out: ``` http://www.domainname.com/page?CONTENT_ITEM_ID=1234 ``` Sometimes there is more than two parameters after the CONTENT\_ITEM\_ID and the ID is different each time, I am thinking it can be done by finding the first & and then slicing off the chars before that &, not quite sure how to do this tho. Cheers
Use the [urlparse](http://docs.python.org/2/library/urlparse.html#urlparse.urlsplit) module. Check this function: ``` import urlparse def process_url(url, keep_params=('CONTENT_ITEM_ID=',)): parsed= urlparse.urlsplit(url) filtered_query= '&'.join( qry_item for qry_item in parsed.query.split('&') if qry_item.startswith(keep_params)) return urlparse.urlunsplit(parsed[:3] + (filtered_query,) + parsed[4:]) ``` In your example: ``` >>> process_url(a) 'http://www.domainname.com/page?CONTENT_ITEM_ID=1234' ``` This function has the added bonus that it's easier to use if you decide that you also want some more query parameters, or if the order of the parameters is not fixed, as in: ``` >>> url='http://www.domainname.com/page?other_value=xx&param3&CONTENT_ITEM_ID=1234&param1' >>> process_url(url, ('CONTENT_ITEM_ID', 'other_value')) 'http://www.domainname.com/page?other_value=xx&CONTENT_ITEM_ID=1234' ```
Splitting a person's name into forename and surname
259,634
17
2008-11-03T19:19:09Z
259,643
15
2008-11-03T19:23:04Z
[ "python", "split" ]
ok so basically I am asking the question of their name I want this to be one input rather than Forename and Surname. Now is there any way of splitting this name? and taking just the last word from the "Sentence" e.g. ``` name = "Thomas Winter" print name.split() ``` and what would be output is just "Winter"
The problem with trying to split the names from a single input is that you won't get the full surname for people with spaces in their surname, and I don't believe you'll be able to write code to manage that completely. I would recommend that you ask for the names separately if it is at all possible.
Splitting a person's name into forename and surname
259,634
17
2008-11-03T19:19:09Z
259,694
57
2008-11-03T19:42:02Z
[ "python", "split" ]
ok so basically I am asking the question of their name I want this to be one input rather than Forename and Surname. Now is there any way of splitting this name? and taking just the last word from the "Sentence" e.g. ``` name = "Thomas Winter" print name.split() ``` and what would be output is just "Winter"
You'll find that your key problem with this approach isn't a technical one, but a human one - different people write their names in different ways. In fact, the terminology of "forename" and "surname" is itself flawed. While many blended families use a hyphenated family name, such as Smith-Jones, there are some who just use both names separately, "Smith Jones" where both names are the family name. Many european family names have multiple parts, such as "de Vere" and "van den Neiulaar". Sometimes these extras have important family history - for example, a prefix awarded by a king hundreds of years ago. Side issue: I've capitalised these correctly for the people I'm referencing - "de" and "van den" don't get captial letters for some families, but do for others. Conversely, many Asian cultures put the family name first, because the family is considered more important than the individual. Last point - some people place great store in being "Junior" or "Senior" or "III" - and your code shouldn't treat those as the family name. Also noting that there are a fair number of people who use a name that isn't the one bestowed by their parents, I've used the following scheme with some success: Full Name (as normally written for addressing mail); Family Name; Known As (the name commonly used in conversation). e.g: Full Name: William Gates III; Family Name: Gates; Known As: Bill Full Name: Soong Li; Family Name: Soong; Known As: Lisa
Most efficient way to search the last x lines of a file in python
260,273
29
2008-11-03T23:01:50Z
260,312
7
2008-11-03T23:21:29Z
[ "python", "file", "search" ]
I have a file and I don't know how big it's going to be (it could be quite large, but the size will vary greatly). I want to search the last 10 lines or so to see if any of them match a string. I need to do this as quickly and efficiently as possible and was wondering if there's anything better than: ``` s = "foo" last_bit = fileObj.readlines()[-10:] for line in last_bit: if line == s: print "FOUND" ```
I think reading the last 2 KB or so of the file should make sure you get 10 lines, and shouldn't be too much of a resource hog. ``` file_handle = open("somefile") file_size = file_handle.tell() file_handle.seek(max(file_size - 2*1024, 0)) # this will get rid of trailing newlines, unlike readlines() last_10 = file_handle.read().splitlines()[-10:] assert len(last_10) == 10, "Only read %d lines" % len(last_10) ```
Most efficient way to search the last x lines of a file in python
260,273
29
2008-11-03T23:01:50Z
260,352
27
2008-11-03T23:40:34Z
[ "python", "file", "search" ]
I have a file and I don't know how big it's going to be (it could be quite large, but the size will vary greatly). I want to search the last 10 lines or so to see if any of them match a string. I need to do this as quickly and efficiently as possible and was wondering if there's anything better than: ``` s = "foo" last_bit = fileObj.readlines()[-10:] for line in last_bit: if line == s: print "FOUND" ```
``` # Tail from __future__ import with_statement find_str = "FIREFOX" # String to find fname = "g:/autoIt/ActiveWin.log_2" # File to check with open(fname, "r") as f: f.seek (0, 2) # Seek @ EOF fsize = f.tell() # Get Size f.seek (max (fsize-1024, 0), 0) # Set pos @ last n chars lines = f.readlines() # Read to end lines = lines[-10:] # Get last 10 lines # This returns True if any line is exactly find_str + "\n" print find_str + "\n" in lines # If you're searching for a substring for line in lines: if find_str in line: print True break ```
Most efficient way to search the last x lines of a file in python
260,273
29
2008-11-03T23:01:50Z
260,394
8
2008-11-04T00:04:13Z
[ "python", "file", "search" ]
I have a file and I don't know how big it's going to be (it could be quite large, but the size will vary greatly). I want to search the last 10 lines or so to see if any of them match a string. I need to do this as quickly and efficiently as possible and was wondering if there's anything better than: ``` s = "foo" last_bit = fileObj.readlines()[-10:] for line in last_bit: if line == s: print "FOUND" ```
If you are running Python on a POSIX system, you can use 'tail -10' to retrieve the last few lines. This may be faster than writing your own Python code to get the last 10 lines. Rather than opening the file directly, open a pipe from the command 'tail -10 filename'. If you are certain of the log output though (for example, you know that there are **never** any very long lines that are hundreds or thousands of characters long) then using one of the 'read the last 2KB' approaches listed would be fine.
Most efficient way to search the last x lines of a file in python
260,273
29
2008-11-03T23:01:50Z
260,433
29
2008-11-04T00:19:26Z
[ "python", "file", "search" ]
I have a file and I don't know how big it's going to be (it could be quite large, but the size will vary greatly). I want to search the last 10 lines or so to see if any of them match a string. I need to do this as quickly and efficiently as possible and was wondering if there's anything better than: ``` s = "foo" last_bit = fileObj.readlines()[-10:] for line in last_bit: if line == s: print "FOUND" ```
Here's an answer like MizardX's, but without its apparent problem of taking quadratic time in the worst case from rescanning the working string repeatedly for newlines as chunks are added. Compared to the activestate solution (which also seems to be quadratic), this doesn't blow up given an empty file, and does one seek per block read instead of two. Compared to spawning 'tail', this is self-contained. (But 'tail' is best if you have it.) Compared to grabbing a few kB off the end and hoping it's enough, this works for any line length. ``` import os def reversed_lines(file): "Generate the lines of file in reverse order." part = '' for block in reversed_blocks(file): for c in reversed(block): if c == '\n' and part: yield part[::-1] part = '' part += c if part: yield part[::-1] def reversed_blocks(file, blocksize=4096): "Generate blocks of file's contents in reverse order." file.seek(0, os.SEEK_END) here = file.tell() while 0 < here: delta = min(blocksize, here) here -= delta file.seek(here, os.SEEK_SET) yield file.read(delta) ``` To use it as requested: ``` from itertools import islice def check_last_10_lines(file, key): for line in islice(reversed_lines(file), 10): if line.rstrip('\n') == key: print 'FOUND' break ``` **Edit:** changed map() to itertools.imap() in head(). **Edit 2:** simplified reversed\_blocks(). **Edit 3:** avoid rescanning tail for newlines. **Edit 4:** rewrote reversed\_lines() because str.splitlines() ignores a final '\n', as BrianB noticed (thanks). Note that in very old Python versions the string concatenation in a loop here will take quadratic time. CPython from at least the last few years avoids this problem automatically.
Play audio with Python
260,738
63
2008-11-04T03:11:03Z
260,770
11
2008-11-04T03:27:13Z
[ "python", "audio" ]
How can I play audio (it would be like a 1 second sound) from a Python script? It would be best if it was platform independent, but firstly it needs to work on a Mac. I know I could just execute the `afplay file.mp3` command from within Python, but is it possible to do it in raw Python? I would also be better if it didn't rely on external libraries.
You can find information about Python audio here: <http://wiki.python.org/moin/Audio/> It doesn't look like it can play .mp3 files without external libraries. You could either convert your .mp3 file to a .wav or other format, or use a library like [PyMedia](http://pymedia.org/).
Play audio with Python
260,738
63
2008-11-04T03:11:03Z
260,901
19
2008-11-04T04:40:50Z
[ "python", "audio" ]
How can I play audio (it would be like a 1 second sound) from a Python script? It would be best if it was platform independent, but firstly it needs to work on a Mac. I know I could just execute the `afplay file.mp3` command from within Python, but is it possible to do it in raw Python? I would also be better if it didn't rely on external libraries.
Your best bet is probably to use [pygame/SDL](http://www.pygame.org). It's an external library, but it has great support across platforms. ``` pygame.mixer.init() pygame.mixer.music.load("file.mp3") pygame.mixer.music.play() ``` You can find more specific documentation about the audio mixer support in the [pygame.mixer.music documentation](http://www.pygame.org/docs/ref/music.html)
Play audio with Python
260,738
63
2008-11-04T03:11:03Z
20,746,883
8
2013-12-23T15:54:08Z
[ "python", "audio" ]
How can I play audio (it would be like a 1 second sound) from a Python script? It would be best if it was platform independent, but firstly it needs to work on a Mac. I know I could just execute the `afplay file.mp3` command from within Python, but is it possible to do it in raw Python? I would also be better if it didn't rely on external libraries.
In [pydub](http://pydub.com) we've recently [opted to use ffplay (via subprocess)](https://github.com/jiaaro/pydub/blob/master/pydub/playback.py) from the ffmpeg suite of tools, which internally uses SDL. It works for our purposes – mainly just making it easier to test the results of pydub code in interactive mode – but it has it's downsides, like causing a new program to appear in the dock on mac. I've linked the implementation above, but a simplified version follows: ``` import subprocess def play(audio_file_path): subprocess.call(["ffplay", "-nodisp", "-autoexit", audio_file_path]) ``` The `-nodisp` flag stops ffplay from showing a new window, and the `-autoexit` flag causes ffplay to exit and return a status code when the audio file is done playing. **edit**: pydub now uses pyaudio for playback when it's installed and falls back to ffplay to avoid the downsides I mentioned. The link above shows that implementation as well.
How to build Python C extension modules with autotools
261,500
7
2008-11-04T10:46:43Z
13,711,218
11
2012-12-04T20:22:22Z
[ "c++", "python", "c", "autotools" ]
Most of the documentation available for building Python extension modules uses distutils, but I would like to achieve this by using the appropriate python autoconf & automake macros instead. I'd like to know if there is an open source project out there that does exactly this. Most of the ones I've found end up relying on a setup.py file. Using that approach works, but unfortunately ends up rebuilding the entire source tree any time I make a modification to the module source files.
Supposing that you have a project with a directory called `src`, so let's follow the follow steps to get a python extension built and packaged using autotools: ## Create the Makefile.am files First, you need to create one Makefile.am in the root of your project, basically (but not exclusively) listing the subdirectories that should also be processed. You will end up with something like this: ``` SUBDIRS = src ``` The second one, inside the `src` directory will hold the instructions to actually compile your python extension. It will look like this: ``` myextdir = $(pkgpythondir) myext_PYTHON = file1.py file2.py pyexec_LTLIBRARIES = _myext.la _myext_la_SOURCES = myext.cpp _myext_la_CPPFLAGS = $(PYTHON_CFLAGS) _myext_la_LDFLAGS = -module -avoid-version -export-symbols-regex initmyext _myext_la_LIBADD = $(top_builddir)/lib/libhollow.la EXTRA_DIST = myext.h ``` ## Write the configure.ac This file must be created in the root directory of the project and must list all libraries, programs or any kind of tool that your project needs to be built, such as a compiler, linker, libraries, etc. Lazy people, like me, usually don't create it from scratch, I prefer to use the `autoscan` tool, that looks for things that you are using and generate a `configure.scan` file that can be used as the basis for your real `configure.ac`. To inform `automake` that you will need python stuff, you can add this to your `configure.ac`: ``` dnl python checks (you can change the required python version bellow) AM_PATH_PYTHON(2.7.0) PY_PREFIX=`$PYTHON -c 'import sys ; print sys.prefix'` PYTHON_LIBS="-lpython$PYTHON_VERSION" PYTHON_CFLAGS="-I$PY_PREFIX/include/python$PYTHON_VERSION" AC_SUBST([PYTHON_LIBS]) AC_SUBST([PYTHON_CFLAGS]) ``` ## Wrap up Basically, `automake` has a built-in extension that knows how to deal with python stuff, you just need to add it to your `configure.ac` file and then take the advantage of this feature in your `Makefile.am`. PyGtk is definitely an awesome example, but it's pretty big, so maybe you will want to check another project, like [Guake](http://github.com/Guake/Guake)
How do I protect Python code?
261,638
408
2008-11-04T11:57:27Z
261,645
277
2008-11-04T12:00:34Z
[ "python", "licensing", "obfuscation", "copy-protection" ]
I am developing a piece of software in Python that will be distributed to my employer's customers. My employer wants to limit the usage of the software with a time restricted license file. If we distribute the .py files or even .pyc files it will be easy to (decompile and) remove the code that checks the license file. Another aspect is that my employer does not want the code to be read by our customers, fearing that the code may be stolen or at least the "novel ideas". Is there a good way to handle this problem? Preferably with an off-the-shelf solution. The software will run on Linux systems (so I don't think py2exe will do the trick).
Python, being a byte-code-compiled interpreted language, is very difficult to lock down. Even if you use a exe-packager like [py2exe](http://py2exe.org), the layout of the executable is well-known, and the Python byte-codes are well understood. Usually in cases like this, you have to make a tradeoff. How important is it really to protect the code? Are there real secrets in there (such as a key for symmetric encryption of bank transfers), or are you just being paranoid? Choose the language that lets you develop the best product quickest, and be realistic about how valuable your novel ideas are. If you decide you really need to enforce the license check securely, write it as a small C extension so that the license check code can be extra-hard (but not impossible!) to reverse engineer, and leave the bulk of your code in Python.
How do I protect Python code?
261,638
408
2008-11-04T11:57:27Z
261,719
30
2008-11-04T12:27:52Z
[ "python", "licensing", "obfuscation", "copy-protection" ]
I am developing a piece of software in Python that will be distributed to my employer's customers. My employer wants to limit the usage of the software with a time restricted license file. If we distribute the .py files or even .pyc files it will be easy to (decompile and) remove the code that checks the license file. Another aspect is that my employer does not want the code to be read by our customers, fearing that the code may be stolen or at least the "novel ideas". Is there a good way to handle this problem? Preferably with an off-the-shelf solution. The software will run on Linux systems (so I don't think py2exe will do the trick).
Is your employer aware that he can "steal" back any ideas that other people get from your code? I mean, if they can read your work, so can you theirs. Maybe looking at how you can benefit from the situation would yield a better return of your investment than fearing how much you could lose. [EDIT] Answer to Nick's comment: Nothing gained and nothing lost. The customer has what he wants (and paid for it since he did the change himself). Since he doesn't release the change, it's as if it didn't happen for everyone else. Now if the customer sells the software, they have to change the copyright notice (which is illegal, so you can sue and will win -> simple case). If they don't change the copyright notice, the 2nd level customers will notice that the software comes from you original and wonder what is going on. Chances are that they will contact you and so you will learn about the reselling of your work. Again we have two cases: The original customer sold only a few copies. That means they didn't make much money anyway, so why bother. Or they sold in volume. That means better chances for you to learn about what they do and do something about it. But in the end, most companies try to comply to the law (once their reputation is ruined, it's much harder to do business). So they will not steal your work but work with you to improve it. So if you include the source (with a license that protects you from simple reselling), chances are that they will simply push back changes they made since that will make sure the change is in the next version and they don't have to maintain it. That's win-win: You get changes and they can make the change themselves if they really, desperately need it even if you're unwilling to include it in the official release.
How do I protect Python code?
261,638
408
2008-11-04T11:57:27Z
261,727
395
2008-11-04T12:29:24Z
[ "python", "licensing", "obfuscation", "copy-protection" ]
I am developing a piece of software in Python that will be distributed to my employer's customers. My employer wants to limit the usage of the software with a time restricted license file. If we distribute the .py files or even .pyc files it will be easy to (decompile and) remove the code that checks the license file. Another aspect is that my employer does not want the code to be read by our customers, fearing that the code may be stolen or at least the "novel ideas". Is there a good way to handle this problem? Preferably with an off-the-shelf solution. The software will run on Linux systems (so I don't think py2exe will do the trick).
"Is there a good way to handle this problem?" No. Nothing can be protected against reverse engineering. Even the firmware on DVD machines has been reverse engineered and [AACS Encryption key](http://en.wikipedia.org/wiki/AACS%5Fencryption%5Fkey%5Fcontroversy) exposed. And that's in spite of the DMCA making that a criminal offense. Since no technical method can stop your customers from reading your code, you have to apply ordinary commercial methods. 1. Licenses. Contracts. Terms and Conditions. This still works even when people can read the code. Note that some of your Python-based components may require that you pay fees before you sell software using those components. Also, some open-source licenses prohibit you from concealing the source or origins of that component. 2. Offer significant value. If your stuff is so good -- at a price that is hard to refuse -- there's no incentive to waste time and money reverse engineering anything. Reverse engineering is expensive. Make your product slightly less expensive. 3. Offer upgrades and enhancements that make any reverse engineering a bad idea. When the next release breaks their reverse engineering, there's no point. This can be carried to absurd extremes, but you should offer new features that make the next release more valuable than reverse engineering. 4. Offer customization at rates so attractive that they'd rather pay you do build and support the enhancements. 5. Use a license key which expires. This is cruel, and will give you a bad reputation, but it certainly makes your software stop working. 6. Offer it as a web service. SaaS involves no downloads to customers.
How do I protect Python code?
261,638
408
2008-11-04T11:57:27Z
261,728
12
2008-11-04T12:29:48Z
[ "python", "licensing", "obfuscation", "copy-protection" ]
I am developing a piece of software in Python that will be distributed to my employer's customers. My employer wants to limit the usage of the software with a time restricted license file. If we distribute the .py files or even .pyc files it will be easy to (decompile and) remove the code that checks the license file. Another aspect is that my employer does not want the code to be read by our customers, fearing that the code may be stolen or at least the "novel ideas". Is there a good way to handle this problem? Preferably with an off-the-shelf solution. The software will run on Linux systems (so I don't think py2exe will do the trick).
In some circumstances, it may be possible to move (all, or at least a key part) of the software into a web service that your organization hosts. That way, the license checks can be performed in the safety of your own server room.
How do I protect Python code?
261,638
408
2008-11-04T11:57:27Z
261,797
8
2008-11-04T12:53:25Z
[ "python", "licensing", "obfuscation", "copy-protection" ]
I am developing a piece of software in Python that will be distributed to my employer's customers. My employer wants to limit the usage of the software with a time restricted license file. If we distribute the .py files or even .pyc files it will be easy to (decompile and) remove the code that checks the license file. Another aspect is that my employer does not want the code to be read by our customers, fearing that the code may be stolen or at least the "novel ideas". Is there a good way to handle this problem? Preferably with an off-the-shelf solution. The software will run on Linux systems (so I don't think py2exe will do the trick).
Depending in who the client is, a simple protection mechanism, combined with a sensible license agreement will be *far* more effective than any complex licensing/encryption/obfuscation system. The best solution would be selling the code as a service, say by hosting the service, or offering support - although that isn't always practical. Shipping the code as `.pyc` files will prevent your protection being foiled by a few `#`s, but it's hardly effective anti-piracy protection (as if there is such a technology), and at the end of the day, it shouldn't achieve anything that a decent license agreement with the company will. Concentrate on making your code as nice to use as possible - having happy customers will make your company far more money than preventing some theoretical piracy..
How do I protect Python code?
261,638
408
2008-11-04T11:57:27Z
261,808
7
2008-11-04T12:59:04Z
[ "python", "licensing", "obfuscation", "copy-protection" ]
I am developing a piece of software in Python that will be distributed to my employer's customers. My employer wants to limit the usage of the software with a time restricted license file. If we distribute the .py files or even .pyc files it will be easy to (decompile and) remove the code that checks the license file. Another aspect is that my employer does not want the code to be read by our customers, fearing that the code may be stolen or at least the "novel ideas". Is there a good way to handle this problem? Preferably with an off-the-shelf solution. The software will run on Linux systems (so I don't think py2exe will do the trick).
What about signing your code with standard encryption schemes by hashing and signing important files and checking it with public key methods? In this way you can issue license file with a public key for each customer. Additional you can use an python obfuscator like [this one](http://www.lysator.liu.se/~astrand/projects/pyobfuscate/) (just googled it).
How do I protect Python code?
261,638
408
2008-11-04T11:57:27Z
261,817
289
2008-11-04T13:03:06Z
[ "python", "licensing", "obfuscation", "copy-protection" ]
I am developing a piece of software in Python that will be distributed to my employer's customers. My employer wants to limit the usage of the software with a time restricted license file. If we distribute the .py files or even .pyc files it will be easy to (decompile and) remove the code that checks the license file. Another aspect is that my employer does not want the code to be read by our customers, fearing that the code may be stolen or at least the "novel ideas". Is there a good way to handle this problem? Preferably with an off-the-shelf solution. The software will run on Linux systems (so I don't think py2exe will do the trick).
# Python is not the tool you need You must use the right tool to do the right thing, and Python was not designed to be obfuscated. It's the contrary; everything is open or easy to reveal or modify in Python because that's the language's philosophy. If you want something you can't see through, look for another tool. This is not a bad thing, it is important that several different tools exist for different usages. # Obfuscation is really hard Even compiled programs can be reverse-engineered so don't think that you can fully protect any code. You can analyze obfuscated PHP, break the flash encryption key, etc. Newer versions of Windows are cracked every time. # Having a legal requirement is a good way to go You cannot prevent somebody from misusing your code, but you can easily discover if someone does. Therefore, it's just a casual legal issue. # Code protection is overrated Nowadays, business models tend to go for selling services instead of products. You cannot copy a service, pirate nor steal it. Maybe it's time to consider to go with the flow...
How do I protect Python code?
261,638
408
2008-11-04T11:57:27Z
262,937
19
2008-11-04T18:53:11Z
[ "python", "licensing", "obfuscation", "copy-protection" ]
I am developing a piece of software in Python that will be distributed to my employer's customers. My employer wants to limit the usage of the software with a time restricted license file. If we distribute the .py files or even .pyc files it will be easy to (decompile and) remove the code that checks the license file. Another aspect is that my employer does not want the code to be read by our customers, fearing that the code may be stolen or at least the "novel ideas". Is there a good way to handle this problem? Preferably with an off-the-shelf solution. The software will run on Linux systems (so I don't think py2exe will do the trick).
Do not rely on obfuscation. As You have correctly concluded, it offers very limited protection. UPDATE: Here is a [link to paper](https://www.usenix.org/system/files/conference/woot13/woot13-kholia.pdf) which reverse engineered obfuscated python code in Dropbox. The approach - opcode remapping is a good barrier, but clearly it can be defeated. Instead, as many posters have mentioned make it: * Not worth reverse engineering time (Your software is so good, it makes sense to pay) * Make them sign a contract and do a license audit if feasible. Alternatively, as the kick-ass Python IDE WingIDE does: **Give away the code**. That's right, give the code away and have people come back for upgrades and support.
How do I protect Python code?
261,638
408
2008-11-04T11:57:27Z
263,314
7
2008-11-04T20:27:05Z
[ "python", "licensing", "obfuscation", "copy-protection" ]
I am developing a piece of software in Python that will be distributed to my employer's customers. My employer wants to limit the usage of the software with a time restricted license file. If we distribute the .py files or even .pyc files it will be easy to (decompile and) remove the code that checks the license file. Another aspect is that my employer does not want the code to be read by our customers, fearing that the code may be stolen or at least the "novel ideas". Is there a good way to handle this problem? Preferably with an off-the-shelf solution. The software will run on Linux systems (so I don't think py2exe will do the trick).
The reliable only way to protect code is to run it on a server you control and provide your clients with a client which interfaces with that server.
How do I protect Python code?
261,638
408
2008-11-04T11:57:27Z
264,450
13
2008-11-05T06:10:26Z
[ "python", "licensing", "obfuscation", "copy-protection" ]
I am developing a piece of software in Python that will be distributed to my employer's customers. My employer wants to limit the usage of the software with a time restricted license file. If we distribute the .py files or even .pyc files it will be easy to (decompile and) remove the code that checks the license file. Another aspect is that my employer does not want the code to be read by our customers, fearing that the code may be stolen or at least the "novel ideas". Is there a good way to handle this problem? Preferably with an off-the-shelf solution. The software will run on Linux systems (so I don't think py2exe will do the trick).
Though there's no perfect solution, the following can be done: 1. Move some critical piece of startup code into a native library. 2. Enforce the license check in the native library. If the call to the native code were to be removed, the program wouldn't start anyway. If it's not removed then the license will be enforced. Though this is not a cross-platform or a pure-Python solution, it will work.
How do I protect Python code?
261,638
408
2008-11-04T11:57:27Z
267,875
52
2008-11-06T07:41:59Z
[ "python", "licensing", "obfuscation", "copy-protection" ]
I am developing a piece of software in Python that will be distributed to my employer's customers. My employer wants to limit the usage of the software with a time restricted license file. If we distribute the .py files or even .pyc files it will be easy to (decompile and) remove the code that checks the license file. Another aspect is that my employer does not want the code to be read by our customers, fearing that the code may be stolen or at least the "novel ideas". Is there a good way to handle this problem? Preferably with an off-the-shelf solution. The software will run on Linux systems (so I don't think py2exe will do the trick).
I understand that you want your customers to use the power of python but do not want expose the source code. Here are my suggestions: (a) Write the critical pieces of the code as C or C++ libraries and then use [SIP](http://www.riverbankcomputing.co.uk/software/sip/intro) or [swig](http://www.swig.org/) to expose the C/C++ APIs to Python namespace. (b) Use [cython](http://cython.org/) instead of Python (c) In both (a) and (b), it should be possible to distribute the libraries as licensed binary with a Python interface.
How do I protect Python code?
261,638
408
2008-11-04T11:57:27Z
554,565
11
2009-02-16T21:09:33Z
[ "python", "licensing", "obfuscation", "copy-protection" ]
I am developing a piece of software in Python that will be distributed to my employer's customers. My employer wants to limit the usage of the software with a time restricted license file. If we distribute the .py files or even .pyc files it will be easy to (decompile and) remove the code that checks the license file. Another aspect is that my employer does not want the code to be read by our customers, fearing that the code may be stolen or at least the "novel ideas". Is there a good way to handle this problem? Preferably with an off-the-shelf solution. The software will run on Linux systems (so I don't think py2exe will do the trick).
Shipping .pyc files has its problems - they are not compatible with any other python version than the python version they were created with, which means you must know which python version is running on the systems the product will run on. That's a very limiting factor.
How do I protect Python code?
261,638
408
2008-11-04T11:57:27Z
827,080
8
2009-05-05T21:53:15Z
[ "python", "licensing", "obfuscation", "copy-protection" ]
I am developing a piece of software in Python that will be distributed to my employer's customers. My employer wants to limit the usage of the software with a time restricted license file. If we distribute the .py files or even .pyc files it will be easy to (decompile and) remove the code that checks the license file. Another aspect is that my employer does not want the code to be read by our customers, fearing that the code may be stolen or at least the "novel ideas". Is there a good way to handle this problem? Preferably with an off-the-shelf solution. The software will run on Linux systems (so I don't think py2exe will do the trick).
Another attempt to make your code harder to steal is to use jython and then use [java obfuscator](http://proguard.sourceforge.net/). This should work pretty well as jythonc translate python code to java and then java is compiled to bytecode. So ounce you obfuscate the classes it will be really hard to understand what is going on after decompilation, not to mention recovering the actual code. The only problem with jython is that you can't use python modules written in c.
How do I protect Python code?
261,638
408
2008-11-04T11:57:27Z
7,347,168
83
2011-09-08T11:14:04Z
[ "python", "licensing", "obfuscation", "copy-protection" ]
I am developing a piece of software in Python that will be distributed to my employer's customers. My employer wants to limit the usage of the software with a time restricted license file. If we distribute the .py files or even .pyc files it will be easy to (decompile and) remove the code that checks the license file. Another aspect is that my employer does not want the code to be read by our customers, fearing that the code may be stolen or at least the "novel ideas". Is there a good way to handle this problem? Preferably with an off-the-shelf solution. The software will run on Linux systems (so I don't think py2exe will do the trick).
## Compile python and distribute binaries! **Sensible idea:** Use [Cython](http://cython.org/) (or something similar) to compile python to C code, then distribute your app as python binary libraries (pyd) instead. That way, no Python (byte) code is left and you've done any reasonable amount of obscurification anyone (i.e. your employer) could expect from regular Code, I think. (.NET or Java less safe than this case, as that bytecode is not obfuscated and can relatively easily be decompiled into reasonable source.) Cython is getting more and more compatible with CPython, so I think it should work. (I'm actually considering this for our product.. We're already building some thirdparty libs as pyd/dlls, so shipping our own python code as binaries is not a overly big step for us.) See [This Blog Post](http://blog.biicode.com/bii-internals-compiling-your-python-application-with-cython/) (not by me) for a tutorial on how to do it. (thx @hithwen) **Crazy idea:** You could probably get Cython to store the C-files separately for each module, then just concatenate them all and build them with heavy inlining. That way, your Python module is pretty monolithic and difficult to chip at with common tools. **Beyond crazy:** You might be able to build a single executable if you can link to (and optimize with) the python runtime and all libraries (dlls) statically. That way, it'd sure be difficult to intercept calls to/from python and whatever framework libraries you use. This cannot be done if you're using LGPL code though.
How do I protect Python code?
261,638
408
2008-11-04T11:57:27Z
11,315,793
8
2012-07-03T17:07:27Z
[ "python", "licensing", "obfuscation", "copy-protection" ]
I am developing a piece of software in Python that will be distributed to my employer's customers. My employer wants to limit the usage of the software with a time restricted license file. If we distribute the .py files or even .pyc files it will be easy to (decompile and) remove the code that checks the license file. Another aspect is that my employer does not want the code to be read by our customers, fearing that the code may be stolen or at least the "novel ideas". Is there a good way to handle this problem? Preferably with an off-the-shelf solution. The software will run on Linux systems (so I don't think py2exe will do the trick).
I think there is one more method to protect your Python code; part of the Obfuscation method. I beleive there was a game like Mount and Blade or something that changed and recompiled their own python interpreter (the original interpreter which i believe is open source) and just changed the OP codes in the OP code table to be different then the standard python OP codes. So the python source is unmodified but the file extentions of the pyc files are different and the op codes don't match to the public python.exe interpreter. If you checked the games data files all the data was in Python source format. All sorts of nasty tricks can be done to mess with amature hackers this way. Stopping a bunch of noob hackers is easy. It's the pro hackers that you will not likely beat. But most companies don't keep pro hackers on staff long I imagine (likely because things get hacked). But amature hackers are all over the place (read as curious IT staff). You could for example, in a modified interpreter, allow it to check for certain comments or docstrings in your source. You could have special OP codes for such lines of code. For example: OP 234 is for source line "# Copyright I wrote this" or compile that line into op codes that are equivelent to "if False:" if "# Copyright" is missing. Basically disabling a whole block of code for what appears to be some obsure reason. One use case where recompiling a modified interpreter may be feasable is where you didn't write the app, the app is big, but you are paid to protect it, such as when you're a dedicated server admin for a financial app. I find it a little contradictory to leave the source or opcodes open for eyeballs, but use SSL for network traffic. SSL is not 100% safe either. But it's used to stop MOST eyes from reading it. A wee bit precaution is sensible. Also, if enough people deem that Python source and opcodes are too visible, it's likely someone will eventually develope at least a simple protection tool for it. So the more people asking "how to protect Python app" only promotes that development.
How do I protect Python code?
261,638
408
2008-11-04T11:57:27Z
30,121,460
9
2015-05-08T10:21:58Z
[ "python", "licensing", "obfuscation", "copy-protection" ]
I am developing a piece of software in Python that will be distributed to my employer's customers. My employer wants to limit the usage of the software with a time restricted license file. If we distribute the .py files or even .pyc files it will be easy to (decompile and) remove the code that checks the license file. Another aspect is that my employer does not want the code to be read by our customers, fearing that the code may be stolen or at least the "novel ideas". Is there a good way to handle this problem? Preferably with an off-the-shelf solution. The software will run on Linux systems (so I don't think py2exe will do the trick).
Have you had a look at [pyminifier](https://liftoff.github.io/pyminifier/)? It does Minify, obfuscate, and compress Python code. The example code looks pretty nasty for casual reverse engineering. ``` $ pyminifier --nonlatin --replacement-length=50 /tmp/tumult.py #!/usr/bin/env python3 ﺭ异𞸐𐤔ﭞﰣﺁں𝕌𨿩𞸇뻛𐬑𥰫嬭ﱌ𢽁𐡆𧪮Ꝫﴹ뙫𢤴퉊ﳦﲣפּܟﺶ𐐤ﶨࠔ𐰷𢡶𧐎𐭈𞸏𢢘𦘼ﶻ𩏃𦽨𞺎𠛘𐠲䉊ﰸﭳᣲמּ=ImportError ﺭ异𞸐𐤔ﭞﰣﺁں𝕌𨿩𞸇뻛𐬑𥰫嬭ﱌ𢽁𐡆𧪮Ꝫﴹ뙫𢤴퉊ﳦﲣפּܟﺶ𐐤ﶨࠔ𐰷𢡶𧐎𐭈𞸏𢢘𦘼ﶻ𩏃𦽨𞺎𠛘𐠲䉊ﰸﭳᣲ燱=print ﺭ异𞸐𐤔ﭞﰣﺁں𝕌𨿩𞸇뻛𐬑𥰫嬭ﱌ𢽁𐡆𧪮Ꝫﴹ뙫𢤴퉊ﳦﲣפּܟﺶ𐐤ﶨࠔ𐰷𢡶𧐎𐭈𞸏𢢘𦘼ﶻ𩏃𦽨𞺎𠛘𐠲䉊ﰸﭳᣲ巡=False ﺭ异𞸐𐤔ﭞﰣﺁں𝕌𨿩𞸇뻛𐬑𥰫嬭ﱌ𢽁𐡆𧪮Ꝫﴹ뙫𢤴퉊ﳦﲣפּܟﺶ𐐤ﶨࠔ𐰷𢡶𧐎𐭈𞸏𢢘𦘼ﶻ𩏃𦽨𞺎𠛘𐠲䉊ﰸﭳᣲ澨=object try: import demiurgic except ﺭ异𞸐𐤔ﭞﰣﺁں𝕌𨿩𞸇뻛𐬑𥰫嬭ﱌ𢽁𐡆𧪮Ꝫﴹ뙫𢤴퉊ﳦﲣפּܟﺶ𐐤ﶨࠔ𐰷𢡶𧐎𐭈𞸏𢢘𦘼ﶻ𩏃𦽨𞺎𠛘𐠲䉊ﰸﭳᣲמּ: ﺭ异𞸐𐤔ﭞﰣﺁں𝕌𨿩𞸇뻛𐬑𥰫嬭ﱌ𢽁𐡆𧪮Ꝫﴹ뙫𢤴퉊ﳦﲣפּܟﺶ𐐤ﶨࠔ𐰷𢡶𧐎𐭈𞸏𢢘𦘼ﶻ𩏃𦽨𞺎𠛘𐠲䉊ﰸﭳᣲ燱("Warning: You're not demiurgic. Actually, I think that's normal.") try: import mystificate except ﺭ异𞸐𐤔ﭞﰣﺁں𝕌𨿩𞸇뻛𐬑𥰫嬭ﱌ𢽁𐡆𧪮Ꝫﴹ뙫𢤴퉊ﳦﲣפּܟﺶ𐐤ﶨࠔ𐰷𢡶𧐎𐭈𞸏𢢘𦘼ﶻ𩏃𦽨𞺎𠛘𐠲䉊ﰸﭳᣲמּ: ﺭ异𞸐𐤔ﭞﰣﺁں𝕌𨿩𞸇뻛𐬑𥰫嬭ﱌ𢽁𐡆𧪮Ꝫﴹ뙫𢤴퉊ﳦﲣפּܟﺶ𐐤ﶨࠔ𐰷𢡶𧐎𐭈𞸏𢢘𦘼ﶻ𩏃𦽨𞺎𠛘𐠲䉊ﰸﭳᣲ燱("Warning: Dark voodoo may be unreliable.") ﺭ异𞸐𐤔ﭞﰣﺁں𝕌𨿩𞸇뻛𐬑𥰫嬭ﱌ𢽁𐡆𧪮Ꝫﴹ뙫𢤴퉊ﳦﲣפּܟﺶ𐐤ﶨࠔ𐰷𢡶𧐎𐭈𞸏𢢘𦘼ﶻ𩏃𦽨𞺎𠛘𐠲䉊ﰸﭳᣲﺬ=ﺭ异𞸐𐤔ﭞﰣﺁں𝕌𨿩𞸇뻛𐬑𥰫嬭ﱌ𢽁𐡆𧪮Ꝫﴹ뙫𢤴퉊ﳦﲣפּܟﺶ𐐤ﶨࠔ𐰷𢡶𧐎𐭈𞸏𢢘𦘼ﶻ𩏃𦽨𞺎𠛘𐠲䉊ﰸﭳᣲ巡 class ﺭ异𞸐𐤔ﭞﰣﺁں𝕌𨿩𞸇뻛𐬑𥰫嬭ﱌ𢽁𐡆𧪮Ꝫﴹ뙫𢤴퉊ﳦﲣפּܟﺶ𐐤ﶨࠔ𐰷𢡶𧐎𐭈𞸏𢢘𦘼ﶻ𩏃𦽨𞺎𠛘𐠲䉊ﰸﭳᣲ𐦚(ﺭ异𞸐𐤔ﭞﰣﺁں𝕌𨿩𞸇뻛𐬑𥰫嬭ﱌ𢽁𐡆𧪮Ꝫﴹ뙫𢤴퉊ﳦﲣפּܟﺶ𐐤ﶨࠔ𐰷𢡶𧐎𐭈𞸏𢢘𦘼ﶻ𩏃𦽨𞺎𠛘𐠲䉊ﰸﭳᣲ澨): def __init__(self,*args,**kwargs): pass def ﺭ异𞸐𐤔ﭞﰣﺁں𝕌𨿩𞸇뻛𐬑𥰫嬭ﱌ𢽁𐡆𧪮Ꝫﴹ뙫𢤴퉊ﳦﲣפּܟﺶ𐐤ﶨࠔ𐰷𢡶𧐎𐭈𞸏𢢘𦘼ﶻ𩏃𦽨𞺎𠛘𐠲䉊ﰸﭳᣲ클(self,dactyl): ﺭ异𞸐𐤔ﭞﰣﺁں𝕌𨿩𞸇뻛𐬑𥰫嬭ﱌ𢽁𐡆𧪮Ꝫﴹ뙫𢤴퉊ﳦﲣפּܟﺶ𐐤ﶨࠔ𐰷𢡶𧐎𐭈𞸏𢢘𦘼ﶻ𩏃𦽨𞺎𠛘𐠲䉊ﰸﭳᣲ퐐=demiurgic.palpitation(dactyl) ﺭ异𞸐𐤔ﭞﰣﺁں𝕌𨿩𞸇뻛𐬑𥰫嬭ﱌ𢽁𐡆𧪮Ꝫﴹ뙫𢤴퉊ﳦﲣפּܟﺶ𐐤ﶨࠔ𐰷𢡶𧐎𐭈𞸏𢢘𦘼ﶻ𩏃𦽨𞺎𠛘𐠲䉊ﰸﭳᣲ𠛲=mystificate.dark_voodoo(ﺭ异𞸐𐤔ﭞﰣﺁں𝕌𨿩𞸇뻛𐬑𥰫嬭ﱌ𢽁𐡆𧪮Ꝫﴹ뙫𢤴퉊ﳦﲣפּܟﺶ𐐤ﶨࠔ𐰷𢡶𧐎𐭈𞸏𢢘𦘼ﶻ𩏃𦽨𞺎𠛘𐠲䉊ﰸﭳᣲ퐐) return ﺭ异𞸐𐤔ﭞﰣﺁں𝕌𨿩𞸇뻛𐬑𥰫嬭ﱌ𢽁𐡆𧪮Ꝫﴹ뙫𢤴퉊ﳦﲣפּܟﺶ𐐤ﶨࠔ𐰷𢡶𧐎𐭈𞸏𢢘𦘼ﶻ𩏃𦽨𞺎𠛘𐠲䉊ﰸﭳᣲ𠛲 def ﺭ异𞸐𐤔ﭞﰣﺁں𝕌𨿩𞸇뻛𐬑𥰫嬭ﱌ𢽁𐡆𧪮Ꝫﴹ뙫𢤴퉊ﳦﲣפּܟﺶ𐐤ﶨࠔ𐰷𢡶𧐎𐭈𞸏𢢘𦘼ﶻ𩏃𦽨𞺎𠛘𐠲䉊ﰸﭳᣲ𐠯(self,whatever): ﺭ异𞸐𐤔ﭞﰣﺁں𝕌𨿩𞸇뻛𐬑𥰫嬭ﱌ𢽁𐡆𧪮Ꝫﴹ뙫𢤴퉊ﳦﲣפּܟﺶ𐐤ﶨࠔ𐰷𢡶𧐎𐭈𞸏𢢘𦘼ﶻ𩏃𦽨𞺎𠛘𐠲䉊ﰸﭳᣲ燱(whatever) if __name__=="__main__": ﺭ异𞸐𐤔ﭞﰣﺁں𝕌𨿩𞸇뻛𐬑𥰫嬭ﱌ𢽁𐡆𧪮Ꝫﴹ뙫𢤴퉊ﳦﲣפּܟﺶ𐐤ﶨࠔ𐰷𢡶𧐎𐭈𞸏𢢘𦘼ﶻ𩏃𦽨𞺎𠛘𐠲䉊ﰸﭳᣲ燱("Forming...") ﺭ异𞸐𐤔ﭞﰣﺁں𝕌𨿩𞸇뻛𐬑𥰫嬭ﱌ𢽁𐡆𧪮Ꝫﴹ뙫𢤴퉊ﳦﲣפּܟﺶ𐐤ﶨࠔ𐰷𢡶𧐎𐭈𞸏𢢘𦘼ﶻ𩏃𦽨𞺎𠛘𐠲䉊ﰸﭳᣲﺃ=ﺭ异𞸐𐤔ﭞﰣﺁں𝕌𨿩𞸇뻛𐬑𥰫嬭ﱌ𢽁𐡆𧪮Ꝫﴹ뙫𢤴퉊ﳦﲣפּܟﺶ𐐤ﶨࠔ𐰷𢡶𧐎𐭈𞸏𢢘𦘼ﶻ𩏃𦽨𞺎𠛘𐠲䉊ﰸﭳᣲ𐦚("epicaricacy","perseverate") ﺭ异𞸐𐤔ﭞﰣﺁں𝕌𨿩𞸇뻛𐬑𥰫嬭ﱌ𢽁𐡆𧪮Ꝫﴹ뙫𢤴퉊ﳦﲣפּܟﺶ𐐤ﶨࠔ𐰷𢡶𧐎𐭈𞸏𢢘𦘼ﶻ𩏃𦽨𞺎𠛘𐠲䉊ﰸﭳᣲﺃ.ﺭ异𞸐𐤔ﭞﰣﺁں𝕌𨿩𞸇뻛𐬑𥰫嬭ﱌ𢽁𐡆𧪮Ꝫﴹ뙫𢤴퉊ﳦﲣפּܟﺶ𐐤ﶨࠔ𐰷𢡶𧐎𐭈𞸏𢢘𦘼ﶻ𩏃𦽨𞺎𠛘𐠲䉊ﰸﭳᣲ𐠯("Codswallop") # Created by pyminifier (https://github.com/liftoff/pyminifier) ```
Converting a List of Tuples into a Dict in Python
261,655
29
2008-11-04T12:03:34Z
261,665
27
2008-11-04T12:07:21Z
[ "python", "data-structures", "iteration" ]
I have a list of tuples like this: ``` [ ('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('c', 1), ] ``` I want to iterate through this keying by the first item, so for example I could print something like this: ``` a 1 2 3 b 1 2 c 1 ``` How would I go about doing this without keeping an item to track whether the first item is the same as I loop round the tuples. This feels rather messy (plus I have to sort the list to start with)... Thanks, Dan
``` l = [ ('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('c', 1), ] d = {} for x, y in l: d.setdefault(x, []).append(y) print d ``` produces: ``` {'a': [1, 2, 3], 'c': [1], 'b': [1, 2]} ```
Converting a List of Tuples into a Dict in Python
261,655
29
2008-11-04T12:03:34Z
261,677
23
2008-11-04T12:11:52Z
[ "python", "data-structures", "iteration" ]
I have a list of tuples like this: ``` [ ('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('c', 1), ] ``` I want to iterate through this keying by the first item, so for example I could print something like this: ``` a 1 2 3 b 1 2 c 1 ``` How would I go about doing this without keeping an item to track whether the first item is the same as I loop round the tuples. This feels rather messy (plus I have to sort the list to start with)... Thanks, Dan
Slightly simpler... ``` >>> from collections import defaultdict >>> fq= defaultdict( list ) >>> for n,v in myList: fq[n].append(v) >>> fq defaultdict(<type 'list'>, {'a': [1, 2, 3], 'c': [1], 'b': [1, 2]}) ```
Converting a List of Tuples into a Dict in Python
261,655
29
2008-11-04T12:03:34Z
261,766
8
2008-11-04T12:42:32Z
[ "python", "data-structures", "iteration" ]
I have a list of tuples like this: ``` [ ('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('c', 1), ] ``` I want to iterate through this keying by the first item, so for example I could print something like this: ``` a 1 2 3 b 1 2 c 1 ``` How would I go about doing this without keeping an item to track whether the first item is the same as I loop round the tuples. This feels rather messy (plus I have to sort the list to start with)... Thanks, Dan
A solution using groupby ``` >>> from itertools import groupby >>> l = [('a',1), ('a', 2),('a', 3),('b', 1),('b', 2),('c', 1),] >>> [(label, [v for l,v in value]) for (label, value) in groupby(l, lambda x:x[0])] [('a', [1, 2, 3]), ('b', [1, 2]), ('c', [1])] ``` groupby(l, lambda x:x[0]) gives you an iterator that contains ['a', [('a', 1), ...], c, [('c', 1)], ...]
Is it possible to change the Environment of a parent process in python?
263,005
11
2008-11-04T19:08:16Z
263,022
11
2008-11-04T19:12:44Z
[ "python", "linux", "environment" ]
In Linux When I invoke python from the shell it replicates its environment, and starts the python process. Therefore if I do something like the following: ``` import os os.environ["FOO"] = "A_Value" ``` When the python process returns, FOO, assuming it was undefined originally, will still be undefined. Is there a way for the python process (or any child process) to modify the environment of its parent process? I know you typically solve this problem using something like ``` source script_name.sh ``` But this conflicts with other requirements I have.
It's not possible, for any child process, to change the environment of the parent process. The best you can do is to output shell statements to stdout that you then source, or write it to a file that you source in the parent.
Is it possible to change the Environment of a parent process in python?
263,005
11
2008-11-04T19:08:16Z
263,068
9
2008-11-04T19:27:27Z
[ "python", "linux", "environment" ]
In Linux When I invoke python from the shell it replicates its environment, and starts the python process. Therefore if I do something like the following: ``` import os os.environ["FOO"] = "A_Value" ``` When the python process returns, FOO, assuming it was undefined originally, will still be undefined. Is there a way for the python process (or any child process) to modify the environment of its parent process? I know you typically solve this problem using something like ``` source script_name.sh ``` But this conflicts with other requirements I have.
No process can change its parent process (or any other existing process' environment). You can, however, create a new environment by creating a new interactive shell with the modified environment. You have to spawn a new copy of the shell that uses the upgraded environment and has access to the existing stdin, stdout and stderr, and does its reinitialization dance. You need to do something like use subprocess.Popen to run `/bin/bash -i`. So the original shell runs Python, which runs a new shell. Yes, you have a lot of processes running. No it's not too bad because the original shell and Python aren't really doing anything except waiting for the subshell to finish so they can exit cleanly, also.
Is it possible to change the Environment of a parent process in python?
263,005
11
2008-11-04T19:08:16Z
263,162
7
2008-11-04T19:41:03Z
[ "python", "linux", "environment" ]
In Linux When I invoke python from the shell it replicates its environment, and starts the python process. Therefore if I do something like the following: ``` import os os.environ["FOO"] = "A_Value" ``` When the python process returns, FOO, assuming it was undefined originally, will still be undefined. Is there a way for the python process (or any child process) to modify the environment of its parent process? I know you typically solve this problem using something like ``` source script_name.sh ``` But this conflicts with other requirements I have.
I would use the bash eval statement, and have the python script output the shell code child.py: ``` #!/usr/bin/env python print 'FOO="A_Value"' ``` parent.sh ``` #!/bin/bash eval `./child.py` ```
Creating a python win32 service
263,296
11
2008-11-04T20:23:17Z
900,775
9
2009-05-23T03:20:19Z
[ "python", "winapi", "pywin32" ]
I am currently trying to create a win32 service using pywin32. My main point of reference has been this tutorial: <http://code.activestate.com/recipes/551780/> What i don't understand is the initialization process, since the Daemon is never initialized directly by Daemon(), instead from my understanding its initialized by the following: ``` mydaemon = Daemon __svc_regClass__(mydaemon, "foo", "foo display", "foo description") __svc_install__(mydaemon) ``` Where **svc\_install**, handles the initalization, by calling Daemon.**init**() and passing some arguments to it. But how can i initialize the daemon object, without initalizing the service? I want to do a few things, before i init the service. Does anyone have any ideas? ``` class Daemon(win32serviceutil.ServiceFramework): def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) def SvcDoRun(self): self.run() def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) def start(self): pass def stop(self): self.SvcStop() def run(self): pass def __svc_install__(cls): win32api.SetConsoleCtrlHandler(lambda x: True, True) try: win32serviceutil.InstallService( cls._svc_reg_class_, cls._svc_name_, cls._svc_display_name_, startType = win32service.SERVICE_AUTO_START ) print "Installed" except Exception, err: print str(err) def __svc_regClass__(cls, name, display_name, description): #Bind the values to the service name cls._svc_name_ = name cls._svc_display_name_ = display_name cls._svc_description_ = description try: module_path = sys.modules[cls.__module__].__file__ except AttributeError: from sys import executable module_path = executable module_file = os.path.splitext(os.path.abspath(module_path))[0] cls._svc_reg_class_ = '%s.%s' % (module_file, cls.__name__) ```
I just create a simple "how to" where the program is in one module and the service is in another place, it uses py2exe to create the win32 service, which I believe is the best you can do for your users that don't want to mess with the python interpreter or other dependencies. You can check my tutorial here: [Create win32 services using Python and py2exe](http://islascruz.org/html/index.php?gadget=StaticPage&action=Page&id=6)
Merging/adding lists in Python
263,457
33
2008-11-04T21:06:36Z
263,465
68
2008-11-04T21:16:39Z
[ "python", "list" ]
I'm pretty sure there should be a more Pythonic way of doing this - but I can't think of one: How can I merge a two-dimensional list into a one-dimensional list? Sort of like zip/map but with more than two iterators. Example - I have the following list: ``` array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] ``` I want to have ``` result = [12, 15, 18] # [1+4+7, 2+5+8, 3+6+9] ``` So far what I've come up with is: ``` def add_list(array): number_items = len(array[0]) result = [0] * number_items for index in range(number_items): for line in array: result[index] += line[index] return result ``` But that doesn't look very elegant/Pythonic to me. Aside from not checking if all the "lines" in the 2D array are of the same length, can be added to each other, etc. What would be a better way to do it?
``` [sum(a) for a in zip(*array)] ```
Merging/adding lists in Python
263,457
33
2008-11-04T21:06:36Z
263,523
62
2008-11-04T21:33:47Z
[ "python", "list" ]
I'm pretty sure there should be a more Pythonic way of doing this - but I can't think of one: How can I merge a two-dimensional list into a one-dimensional list? Sort of like zip/map but with more than two iterators. Example - I have the following list: ``` array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] ``` I want to have ``` result = [12, 15, 18] # [1+4+7, 2+5+8, 3+6+9] ``` So far what I've come up with is: ``` def add_list(array): number_items = len(array[0]) result = [0] * number_items for index in range(number_items): for line in array: result[index] += line[index] return result ``` But that doesn't look very elegant/Pythonic to me. Aside from not checking if all the "lines" in the 2D array are of the same length, can be added to each other, etc. What would be a better way to do it?
[sum(value) for value in zip(\*array)] is pretty standard. This might help you understand it: ``` In [1]: array=[[1, 2, 3], [4, 5, 6], [7, 8, 9]] In [2]: array Out[2]: [[1, 2, 3], [4, 5, 6], [7, 8, 9]] In [3]: *array ------------------------------------------------------------ File "<ipython console>", line 1 *array ^ <type 'exceptions.SyntaxError'>: invalid syntax ``` *The unary star is not an operator by itself. It unwraps array elements into arguments into function calls.* ``` In [4]: zip(*array) Out[4]: [(1, 4, 7), (2, 5, 8), (3, 6, 9)] ``` *zip() is a built-in function* ``` In [5]: zip(*array)[0] Out[5]: (1, 4, 7) ``` *each element for the list returned by zip is a set of numbers you want.* ``` In [6]: sum(zip(*array)[0]) Out[6]: 12 In [7]: [sum(values) for values in zip(*array)] Out[7]: [12, 15, 18] ```
Merging/adding lists in Python
263,457
33
2008-11-04T21:06:36Z
265,472
8
2008-11-05T15:24:08Z
[ "python", "list" ]
I'm pretty sure there should be a more Pythonic way of doing this - but I can't think of one: How can I merge a two-dimensional list into a one-dimensional list? Sort of like zip/map but with more than two iterators. Example - I have the following list: ``` array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] ``` I want to have ``` result = [12, 15, 18] # [1+4+7, 2+5+8, 3+6+9] ``` So far what I've come up with is: ``` def add_list(array): number_items = len(array[0]) result = [0] * number_items for index in range(number_items): for line in array: result[index] += line[index] return result ``` But that doesn't look very elegant/Pythonic to me. Aside from not checking if all the "lines" in the 2D array are of the same length, can be added to each other, etc. What would be a better way to do it?
If you're doing a lot of this kind of thing, you want to learn about [`scipy`.](http://scipy.org/) ``` >>> import scipy >>> sum(scipy.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])) array([12, 15, 18]) ``` All array sizes are checked for you automatically. The sum is done in pure C, so it's very fast. `scipy` arrays are also very memory efficient. The drawback is you're dependent on a fairly complex third-party module. But that's a very good tradeoff for many purposes.
Merging/adding lists in Python
263,457
33
2008-11-04T21:06:36Z
265,495
13
2008-11-05T15:31:04Z
[ "python", "list" ]
I'm pretty sure there should be a more Pythonic way of doing this - but I can't think of one: How can I merge a two-dimensional list into a one-dimensional list? Sort of like zip/map but with more than two iterators. Example - I have the following list: ``` array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] ``` I want to have ``` result = [12, 15, 18] # [1+4+7, 2+5+8, 3+6+9] ``` So far what I've come up with is: ``` def add_list(array): number_items = len(array[0]) result = [0] * number_items for index in range(number_items): for line in array: result[index] += line[index] return result ``` But that doesn't look very elegant/Pythonic to me. Aside from not checking if all the "lines" in the 2D array are of the same length, can be added to each other, etc. What would be a better way to do it?
An alternative way: ``` map(sum, zip(*array)) ```
What is a Ruby equivalent for Python's "zip" builtin?
263,623
14
2008-11-04T21:58:29Z
263,652
21
2008-11-04T22:05:46Z
[ "python", "ruby", "translation" ]
Is there any Ruby equivalent for Python's builtin `zip` function? If not, what is a concise way of doing the same thing? A bit of context: this came up when I was trying to find a clean way of doing a check involving two arrays. If I had `zip`, I could have written something like: ``` zip(a, b).all? {|pair| pair[0] === pair[1]} ``` I'd also accept a clean way of doing this without anything resembling `zip` (where "clean" means "without an explicit loop").
Ruby has a zip function: ``` [1,2].zip([3,4]) => [[1,3],[2,4]] ``` so your code example is actually: ``` a.zip(b).all? {|pair| pair[0] === pair[1]} ``` or perhaps more succinctly: ``` a.zip(b).all? {|a,b| a === b } ```
How to fetch more than 1000?
264,154
46
2008-11-05T01:56:20Z
264,171
14
2008-11-05T02:07:43Z
[ "python", "google-app-engine", "google-cloud-datastore" ]
How can I fetch more than 1000 record from data store and put all in one single list to pass to django?
**You can't.** Part of the FAQ states that there is no way you can access beyond row 1000 of a query, increasing the "OFFSET" will just result in a shorter result set, ie: OFFSET 999 --> 1 result comes back. From Wikipedia: > App Engine limits the maximum rows > returned from an entity get to 1000 > rows per Datastore call. Most web > database applications use paging and > caching, and hence do not require this > much data at once, so this is a > non-issue in most scenarios.[citation > needed] If an application needs more > than 1,000 records per operation, it > can use its own client-side software > or an Ajax page to perform an > operation on an unlimited number of > rows. From <http://code.google.com/appengine/docs/whatisgoogleappengine.html> > Another example of a service limit is > the number of results returned by a > query. A query can return at most > 1,000 results. Queries that would > return more results only return the > maximum. In this case, a request that > performs such a query isn't likely to > return a request before the timeout, > but the limit is in place to conserve > resources on the datastore. From <http://code.google.com/appengine/docs/datastore/gqlreference.html> > Note: A LIMIT clause has a maximum of > 1000. If a limit larger than the maximum is specified, the maximum is > used. This same maximum applies to the > fetch() method of the GqlQuery class. > > Note: Like the offset parameter for > the fetch() method, an OFFSET in a GQL > query string does not reduce the > number of entities fetched from the > datastore. It only affects which > results are returned by the fetch() > method. A query with an offset has > performance characteristics that > correspond linearly with the offset > size. From <http://code.google.com/appengine/docs/datastore/queryclass.html> > The limit and offset arguments control > how many results are fetched from the > datastore, and how many are returned > by the fetch() method: > > * The datastore fetches offset + limit results to the application. The first offset results are **not** skipped by the datastore itself. > * The fetch() method skips the first offset results, then returns the rest (limit results). > * The query has performance characteristics that correspond > linearly with the offset amount plus the limit. ## What this means is If you have a singular query, there is no way to request anything outside the range 0-1000. Increasing offset will just raise the 0, so ``` LIMIT 1000 OFFSET 0 ``` Will return 1000 rows, and ``` LIMIT 1000 OFFSET 1000 ``` Will return **0 rows**, thus, making it impossible to, with a single query syntax, fetch 2000 results either manually or using the API. ## The only plausible exception Is to create a numeric index on the table, ie: ``` SELECT * FROM Foo WHERE ID > 0 AND ID < 1000 SELECT * FROM Foo WHERE ID >= 1000 AND ID < 2000 ``` If your data or query can't have this 'ID' hardcoded identifier, then you are **out of luck**
How to fetch more than 1000?
264,154
46
2008-11-05T01:56:20Z
264,183
7
2008-11-05T02:17:22Z
[ "python", "google-app-engine", "google-cloud-datastore" ]
How can I fetch more than 1000 record from data store and put all in one single list to pass to django?
The 1000 record limit is a hard limit in Google AppEngine. This presentation <http://sites.google.com/site/io/building-scalable-web-applications-with-google-app-engine> explains how to efficiently page through data using AppEngine. (Basically by using a numeric id as key and specifying a WHERE clause on the id.)
How to fetch more than 1000?
264,154
46
2008-11-05T01:56:20Z
264,334
17
2008-11-05T04:21:46Z
[ "python", "google-app-engine", "google-cloud-datastore" ]
How can I fetch more than 1000 record from data store and put all in one single list to pass to django?
Every time this comes up as a limitation, I always wonder "*why* do you need more than 1,000 results?" Did you know that Google themselves doesn't serve up more than 1,000 results? Try this search: <http://www.google.ca/search?hl=en&client=firefox-a&rls=org.mozilla:en-US:official&hs=qhu&q=1000+results&start=1000&sa=N> I didn't know that until recently, because I'd never taken the time to click into the 100th page of search results on a query. If you're actually returning more than 1,000 results back to the user, then I think there's a bigger problem at hand than the fact that the data store won't let you do it. One possible (legitimate) reason to need that many results is if you were doing a large operation on the data and presenting a summary (for example, what is the average of all this data). The solution to this problem (which is talked about in the Google I/O talk) is to calculate the summary data on-the-fly, as it comes in, and save it.
How to fetch more than 1000?
264,154
46
2008-11-05T01:56:20Z
721,858
19
2009-04-06T14:59:46Z
[ "python", "google-app-engine", "google-cloud-datastore" ]
How can I fetch more than 1000 record from data store and put all in one single list to pass to django?
App Engine gives you a nice way of "paging" through the results by 1000 by ordering on Keys and using the last key as the next offset. They even provide some sample code here: <http://code.google.com/appengine/docs/python/datastore/queriesandindexes.html#Queries_on_Keys> Although their example spreads the queries out over many requests, you can change the page size from 20 to 1000 and query in a loop, combining the querysets. Additionally you might use itertools to link the queries without evaluating them before they're needed. For example, to count how many rows beyond 1000: ``` class MyModel(db.Expando): @classmethod def count_all(cls): """ Count *all* of the rows (without maxing out at 1000) """ count = 0 query = cls.all().order('__key__') while count % 1000 == 0: current_count = query.count() if current_count == 0: break count += current_count if current_count == 1000: last_key = query.fetch(1, 999)[0].key() query = query.filter('__key__ > ', last_key) return count ```
How to fetch more than 1000?
264,154
46
2008-11-05T01:56:20Z
2,204,144
10
2010-02-04T23:58:37Z
[ "python", "google-app-engine", "google-cloud-datastore" ]
How can I fetch more than 1000 record from data store and put all in one single list to pass to django?
This 1K limit issue is resolved. query = MyModel.all() for doc in query: print doc.title By treating the Query object as an iterable: The iterator retrieves results from the datastore in small batches, allowing for the app to stop iterating on results to avoid fetching more than is needed. Iteration stops when all of the results that match the query have been retrieved. As with fetch(), the iterator interface does not cache results, so creating a new iterator from the Query object will re-execute the query. The max batch size is 1K. And you still have the auto Datastore quotas as well. But with the plan 1.3.1 SDK, they've introduced cursors that can be serialized and saved so that a future invocation can begin the query where it last left off at.
How to fetch more than 1000?
264,154
46
2008-11-05T01:56:20Z
2,305,538
23
2010-02-21T10:08:56Z
[ "python", "google-app-engine", "google-cloud-datastore" ]
How can I fetch more than 1000 record from data store and put all in one single list to pass to django?
Just for the record - fetch limit of 1000 entries is now gone: <http://googleappengine.blogspot.com/2010/02/app-engine-sdk-131-including-major.html> Quotation: > No more 1000 result limit - That's > right: with addition of Cursors and > the culmination of many smaller > Datastore stability and performance > improvements over the last few months, > we're now confident enough to remove > the maximum result limit altogether. > Whether you're doing a fetch, > iterating, or using a Cursor, there's > no limits on the number of results.
How to fetch more than 1000?
264,154
46
2008-11-05T01:56:20Z
3,543,527
36
2010-08-22T21:38:31Z
[ "python", "google-app-engine", "google-cloud-datastore" ]
How can I fetch more than 1000 record from data store and put all in one single list to pass to django?
Starting with Version 1.3.6 (released Aug-17-2010) you **CAN** [From the changelog:](http://code.google.com/p/googleappengine/wiki/SdkReleaseNotes#Version_1.3.6_-_August_17,_2010) > Results of datastore count() queries **and offsets for all datastore queries are no longer capped at 1000**.
setting the gzip timestamp from Python
264,224
3
2008-11-05T02:50:59Z
264,303
7
2008-11-05T03:49:51Z
[ "python", "gzip" ]
I'm interested in compressing data using Python's `gzip` module. It happens that I want the compressed output to be deterministic, because that's often a really convenient property for things to have in general -- if some non-gzip-aware process is going to be looking for changes in the output, say, or if the output is going to be cryptographically signed. Unfortunately, the output is different every time. As far as I can tell, the only reason for this is the timestamp field in the gzip header, which the Python module always populates with the current time. I don't think you're actually allowed to have a gzip stream without a timestamp in it, which is too bad. In any case, there doesn't seem to be a way for the caller of Python's `gzip` module to supply the correct modification time of the underlying data. (The actual `gzip` program seems to use the timestamp of the input file when possible.) I imagine this is because basically the only thing that ever cares about the timestamp is the `gunzip` command when writing to a file -- and, now, me, because I want deterministic output. Is that so much to ask? Has anyone else encountered this problem? What's the least terrible way to `gzip` some data with an arbitrary timestamp from Python?
Yeah, you don't have any pretty options. The time is written with this line in \_write\_gzip\_header: ``` write32u(self.fileobj, long(time.time())) ``` Since they don't give you a way to override the time, you can do one of these things: 1. Derive a class from GzipFile, and copy the `_write_gzip_header` function into your derived class, but with a different value in this one line. 2. After importing the gzip module, assign new code to its time member. You will essentially be providing a new definition of the name time in the gzip code, so you can change what time.time() means. 3. Copy the entire gzip module, and name it my\_stable\_gzip, and change the line you need to. 4. Pass a CStringIO object in as fileobj, and modify the bytestream after gzip is done. 5. Write a fake file object that keeps track of the bytes written, and passes everything through to a real file, except for the bytes for the timestamp, which you write yourself. Here's an example of option #2 (untested): ``` class FakeTime: def time(self): return 1225856967.109 import gzip gzip.time = FakeTime() # Now call gzip, it will think time doesn't change! ``` Option #5 may be the cleanest in terms of not depending on the internals of the gzip module (untested): ``` class GzipTimeFixingFile: def __init__(self, realfile): self.realfile = realfile self.pos = 0 def write(self, bytes): if self.pos == 4 and len(bytes) == 4: self.realfile.write("XYZY") # Fake time goes here. else: self.realfile.write(bytes) self.pos += len(bytes) ```
Python - one variable equals another variable when it shouldn't
264,575
5
2008-11-05T07:54:08Z
264,592
30
2008-11-05T08:13:16Z
[ "python", "variables" ]
Here is my sample code. It is meant to be an iterative procedure for gauss seidel (matrix solver). Essentially when the error is small enough it breaks out of the while loop. ``` i=1 while (i>0): x_past = x_present j=0 while(j<3): value=0 k=0 while(k<3): if(k!=j): if(i==1): if(k>j): value=value+0 else: value=value+x_present[k]*eqn[j][k] else: value=value+x_present[k]*eqn[j][k] else: value=value+eqn[j][k] k=k+1 x_present[j:j+1]=[value] j=j+1 print "X_PAST" print x_past print "X_PRESENT" print x_present if(error(x_past, x_present)<10**-2): break; i=i+1 ``` I've reduced the code so its more manageable. if you don't understand what its doing its not really that important to solving this problem. Here is the issue. Everytime ``` x_present[j:j+1]=[value] ``` is run, x\_past is made equal to x\_present. I don't know why this is the case as the only place i have set x\_past equal to x\_present is at the top of the loop. If I take away the ``` x_past=x_present ``` sentence, x\_past is never made equal to x\_present. This leads me to think it is some combination of the two statements that is causing the issue. This is a big problem cause if x\_past = x\_present the error = 0 every time and the loop breaks after the first iteration. The code does work, for example if I tell the code to run for 8 iterations and the break it gives me the answer its supposed to. I've been trying to figure this out for the last 4 hours and am completely stumped. I haven't been working with python long, so my trouble shooting skills syntax wise aren't that great. Any help would be appreciated!!
Yes, I think the answers here show your problem. Just to try and clarify a little bit. You're referencing a list, so when the list changes any reference to that list will reflect that change. To demonstrate: ``` >>> x_present = [4,5,6] >>> >>> x_past = x_present >>> >>> x_past [4, 5, 6] >>> >>> x_present.append(7) >>> >>> x_past [4, 5, 6, 7] >>> ``` If you want a copy of the list you have to do do this, **listcopy = mylist[:]**. ``` >>> x_past = x_present[:] >>> x_past [4, 5, 6, 7] >>> >>> x_present.append(8) >>> >>> x_past [4, 5, 6, 7] ```
Why the Global Interpreter Lock?
265,687
70
2008-11-05T16:23:48Z
265,731
27
2008-11-05T16:32:37Z
[ "python", "multithreading", "scripting", "locking", "bytecode" ]
What is exactly the function of Python's Global Interpreter Lock? Do other languages that are compiled to bytecode employ a similar mechanism?
The following is from the [official Python/C API Reference Manual](http://www.python.org/doc/2.5.2/api/threads.html): > The Python interpreter is not fully > thread safe. In order to support > multi-threaded Python programs, > there's a global lock that must be > held by the current thread before it > can safely access Python objects. > Without the lock, even the simplest > operations could cause problems in a > multi-threaded program: for example, > when two threads simultaneously > increment the reference count of the > same object, the reference count could > end up being incremented only once > instead of twice. > > Therefore, the rule exists that only > the thread that has acquired the > global interpreter lock may operate on > Python objects or call Python/C API > functions. In order to support > multi-threaded Python programs, the > interpreter regularly releases and > reacquires the lock -- by default, > every 100 bytecode instructions (this > can be changed with > sys.setcheckinterval()). The lock is > also released and reacquired around > potentially blocking I/O operations > like reading or writing a file, so > that other threads can run while the > thread that requests the I/O is > waiting for the I/O operation to > complete. I think it sums up the issue pretty well.
Why the Global Interpreter Lock?
265,687
70
2008-11-05T16:23:48Z
265,733
16
2008-11-05T16:32:50Z
[ "python", "multithreading", "scripting", "locking", "bytecode" ]
What is exactly the function of Python's Global Interpreter Lock? Do other languages that are compiled to bytecode employ a similar mechanism?
The global interpreter lock is a big mutex-type lock that protects reference counters from getting hosed. If you are writing pure python code, this all happens behind the scenes, but if you embedding Python into C, then you might have to explicitly take/release the lock. This mechanism is not related to Python being compiled to bytecode. It's not needed for Java. In fact, it's not even needed for [Jython](http://www.jython.org/) (python compiled to jvm). see also [this question](http://stackoverflow.com/questions/105095/are-locks-unnecessary-in-multi-threaded-python-code-because-of-the-gil)
Why the Global Interpreter Lock?
265,687
70
2008-11-05T16:23:48Z
265,795
56
2008-11-05T16:44:11Z
[ "python", "multithreading", "scripting", "locking", "bytecode" ]
What is exactly the function of Python's Global Interpreter Lock? Do other languages that are compiled to bytecode employ a similar mechanism?
In general, for any thread safety problem you will need to protect your internal data structures with locks. This can be done with various levels of granularity. * You can use fine-grained locking, where every separate structure has its own lock. * You can use coarse-grained locking where one lock protects everything (the GIL approach). There are various pros and cons of each method. Fine-grained locking allows greater parallelism - two threads can execute in parallel when they don't share any resources. However there is a much larger administrative overhead. For every line of code, you may need to acquire and release several locks. The coarse grained approach is the opposite. Two threads can't run at the same time, but an individual thread will run faster because its not doing so much bookkeeping. Ultimately it comes down to a tradeoff between single-threaded speed and parallelism. There have been a few attempts to remove the GIL in python, but the extra overhead for single threaded machines was generally too large. Some cases can actually be slower even on multi-processor machines due to lock contention. > Do other languages that are compiled to bytecode employ a similar mechanism? It varies, and it probably shouldn't be considered a language property so much as an implementation property. For instance, there are Python implementations such as Jython and IronPython which use the threading approach of their underlying VM, rather than a GIL approach. Additionally, the next version of Ruby looks to be moving [towards](http://www.infoq.com/news/2007/05/ruby-threading-futures) introducing a GIL.
Why the Global Interpreter Lock?
265,687
70
2008-11-05T16:23:48Z
266,111
10
2008-11-05T18:18:32Z
[ "python", "multithreading", "scripting", "locking", "bytecode" ]
What is exactly the function of Python's Global Interpreter Lock? Do other languages that are compiled to bytecode employ a similar mechanism?
Python, like perl 5, was not designed from the ground up to be thread safe. Threads were grafted on after the fact, so the global interpreter lock is used to maintain mutual exclusion to where only one thread is executing code at a given time in the bowels of the interpreter. Individual Python threads are cooperatively multitasked by the interpreter itself by cycling the lock every so often. Grabbing the lock yourself is needed when you are talking to Python from C when other Python threads are active to 'opt in' to this protocol and make sure that nothing unsafe happens behind your back. Other systems that have a single-threaded heritage that later evolved into mulithreaded systems often have some mechanism of this sort. For instance, the Linux kernel has the "Big Kernel Lock" from its early SMP days. Gradually over time as multi-threading performance becomes an issue there is a tendency to try to break these sorts of locks up into smaller pieces or replace them with lock-free algorithms and data structures where possible to maximize throughput.
HTTP Request Timeout
265,720
2
2008-11-05T16:30:22Z
265,741
9
2008-11-05T16:34:28Z
[ "python", "http" ]
In Python 2.6, a new "timeout" parameter was added to the httplib.HTTPConnection class: <http://docs.python.org/library/httplib.html#httplib.HTTPConnection> However, this is only a timeout for the connection to a server. I am looking to set a timeout value for the **request**, not the connection. This doesn't seem to be supported by httplib. Is there any way to emulate this behavior?
You can set a global socket timeout (\*): ``` import socket timeout = 10 socket.setdefaulttimeout(timeout) ``` --- (\*) **EDIT**: As people in the comments correctly point out: This is technically true, but it only has predictable results for tasks that involve a single socket operation. An HTTP request consists of multiple socket operations (e.g. DNS requests or other things that might be abstracted away from an HTTP client). The timeout of the overall operation becomes unpredictable because of that.
HTTP Request Timeout
265,720
2
2008-11-05T16:30:22Z
268,174
7
2008-11-06T10:09:21Z
[ "python", "http" ]
In Python 2.6, a new "timeout" parameter was added to the httplib.HTTPConnection class: <http://docs.python.org/library/httplib.html#httplib.HTTPConnection> However, this is only a timeout for the connection to a server. I am looking to set a timeout value for the **request**, not the connection. This doesn't seem to be supported by httplib. Is there any way to emulate this behavior?
No, there isn't. It's because the [HTTP spec](http://www.greenbytes.de/tech/webdav/rfc2616.html) does not provide anything for the client to specify time-to-live information with a HTTP request. You can do this only on TCP level, as you mentioned. On the other hand, the server may inform the client about timeout situations with HTTP status codes [408 Request Timeout](http://www.greenbytes.de/tech/webdav/rfc2616.html#status.408) resp. [504 Gateway Timeout](http://www.greenbytes.de/tech/webdav/rfc2616.html#status.504).
Best way to strip punctuation from a string in Python
265,960
282
2008-11-05T17:30:32Z
265,995
16
2008-11-05T17:39:55Z
[ "python", "string", "punctuation" ]
It seems like there should be a simpler way than: ``` import string s = "string. With. Punctuation?" # Sample string out = s.translate(string.maketrans("",""), string.punctuation) ``` Is there?
Not necessarily simpler, but a different way, if you are more familiar with the re family. ``` import re, string s = "string. With. Punctuation?" # Sample string out = re.sub('[%s]' % re.escape(string.punctuation), '', s) ```
Best way to strip punctuation from a string in Python
265,960
282
2008-11-05T17:30:32Z
266,000
20
2008-11-05T17:41:27Z
[ "python", "string", "punctuation" ]
It seems like there should be a simpler way than: ``` import string s = "string. With. Punctuation?" # Sample string out = s.translate(string.maketrans("",""), string.punctuation) ``` Is there?
I usually use something like this: ``` >>> s = "string. With. Punctuation?" # Sample string >>> import string >>> for c in string.punctuation: ... s= s.replace(c,"") ... >>> s 'string With Punctuation' ```
Best way to strip punctuation from a string in Python
265,960
282
2008-11-05T17:30:32Z
266,162
383
2008-11-05T18:36:11Z
[ "python", "string", "punctuation" ]
It seems like there should be a simpler way than: ``` import string s = "string. With. Punctuation?" # Sample string out = s.translate(string.maketrans("",""), string.punctuation) ``` Is there?
From an efficiency perspective, you're not going to beat translate() - it's performing raw string operations in C with a lookup table - there's not much that will beat that but writing your own C code. If speed isn't a worry, another option though is: ``` exclude = set(string.punctuation) s = ''.join(ch for ch in s if ch not in exclude) ``` This is faster than s.replace with each char, but won't perform as well as non-pure python approaches such as regexes or string.translate, as you can see from the below timings. For this type of problem, doing it at as low a level as possible pays off. Timing code: ``` import re, string, timeit s = "string. With. Punctuation" exclude = set(string.punctuation) table = string.maketrans("","") regex = re.compile('[%s]' % re.escape(string.punctuation)) def test_set(s): return ''.join(ch for ch in s if ch not in exclude) def test_re(s): # From Vinko's solution, with fix. return regex.sub('', s) def test_trans(s): return s.translate(table, string.punctuation) def test_repl(s): # From S.Lott's solution for c in string.punctuation: s=s.replace(c,"") return s print "sets :",timeit.Timer('f(s)', 'from __main__ import s,test_set as f').timeit(1000000) print "regex :",timeit.Timer('f(s)', 'from __main__ import s,test_re as f').timeit(1000000) print "translate :",timeit.Timer('f(s)', 'from __main__ import s,test_trans as f').timeit(1000000) print "replace :",timeit.Timer('f(s)', 'from __main__ import s,test_repl as f').timeit(1000000) ``` This gives the following results: ``` sets : 19.8566138744 regex : 6.86155414581 translate : 2.12455511093 replace : 28.4436721802 ```
Best way to strip punctuation from a string in Python
265,960
282
2008-11-05T17:30:32Z
2,402,306
39
2010-03-08T15:19:09Z
[ "python", "string", "punctuation" ]
It seems like there should be a simpler way than: ``` import string s = "string. With. Punctuation?" # Sample string out = s.translate(string.maketrans("",""), string.punctuation) ``` Is there?
``` myString.translate(None, string.punctuation) ```
Best way to strip punctuation from a string in Python
265,960
282
2008-11-05T17:30:32Z
7,268,456
12
2011-09-01T09:29:45Z
[ "python", "string", "punctuation" ]
It seems like there should be a simpler way than: ``` import string s = "string. With. Punctuation?" # Sample string out = s.translate(string.maketrans("",""), string.punctuation) ``` Is there?
string.punctuation is ascii ONLY! A more correct (but also much slower) way is to use the unicodedata module: ``` # -*- coding: utf-8 -*- from unicodedata import category s = u'String — with - «punctation »...' s = ''.join(ch for ch in s if category(ch)[0] != 'P') print 'stripped', s ```
Best way to strip punctuation from a string in Python
265,960
282
2008-11-05T17:30:32Z
16,799,238
27
2013-05-28T18:47:47Z
[ "python", "string", "punctuation" ]
It seems like there should be a simpler way than: ``` import string s = "string. With. Punctuation?" # Sample string out = s.translate(string.maketrans("",""), string.punctuation) ``` Is there?
Regular expressions are simple enough, if you know them. ``` import re s = "string. With. Punctuation?" s = re.sub(r'[^\w\s]','',s) ```
Python: Check if uploaded file is jpg
266,648
15
2008-11-05T21:00:36Z
266,731
36
2008-11-05T21:17:54Z
[ "python", "google-app-engine", "image", "image-processing", "mime" ]
How can I check if a file uploaded by a user is a real jpg file in Python (Google App Engine)? This is how far I got by now: Script receives image via HTML Form Post and is processed by the following code ``` ... incomming_image = self.request.get("img") image = db.Blob(incomming_image) ... ``` I found mimetypes.guess\_type, but it does not work for me.
If you need more than looking at extension, one way would be to read the JPEG header, and check that it matches valid data. The format for this is: ``` Start Marker | JFIF Marker | Header Length | Identifier 0xff, 0xd8 | 0xff, 0xe0 | 2-bytes | "JFIF\0" ``` so a quick recogniser would be: ``` def is_jpg(filename): data = open(filename,'rb').read(11) if data[:4] != '\xff\xd8\xff\xe0': return False if data[6:] != 'JFIF\0': return False return True ``` However this won't catch any bad data in the body. If you want a more robust check, you could try loading it with [PIL](http://www.pythonware.com/products/pil/). eg: ``` from PIL import Image def is_jpg(filename): try: i=Image.open(filename) return i.format =='JPEG' except IOError: return False ```
Python: Check if uploaded file is jpg
266,648
15
2008-11-05T21:00:36Z
1,040,027
32
2009-06-24T18:18:02Z
[ "python", "google-app-engine", "image", "image-processing", "mime" ]
How can I check if a file uploaded by a user is a real jpg file in Python (Google App Engine)? This is how far I got by now: Script receives image via HTML Form Post and is processed by the following code ``` ... incomming_image = self.request.get("img") image = db.Blob(incomming_image) ... ``` I found mimetypes.guess\_type, but it does not work for me.
No need to use and install the PIL lybrary for this, there is the imghdr standard module exactly fited for this sort of usage. See <http://docs.python.org/library/imghdr.html> ``` import imghdr image_type = imghdr.what(filename) if not image_type: print "error" else: print image_type ``` As you have an image from a stream you may use the stream option probably like this : ``` image_type = imghdr.what(filename, incomming_image) ``` --- Actualy this works for me in Pylons (even if i have not finished everything) : in the Mako template : ``` ${h.form(h.url_for(action="save_image"), multipart=True)} Upload file: ${h.file("upload_file")} <br /> ${h.submit("Submit", "Submit")} ${h.end_form()} ``` in the upload controler : ``` def save_image(self): upload_file = request.POST["upload_file"] image_type = imghdr.what(upload_file.filename, upload_file.value) if not image_type: return "error" else: return image_type ```
How do I treat an ASCII string as unicode and unescape the escaped characters in it in python?
267,436
20
2008-11-06T01:55:40Z
267,475
36
2008-11-06T02:26:05Z
[ "python", "unicode", "ascii" ]
For example, if I have a *unicode* string, I can encode it as an *ASCII* string like so: ``` >>> u'\u003cfoo/\u003e'.encode('ascii') '<foo/>' ``` However, I have e.g. this *ASCII* string: ``` '\u003foo\u003e' ``` ... that I want to turn into the same *ASCII* string as in my first example above: ``` '<foo/>' ```
It took me a while to figure this one out, but [this page](http://www.egenix.com/www2002/python/unicode-proposal.txt) had the best answer: ``` >>> s = '\u003cfoo/\u003e' >>> s.decode( 'unicode-escape' ) u'<foo/>' >>> s.decode( 'unicode-escape' ).encode( 'ascii' ) '<foo/>' ``` There's also a 'raw-unicode-escape' codec to handle the other way to specify Unicode strings -- check the "Unicode Constructors" section of the linked page for more details (since I'm not that Unicode-saavy). EDIT: See also [Python Standard Encodings](http://www.python.org/doc/2.5.2/lib/standard-encodings.html).
Install MySQLdb (for python) as non-compressed egg
268,025
4
2008-11-06T09:15:21Z
268,101
7
2008-11-06T09:44:54Z
[ "python", "install", "mysql", "egg" ]
The install instructions are: ``` $ python setup.py build $ sudo python setup.py install # or su first ``` This gives me an .egg file. How do I tell the install to dump the files as a normal, uncompressed library? Thanks!
OK, I hate to answer my own question, but: find your python site-packages (mine is /usr/local/lib/python2.5/site-packages ) then: ``` $ unzip MySQL_python-1.2.2-py2.5-linux-i686.egg ``` This worked fine for me
Multiple database support in django
268,089
9
2008-11-06T09:39:20Z
1,836,058
9
2009-12-02T21:49:37Z
[ "python", "django", "database-connection" ]
From some forum I came to know that Multiple database support is added in Django at lower level, but the higher level apis are not added yet. Can anyone please tell me how one can achieve multiple database connections in Django. Does anyone have any idea by when Django will fully/officially support Multiple database connections.
If you simply need multiple connections, you can do something like this: ``` from django.db import load_backend myBackend = load_backend('postgresql_psycopg2') # or 'mysql', 'sqlite3', 'oracle' myConnection = myBackend.DatabaseWrapper({ 'DATABASE_HOST': '192.168.1.1', 'DATABASE_NAME': 'my_database', 'DATABASE_OPTIONS': {}, 'DATABASE_PASSWORD': "", 'DATABASE_PORT': "", 'DATABASE_USER': "my_user", 'TIME_ZONE': "America/New_York",}) # Now we can do all the standard raw sql stuff with myConnection. myCursor = myConnection.cursor() myCursor.execute("SELECT COUNT(1) FROM my_table;") myCursor.fetchone() ```
Getting key with maximum value in dictionary?
268,272
302
2008-11-06T10:49:58Z
268,285
253
2008-11-06T10:58:45Z
[ "python", "dictionary", "max" ]
I have a `dictionary`: keys are strings, values are integers. Example: ``` stats = {'a':1000, 'b':3000, 'c': 100} ``` I'd like to get `'b'` as an answer, since it's the key with a higher value. I did the following, using an intermediate list with reversed key-value tuples: ``` inverse = [(value, key) for key, value in stats.items()] print max(inverse)[1] ``` Is that one the better (or even more elegant) approach?
You can use `operator.itemgetter` for that: ``` import operator stats = {'a':1000, 'b':3000, 'c': 100} max(stats.iteritems(), key=operator.itemgetter(1))[0] ``` And instead of building a new list in memory use `stats.iteritems()`. The `key` parameter to the `max()` function is a function that computes a key that is used to determine how to rank items. Please note that if you were to have another key-value pair 'd': 3000 that this method will only return **one** of the **two** even though they both have the maximum value. ``` >>> import operator >>> stats = {'a':1000, 'b':3000, 'c': 100, 'd':3000} >>> max(stats.iteritems(), key=operator.itemgetter(1))[0] 'b' ```
Getting key with maximum value in dictionary?
268,272
302
2008-11-06T10:49:58Z
268,350
24
2008-11-06T11:28:56Z
[ "python", "dictionary", "max" ]
I have a `dictionary`: keys are strings, values are integers. Example: ``` stats = {'a':1000, 'b':3000, 'c': 100} ``` I'd like to get `'b'` as an answer, since it's the key with a higher value. I did the following, using an intermediate list with reversed key-value tuples: ``` inverse = [(value, key) for key, value in stats.items()] print max(inverse)[1] ``` Is that one the better (or even more elegant) approach?
Here is another one: ``` stats = {'a':1000, 'b':3000, 'c': 100} max(stats.iterkeys(), key=lambda k: stats[k]) ``` The function `key` simply returns the value that should be used for ranking and `max()` returns the demanded element right away.
Getting key with maximum value in dictionary?
268,272
302
2008-11-06T10:49:58Z
272,269
18
2008-11-07T14:41:33Z
[ "python", "dictionary", "max" ]
I have a `dictionary`: keys are strings, values are integers. Example: ``` stats = {'a':1000, 'b':3000, 'c': 100} ``` I'd like to get `'b'` as an answer, since it's the key with a higher value. I did the following, using an intermediate list with reversed key-value tuples: ``` inverse = [(value, key) for key, value in stats.items()] print max(inverse)[1] ``` Is that one the better (or even more elegant) approach?
``` key, value = max(stats.iteritems(), key=lambda x:x[1]) ``` If you don't care about value (I'd be surprised, but) you can do: ``` key, _ = max(stats.iteritems(), key=lambda x:x[1]) ``` I like the tuple unpacking better than a [0] subscript at the end of the expression. I never like the readability of lambda expressions very much, but find this one better than the operator.itemgetter(1) IMHO.
Getting key with maximum value in dictionary?
268,272
302
2008-11-06T10:49:58Z
280,156
299
2008-11-11T06:24:30Z
[ "python", "dictionary", "max" ]
I have a `dictionary`: keys are strings, values are integers. Example: ``` stats = {'a':1000, 'b':3000, 'c': 100} ``` I'd like to get `'b'` as an answer, since it's the key with a higher value. I did the following, using an intermediate list with reversed key-value tuples: ``` inverse = [(value, key) for key, value in stats.items()] print max(inverse)[1] ``` Is that one the better (or even more elegant) approach?
``` max(stats, key=stats.get) ```
Getting key with maximum value in dictionary?
268,272
302
2008-11-06T10:49:58Z
12,343,826
104
2012-09-09T23:30:37Z
[ "python", "dictionary", "max" ]
I have a `dictionary`: keys are strings, values are integers. Example: ``` stats = {'a':1000, 'b':3000, 'c': 100} ``` I'd like to get `'b'` as an answer, since it's the key with a higher value. I did the following, using an intermediate list with reversed key-value tuples: ``` inverse = [(value, key) for key, value in stats.items()] print max(inverse)[1] ``` Is that one the better (or even more elegant) approach?
I have tested MANY variants, and this is the fastest way to return the key of dict with the max value: ``` def keywithmaxval(d): """ a) create a list of the dict's keys and values; b) return the key with the max value""" v=list(d.values()) k=list(d.keys()) return k[v.index(max(v))] ``` To give you an idea, here are some candidate methods: ``` def f1(): v=list(d1.values()) k=list(d1.keys()) return k[v.index(max(v))] def f2(): d3={v:k for k,v in d1.items()} return d3[max(d3)] def f3(): return list(filter(lambda t: t[1]==max(d1.values()), d1.items()))[0][0] def f3b(): # same as f3 but remove the call to max from the lambda m=max(d1.values()) return list(filter(lambda t: t[1]==m, d1.items()))[0][0] def f4(): return [k for k,v in d1.items() if v==max(d1.values())][0] def f4b(): # same as f4 but remove the max from the comprehension m=max(d1.values()) return [k for k,v in d1.items() if v==m][0] def f5(): return max(d1.items(), key=operator.itemgetter(1))[0] def f6(): return max(d1,key=d1.get) def f7(): """ a) create a list of the dict's keys and values; b) return the key with the max value""" v=list(d1.values()) return list(d1.keys())[v.index(max(v))] def f8(): return max(d1, key=lambda k: d1[k]) tl=[f1,f2, f3b, f4b, f5, f6, f7, f8, f4,f3] cmpthese.cmpthese(tl,c=100) ``` The test dictionary: ``` d1={1: 1, 2: 2, 3: 8, 4: 3, 5: 6, 6: 9, 7: 17, 8: 4, 9: 20, 10: 7, 11: 15, 12: 10, 13: 10, 14: 18, 15: 18, 16: 5, 17: 13, 18: 21, 19: 21, 20: 8, 21: 8, 22: 16, 23: 16, 24: 11, 25: 24, 26: 11, 27: 112, 28: 19, 29: 19, 30: 19, 3077: 36, 32: 6, 33: 27, 34: 14, 35: 14, 36: 22, 4102: 39, 38: 22, 39: 35, 40: 9, 41: 110, 42: 9, 43: 30, 44: 17, 45: 17, 46: 17, 47: 105, 48: 12, 49: 25, 50: 25, 51: 25, 52: 12, 53: 12, 54: 113, 1079: 50, 56: 20, 57: 33, 58: 20, 59: 33, 60: 20, 61: 20, 62: 108, 63: 108, 64: 7, 65: 28, 66: 28, 67: 28, 68: 15, 69: 15, 70: 15, 71: 103, 72: 23, 73: 116, 74: 23, 75: 15, 76: 23, 77: 23, 78: 36, 79: 36, 80: 10, 81: 23, 82: 111, 83: 111, 84: 10, 85: 10, 86: 31, 87: 31, 88: 18, 89: 31, 90: 18, 91: 93, 92: 18, 93: 18, 94: 106, 95: 106, 96: 13, 9232: 35, 98: 26, 99: 26, 100: 26, 101: 26, 103: 88, 104: 13, 106: 13, 107: 101, 1132: 63, 2158: 51, 112: 21, 113: 13, 116: 21, 118: 34, 119: 34, 7288: 45, 121: 96, 122: 21, 124: 109, 125: 109, 128: 8, 1154: 32, 131: 29, 134: 29, 136: 16, 137: 91, 140: 16, 142: 104, 143: 104, 146: 117, 148: 24, 149: 24, 152: 24, 154: 24, 155: 86, 160: 11, 161: 99, 1186: 76, 3238: 49, 167: 68, 170: 11, 172: 32, 175: 81, 178: 32, 179: 32, 182: 94, 184: 19, 31: 107, 188: 107, 190: 107, 196: 27, 197: 27, 202: 27, 206: 89, 208: 14, 214: 102, 215: 102, 220: 115, 37: 22, 224: 22, 226: 14, 232: 22, 233: 84, 238: 35, 242: 97, 244: 22, 250: 110, 251: 66, 1276: 58, 256: 9, 2308: 33, 262: 30, 263: 79, 268: 30, 269: 30, 274: 92, 1300: 27, 280: 17, 283: 61, 286: 105, 292: 118, 296: 25, 298: 25, 304: 25, 310: 87, 1336: 71, 319: 56, 322: 100, 323: 100, 325: 25, 55: 113, 334: 69, 340: 12, 1367: 40, 350: 82, 358: 33, 364: 95, 376: 108, 377: 64, 2429: 46, 394: 28, 395: 77, 404: 28, 412: 90, 1438: 53, 425: 59, 430: 103, 1456: 97, 433: 28, 445: 72, 448: 23, 466: 85, 479: 54, 484: 98, 485: 98, 488: 23, 6154: 37, 502: 67, 4616: 34, 526: 80, 538: 31, 566: 62, 3644: 44, 577: 31, 97: 119, 592: 26, 593: 75, 1619: 48, 638: 57, 646: 101, 650: 26, 110: 114, 668: 70, 2734: 41, 700: 83, 1732: 30, 719: 52, 728: 96, 754: 65, 1780: 74, 4858: 47, 130: 29, 790: 78, 1822: 43, 2051: 38, 808: 29, 850: 60, 866: 29, 890: 73, 911: 42, 958: 55, 970: 99, 976: 24, 166: 112} ``` And the test results under Python 3.2: ``` rate/sec f4 f3 f3b f8 f5 f2 f4b f6 f7 f1 f4 454 -- -2.5% -96.9% -97.5% -98.6% -98.6% -98.7% -98.7% -98.9% -99.0% f3 466 2.6% -- -96.8% -97.4% -98.6% -98.6% -98.6% -98.7% -98.9% -99.0% f3b 14,715 3138.9% 3057.4% -- -18.6% -55.5% -56.0% -56.4% -58.3% -63.8% -68.4% f8 18,070 3877.3% 3777.3% 22.8% -- -45.4% -45.9% -46.5% -48.8% -55.5% -61.2% f5 33,091 7183.7% 7000.5% 124.9% 83.1% -- -1.0% -2.0% -6.3% -18.6% -29.0% f2 33,423 7256.8% 7071.8% 127.1% 85.0% 1.0% -- -1.0% -5.3% -17.7% -28.3% f4b 33,762 7331.4% 7144.6% 129.4% 86.8% 2.0% 1.0% -- -4.4% -16.9% -27.5% f6 35,300 7669.8% 7474.4% 139.9% 95.4% 6.7% 5.6% 4.6% -- -13.1% -24.2% f7 40,631 8843.2% 8618.3% 176.1% 124.9% 22.8% 21.6% 20.3% 15.1% -- -12.8% f1 46,598 10156.7% 9898.8% 216.7% 157.9% 40.8% 39.4% 38.0% 32.0% 14.7% -- ``` And under Python 2.7: ``` rate/sec f3 f4 f8 f3b f6 f5 f2 f4b f7 f1 f3 384 -- -2.6% -97.1% -97.2% -97.9% -97.9% -98.0% -98.2% -98.5% -99.2% f4 394 2.6% -- -97.0% -97.2% -97.8% -97.9% -98.0% -98.1% -98.5% -99.1% f8 13,079 3303.3% 3216.1% -- -5.6% -28.6% -29.9% -32.8% -38.3% -49.7% -71.2% f3b 13,852 3504.5% 3412.1% 5.9% -- -24.4% -25.8% -28.9% -34.6% -46.7% -69.5% f6 18,325 4668.4% 4546.2% 40.1% 32.3% -- -1.8% -5.9% -13.5% -29.5% -59.6% f5 18,664 4756.5% 4632.0% 42.7% 34.7% 1.8% -- -4.1% -11.9% -28.2% -58.8% f2 19,470 4966.4% 4836.5% 48.9% 40.6% 6.2% 4.3% -- -8.1% -25.1% -57.1% f4b 21,187 5413.0% 5271.7% 62.0% 52.9% 15.6% 13.5% 8.8% -- -18.5% -53.3% f7 26,002 6665.8% 6492.4% 98.8% 87.7% 41.9% 39.3% 33.5% 22.7% -- -42.7% f1 45,354 11701.5% 11399.0% 246.8% 227.4% 147.5% 143.0% 132.9% 114.1% 74.4% -- ``` You can see that `f1` is the fastest under Python 3.2 and 2.7 (or, more completely, `keywithmaxval` at the top of this post)