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
Python: Generic getters and setters
10,149,344
11
2012-04-13T22:59:15Z
10,149,376
10
2012-04-13T23:04:03Z
[ "python" ]
**TL;DR: Having to define a unique set of getters and setters for each property()'d variable sucks. Can I define generic getters and setters and use them with whatever variable I want?** Let's say I make a class with some nice getters and setters: ``` class Foo def getter(self): return _bar+' sasquatch' ...
How about just: ``` def sasquatchicorn(name): return property(lambda self: getattr(self, name) + ' sasquatch', lambda self, val: setattr(self, name, val + ' unicorns')) class Foo(object): bar = sasquatchicorn('_bar') baz = sasquatchicorn('_baz') ``` Somewhat more generically: ``` def...
Numpy modify array in place?
10,149,416
15
2012-04-13T23:10:30Z
10,149,508
12
2012-04-13T23:20:58Z
[ "python", "arrays", "numpy", "in-place" ]
I have the following code which is attempting to normalize the values of an `m x n` array (It will be used as input to a neural network, where `m` is the number of training examples and `n` is the number of features). However, when I inspect the array in the interpreter after the script runs, I see that the values are...
If you want to apply mathematical operations to a numpy array in-place, you can simply use the standard in-place operators `+=`, `-=`, `/=`, etc. So for example: ``` >>> def foo(a): ... a += 10 ... >>> a = numpy.arange(10) >>> a array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> foo(a) >>> a array([10, 11, 12, 13, 14, 15,...
AND/OR in Python?
10,149,747
15
2012-04-13T23:51:29Z
10,149,868
15
2012-04-14T00:13:16Z
[ "python", "logic" ]
I know that the `and` and `or` expressions exist in python, but is there any `and/or` expression? Or some way to combine them in order to produce the same effect as a `and/or` expression? my code looks something like this: ``` if input=="a": if "a" or "á" or "à" or "ã" or "â" in someList: ...
As [Matt Ball](http://stackoverflow.com/a/10149756/577088)'s answer explains, `or` *is* "and/or". But `or` doesn't work with `in` the way you use it above. You have to say `if "a" in someList or "á" in someList or...`. Or better yet, ``` if any(c in someList for c in ("a", "á", "à", "ã", "â")): ... ``` Also,...
How do I post unicode characters using httplib?
10,149,961
8
2012-04-14T00:28:25Z
10,150,120
8
2012-04-14T00:58:46Z
[ "python", "unicode", "httplib" ]
I try to post unicode data with the `httplib.request` function: ``` s = u"עברית" data = """ <spellrequest textalreadyclipped="0" ignoredups="1" ignoredigits="1" ignoreallcaps="0"> <text>%s</text> </spellrequest> """ % s con = httplib.HTTPSConnection("www.google.com") con.request("POST", "/tbproxy/spell?lang=he",...
http is not defined in terms of a particular character encoding, and instead uses octets. You need to convert your data to an encoding, and then you need to tell the server which encoding you have used. Lets use utf8, since it's usually the best choice: This data looks a bit like XML, but you are skipping the xml tag....
Python reversing slice of a list
10,150,260
2
2012-04-14T01:29:38Z
10,150,278
7
2012-04-14T01:34:26Z
[ "python", "list" ]
How do I reversed or iterate a list using its index? Here is an example ``` lst = [3,2,4,1,5] ``` Output would be: `[3,2,4,5,1]` (index 3 which is 1 is place in the end) Another example: ``` lst = [1,5,4,2,3] ``` Output: `[1,5,4,3,2]` (index 3 which is 2 is place in the end) It is like the list is been reversed ...
If you want to reverse the part of a list past a certain point, the most straightforward way would be: ``` output = (lst[:3] # take the list before element 3 + # and add lst[3:] # the list from element 3 on [::-1] # reversed ) ``` or, without the comments: ``` output = lst[:3] ...
Printing Objects in Django
10,150,305
6
2012-04-14T01:42:20Z
10,150,323
9
2012-04-14T01:45:15Z
[ "python", "django" ]
So I've connected Django to a pre-existing database successfully (inspect, validate and sync) and I've created an app and a project and all that (I'm reading the Django book and I'm on chapter 5), but when I actually run it and print stuff, I get an (assumed) error. While in python, I properly import what I need (`from...
Django uses an ORM (Object-Relational Mapper) that translates data back and forth between Python objects and database rows. So when you use it to get an item from the database, it converts it into a Python object. If that object doesn't define how to display itself as text, Django does it for you. Python does the same...
Can't import Flask while using Google App Engine
10,151,294
2
2012-04-14T05:32:57Z
14,248,871
7
2013-01-10T00:24:18Z
[ "python", "google-app-engine", "flask" ]
I'm following [this guide](http://f.souza.cc/2010/08/flying-with-flask-on-google-app-engine/) and trying to develop a Flask app to run on the Google App Engine. I followed the guide to the letter but when I launch the dev app server from the Launcher and go to <http://localhost:8080/>, I get a HTTP 500 error. I check ...
Working a bit with GAE and Flask I have realized this: **Running directly with Python** To run the app with python directly (`python app.py`) you need have the dependents packages installed in your environment using the command: `pip install flask` **Running with dev\_appserver.py** To run the app with the dev\_app...
Change level of python fileConfig logger
10,151,698
3
2012-04-14T06:54:50Z
10,151,760
7
2012-04-14T07:05:55Z
[ "python", "logging" ]
I have a logger configured from a file and would like to change the level of my logging without having to change the .conf file, but instead using inline code; ``` import logging.config logging.config.fileConfig('..\\LoggingConfig\\loggingfile.conf') logging.StreamHandler.setLevel(logging.info) logging.debug("Debug...
You need to call `setLevel` on your `Logger` instance. ``` LOGGER = logging.getLogger('your.module.file.name') LOGGER.setLevel(_level) LOGGER.info('foo') ``` If you are only using the basic logger, you can do it like this ``` logging.basicConfig(level=_level) logging.info('foo') ``` See <http://docs.python.org/howt...
write better code instead of 2 for loops
10,151,847
15
2012-04-14T07:23:09Z
10,151,889
26
2012-04-14T07:30:48Z
[ "python", "list", "for-loop" ]
I have 2 for loops and I want to make it better like list comprehension or lambda or else. how can i achieve the same? for example : ``` filename = ['a.txt', 'b.txt', 'c.txt'] for files in filename: for f in glob.glob(os.path.join(source_path, files)): print f ... some processing... ```
Your code is perfectly fine as it is. You can only make it less legible by introducing unnecessary complex constructs.
How do I index the 3 highest values in a list?
10,152,131
2
2012-04-14T08:18:06Z
10,152,145
13
2012-04-14T08:21:33Z
[ "python" ]
so i have these 2 lists: ``` score = [350, 914, 569, 223, 947, 284, 567, 333, 697, 245, 227, 785, 120, 794, 343, 773, 293, 995] name = [Ryan, Stacy, Jenna, Peter, Sophie, Bryan, Cole, Andrea, Emily, Blake, Mike, Stephan, Rob, Eliza, Heather, Daniel, Elisabeth, Samantha] ``` I have to find the 3 highest scores and tal...
I think this will do it ``` sorted(zip(score, name), reverse=True)[:3] ``` So you understand what is going on: [zip](http://docs.python.org/library/functions.html#zip): takes iterables as it's arguments and takes on element from each iterable, placing them in a tuple. So: ``` >>> zip(score, name) [(350, 'Ryan'), (...
How do I index the 3 highest values in a list?
10,152,131
2
2012-04-14T08:18:06Z
10,152,186
10
2012-04-14T08:28:21Z
[ "python" ]
so i have these 2 lists: ``` score = [350, 914, 569, 223, 947, 284, 567, 333, 697, 245, 227, 785, 120, 794, 343, 773, 293, 995] name = [Ryan, Stacy, Jenna, Peter, Sophie, Bryan, Cole, Andrea, Emily, Blake, Mike, Stephan, Rob, Eliza, Heather, Daniel, Elisabeth, Samantha] ``` I have to find the 3 highest scores and tal...
If you're only interested on the top 3, there's[`heapq.nlargest`](http://docs.python.org/py3k/library/heapq.html#heapq.nlargest): ``` >>> heapq.nlargest(3, zip(score, name)) [(995, 'Samantha'), (947, 'Sophie'), (914, 'Stacy')] ``` From the [official doc](http://docs.python.org/py3k/library/heapq.html#heapq.nlargest):...
Django ORM, group by day
10,154,227
18
2012-04-14T14:00:02Z
10,154,412
23
2012-04-14T14:38:37Z
[ "python", "mysql", "django", "django-orm" ]
I am trying to group products by DAY, however date\_created is a datetime field. ``` Product.objects.values('date_created') \ .annotate(available=Count('available_quantity')) ``` returns: ``` [ {'date_created': datetime.datetime(2012, 4, 14, 13, 3, 6), 'available': 1}, {'date_created': datetim...
Inspired by [this question](http://stackoverflow.com/questions/3543379/django-annotate-groupings-by-month) try this for mysql ``` Product.objects.extra(select={'day': 'date( date_created )'}).values('day') \ .annotate(available=Count('date_created')) ```
Use BeautifulSoup to extract text before the first child tag
10,154,289
5
2012-04-14T14:08:30Z
10,154,518
9
2012-04-14T14:53:28Z
[ "python", "beautifulsoup" ]
From this html source: ``` <div class="category_link"> Category: <a href="/category/personal">Personal</a> </div> ``` I wish to extract the text `Category:` Here are my attempts using Python/BeautifulSoup (with output as comment - after the #) ``` parsed = BeautifulSoup(sample_html) parsed_div = parsed.findAll(...
I'm fairly sure the following should do what you want ``` parsed.find('a').previousSibling # or something like that ``` That would return a `NavigableString` instance which is pretty much the same thing as a `unicode` instance, but you may call `unicode` on that to get a unicode object. I'll see if I can test this o...
Postpone code for later execution in python (like setTimeout in javascript)
10,154,568
8
2012-04-14T15:01:00Z
10,154,915
7
2012-04-14T15:45:33Z
[ "python" ]
I have to do a program in python that needs to execute for some time and then (does not matter where it was executing) it must dump information to a file, close the file and then exit. The behavior here is equivalent in JavaScript to using `setTimeout(func, 1000000)` where its first parameter (func) would be a pointer...
You can use signals in python as well (unix only) ``` import signal, sys # install a SIGALRM handler def handler(signum, frame): print "got signal, exiting" sys.exit(1) signal.signal(signal.SIGALRM, handler) # emit SIGALRM after 5 secs signal.setitimer(signal.ITIMER_REAL, 5) # do stuff i = 1 while True...
Postpone code for later execution in python (like setTimeout in javascript)
10,154,568
8
2012-04-14T15:01:00Z
15,456,828
18
2013-03-17T02:02:43Z
[ "python" ]
I have to do a program in python that needs to execute for some time and then (does not matter where it was executing) it must dump information to a file, close the file and then exit. The behavior here is equivalent in JavaScript to using `setTimeout(func, 1000000)` where its first parameter (func) would be a pointer...
In practice, a [Timer](http://docs.python.org/2/library/threading.html#timer-objects) is probably the simplest way to do what you want. This code will do the following: * After 1 second, it prints "arg1 arg2" * After 2 seconds, it prints "OWLS OWLS OWLS" === ``` from threading import Timer def twoArgs(arg1,arg2): ...
Load CSV data into MySQL in Python
10,154,633
17
2012-04-14T15:09:17Z
10,154,650
36
2012-04-14T15:11:44Z
[ "python", "mysql" ]
Not sure what I'm missing here but this code runs without any error message, but there's nothing in the table. I'm loading a CSV values in three columns into mysql table ``` import csv import MySQLdb mydb = MySQLdb.connect(host='localhost', user='root', passwd='', db='mydb') cursor = mydb.cursor() csv_da...
I think you have to do `mydb.commit()` all the insert into. Something like this ``` import csv import MySQLdb mydb = MySQLdb.connect(host='localhost', user='root', passwd='', db='mydb') cursor = mydb.cursor() csv_data = csv.reader(file('students.csv')) for row in csv_data: cursor.execute('INSERT IN...
Constrained Linear Regression in Python
10,154,922
12
2012-04-14T15:46:11Z
10,154,976
7
2012-04-14T15:53:34Z
[ "python", "numpy", "scipy", "mathematical-optimization", "linear-regression" ]
I have a [classic linear](http://en.wikipedia.org/wiki/Linear_regression) regression problem of the form: `y = X b` where `y` is a *response vector* `X` is a *matrix* of input variables and `b` is the vector of fit parameters I am searching for. Python provides `b = numpy.linalg.lstsq( X , y )` for solving problems ...
Have a look at: <http://scipy-central.org/item/17/3/pymls-solving-bounded-linear-least-squares-problems> Also Openopt has bindings to bvls, another bounded linear lsq solver. Edit: You could also try if [scipy.optimize.nnls](http://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.optimize.nnls.html) is enoug...
Constrained Linear Regression in Python
10,154,922
12
2012-04-14T15:46:11Z
10,814,871
8
2012-05-30T10:55:41Z
[ "python", "numpy", "scipy", "mathematical-optimization", "linear-regression" ]
I have a [classic linear](http://en.wikipedia.org/wiki/Linear_regression) regression problem of the form: `y = X b` where `y` is a *response vector* `X` is a *matrix* of input variables and `b` is the vector of fit parameters I am searching for. Python provides `b = numpy.linalg.lstsq( X , y )` for solving problems ...
You mention you would find Lasso Regression or Ridge Regression acceptable. These and many other constrained linear models are available in the [scikit-learn](http://scikit-learn.org/) package. Check out the [section on generalized linear models](http://scikit-learn.org/dev/modules/classes.html#module-sklearn.linear_mo...
Add entry to list and remove first one in Python
10,155,684
2
2012-04-14T17:22:38Z
10,155,734
9
2012-04-14T17:28:09Z
[ "python", "list", "append" ]
I have a `list` of about 40 entries. And I frequently want to append an item to the start of the list (with id 0) and want to `delete` the `last` entry (with id 40) of the list. how do i do this the best? `like:` (example with 5 entries) ``` [0] = "herp" [1] = "derp" [2] = "blah" [3] = "what" [4]...
Use `insert()` to place an item at the beginning of the list: ``` myList.insert(0, "wuggah") ``` Use `pop()` to remove and return an item in the list. Pop with no arguments pops the last item in the list ``` myList.pop() #removes and returns "da..." ```
call python with system() in R to run a python script emulating the python console
10,155,703
9
2012-04-14T17:25:28Z
10,155,767
10
2012-04-14T17:30:58Z
[ "python" ]
I want to pass a chunk of Python code to Python in R with something like `system('python ...')`, and I'm wondering if there is an easy way to emulate the python console in this case. For example, suppose the code is `"print 'hello world'"`, how can I get the output like this in R? ``` >>> print 'hello world' hello wor...
Do you mean something like this? ``` export NUM=10 R -q -e "rnorm($NUM)" ``` You might also like to check out `littler` - <http://dirk.eddelbuettel.com/code/littler.html> **UPDATED** Following your comment below, I think I am beginning to understand your question better. You are asking about running python inside t...
What is the difference between slice assignment that slices the whole list and direct assignment?
10,155,951
12
2012-04-14T17:57:44Z
10,155,987
19
2012-04-14T18:02:33Z
[ "python", "list", "variable-assignment", "slice" ]
I see at many places the use of slice assignment for `list`s. I am able to understand its use when used with (non-default) indices, but I am not able to understand its use like: ``` a_list[:] = ['foo', 'bar'] ``` How is that different from ``` a_list = ['foo', 'bar'] ``` ?
``` a_list = ['foo', 'bar'] ``` Creates a new `list` in memory and points the name `a_list` at it. It is irrelevant what `a_list` pointed at before. ``` a_list[:] = ['foo', 'bar'] ``` Calls the [`__setitem__`](http://docs.python.org/reference/datamodel.html#object.__setitem__) method of the `a_list` object with a [`...
What is the difference between slice assignment that slices the whole list and direct assignment?
10,155,951
12
2012-04-14T17:57:44Z
10,156,007
7
2012-04-14T18:04:32Z
[ "python", "list", "variable-assignment", "slice" ]
I see at many places the use of slice assignment for `list`s. I am able to understand its use when used with (non-default) indices, but I am not able to understand its use like: ``` a_list[:] = ['foo', 'bar'] ``` How is that different from ``` a_list = ['foo', 'bar'] ``` ?
The difference is quite huge! In ``` a_list[:] = ['foo', 'bar'] ``` You modify a existing list that was bound to the name `a_list`. On the other hand, ``` a_list = ['foo', 'bar'] ``` assigns a new list to the name `a_list`. Maybe this will help: ``` a = a_list = ['foo', 'bar'] # another name for the same list a_l...
How do I detect if a file is encoded using UTF-8?
10,156,090
4
2012-04-14T18:16:07Z
10,156,116
12
2012-04-14T18:19:47Z
[ "python", "unicode", "utf-8", "character-encoding" ]
Is there a way to recognize if text file is UTF-8 in Python? I would really like to get if the file is UTF-8 or not. I don't need to detect other encodings.
You mentioned in a comment you only need to detect UTF-8. If you know the alternative consists of only single byte encodings, then there is a solution that often works. If you know it's either UTF-8 or single byte encoding like `latin-1`, then try opening it first in UTF-8 and then in the other encoding. If the file c...
IDLE won't highlight my syntax
10,156,386
4
2012-04-14T18:56:41Z
17,601,763
11
2013-07-11T19:27:45Z
[ "python", "syntax-highlighting", "python-idle" ]
Using IDLE and Python version 2.7.3. Only when I start a new file it highlights for a few lines and then just stops after I press F5. So all my text becomes plain black. If there are equally good/better command line and editor combinations out there, you may always suggest them.
This happened to me too. Save it as .py (manually type .py in the document name), and the highlighting will come back.
Python: Why do int.numerator and int.denominator exist?
10,156,777
15
2012-04-14T19:42:09Z
10,156,804
15
2012-04-14T19:45:24Z
[ "python", "math", "int" ]
`int.numerator` and `int.denominator` are a mystery to me. `help(int.numerator)` states: > the numerator of a rational number in lowest terms But as far as I know, `int` is not a rational number. So why do these properties exist?
See <http://docs.python.org/library/numbers.html> - int (`numbers.Integral`) is a subtype of `numbers.Rational`. ``` >>> import numbers >>> isinstance(1337, numbers.Integral) True >>> isinstance(1337, numbers.Rational) True >>> issubclass(numbers.Integral, numbers.Rational) True ``` The denominator of an int is alway...
Microsoft Outlook Create Rule Run Application/Script Python
10,156,795
10
2012-04-14T19:44:24Z
10,539,111
24
2012-05-10T17:17:39Z
[ "python", "outlook", "rule" ]
I have created a shutdown.py script that shuts down my computer when executed. I have also created a rule in Microsoft Outlook that executes my Python script when I receive an email that has %BLAHBLAHBLAH% in the subject. I have tested it out and it works flawlessly; however, my question for you all is: is it possible ...
Why creating a rule in outlook that runs a script if an email is received, when you can simply do it all from python. Using Python to monitor outlook for all incoming emails and then execute some code if an email, with %BLAHBLAH% in the subject, is received is possible. Here is an example: ``` import win32com.client ...
How can I use Bootstrap with Django?
10,157,059
24
2012-04-14T20:19:39Z
10,604,710
33
2012-05-15T16:08:26Z
[ "python", "django", "twitter-bootstrap" ]
I'm learning python and Django coming from PHP. This is all really exciting, and I would love to use Bootstrap with Django to create sexy web pages. As I understand it (I'm following the Django tutorial on their website), Django uses "apps" which can be included in your `settings.py` file. I did a quick search and fou...
Re-reading your question, it seems that you're searching for a way to install Twitter Bootstrap as a Django app. While there are some apps out there that facilitate using Twitter Bootstrap with Django, you don't really need to use any of them. You can simply include the Twitter Bootstrap CSS and JS at either the proje...
How do I get the visitor's current timezone then convert timezone.now() to string of the local time in Django 1.4?
10,157,720
4
2012-04-14T22:01:56Z
10,157,845
10
2012-04-14T22:23:08Z
[ "python", "django", "timezone" ]
I understand that the best practice now with Django 1.4 is to store all `datetime` in UTC and I agree with that. I also understand that all timezone conversation should be done in the template level like this: ``` {% load tz %} {% timezone "Europe/Paris" %} Paris time: {{ value }} {% endtimezone %} ``` However, ...
You need to read the [Django Timezones docs](https://docs.djangoproject.com/en/1.4/topics/i18n/timezones/) carefully. One important point: > there's no equivalent of the Accept-Language HTTP header that Django could use to determine the user's time zone automatically. You have to ask the user what their timezone is ...
how to put a image as a background in tkinter in python
10,158,552
5
2012-04-15T00:24:47Z
10,181,434
11
2012-04-16T20:45:22Z
[ "python", "tkinter" ]
``` #import statements from Tkinter import * import tkMessageBox import tkFont from PIL import ImageTk,Image ``` Code to import image: ``` app = Tk() app.title("Welcome") image2 =Image.open('C:\\Users\\adminp\\Desktop\\titlepage\\front.gif') image1 = ImageTk.PhotoImage(image2) w = image1.width() h = image1.height() a...
Use `place` to use an image as a background image. For example: ``` background_image=tk.PhotoImage(...) background_label = tk.Label(parent, image=background_image) background_label.place(x=0, y=0, relwidth=1, relheight=1) ``` You can then `grid` or `pack` other widgets in the parent as normal. Just make sure you crea...
Connecting to dbus over tcp
10,158,684
12
2012-04-15T00:52:25Z
13,275,973
17
2012-11-07T18:35:58Z
[ "python", "dbus" ]
I wrote a simple python program to play and pause banshee music player. While its working on my own machine, I have trouble doing it to a remote computer, connected to the same router (LAN). I edited the session.conf of the remote machine, to add this line: ``` <listen>tcp:host=localhost,port=12434</listen> ``` and h...
I recently needed to set this up, and discovered that the trick is: *order matters* for the `<listen>` elements in `session.conf`. You should make sure the TCP element occurs first. Bizarre, I know, but true, at least for my case. (I see *exactly* the same black screen behavior if I reverse the order and put the UNIX s...
Connecting to dbus over tcp
10,158,684
12
2012-04-15T00:52:25Z
20,012,176
7
2013-11-15T23:04:25Z
[ "python", "dbus" ]
I wrote a simple python program to play and pause banshee music player. While its working on my own machine, I have trouble doing it to a remote computer, connected to the same router (LAN). I edited the session.conf of the remote machine, to add this line: ``` <listen>tcp:host=localhost,port=12434</listen> ``` and h...
since dbus 1.6.12 (e.g. kubuntu 13.10), your connection will also be rejected unless you add to your dbus config file (either /etc/dbus-1/*mybus*.conf or the interface requiring remote access i.e. system.d/*my.interface.conf*) ``` <apparmor mode="disabled"/> ``` **UPDATE:** After struggling to create a apparmor profi...
How To Capture Output of Curl from Python script
10,158,701
9
2012-04-15T00:56:02Z
10,158,752
14
2012-04-15T01:02:50Z
[ "python" ]
I want to find the info about a webpage using curl, but in Python, so far I have this: ``` os.system("curl --head www.google.com") ``` If I run that, it prints out: ``` HTTP/1.1 200 OK Date: Sun, 15 Apr 2012 00:50:13 GMT Expires: -1 Cache-Control: private, max-age=0 Content-Type: text/html; charset=ISO-8859-1 Set-Co...
Try this, using [`subprocess.Popen()`](http://docs.python.org/library/subprocess.html#popen-constructor): ``` import subprocess proc = subprocess.Popen(["curl", "--head", "www.google.com"], stdout=subprocess.PIPE) (out, err) = proc.communicate() print out ``` As stated in the [documentation](http://docs.python.org/li...
What's a good approach to managing the db connection in a Google Cloud SQL (GAE) Python app?
10,158,805
10
2012-04-15T01:13:01Z
10,438,622
8
2012-05-03T20:10:29Z
[ "python", "mysql", "google-app-engine", "webapp2", "google-cloud-sql" ]
I'm just learning Google App Engine and am trying to figure out a good approach to managing my database connection to a Google Cloud SQL instance (if you haven't used GC-SQL, basically, it's MySQL in the cloud, with a few limitations). I'm using the python (2.7) GAE environment with the webapp2 framework for handling ...
Here is a complete example of the helloworld example app from the [Getting Started Guide](https://developers.google.com/cloud-sql/docs/developers_guide_python). It is based on snippets from [Shay Erlichmen](http://stackoverflow.com/a/10162674/1373093) and [JJC](http://stackoverflow.com/questions/10424442), but this ver...
How to create a 2D "rect" array (square block of 1's, else 0's) in numpy?
10,159,178
3
2012-04-15T02:57:38Z
10,159,200
7
2012-04-15T03:04:27Z
[ "python", "arrays", "numpy", "rect" ]
What is the "correct" way of creating a 2D numpy "rect" array, like: ``` 0000000000000000000 0000000000000000000 0000000000111110000 0000000000111110000 0000000000111110000 0000000000000000000 ``` i.e. an array which has a given value inside certain bounds, or zero otherwise?
Just create an array of zeros and set the area you want to one. E.g. ``` import numpy as np data = np.zeros((6,18)) data[2:5, 9:14] = 1 print data ``` This yields: ``` [[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0....
App Engine, transactions, and idempotency
10,159,439
6
2012-04-15T04:14:53Z
13,392,006
12
2012-11-15T05:27:43Z
[ "python", "google-app-engine", "transactions" ]
Please help me find my misunderstanding. I am writing an RPG on App Engine. Certain actions the player takes consume a certain stat. If the stat reaches zero the player can take no more actions. I started worrying about cheating players, though -- what if a player sent two actions very quickly, right next to each othe...
First, Nick's answer is not correct. DHayes's transaction is not idempotent, so if it's run multiple times (ie. a retry when the first attempt was thought to have failed, when it didn't), then the value will have been decremented multiple times. Nick says that "the datastore checks if the entities have been modified si...
Import python module NOT on path
10,161,568
31
2012-04-15T11:21:00Z
10,161,654
51
2012-04-15T11:32:32Z
[ "python", "import", "external", "python-module" ]
I have a module foo, containing util.py and bar.py. I want to import it in IDLE or python session. How do I go about this? I could find no documentation on how to import modules not in the current directory or the default python PATH. After trying `import "<full path>/foo/util.py"`, and `from "<full path>" import uti...
One way is to simply amend your [path](http://docs.python.org/library/sys.html#sys.path): ``` import sys sys.path.append('C:/full/path') from foo import util,bar ``` Note that this requires foo to be a python package, i.e. contain a `__init__.py` file. If you don't want to modify `sys.path`, you can [also modify the ...
AppEngine id/key/from_path is quite confusing what should I use
10,162,510
4
2012-04-15T13:37:14Z
10,164,147
9
2012-04-15T17:02:23Z
[ "python", "google-app-engine", "python-2.7" ]
I am back into AppEngine development. And I am quite hang up with the Datastorage. I am used to "ids", building the website with links like "/view?id=322345" gets me the GuestBook entry with this id voilà. But in AppEngine I always see the db.Key.from\_path() method called and other stuff like "Ancestors" and "paren...
If you are using the numeric ids that are automatically assigned by the datastore when you `put` an entity, you can then retrieve the entity with the model's `get_by_id` method: ``` class User(db.Model): name = db.StringProperty() # etc. def AddUser(webapp2.RequestHandler): def get(self): newUser ...
Python: delete element from heap
10,162,679
18
2012-04-15T14:00:35Z
10,163,422
15
2012-04-15T15:35:11Z
[ "python", "heap" ]
Python has `heapq` module which implements heap data structure and it supports some basic operations (push, pop). How to remove i-th element from the heap in O(log n)? Is it even possible with `heapq` or do I have to use another module? Note, there is an example at the bottom of the documentation: <http://docs.python...
You can remove the i-th element from a heap quite easily: ``` h[i] = h[-1] h.pop() heapq.heapify(h) ``` Just replace the element you want to remove with the last element and remove the last element then re-heapify the heap. This is O(n), if you want you can do the same thing in O(log(n)) but you'll need to call a cou...
How to close IPython Notebook properly?
10,162,707
31
2012-04-15T14:04:10Z
10,162,738
29
2012-04-15T14:08:41Z
[ "python", "ipython", "ipython-notebook" ]
How to close IPython Notebook properly? Currently, I just close the browser tabs and then use `Ctrl+C` in the terminal. Unfortunately, neither `exit()` nor ticking `Kill kernel upon exit` does help (they do kill the kernel they but don't exit the iPython).
There isn't currently a better way to do it than Ctrl+C in the terminal. We're thinking about how to have an explicit shutdown, but there's some tension between the notebook as a single-user application, where the user is free to stop it, and as a multi-user server, where only an admin should be able to stop it. We ha...
How to close IPython Notebook properly?
10,162,707
31
2012-04-15T14:04:10Z
32,745,046
7
2015-09-23T16:43:22Z
[ "python", "ipython", "ipython-notebook" ]
How to close IPython Notebook properly? Currently, I just close the browser tabs and then use `Ctrl+C` in the terminal. Unfortunately, neither `exit()` nor ticking `Kill kernel upon exit` does help (they do kill the kernel they but don't exit the iPython).
If you run jupyter in the background like me: ``` jupyter notebook &> /dev/null & ``` Then to exit jupyter completely, instead of Ctl-C, make an alias command: ``` echo 'alias quitjupyter="kill $(pgrep jupyter)"' >> ~/.bashrc ``` Restart your terminal. Kill all jupyter instances: ``` quitjupyter ``` Note: use dou...
Regular expression to match function name and all arguments in Python
10,164,137
3
2012-04-15T17:01:39Z
10,164,287
7
2012-04-15T17:21:58Z
[ "python", "regex" ]
Suppose I have a string such as the following: ``` "func(arg1, arg2, arg3, arg4, ..., argn)" ``` EDIT: This function is not in some particular language. It just has this format. If it makes it easier, don't think of it as a function call, just a string. I want to write a regular expression to match the function and ...
Regular expressions cannot parse complex programming languages. If you're just trying to parse Python, I suggest taking a look at the [ast](http://docs.python.org/library/ast.html) module, which will parse it for you.
How do you count cardinality of very large datasets efficiently in Python?
10,164,608
16
2012-04-15T18:01:13Z
10,165,586
8
2012-04-15T20:03:04Z
[ "python", "optimization", "memcached", "set", "cardinality" ]
I have been playing at work with some very very large sets of data, typically several billions of elements, that are all maintained in a [memcached](http://memcached.org/) cloud and periodically dumped into files, and for one of my tasks I'm trying to count the cardinality of this set. For some context, each item cont...
I would recommend the usage of Hash Sketches, namely (Super)Log Log sketches or Hyper Log Sketches. You can check and perhaps use and improve the simple python implementation that I made: <https://github.com/goncalvesnelson/Log-Log-Sketch>
How do I get a regular expression to recognize non-ASCII characters as letters?
10,165,102
3
2012-04-15T19:02:41Z
10,165,314
7
2012-04-15T19:31:01Z
[ "python", "regex", "utf-8", "character-encoding", "ascii" ]
I'm extracting information from a webpage in Swedish. This page is using characters like: öäå. My problem is that when I print the information the öäå are gone. I'm extracting the information using Beautiful Soup. I think that the problem is that I do a bunch of regular expressions on the strings that I extract...
**Always work in unicode** and only convert to an encoded representation when necessary. For this particular situation, you also need to use the [`re.U`](http://docs.python.org/library/re.html#re.U) flag so `\w` matches unicode letters: ``` #coding: utf-8 import re location = "öäå".decode('utf-8') location = re....
What is L[L[3]] in a list?
10,165,457
3
2012-04-15T19:49:32Z
10,165,484
11
2012-04-15T19:51:41Z
[ "python", "python-3.x" ]
Im studying for a computer science final right now and I do not understand how this works at all: ``` L = [ 8, 6, 7, 5, 3, 0, 9 ] 30. L[L[3]] - 1 is? (A) * -1 (B) an error (C) 8 (D) 4 (E) 7 ``` The answer is -1.. SO to test how this works I just did L[L[3]] and the answer is 0, then i did L[L[4]] and thar equals 5, ...
`L[3]` is `5`, `L[L[3]]` is `L[5]` is `0`, and `0 - 1` is `-1`.
Django isn't serving static files, getting 404 errors
10,165,638
9
2012-04-15T20:09:22Z
10,165,796
20
2012-04-15T20:31:05Z
[ "python", "css", "django", "url-routing" ]
I can't seem to get my static files to load from my templates. I've followed the official documentation but I must be missing something. My directory layout (generated by Django, most files omitted): ``` myproject myproject settings.py urls.py static css bootstrap.css main.css templates ...
Have you defined your static files directory in `settings.py` ? I'm guessing you have `'django.contrib.staticfiles',` in your installed apps. If you haven't defined your static files dir, you could by doing something like this: ``` import os.path PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) STATICFILE...
Using Tornado, how do I serve static files and serve a favicon.ico from a different directory than the static path?
10,165,665
25
2012-04-15T20:14:37Z
10,165,739
41
2012-04-15T20:23:21Z
[ "python", "static", "tornado", "favicon" ]
I am trying this: ``` favicon_path = '/path/to/favicon.ico' settings = {'debug': True, 'static_path': os.path.join(PATH, 'static')} handlers = [(r'/', WebHandler), (r'/favicon.ico', tornado.web.StaticFileHandler, {'path': favicon_path})] application = tornado.web.Application(handlers, **set...
You can simply do something like this: a. delete static\_path from the app settings. b. ``` handlers = [ (r'/favicon.ico', tornado.web.StaticFileHandler, {'path': favicon_path}), (r'/static/(.*)', tornado.web.StaticFileHandler, {'path': static_path}), (r'/', WebHandler) ] ``` hav...
Python win32com and 2-dimensional arrays
10,166,064
3
2012-04-15T21:01:53Z
17,891,657
7
2013-07-26T21:56:11Z
[ "python", "multidimensional-array", "coordinates", "win32com" ]
When using python and win32com to automate the software form Adobe one encounters problem with passing arrays of 2d coordinates. If one looks at code that Adobe ships for visual basic (VB) its simple. A simplified example for drawing a line in Illustrator would look as follows: ``` Set appObj = CreateObject("Illustrat...
Here is a alternate solution that actually uses *win32com* module. It happens that the array type of **Illustrator** as well as **Photoshop** is a singe array of variant types. Where the variant type is also an array. There are also other applications like solidworks that use the same strategy. You can force win32com t...
how do I exit program in try except
10,166,686
10
2012-04-15T22:25:20Z
10,166,700
14
2012-04-15T22:27:04Z
[ "python" ]
i have this try except code: ``` document = raw_input ('Your document name is ') try: with open(document, 'r') as a: for element in a: print element except: print document, 'does not exist' ``` my question is, how do i exit the program after I print filename does not exist? break and pass...
Use the sys.exit: ``` import sys try: # do something except Exception, e: print >> sys.stderr, "does not exist" print >> sys.stderr, "Exception: %s" % str(e) sys.exit(1) ``` A good practice is to print the Exception that occured so you can debug afterwards. You can also print the stacktrace with the...
Change the position of the origin in PyGame coordinate system
10,167,329
2
2012-04-16T00:12:16Z
10,183,996
8
2012-04-17T01:43:24Z
[ "python", "coordinates", "pygame" ]
I am doing some operations with vectors and physics in PyGame and the default coordinate system is inconvenient for me. Normally the `(0, 0)` point is at the top-left corner, but I would rather that the origin were at the bottom-left corner. I would rather change the coordinate system than converting every single thing...
Unfortunately, pygame does not provide any such functionality. The simplest way to do it would be to have a function to convert coordinates, and use it just before drawing any object. ``` def to_pygame(coords, height): """Convert coordinates into pygame coordinates (lower-left => top left).""" return (coords[0...
Why do variables live longer (have bigger scopes) in Python than in C?
10,167,521
4
2012-04-16T00:49:42Z
10,167,529
8
2012-04-16T00:51:04Z
[ "python", "c", "scope" ]
Python code: ``` for i in xrange(10): for j in xrange(5): pass # The for-loop ends, but i,j still live on print i,j # 9, 4 ``` C code: ``` for(int i=0; i<=10; i++) for(int =0; j<=5; j++) ; // The for-loop ends, so i,j can't be accessed, right? printf("%d, %d", i, j); // won't compile ``` ...
Only functions, modules, and the bodies of class definitions delineate scopes in Python. Other control structures don't. Some basic information about this is in the [Python Scopes and Namespaces](http://docs.python.org/tutorial/classes.html#python-scopes-and-namespaces) section of the Classes page of the Python Tutori...
Loading large file (25k entries) into dict is slow in Python?
10,168,349
5
2012-04-16T03:22:18Z
10,168,398
9
2012-04-16T03:29:57Z
[ "python", "performance", "dictionary", "io" ]
I have a file which has about 25000 lines, and it's a s19 format file. each line is like: S214 **780010** ***00802000000010000000000A508CC78C*** 7A There are no spaces in the actual file, the first part `780010` is the address of this line, and I want it to be a dict's key value, and I want the data part ***008020000...
How about something like this? (I made a test file with just a line `S21478001000802000000010000000000A508CC78C7A` so you might have to adjust the slicing.) ``` >>> with open('test.test') as f: ... dict_by_address = {line[4:10]:line[10:-3] for line in f} ... >>> dict_by_address {'780010': '00802000000010000000000...
How to make buttons in python/pygame?
10,168,447
6
2012-04-16T03:38:23Z
10,169,083
10
2012-04-16T05:26:51Z
[ "python", "button", "pygame" ]
I'm making a game in pygame and on the first screen I want there to be buttons that you can press to (i) start the game, (ii) load a new screen with instructions, and (iii) exit the program. I've found this code online for button making, but I don't really understand it (I'm not that good at object oriented programmin...
I don't have a code example for you, but how I would do it is to: 1. Make a Button class, with the text to go on the button as a constructor argument 1. Create a PyGame surface, either of an image or filled Rect 2. Render text on it with the Font.Render stuff in Pygame 2. Blit to game screen, save that rect. 3. ...
Static folders structure in Django 1.4?
10,168,761
7
2012-04-16T04:34:46Z
10,169,201
7
2012-04-16T05:44:04Z
[ "python", "django", "convention", "folder-structure", "django-1.4" ]
This is the new project structure (from the Django 1.4 release notes). ``` myproject |-- manage.py |-- myproject | |-- __init__.py | |-- settings.py | |-- urls.py | `-- wsgi.py `-- polls |-- __init__.py |-- models.py |-- tests.py `-- views.py ``` What I am not sure about is whether I should po...
`STATIC_ROOT` is not related to Python importing, so it totally depends on you. Normally, `myproject/static/`, thus `os.path.join(PROJECT_ROOT, 'static/')` in settings, is easier. *update* as San4ez suggested, and notes inside settings.py ``` # Absolute path to the directory static files should be collected to. # D...
Parsing nested function calls using pyparsing
10,168,935
7
2012-04-16T05:05:44Z
10,188,486
10
2012-04-17T09:19:46Z
[ "python", "parsing", "pyparsing" ]
I'm trying to use `pyparsing` to parse function calls in the form: ``` f(x, y) ``` That's easy. But since it's a recursive-descent parser, it should also be easy to parse: ``` f(g(x), y) ``` That's what I can't get. Here's a boiled-down example: ``` from pyparsing import Forward, Word, alphas, alphanums, nums, Zer...
Nice catch on figuring out that `identifier` was masking `expression` in your definition of `arg`. Here are some other tips on your parser: `x + ZeroOrMore(',' + x)` is a very common pattern in pyparsing parsers, so pyparsing includes a helper method `delimitedList` which allows you to replace that expression with `de...
Full proto too large to save, cleared variables
10,169,574
9
2012-04-16T06:26:16Z
10,192,419
8
2012-04-17T13:40:39Z
[ "python", "django", "google-app-engine" ]
I got this error while rendering google app engine code. Do any body have knowledge about this error?
Are you using appstats? It looks like this can happen when appstats is recording state about your app, especially if you're storing lots of data on the stack. It isn't harmful, but you won't be able to see everything when inspecting calls in appstats.
python matrix transpose and zip
10,169,919
5
2012-04-16T07:03:54Z
10,169,944
11
2012-04-16T07:06:09Z
[ "python" ]
How to get the transpose of this matrix..Any easier ,algorithmic way to do this... 1st question: ``` Input a=[[1,2,3],[4,5,6],[7,8,9]] Expected output a=[[1, 4, 7], [2, 5, 8], [3, 6, 9]] ``` 2nd Question: Zip gives me the following output said below,how can i zip when i dont know how many elements are there in t...
question answers: ``` >>> import numpy as np >>> first_answer = np.transpose(a) >>> second_answer = [list(i) for i in zip(*a)] ``` thanks to afg for helping out
python matrix transpose and zip
10,169,919
5
2012-04-16T07:03:54Z
19,888,067
8
2013-11-10T09:16:27Z
[ "python" ]
How to get the transpose of this matrix..Any easier ,algorithmic way to do this... 1st question: ``` Input a=[[1,2,3],[4,5,6],[7,8,9]] Expected output a=[[1, 4, 7], [2, 5, 8], [3, 6, 9]] ``` 2nd Question: Zip gives me the following output said below,how can i zip when i dont know how many elements are there in t...
Use `zip(*a)`: ``` >>> zip(*a) [(1, 4, 7), (2, 5, 8), (3, 6, 9)] ``` How it works: zip(\*a) is equal to zip(a[0], a[1], a[2]).
Changing plot scale by a factor in matplotlib
10,171,618
10
2012-04-16T09:26:26Z
17,816,809
18
2013-07-23T17:17:07Z
[ "python", "plot", "matplotlib" ]
I am creating a plot in python. Is there a way to re-scale the axis by a factor? The `yscale` and `xscale` commands only allow me to turn log scale off. *Edit:* For example. If I have a plot where the `x` scales goes from 1 nm to 50 nm, the x scale will range from 1x10^(-9) to 50x10^(-9) and I want it to change from...
As you have noticed, `xscale` and `yscale` does not support a simple linear re-scaling (unfortunately). As an alternative to Hooked's answer, instead of messing with the data, you can trick the labels like so: ``` ticks = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x*scale)) ax.xaxis.set_major_formatter(ticks) ...
How come I can't get the exactly result to *pip install* by manually *python setup.py install*?
10,172,286
7
2012-04-16T10:18:06Z
10,173,805
15
2012-04-16T12:08:56Z
[ "python", "setuptools" ]
I like to figure out the myth behind Python's namespace packages by *setuptools*, and here is what I did test. * Make a *virtual environment* by `virtualenv`. * Find a namespaced package on *PyPI*. * Install that package by `pip install`. * Check the installed file hierarchy. The package I played with is [zope.interf...
`pip` uses `setup.py` internally. It just passes additional option to it. To reproduce what `pip` is doing, execute ``` python setup.py install --single-version-externally-managed ``` You can also run `pip -vv` to see exactly which commands are run.
make an "always relative to current module" file path?
10,174,211
5
2012-04-16T12:37:11Z
10,174,657
8
2012-04-16T13:04:00Z
[ "python", "module", "path", "relative" ]
Lets say you have a module which contains ``` myfile = open('test.txt', 'r') ``` And the 'test.txt' file is in the same folder. If you'll run the module, the file will be opened successfully. Now lets say you import that module from another one which is in another folder. The file won't be searched in the same folder...
The solution is to use `__file__` and it's pretty clean: ``` import os TEST_FILENAME = os.path.join(os.path.dirname(__file__), 'test.txt') ```
web.py: how to get POST parameter and GET parameter?
10,174,738
6
2012-04-16T13:07:57Z
10,300,958
13
2012-04-24T15:20:52Z
[ "python", "web", "web.py" ]
I'm new to `web.py`. I used PHP alot. In PHP, POST parameter and GET parameter is stored in different global variables For example: `curl http://127.0.0.1/test?get_param1=1 -d 'post_param1=2'` In PHP you can get `$_GET['get_param1']` is 1 and `$_POST['post_param1']` is 2. But it seems impossible to distinct GET/POS...
There's actually an (undocumented?) `_method` parameter that can be `get`, `post` or `both` (the default) to return variables from the different sources. [See the source for web.input().](https://github.com/webpy/webpy/blob/master/web/webapi.py#L324) So for example: ``` get_input = web.input(_method='get') post_input ...
Copy cursor object in Python
10,175,519
2
2012-04-16T13:56:12Z
10,175,739
7
2012-04-16T14:09:59Z
[ "python", "cursor", "deep-copy" ]
I am working on a Trac-Plugin... To retrieve my data I create a cursor object and get the result table like this: ``` db = self.env.get_db_cnx() cursor = db.cursor() cursor.execute("SELECT...") ``` Now the result is being used in 3 different functions. My Problem is now that the cursor is being cleaned out while ...
Storing the values from *any finite iterable* is simple: ``` results = list(cursor) ``` Iterate over the iterable and store the results in a list. This list can be iterated over as many times as necessary. You don't need a copy of the cursor, just a copy of the results of the query. For this specific case, you shou...
Python "set" with duplicate/repeated elements
10,176,037
21
2012-04-16T14:28:00Z
10,176,151
9
2012-04-16T14:34:29Z
[ "python", "collections", "dictionary", "set" ]
Is there a standard way to represent a "set" that can contain duplicate elements. As I understand it, a set has exactly one or zero of an element. I want functionality to have any number. I am currently using a dictionary with elements as keys, and quantity as values, but this seems wrong for many reasons. **Motivat...
Your approach with dict with element/count seems ok to me. You probably need some more functionality. Have a look at [`collections.Counter`](http://docs.python.org/library/collections.html#collections.Counter). * O(1) test whether an element is present and current count retrieval (faster than with `element in list` an...
Python "set" with duplicate/repeated elements
10,176,037
21
2012-04-16T14:28:00Z
10,176,311
24
2012-04-16T14:43:23Z
[ "python", "collections", "dictionary", "set" ]
Is there a standard way to represent a "set" that can contain duplicate elements. As I understand it, a set has exactly one or zero of an element. I want functionality to have any number. I am currently using a dictionary with elements as keys, and quantity as values, but this seems wrong for many reasons. **Motivat...
You are looking for a [multiset](http://en.wikipedia.org/wiki/Multiset). Python's closest datatype is [`collections.Counter`](http://docs.python.org/dev/library/collections.html#collections.Counter): > A `Counter` is a `dict` subclass for counting hashable objects. It is an > unordered collection where elements are s...
How to pass extra arguments to python decorator?
10,176,226
53
2012-04-16T14:38:33Z
10,176,276
77
2012-04-16T14:41:28Z
[ "python", "python-2.7" ]
I have a decorator like below ``` def myDecorator(test_func): return callSomeWrapper(test_func) def callSomeWrapper(test_func): return test_func @myDecorator def someFunc(): print 'hello' ``` I want to enhance this decorator to accept another argument like below ``` def myDecorator(test_func,logIt): ...
Since you are calling the decorator like a function, it needs to return another function which is the actual decorator: ``` def myDecorator(logIt): def actualDecorator(test_func): if logIt: print "Calling Function: " + test_func.__name__ return callSomeWrapper(test_func) return actu...
How to pass extra arguments to python decorator?
10,176,226
53
2012-04-16T14:38:33Z
10,176,742
32
2012-04-16T15:09:02Z
[ "python", "python-2.7" ]
I have a decorator like below ``` def myDecorator(test_func): return callSomeWrapper(test_func) def callSomeWrapper(test_func): return test_func @myDecorator def someFunc(): print 'hello' ``` I want to enhance this decorator to accept another argument like below ``` def myDecorator(test_func,logIt): ...
Just to provide a different viewpoint: the syntax ``` @expr def func(...): #stuff ``` is equivalent to ``` def func(...): #stuff func = expr(func) ``` In particular, `expr` can be anything you like, as long as it evaluates to a callable. In *particular* particular, `expr` can be a decorator factory: you give it som...
Python error: could not convert string to float
10,176,409
5
2012-04-16T14:48:55Z
10,176,462
16
2012-04-16T14:51:58Z
[ "python", "string", "floating-point", "text-files" ]
I have some Python code that pulls strings out of a text file: ``` [2.467188005806714e-05, 0.18664554919828535, 0.5026880460053854, ....] ``` Python code: ``` v = string[string.index('['):].split(',') for elem in v: new_list.append(float(elem)) ``` This gives an error: ``` ValueError: could not convert string ...
You've still got the `[` in front of your "float" which prevents parsing. Why not use a proper module for that? For example: ``` >>> a = "[2.467188005806714e-05, 0.18664554919828535, 0.5026880460053854]" >>> import json >>> b = json.loads(a) >>> b [2.467188005806714e-05, 0.18664554919828535, 0.5026880460053854] ``` ...
Pyparsing setParseAction function is getting no arguments
10,177,276
13
2012-04-16T15:40:27Z
10,184,830
18
2012-04-17T03:55:11Z
[ "python", "parsing", "pyparsing" ]
I'm trying to parse a simple key = value query language. I've actually accomplished it with a huge monstrosity parser that I then make a second pass through to clean up the parse tree. What I'd like to do is make a clean parse from the bottom up, which includes things like using sets for the (key,val) pairs so redundan...
Well, the latest version of `setParseAction` does do some extra magic, but unfortunately at the expense of some development simplicity. The argument detection logic in setParseAction now relies on the raising of exceptions in the parse action until it is called with the correct number of arguments, starting at 3 and wo...
Save a function definition in ipython
10,177,492
11
2012-04-16T15:53:48Z
10,177,600
9
2012-04-16T16:00:52Z
[ "python", "macros", "ipython" ]
When using ipython I often want to save specific functions I have defined during my session, e.g.: ``` In [1]: def func1(): ...: pass ...: In [2]: %save func1.py func1 func1 is neither a string nor a macro. ``` Instead I have to pick out the function definition line number from `enumerate(_ih)`, or manually ...
You can save the contents of line `1` with `%save` using: ``` In [2]: %save func1.py 1 The following commands were written to file `func1.py`: def func1(): pass ``` Help on `%save` is available with: ``` In [2]: %save? Type: Magic function ... Docstring: Save a set of lines or a macro to a given filename. ...
Pythonic way to modify all items in a list, and save list to .txt file
10,178,573
6
2012-04-16T17:12:44Z
10,178,606
7
2012-04-16T17:15:13Z
[ "python", "file", "list" ]
I have a list of strings. ``` theList = ['a', 'b', 'c'] ``` I want to add integers to the strings, resulting in an output like this: ``` newList = ['a0', 'b0', 'c0', 'a1', 'b1', 'c1', 'a2', 'b2', 'c2', 'a3', 'b3', 'c3'] ``` I want to save this to a .txt file, in this format: ``` a0 b0 c0 a1 b1 c1 a2 b2 c2 a3 b3 c3...
Instead of your last line, use: ``` f.write("\n".join(newList)) ``` This will write the strings in newList, separated by newlines, to f. Note that if you don't actually need newList, you can combine your two loops and write the strings as you go: ``` the_list = ['a', 'b', 'c'] with open('myFile.txt', 'w') as f: ...
Python and numpy : subtracting line by line a 2-dim array from a 1-dim array
10,178,823
4
2012-04-16T17:32:04Z
10,178,879
7
2012-04-16T17:36:30Z
[ "python", "arrays", "math", "numpy" ]
In python, I wish to subtract line by line a 2-dim array from a 1-dim array. I know how to do it with a 'for' loop and indexes but I suppose it may be quicker to use numpy functions. However I did not find a way to do it. Here is an example with a 'for' loop : ``` from numpy import * x=array([[1,2,3,4,5],[6,7,8,9,10]...
The problem is that `y-x` have the respective shapes `(2) (2,5)`. To do proper broadcasting, you'll need shapes `(2,1) (2,5)`. We can do this with `.reshape` as long as the number of elements are preserved: ``` y.reshape(2,1) - x ``` Gives: ``` array([[19, 18, 17, 16, 15], [ 4, 3, 2, 1, 0]]) ```
filter foreignkey field in django admin
10,179,129
8
2012-04-16T17:56:00Z
10,182,504
14
2012-04-16T22:17:29Z
[ "python", "django" ]
I have these models: ``` class Entity(models.Model): name=models.CharField(max_length=100) class Theme(models.Model): name=models.CharField(max_length=100) entity=models.OneToOneField(Entity) class Company(models.Model): name=models.CharField(max_length=100) theme=models.OneToOneField(Theme,null...
use the render\_change\_form method ``` class CompanyAdmin(admin.ModelAdmin): def render_change_form(self, request, context, *args, **kwargs): context['adminform'].form.fields['theme'].queryset = Theme.objects.filter(name__iexact='company') return super(CompanyAdmin, self).render_change_form(requ...
filter foreignkey field in django admin
10,179,129
8
2012-04-16T17:56:00Z
32,882,059
8
2015-10-01T07:43:17Z
[ "python", "django" ]
I have these models: ``` class Entity(models.Model): name=models.CharField(max_length=100) class Theme(models.Model): name=models.CharField(max_length=100) entity=models.OneToOneField(Entity) class Company(models.Model): name=models.CharField(max_length=100) theme=models.OneToOneField(Theme,null...
I actually prefer to do it in `get_form` like so: ``` class CompanyAdmin(admin.ModelAdmin): def get_form(self, request, obj=None, **kwargs): form = super(CompanyAdmin, self).get_form(request, obj, **kwargs) form.base_fields['theme'].queryset = Theme.objects.filter(name__iexact='company') re...
How to create a dictionary from a couple of tuples of the same size?
10,179,743
2
2012-04-16T18:41:39Z
10,179,755
8
2012-04-16T18:42:26Z
[ "python", "dictionary", "constructor" ]
Consider I have the two following tuples: ``` keys=("second", "minute", "hour", "day") values=(1, 60, 60, 24) ``` I would like to create a dictionary that has the `keys` tuple as keys and the `values` tuple as values. Here's my naive way of doing it: ``` d={} for i in xrange(len(keys)): d[keys[i]] = values[i] ``...
``` >>> keys=("second", "minute", "hour", "day") >>> values=(1, 60, 60, 24) >>> dict(zip(keys,values)) {'second': 1, 'hour': 60, 'minute': 60, 'day': 24} ```
How to create a dictionary from a couple of tuples of the same size?
10,179,743
2
2012-04-16T18:41:39Z
10,179,791
7
2012-04-16T18:45:17Z
[ "python", "dictionary", "constructor" ]
Consider I have the two following tuples: ``` keys=("second", "minute", "hour", "day") values=(1, 60, 60, 24) ``` I would like to create a dictionary that has the `keys` tuple as keys and the `values` tuple as values. Here's my naive way of doing it: ``` d={} for i in xrange(len(keys)): d[keys[i]] = values[i] ``...
The `zip` function turns a pair of iterables into a list of pairs. The `dict` constructor accepts a number of forms of arguments, one of which is a sequence of (key, value) pairs. Put the two together, and you get just what you want: ``` dict(zip(keys, values)) ```
MySQLdb executemany using a list as input?
10,180,335
3
2012-04-16T19:24:17Z
10,180,409
8
2012-04-16T19:29:54Z
[ "python", "mysql-python" ]
I am wanting to use an executemany within my program to store 20 records at once, heres what it says in the documentation... ``` c.executemany( """INSERT INTO breakfast (name, spam, eggs, sausage, price) VALUES (%s, %s, %s, %s, %s)""", [ ("Spam and Sausage Lover's Plate", 5, 1, 8, 7.95 ), ("Not So Much Spam ...
``` params = [(str(keywords[i]), date, time, position[i]) for i in range(20)] ```
why does python `any` return a bool instead of the value
10,180,344
36
2012-04-16T19:24:57Z
10,180,542
18
2012-04-16T19:41:07Z
[ "python", "function", "design", "internal" ]
`and` and `or` return the last element they evaluated, but why doesn't Python's built-in function `any`? I mean it's pretty easy to implement oneself like this, but I'm still left wondering why. ``` def any(l): for x in l: if x: return x return x ``` edit: To add to the answers below, he...
`and` and `or` can be sensibly defined in a way that they *always* return one of their operands. However, `any` and `all` cannot sensibly be defined always to return a value from their input sequence: specifically they cannot do so when the list is empty. Both `any` and `all` currently have a well defined result in thi...
why does python `any` return a bool instead of the value
10,180,344
36
2012-04-16T19:24:57Z
10,180,745
41
2012-04-16T19:56:51Z
[ "python", "function", "design", "internal" ]
`and` and `or` return the last element they evaluated, but why doesn't Python's built-in function `any`? I mean it's pretty easy to implement oneself like this, but I'm still left wondering why. ``` def any(l): for x in l: if x: return x return x ``` edit: To add to the answers below, he...
This very issue came up up on the Python developer's mailing list in 2005, when Guido Van Rossum proposed adding `any` and `all` to Python 2.5. Bill Janssen [requested](http://mail.python.org/pipermail/python-dev/2005-March/052012.html) that they be implemented as ``` def any(S): for x in S: if x: ...
open file with a unicode filename?
10,180,765
4
2012-04-16T19:58:35Z
10,180,806
18
2012-04-16T20:00:57Z
[ "python", "file", "unicode" ]
I don't seem to be able to open a file which has a unicode filename. Lets say I do: ``` for i in os.listdir(): open(i, 'r') ``` When I try to search for some solution, I always get pages about how to read and write a unicode string to a file, not how to open a file with `file()` or `open()` which has a unicode na...
Simply pass `open()` a unicode string for the file name: In Python 2.x: ``` >>> open(u'someUnicodeFilenameλ') <open file u'someUnicodeFilename\u03bb', mode 'r' at 0x7f1b97e70780> ``` In Python 3.x, all strings are Unicode, so there is literally nothing to it. As always, note that the best way to open a file is alw...
How to get all messages in Amazon SQS queue using boto library in Python?
10,180,851
5
2012-04-16T20:03:34Z
10,180,897
10
2012-04-16T20:06:24Z
[ "python", "boto", "amazon-sqs" ]
I'm working on an application whose workflow is managed by passing messages in SQS, using boto. My SQS queue is growing gradually, and I have no way to check how many elements it is supposed to contain. Now I have a daemon that periodically polls the queue, and checks if i have a fixed-size set of elements. For examp...
Put your call to `q.get_messages(n)` inside while loop: ``` all_messages=[] rs=q.get_messages(10) while len(rs)>0: all_messages.extend(rs) rs=q.get_messages(10) ``` Additionally, [dump won't support more than 10 messages](https://github.com/boto/boto/blob/develop/boto/sqs/queue.py) either: ``` def dump(self,...
trying to get reasonable values from scipy powerlaw fit
10,181,151
7
2012-04-16T20:23:42Z
10,182,515
7
2012-04-16T22:19:20Z
[ "python", "numpy", "scipy", "curve-fitting", "least-squares" ]
I'm trying to fit some data from a simulation code I've been running in order to figure out a power law dependence. When I plot a linear fit, the data does not fit very well. Here's the python script I'm using to fit the data: ``` #!/usr/bin/env python from scipy import optimize import numpy xdata=[ 0.00010851, 0.0...
It is much better to first take the logarithm, then use `leastsquare` to fit to this linear equation, which will give you a much better fit. There is a great example in the [scipy cookbook](http://www.scipy.org/Cookbook/FittingData), which I've adapted below to fit your code. The best fits like this are: amplitude = 0...
How to pass member function as argument in python?
10,181,450
9
2012-04-16T20:46:13Z
10,181,503
9
2012-04-16T20:50:16Z
[ "python", "python-2.7" ]
I want to pass something similar to a member function pointer. I tried the following. ``` class dummy: def func1(self,name): print 'hello %s' % name def func2(self,name): print 'hi %s' % name def greet(f,name): d = getSomeDummy() d.f(name) greet(dummy.func1,'Bala') ``` Expected outpu...
`dummy.func1` is [unbound](http://stackoverflow.com/questions/114214/class-method-differences-in-python-bound-unbound-and-static), and therefore simply takes an explicit `self` argument: ``` def greet(f,name): d = dummy() f(d, name) greet(dummy.func1,'Bala') ```
How do I download only unread attachments from a specific gmail label?
10,182,499
4
2012-04-16T22:17:09Z
10,182,957
7
2012-04-16T23:09:47Z
[ "python", "gmail", "attachment", "imaplib" ]
I have a Python script adapted from [Downloading MMS emails sent to Gmail using Python](http://stackoverflow.com/questions/7596789/downloading-mms-emails-sent-to-gmail-using-python) ``` import email, getpass, imaplib, os detach_dir = '.' # directory where to save attachments (default: current) user = raw_input("Enter...
Try modifying this line: ``` resp, items = m.search(None, 'FROM', '"Impact Stats Script"') ``` to: ``` resp, items = m.search(None, 'UNSEEN', 'FROM', '"Impact Stats Script"') ``` The [Python `imaplib` documentation shows just adding more search criteria](http://docs.python.org/library/imaplib.html#imaplib.IMAP4.sea...
Check for camel case in Python
10,182,664
2
2012-04-16T22:34:37Z
10,182,901
10
2012-04-16T23:00:53Z
[ "python", "regex", "camelcasing" ]
I would like to check if a string is a camel case or not (boolean). I am inclined to use a regex but any other elegant solution would work. I wrote a simple regex ``` (?:[A-Z])(?:[a-z])+(?:[A-Z])(?:[a-z])+ ``` Would this be correct? Or am I missing something? **Edit** I would like to capture names in a collection o...
You could check if a string has both upper and lowercase. ``` def camel(s): return (s != s.lower() and s != s.upper()) tests = [ "camel", "camelCase", "CamelCase", "CAMELCASE", "camelcase", "Camelcase", "Case" ] for test in tests: print test, ca...
Add parent tags with beautiful soup
10,182,685
2
2012-04-16T22:36:44Z
10,192,634
9
2012-04-17T13:54:33Z
[ "python", "html-parsing", "beautifulsoup" ]
I have many pages of HTML with various sections containing these code snippets: ``` <div class="footnote" id="footnote-1"> <h3>Reference:</h3> <table cellpadding="0" cellspacing="0" class="floater" style="margin-bottom:0;" width="100%"> <tr> <td valign="top" width="20px"> <a href="javascript:void(0);" onclick='javascr...
How about this: ``` def wrap(to_wrap, wrap_in): contents = to_wrap.replace_with(wrap_in) wrap_in.append(contents) ``` Simple example: ``` from bs4 import BeautifulSoup soup = BeautifulSoup("<body><a>Some text</a></body>") wrap(soup.a, soup.new_tag("b")) print soup.body # <body><b><a>Some text</a></b></body> ...
Installing (build) matplotlib in mac osx lion
10,183,144
5
2012-04-16T23:35:16Z
10,183,340
14
2012-04-17T00:04:40Z
[ "python", "matplotlib", "osx-lion" ]
I installed pynum and scipy (on osx Lion with python 2.7), but when I tried to build matplotlib ``` git clone https://github.com/matplotlib/matplotlib.git cd matplotlib python setup.py build python setup.py install ``` I've got these errors: ``` /System/Library/Frameworks/ApplicationServices.framework/Frameworks/ATS...
I always find this process more painful than it should be, but I've done it a few times now and I believe that these steps should get you set up: 1. Get Xcode 4.3.2, it's required for some of the later steps. 2. [Download](http://python.org/download/) the latest version of python for OSX from python.org 3. Grab the [S...
Is there a way to read a file in a loop in python using a separator other than newline
10,183,784
10
2012-04-17T01:09:45Z
10,183,966
7
2012-04-17T01:37:01Z
[ "python" ]
I usually read files like this in Python: ``` f = open('filename.txt', 'r') for x in f: doStuff(x) f.close() ``` However, this splits the file by newlines. I now have a file which has all of its info in one line (45,000 strings separated by commas). While a file of this size is trivial to read in using something ...
The following function is a fairly straightforward way to do what you want: ``` def file_split(f, delim=',', bufsize=1024): prev = '' while True: s = f.read(bufsize) if not s: break split = s.split(delim) if len(split) > 1: yield prev + split[0] ...
py2app is not copying the Python.framework to the new app while using virutalenv
10,184,974
7
2012-04-17T04:16:07Z
10,185,941
8
2012-04-17T06:01:38Z
[ "python", "osx-lion", "virtualenv", "pyobjc", "py2app" ]
environment: MacOS X 10.7.2, system installed python 2.7.1, virtualenv 1.7.2, pyobjc 2.3, py2app 0.6.4+ I have a newly created virtualenv with pyobc 2.3 and py2app installed. When I run python setup.py py2app to create an app (for example in py2app/examples/simple) everything seems to compile and it does produce a dou...
`py2app` never copies a system Python into an app bundle that it produces. If you want to make a standalone app that can be deployed on multiple versions of OS X, you need to use `py2app` with a separately-installed Python, like from a python.org installer. See, for example, [Py2App Can't find standard modules](http://...
Python script writes text to file, but doesn't add the text it's supposed to
10,185,424
3
2012-04-17T05:11:54Z
10,185,481
7
2012-04-17T05:16:18Z
[ "python", "file-manipulation" ]
I'm ashamed to resort to asking for help again, but I'm stuck. I have a spanish novel (in plain text), and I have a Python script that's supposed to put translations for difficult words in parentheses, using a custom dictionary in another text file. After a lot of trial and error, I've managed to have the script run,...
Change: ``` bookin.replace(ogword, subword) ``` to ``` bookin = bookin.replace(ogword, subword) ``` Explanation: `replace` does not change the string in place- in fact, strings are immutable- instead, it returns a new version.
How do I install Python 2.7.3 32 bit and 64 bit on Windows side by side
10,187,072
25
2012-04-17T07:35:43Z
12,448,411
24
2012-09-16T16:02:32Z
[ "python", "win64" ]
I have Windows Vista 64. I have some projects requiring Python 2.7.3 64 bit and others requiring Python 2.7.3 32 bit (because some extensions do not work in 64 bit). How do I prevent the Python 2.7.3 MSI installer (32 or 64 bot) from deleting the other version. Side by side worked for me with Python 2.7.2 without pr...
This appears to be working for me on Windows 7 64 bit. Choose one version to be your default installation, e.g. 64 bit, and install it first. Before doing anything else install the other version. Specify a different installation directory and in the `Customize Python 2.7.3` screen select `Register Extensions` and sele...
PyOpenGL TypeError: 'NoneType' object is not callable
10,188,595
16
2012-04-17T09:27:55Z
10,797,801
12
2012-05-29T10:59:28Z
[ "python", "pyopengl" ]
I am trying to learn the basics of game programming and I have installed `pygame` and `pyopengl` for that. MyCode: ``` import sys import OpenGL from OpenGL.GL import * from OpenGL.GLU import * from OpenGL.GLUT import * def draw(): glClear(GL_COLOR_BUFFER_BIT) glutWireTeapot(0.5) glFlush()...
I was using Python 2.7.3 on Windows 7 64-bit and had a problem causing the same symptoms as Noob. But the above PyOpenGL reinstallation solution did not help me. I try a longshot - installation of freeglut - and it helped! I used Windows MSVC 2.8.0 binary package from [here](http://www.transmissionzero.co.uk/softwar...
PyOpenGL TypeError: 'NoneType' object is not callable
10,188,595
16
2012-04-17T09:27:55Z
12,150,764
8
2012-08-27T23:04:25Z
[ "python", "pyopengl" ]
I am trying to learn the basics of game programming and I have installed `pygame` and `pyopengl` for that. MyCode: ``` import sys import OpenGL from OpenGL.GL import * from OpenGL.GLU import * from OpenGL.GLUT import * def draw(): glClear(GL_COLOR_BUFFER_BIT) glutWireTeapot(0.5) glFlush()...
I installed **PyOpenGL-3.0.2b2** on **Python 3.2** using the setup.py install (with administrator privileges), it came out with the same error as the OP. The setup script didn't copy the DLLS folder, so you have to copy it yourself the whole folder **\PyOpenGL-3.0.2b2\OpenGL\DLLS**. This worked for me, hope it helps ...
Google contacts import using oauth2.0
10,188,768
6
2012-04-17T09:40:01Z
14,161,012
15
2013-01-04T16:31:50Z
[ "python", "google-api", "oauth-2.0", "contacts", "google-api-python-client" ]
What possible ways to import google contacts using python and **oauth2.0** exists? We successfully got credentials, and our application requests access to contacts, but after getting credentials I can't find way to discover contacts api. So things like: ``` from apiclient.discover import build import httplib2 htt...
The [Google Contacts API](https://developers.google.com/google-apps/contacts/v3/) can't be used with the `google-api-python-client` library because it is a [Google Data API](https://developers.google.com/gdata/docs/2.0/reference), while `google-api-python-client` is intended to be used with [discovery-based APIs](https...
For a Python dictionary, does iterkeys offer any advantages over viewkeys?
10,189,273
19
2012-04-17T10:14:43Z
10,189,891
17
2012-04-17T10:57:21Z
[ "python", "python-2.7" ]
In Python 2.7, dictionaries have both an `iterkeys` method and a `viewkeys` method (and similar pairs for values and items), giving two different ways to lazily iterate over the keys of the dictionary. The `viewkeys` method provides the principal feature of `iterkeys`, with `iter(d.viewkeys())` effectively equivalent t...
A dictionary view updates as the dictionary does, while an iterator does not necessarily do this. This means if you work with the view, change the dictionary, then work with the view again, the view will have changed to reflect the dictionary's new state. > They provide a dynamic view on the dictionary’s entries, w...
For a Python dictionary, does iterkeys offer any advantages over viewkeys?
10,189,273
19
2012-04-17T10:14:43Z
10,190,228
11
2012-04-17T11:20:11Z
[ "python", "python-2.7" ]
In Python 2.7, dictionaries have both an `iterkeys` method and a `viewkeys` method (and similar pairs for values and items), giving two different ways to lazily iterate over the keys of the dictionary. The `viewkeys` method provides the principal feature of `iterkeys`, with `iter(d.viewkeys())` effectively equivalent t...
Functionality-wise, as you have observed, views are better. Compatibility-wise, they're worse. Some performance metrics, taken from Python 2.7.2 on a 64-bit Ubuntu machine: ``` >>> from timeit import timeit ``` Dealing with an empty dictionary: ``` >>> emptydict = {} >>> timeit(lambda: emptydict.viewkeys()) 0.24384...
AttributeError: 'tuple' object has no attribute 'write'
10,189,723
4
2012-04-17T10:46:12Z
10,189,754
7
2012-04-17T10:47:42Z
[ "python", "tuples", "attributeerror" ]
I have a homework assignment for a Python class and am running into an error that I don't understand. Running Python IDLE v3.2.2 on Windows 7. Below is where the problem is happening: ``` #local variables number=0 item='' cost='' #prompt user how many entries number=int(input('\nHow many items to add?: ')) #open fi...
You're missing the [open](http://docs.python.org/py3k/library/functions.html#open). ``` openfile = open('test.txt','w') ``` And at the end there are missing parens when you try to close the file ``` openfile.close() ``` *Edit*: I just saw another problem. ``` openfile.write(str(cost)+'\n') ```
Get a unique ID for worker in python multiprocessing pool
10,190,981
15
2012-04-17T12:11:09Z
10,192,611
28
2012-04-17T13:53:11Z
[ "python", "multiprocessing" ]
Is there a way to assign each worker in a python multiprocessing pool a unique ID in a way that a job being run by a particular worker in the pool could know which worker is running it? According to the docs, a `Process` has a `name` but > The name is a string used for identification purposes only. It has no > semanti...
It seems like what you want is simple: `multiprocessing.current_process()`. For example: ``` import multiprocessing def f(x): print multiprocessing.current_process() return x * x p = multiprocessing.Pool() print p.map(f, range(6)) ``` Output: ``` $ python foo.py <Process(PoolWorker-1, started daemon)> <Pr...
How to do a HTTP DELETE request with Requests library
10,191,733
11
2012-04-17T12:57:30Z
10,191,804
18
2012-04-17T13:02:00Z
[ "python", "django", "httprequest" ]
I'm using the [requests](http://docs.python-requests.org/en/latest/user/quickstart/#response-status-codes) package for interacting with the toggl.com API. I can perform GET and POST requests: ``` payload = {'some':'data'} headers = {'content-type': 'application/json'} url = "https://www.toggl.com/api/v6/"...
Use [requests.delete](http://docs.python-requests.org/en/latest/api/?highlight=delete#requests.delete) instead of `requests.post` ``` payload = {'some':'data'} headers = {'content-type': 'application/json'} url = "https://www.toggl.com/api/v6/" + data_description + ".json" response = requests.delete(url, data=json.dum...
How to get the list of options that Python was compiled with?
10,192,758
29
2012-04-17T14:02:05Z
10,192,835
32
2012-04-17T14:07:27Z
[ "python", "compilation", "packages" ]
You can compile Python in various ways. I'd like to find out with which options my Python was compiled. Concrete use-case: was my Python compiled with readline? I know I can see this by doing "import readline", but I'd like to see a list of compilation setting for my Python binary. Edit: I mean the Python executable ...
There is a module to see the system config ``` import sysconfig print(sysconfig.get_config_vars()) ``` It offers an interface to get individual variables as well. ``` sysconfig.get_config_var('HAVE_LIBREADLINE') ``` Edit: before python2.7, you have to use ``` import distutils.sysconfig print distutils.sysconfig.g...
How to get the list of options that Python was compiled with?
10,192,758
29
2012-04-17T14:02:05Z
23,231,572
14
2014-04-22T22:39:17Z
[ "python", "compilation", "packages" ]
You can compile Python in various ways. I'd like to find out with which options my Python was compiled. Concrete use-case: was my Python compiled with readline? I know I can see this by doing "import readline", but I'd like to see a list of compilation setting for my Python binary. Edit: I mean the Python executable ...
To build on mirk's answer, to find the configure flags that were actually used during the build, the value you're looking for is `CONFIG_ARGS`. For example, this is the output for an Ubuntu-compiled Python: ``` >>> print distutils.sysconfig.get_config_var('CONFIG_ARGS') '--enable-shared' '--prefix=/usr' '--enable-ipv...