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 iterati... | 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 iterati... | 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 iterati... | 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 iterati... | ```
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.std... |
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 iterati... | 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 iterati... | 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 iterati... | 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'); p... |
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 iterati... | 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)
>>> ... | 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 d... | 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 ... |
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 d... | 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... |
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:
``... | 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 ob... | 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 ob... | 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 ob... | 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... |
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... | 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` w... |
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 li... | 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, r... |
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 dumpima... |
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) ==... |
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... |
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 compara... |
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... |
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 ... | 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 shoul... |
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.
Thi... | 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... |
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 inheri... | 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, r... |
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 al... | 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/t... |
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¶m2=123>
<http://www.domainname.com/images?IMAGE_ID=10>
<http://www.domainname.com/pagename?CONTENT_ITEM_ID=101¶m2=123>
<http://www.domainname.com/images?IMAGE_ID=11>
<http://w... | 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¶m2¶m3
```
How could I slice out:
```
http://www.domainname.com/page?CONTENT_ITEM_ID=1234
```
Sometimes there is more than two paramet... | 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('&... |
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 j... |
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"
las... | 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_han... |
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"
las... | ```
# 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 @ ... |
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"
las... | 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 exa... |
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"
las... | 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 se... |
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 d... | 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 d... | 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.mix... |
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 d... | 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 â... |
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... | 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 subdirector... |
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.... | 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 ... |
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.... | 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 com... |
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.... | "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 crimi... |
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.... | 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.... | 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'... |
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.... | 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/proje... |
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.... | # 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. T... |
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.... | 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 cl... |
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.... | 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.... | 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 enfor... |
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.... | 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... |
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.... | 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 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 ... |
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.... | ## 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... |
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.... | 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... |
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.... | 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
ïºå¼í »í¸í í´ïï°£ïºÚºí µ... |
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... | ```
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... | 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... | 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 i... |
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... | 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... | 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... |
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... | 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 initializ... | 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 wi... |
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 hav... | ```
[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 hav... | [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
... |
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 hav... | 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 al... |
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 hav... | 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] =... | 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 Datast... |
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> ... |
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... |
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... |
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
> improvem... |
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 ... | 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 int... |
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):
... | 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)
>>... |
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 acces... |
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 c... |
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 ... |
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 cooperativel... |
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 ... | 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... |
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 ... | 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 situ... |
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... |
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.gu... | 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(fi... |
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.gu... | 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 imag... |
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... |
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 ... | 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',
'DATAB... |
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, valu... | 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 u... |
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, valu... | 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, valu... | ```
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 expre... |
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, valu... | ```
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, valu... | 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))]
```
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.