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 to use bash variables inside a Python code?
6,142,826
5
2011-05-26T17:44:52Z
6,142,889
11
2011-05-26T17:48:53Z
[ "python", "bash" ]
I wanna do this: ``` import subprocess subprocess.call(['var="foo_bar"'], shell=True) subprocess.call(['echo $var'], shell=True) ``` But when i will use the $var in the second line your value is losted. Somebody know some say to solve this problem? This is a simple example, but a need to do that in a mu...
Inject the value into the environment with `os.environ`. ``` os.environ['var'] = "foo_bar" subprocess.call(['echo $var'], shell=True) ```
Error: "x instance has no attribute y" when trying to inherit from class
6,143,693
4
2011-05-26T19:00:37Z
6,143,744
12
2011-05-26T19:05:44Z
[ "python", "inheritance", "attributes", "instance" ]
I can't really understand what I'm doing wrong, since when I try it in "small scale" and it is working there. I have a class named `Play()` I goes like this: ``` class Play(): def __init__(self): file = open("/home/trufa/Desktop/test", "r") self.word = random.choice(file.readlines()).rstrip() ...
You overwrite the original `__init__`, which is then never called and doesn't initialize the members. You must call the parent's `__init__` separately, usually with this snippet: ``` def __init__(self): super(Score, self).__init__() ``` See the [docs for `super()`](http://docs.python.org/library/functions.html#su...
Python zip() behavior in bash?
6,145,540
7
2011-05-26T21:50:46Z
6,145,615
11
2011-05-26T21:58:07Z
[ "python", "bash" ]
Is there similar Python zip() functionailty in bash? To be specific, I'm looking for the equivilent functionality in bash without using python: ``` $ echo "A" > test_a $ echo "B" >> test_a $ echo "1" > test_b $ echo "2" >> test_b $ python -c "print '\n'.join([' '.join([a.strip(),b.strip()]) for a,b in zip(open('test_a...
Pure bash: ``` liori@marvin:~$ zip34() { while read word3 <&3; do read word4 <&4 ; echo $word3 $word4 ; done } liori@marvin:~$ zip34 3<a 4<b alpha one beta two gamma three delta four epsilon five liori@marvin:~$ ``` (old answer) Look at `join`. ``` liori:~% cat a alpha beta gamma delta epsilon liori:~% cat b one two...
Python GPS Module: Reading latest GPS Data
6,146,131
8
2011-05-26T23:09:01Z
6,146,351
16
2011-05-26T23:49:09Z
[ "python", "gps", "gpsd" ]
I have been trying to work with the standard **GPS (gps.py) module in python** 2.6. This is supposed to act as a client and read GPS Data from gpsd running in Ubuntu. According to the documentation from GPSD webpage on client design ([GPSD Client Howto](http://gpsd.berlios.de/client-howto.html#_python_examples)), I sh...
What you need to do is regularly poll 'session.next()' - the issue here is that you're dealing with a serial interface - you get results in the order they were received. Its up to you to maintain a 'current\_value' that has the latest retrieved value. If you don't poll the session object, eventually your UART FIFO wil...
Plotting a line over several graphs
6,146,290
13
2011-05-26T23:37:21Z
6,146,591
9
2011-05-27T00:33:18Z
[ "python", "plot", "numerical", "matplotlib" ]
I don't know how this thing is called, or even how to describe it, so the title may be a little bit misleading. The first attached graph was created with pyplot. I would like to draw a straight line that goes through all graphs instead of the three red dot I currently use. Is it possible in pyplot? Second image i...
Relevant documentation: <http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.axvline> Edit: since [@DSM's answer](http://stackoverflow.com/questions/6146290/plotting-a-line-over-several-graphs/6147154#6147154) was so much better than mine I have shamefully incorporated some of that answer in an a...
Plotting a line over several graphs
6,146,290
13
2011-05-26T23:37:21Z
6,147,154
18
2011-05-27T02:15:05Z
[ "python", "plot", "numerical", "matplotlib" ]
I don't know how this thing is called, or even how to describe it, so the title may be a little bit misleading. The first attached graph was created with pyplot. I would like to draw a straight line that goes through all graphs instead of the three red dot I currently use. Is it possible in pyplot? Second image i...
You can pull this off by turning clipping off for the relevant lines. There's probably a cleaner way to do this -- you might be able to draw lines on the main frame directly -- but the following worked for me: ``` from matplotlib import pyplot as plt from numpy import arange, sin, cos xx = arange(100) cut = (xx > 0) ...
Running python script with cron only if not running
6,146,523
11
2011-05-27T00:21:38Z
6,146,908
9
2011-05-27T01:28:19Z
[ "python", "cron", "flock" ]
I need to run a python script (job.py) every minute. This script must not be started if it is already running. Its execution time can be between 10 seconds and several hours. So I put into my crontab: ``` * * * * * root cd /home/lorenzo/cron && python -u job.py 1>> /var/log/job/log 2>> /var/log/job/err ``` To avoid ...
The only suggestion I would make is to make your exception handling a little more specific. You don't want to accidentally delete the `fcntl` import one day and hide the `NameError` that results. Always try to catch the most specific exception you want to handle. In this case, I suggest something like: ``` import errn...
matplotlib Legend Markers Only Once
6,146,778
176
2011-05-27T01:08:06Z
6,146,871
185
2011-05-27T01:22:43Z
[ "python", "matplotlib" ]
I often plot a point on a matplotlib plot with: ``` x = 10 y = 100 plot(x, y, "k*", label="Global Optimum") legend() ``` However, this causes the legend to put a star in the legend twice, such that it looks like: ``` * * Global Optimum ``` when I really want it to look like: ``` * Global Optimum ``` How do I do...
This should work: ``` legend(numpoints=1) ``` BTW, if you add the line ``` legend.numpoints : 1 # the number of points in the legend line ``` to your matplotlibrc file, then this will be the new default. [See also scatterpoints, depending on your plot.] API: [Link to API docs](http://matplotlib.org/api/a...
matplotlib Legend Markers Only Once
6,146,778
176
2011-05-27T01:08:06Z
15,093,684
19
2013-02-26T16:02:13Z
[ "python", "matplotlib" ]
I often plot a point on a matplotlib plot with: ``` x = 10 y = 100 plot(x, y, "k*", label="Global Optimum") legend() ``` However, this causes the legend to put a star in the legend twice, such that it looks like: ``` * * Global Optimum ``` when I really want it to look like: ``` * Global Optimum ``` How do I do...
I like to change my matplotlib rc parameters dynamically in every python script. To achieve this goal I simply use somthing like that at the beginning of my python files. ``` from pylab import * rcParams['legend.numpoints'] = 1 ``` This will apply to all plots generated from my python file. EDIT: For those who do no...
When is del useful in python?
6,146,963
164
2011-05-27T01:37:06Z
6,146,992
90
2011-05-27T01:41:49Z
[ "python", "python-internals", "del" ]
I can't really think of any reason why python needs the `del` keyword (and most languages seem to not have a similar keyword). For instance, rather than deleting a variable, one could just assign `None` to it. And when deleting from a dictionary, a `del` method could be added. Is there any reason to keep `del` in pyth...
There's this part of what `del` does (from the [Python Language Reference](http://docs.python.org/reference/simple_stmts.html#the-del-statement)): > Deletion of a name removes the binding of that name from the local or global namespace Assigning `None` to a name does not remove the binding of the name from the namesp...
When is del useful in python?
6,146,963
164
2011-05-27T01:37:06Z
6,147,100
229
2011-05-27T02:02:54Z
[ "python", "python-internals", "del" ]
I can't really think of any reason why python needs the `del` keyword (and most languages seem to not have a similar keyword). For instance, rather than deleting a variable, one could just assign `None` to it. And when deleting from a dictionary, a `del` method could be added. Is there any reason to keep `del` in pyth...
Firstly, you can del other things besides local variables ``` del list_item[4] del dictionary["alpha"] ``` Both of which should be clearly useful. Secondly, using del on a local variable makes the intent clearer. Compare: ``` del foo ``` to ``` foo = None ``` I know in the case of `del foo` that the intent ...
When is del useful in python?
6,146,963
164
2011-05-27T01:37:06Z
13,873,748
12
2012-12-14T06:25:50Z
[ "python", "python-internals", "del" ]
I can't really think of any reason why python needs the `del` keyword (and most languages seem to not have a similar keyword). For instance, rather than deleting a variable, one could just assign `None` to it. And when deleting from a dictionary, a `del` method could be added. Is there any reason to keep `del` in pyth...
Just another thinking. When debugging http applications in framework like Django, the call stack full of useless and messed up variables previously used, especially when it's a very long list, could be very painful for developers. so, at this point, namespace controlling could be useful.
When is del useful in python?
6,146,963
164
2011-05-27T01:37:06Z
30,624,730
14
2015-06-03T15:40:36Z
[ "python", "python-internals", "del" ]
I can't really think of any reason why python needs the `del` keyword (and most languages seem to not have a similar keyword). For instance, rather than deleting a variable, one could just assign `None` to it. And when deleting from a dictionary, a `del` method could be added. Is there any reason to keep `del` in pyth...
One place I've found `del` useful is cleaning up extraneous variables in for loops: ``` for x in some_list: do(x) del x ``` Now you can be sure that x will be undefined if you use it outside the for loop.
Locate MacPorts package?
6,147,035
7
2011-05-27T01:49:27Z
6,147,093
11
2011-05-27T02:01:16Z
[ "python", "macports" ]
I just installed the py27-numpy package via MacPorts and python will not find the module when I use this command: `import scipy` I used the `help('modules')` command and the scipy port did not come up. Clearly the path is not configured correctly or MacPorts is not installing in the correct place, but either way, it ...
To find the location of installed components, use the `contents` subcommand: ``` port contents py27-numpy ``` As for getting `python` to find the package, see [@fardjad's response](http://stackoverflow.com/questions/6147035/locate-macports-package/6147071#6147071).
Locate MacPorts package?
6,147,035
7
2011-05-27T01:49:27Z
6,147,103
13
2011-05-27T02:03:41Z
[ "python", "macports" ]
I just installed the py27-numpy package via MacPorts and python will not find the module when I use this command: `import scipy` I used the `help('modules')` command and the scipy port did not come up. Clearly the path is not configured correctly or MacPorts is not installing in the correct place, but either way, it ...
Your PATH is incorrect. It appears to be picking up another Python 2.7, likely one installed using a binary installer from python.org or elsewhere, and not the MacPorts installed one. Try removing the the `/Library/Frameworks/Python.framework/Versions/2.7/bin` from PATH or just invoke the MacPorts Python directly: ```...
Python: Using variables in Pylab Titles
6,147,387
6
2011-05-27T02:56:50Z
6,149,373
9
2011-05-27T07:56:04Z
[ "python", "matplotlib" ]
I have variables N and W which change with each run. Is it possible to do something like the following?: ``` pylab.title('Minimal Energy Configuration of' N 'Charges on Disc' 'W = 'W) ```
I think your talking about string interpolation like this : ``` pylab.title('Minimal Energy Configuration of %s Charges on Disc W = %s'%(N, W)) ```
Linear regression with matplotlib / numpy
6,148,207
45
2011-05-27T05:32:22Z
6,148,315
86
2011-05-27T05:47:26Z
[ "python", "numpy", "matplotlib", "linear-regression" ]
I'm trying to generate a linear regression on a scatter plot I have generated, however my data is in list format, and all of the examples I can find of using `polyfit` require using `arange`. `arange` doesn't accept lists though. I have searched high and low about how to convert a list to an array and nothing seems cle...
`arange` *generates* lists (well, numpy arrays); type `help(np.arange)` for the details. You don't need to call it on existing lists. ``` >>> x = [1,2,3,4] >>> y = [3,5,7,9] >>> >>> m,b = np.polyfit(x, y, 1) >>> m 2.0000000000000009 >>> b 0.99999999999999833 ``` I should add that I tend to use `poly1d` here rather ...
Linear regression with matplotlib / numpy
6,148,207
45
2011-05-27T05:32:22Z
27,363,639
8
2014-12-08T17:37:02Z
[ "python", "numpy", "matplotlib", "linear-regression" ]
I'm trying to generate a linear regression on a scatter plot I have generated, however my data is in list format, and all of the examples I can find of using `polyfit` require using `arange`. `arange` doesn't accept lists though. I have searched high and low about how to convert a list to an array and nothing seems cle...
This code: ``` from scipy.stats import linregress linregress(x,y) #x and y are arrays or lists. ``` gives out a list with the following: > slope : float > slope of the regression line > intercept : float > intercept of the regression line > r-value : float > correlation coefficient > p-value : float >...
Start index for iterating Python list
6,148,619
19
2011-05-27T06:28:56Z
6,148,636
40
2011-05-27T06:31:21Z
[ "python", "iteration" ]
What is the best way to set a start index when iterating a list in Python. For example, I have a list of the days of the week - Sunday, Monday, Tuesday, ... Saturday - but I want to iterate through the list starting at Monday. What is the best practice for doing this?
You can use [slicing](http://stackoverflow.com/questions/509211/good-primer-for-python-slice-notation): ``` for item in list[2:]: # do stuff ``` This will start at the third element and iterate to the end.
Start index for iterating Python list
6,148,619
19
2011-05-27T06:28:56Z
6,148,789
11
2011-05-27T06:49:23Z
[ "python", "iteration" ]
What is the best way to set a start index when iterating a list in Python. For example, I have a list of the days of the week - Sunday, Monday, Tuesday, ... Saturday - but I want to iterate through the list starting at Monday. What is the best practice for doing this?
This has the advantage that it doesn't need to copy part of the list ``` from itertools import islice for day in islice(days, 1, None): ... ```
Display a float with two decimal places in Python
6,149,006
38
2011-05-27T07:13:47Z
6,149,026
59
2011-05-27T07:15:30Z
[ "python", "string", "programming-languages", "floating-point" ]
I have a function taking float arguments (generally integers or decimals with one significant digit), and I need to output the values in a string with two decimal places (5 -> 5.00, 5.5 -> 5.50, etc). How can I do this in Python?
You could use the string formatting operator for that: ``` >>> '%.2f' % 1.234 '1.23' >>> '%.2f' % 5.0 '5.00' ``` The result of the operator is a string, so you can store it in a variable, print etc.
Display a float with two decimal places in Python
6,149,006
38
2011-05-27T07:13:47Z
6,149,115
81
2011-05-27T07:22:58Z
[ "python", "string", "programming-languages", "floating-point" ]
I have a function taking float arguments (generally integers or decimals with one significant digit), and I need to output the values in a string with two decimal places (5 -> 5.00, 5.5 -> 5.50, etc). How can I do this in Python?
Since this post might be here for a while, lets also point out python 3 syntax: ``` "{0:.2f}".format(5) ```
Python, working with list comprehensions
6,149,370
5
2011-05-27T07:55:20Z
6,149,394
7
2011-05-27T07:57:50Z
[ "python", "list", "list-comprehension" ]
I have such code: ``` a = [[1, 1], [2, 1], [3, 0]] ``` I want to get two lists, the first contains elements of `'a'`, where `a[][1] = 1`, and the second - elements where `a[][1] = 0`. So ``` first_list = [[1, 1], [2, 1]] second_list = [[3, 0]]. ``` I can do such thing with two list comprehension: ``` first_list ...
List comprehension are very pythonic and the recommended way of doing this. Your code is fine.
_imaging C module error in python PIL
6,149,634
7
2011-05-27T08:22:51Z
6,846,116
8
2011-07-27T14:30:04Z
[ "python", "python-imaging-library", "libjpeg" ]
I have read the other posts about the notorious \_imaging C module error when installing PIL on Mac OS X and none of the solutions provided anywhere, including the PIL FAQ, have proven helpful. I have the newest versions of libjpeg and zlib freshly installed from source. I have edited the Makefiles in each of these to...
Since you have been trying this a few times, I recommend running a few commands to clean out the old items first and start from the beginning. I used jpeg v8c and Imaging 1.1.6 on Mac OS X, 10.6 and 10.7 get v8c of jpeg cd into jpeg directory. ``` sudo make clean CC="gcc -arch i386" ./configure --enable-shared --ena...
Python : How to Pretty print html into a file
6,150,108
26
2011-05-27T09:09:21Z
6,167,432
43
2011-05-29T11:14:31Z
[ "python", "html", "lxml", "pretty-print" ]
I am using [lxml.html](http://lxml.de/lxmlhtml.html) to generate some HTML. I want to pretty print (with indentation) my final result into an html file. How do I do that? This is what I have tried and got till now (I am relatively new to Python and lxml) : ``` import lxml.html as lh from lxml.html import builder as E...
I ended up using [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) directly. That is something [lxml.html.soupparser](http://lxml.de/elementsoup.html) uses for parsing HTML. BeautifulSoup has a prettify method that does exactly what it says it does. It prettifies the HTML with proper indents and everythin...
Python : How to Pretty print html into a file
6,150,108
26
2011-05-27T09:09:21Z
16,505,750
10
2013-05-12T09:01:39Z
[ "python", "html", "lxml", "pretty-print" ]
I am using [lxml.html](http://lxml.de/lxmlhtml.html) to generate some HTML. I want to pretty print (with indentation) my final result into an html file. How do I do that? This is what I have tried and got till now (I am relatively new to Python and lxml) : ``` import lxml.html as lh from lxml.html import builder as E...
Though my answer might not be helpful now, I am dropping it here to act as a reference to anybody else in future. `lxml.html.tostring()`, indeed, doesn't pretty print the provided HTML in spite of `pretty_print=True`. However, the "sibling" of `lxml.html` - `lxml.etree` has it working well. So one might use it as fo...
macports didn't place python_select in /opt/local/bin
6,152,765
23
2011-05-27T13:17:51Z
6,159,178
28
2011-05-28T01:49:07Z
[ "python", "macports" ]
I've uninstalled and reinstalled python\_select using MacPorts and yet it won't show up in /opt/local/bin. Consequently, I get a "command not found" error when attempting to run it. Yet MacPorts insists that it is installed. Have even tried uninstall -f and port clean --all python\_select. Is there a more drastic step...
It seems that [`python_select` has been deprecated](https://trac.macports.org/ticket/29531): > "python\_select" (and other standalone \*\_select scripts) is gone. > > Use "sudo port select python python26" etc.
macports didn't place python_select in /opt/local/bin
6,152,765
23
2011-05-27T13:17:51Z
6,566,479
11
2011-07-04T00:54:24Z
[ "python", "macports" ]
I've uninstalled and reinstalled python\_select using MacPorts and yet it won't show up in /opt/local/bin. Consequently, I get a "command not found" error when attempting to run it. Yet MacPorts insists that it is installed. Have even tried uninstall -f and port clean --all python\_select. Is there a more drastic step...
``` sudo port select --set python python25 ``` This will set the Python alias (/opt/local/bin/python) to python25 If you're not sure which versions of Python you have to select from, you can use: ``` $ port select --list python Available versions for python: none python24 python25-apple python26 ...
Suds ignoring cache setting?
6,153,652
4
2011-05-27T14:26:58Z
6,203,678
10
2011-06-01T15:26:28Z
[ "python", "django", "caching", "suds" ]
I'm using suds 0.3.8, Python 2.4.3, and Django 1.1.1. The code I inherited has a long duration for the cached files, but it's expiring on the default cadence of once every 24 hours. The external servers hosting the schemas are spotty, so the site is going down nightly and I'm at the end of my rope. Any idea what is ja...
Answering my own question: This ended up not being a version issue, but user error. Unfortunately the suds documentation isn't as clear as it could be. Reading it, one would think the code above would work, but (on suds v0.39+) it should be written as: ``` imp = Import('http://domain2.com/url') imp.filter.add('http:/...
Django pre_save signal does not work
6,153,730
7
2011-05-27T14:32:53Z
6,154,065
8
2011-05-27T14:59:26Z
[ "python", "django", "django-signals" ]
I tested the "pre\_save" signal of Django in the following ways, but cannot catch the signal in either of them. $ ``` from django.db.models.signals import pre_save import logging def my_callback(sender, **kwargs): logging.debug("======================================") pre_save.connect(my_callback) ``` 1. Run t...
You're not setting the sender class for one. ``` from django.db.models.signals import pre_save from myapp.models import MyModel import logging def my_callback(sender, **kwargs): logging.debug("======================================") pre_save.connect(my_callback, sender=MyModel) ``` Secondly, if you're using Dja...
In Python, how can I detect whether the computer is on battery power?
6,153,860
15
2011-05-27T14:43:25Z
6,156,606
12
2011-05-27T19:03:46Z
[ "python", "windows", "pygame" ]
I'm playing around with pygame, and one thing I'd like to do is reduce the number of frames per second when the computer is on battery power (to lower the CPU usage and extend battery life). How can I detect, from Python, whether the computer is currently on battery power? I'm using Python 3.1 on Windows.
If you want to do it without `win32api`, you can use the built-in [`ctypes`](http://docs.python.org/library/ctypes.html) module. I usually run CPython without `win32api`, so I kinda like these solutions. It's a tiny bit more work for `GetSystemPowerStatus()` because you have to define the `SYSTEM_POWER_STATUS` structu...
How to alternate around directories using subprocess
6,154,218
8
2011-05-27T15:11:36Z
6,154,251
13
2011-05-27T15:14:34Z
[ "python", "unix", "subprocess" ]
I want to change the current directory using subprocess. For example: ``` import os, sys, subprocess os.environ['a'] = '/home' os.environ['b'] = '/' subprocess.call('cd $a', shell=True) subprocess.call('ls', shell=True) subprocess.call('cd $b', shell=True) subprocess.call('ls', shell=True) ``` I think that this s...
To change the directory just use `os.chdir()` instead. You can also execute commands in specific directoeies by running `subprocess.Popen(...)` - it has an optional parameter `cwd=None`. Just use it to specify the working directory. Also, you could take a look at a small module I wrote that completes some missing fun...
Sort a numpy array by another array, along a particular axis
6,155,649
22
2011-05-27T17:20:46Z
6,155,887
17
2011-05-27T17:46:41Z
[ "python", "sorting", "multidimensional-array", "numpy" ]
Similar to [this answer](http://stackoverflow.com/questions/1903462/how-can-i-zip-sort-parallel-numpy-arrays/1903579#1903579), I have a pair of 3D numpy arrays, `a` and `b`, and I want to sort the entries of `b` by the values of `a`. Unlike [this answer](http://stackoverflow.com/questions/1903462/how-can-i-zip-sort-par...
You still have to supply indices for the other two dimensions for this to work correctly. ``` >>> a = numpy.zeros((3, 3, 3)) >>> a += numpy.array((1, 3, 2)).reshape((3, 1, 1)) >>> b = numpy.arange(3*3*3).reshape((3, 3, 3)) >>> sort_indices = numpy.argsort(a, axis=0) >>> static_indices = numpy.indices((3, 3, 3)) >>> b[...
What is the Python equivalent of Tomcat?
6,157,049
30
2011-05-27T19:52:09Z
6,157,070
26
2011-05-27T19:53:53Z
[ "java", "python", "tomcat", "deployment" ]
This question likely betrays a misconception, but I'm curious what the "Tomcat" of the Python world is. All of my web programming experience is in Java (or Groovy) so I think in Java terms. And when I think of making a basic web-app, I think of writing some servlets, building a WAR file, and deploying it in Tomcat or ...
There are different approaches which have one thing in common: They usually communicate via WSGI with their "container" (the server receiving the HTTP requests before they go to your Python code). There are various containers: * wsgiref - a very simple reference implementation which is nice during development * Apach...
No such table error when running a django server from Eclipse
6,157,152
11
2011-05-27T20:02:05Z
6,157,354
11
2011-05-27T20:25:34Z
[ "python", "django", "eclipse", "sqlite", "pydev" ]
I'm developing a website using djago. When I run the server through the command prompt like so: ``` python manage.py runserver ``` it runs fine, but when I do it from Eclipse (right click on the project -> `Run As...` -> `django project`, I get the following error: > DatabaseError at / > no such table: django\_ses...
Probably Eclipse/PyDev is not able to find the database. Assuming that you use a sqlite3 database, use a full path in the DATABASES settings. Test it via the console and afterwards within Eclipse. That should work ;-) edit: As photioionized suggested, the best approach is to put those lines in settings.py ``` import ...
Why does re.findall() give me different results than re.finditer() in Python?
6,157,671
5
2011-05-27T21:04:36Z
6,157,736
7
2011-05-27T21:12:41Z
[ "python", "regex" ]
I wrote up this regular expression: ``` p = re.compile(r''' \[\[ #the first [[ [^:]*? #no :s are allowed .*? #a bunch of chars ( \| #either go until a | |\]\] #or the last ]] ) ''', re.VERBOSE) ``` I want to use `re.findall` to get all the matchin...
Findall returns a list of matching groups. The parantheses in your regex defines a group that findall thinks you want, but you don't want groups. `(?:...)` is a non-capturing paranthesis. Change your regex to: ``` ''' \[\[ #the first [[ [^:]*? #no :s are allowed .*? #a bunch of chars (?...
Advice on writing to a log file with python
6,157,781
7
2011-05-27T21:16:51Z
6,157,826
11
2011-05-27T21:21:45Z
[ "python" ]
I have some code that will need to write about 20 bytes of data every 10 seconds. I'm on Windows 7 using python 2.7 You guys recommend any 'least strain to the os/hard drive' way to do this? I was thinking about opening and closing the same file very 10 seconds: ``` f = open('log_file.txt', 'w') f.write(information)...
As expected, python comes included with a great tool for this, have a look at the [logging](http://docs.python.org/howto/logging.html#logging-basic-tutorial) module
Find phase difference between two (inharmonic) waves
6,157,791
13
2011-05-27T21:17:33Z
6,157,997
18
2011-05-27T21:41:57Z
[ "python", "numpy", "neural-network", "physics", "scipy" ]
I have two datasets listing the average voltage outputs of two assemblies of neural networks at times t, that look something like this: ``` A = [-80.0, -80.0, -80.0, -80.0, -80.0, -80.0, -79.58, -79.55, -79.08, -78.95, -78.77, -78.45,-77.75, -77.18, -77.08, -77.18, -77.16, -76.6, -76.34, -76.35] B = [-80.0, -80.0, -8...
Perhaps you are looking for the cross-correlation: ``` scipy.​signal.​signaltools.correlate(A, B) ``` The position of the peak in the cross-correlation will be an estimate of the phase difference. **EDIT 3:** Update now that I have looked at the real data files. There are two reasons that you find a phase shift ...
Python random.choice() function - how to never have two choices in a row or close to one another
6,157,967
4
2011-05-27T21:38:36Z
6,158,052
8
2011-05-27T21:48:56Z
[ "python", "random", "module" ]
Let's say I have ``` mychoice = random.choice(['this is random response 1','this is random response 2', 'this is random response 3', 'and 4', 'and so on']) ``` How can I avoid having the same choice being repeated more than once in a row? Or how can I can I set a condition to make a particular choice only appear aft...
the simplest solution would probably be to construct a `usedQueue` of length `k` (where k is the number of selections before a choice is allowed to repeat.) When you select a choice, remove it from your original list and place it in `usedQueue`. Then, if `usedQueue.length > k`, pop one back onto your array. As already...
How is memory management in PHP different from that in Python?
6,158,033
7
2011-05-27T21:46:51Z
6,208,958
7
2011-06-01T23:39:50Z
[ "php", "python", "memory-management", "garbage-collection", "webserver" ]
What is the difference in how they are handled? Specifically, why is it common to find Python used in production-level long lived applications like web-servers while PHP isn't given their similar efficiency levels?
PHP was designed as a hypertext scripting language. Every process was designed to end after a very short time. So memory management and GC basically didn't matter. However the ease and popularity of PHP have invoked its usage in long lived programs such as daemons, extensive calculations, socket servers etc. PHP 5.3 ...
Does Python classes support events like other languages?
6,158,602
2
2011-05-27T23:27:22Z
6,158,658
7
2011-05-27T23:40:04Z
[ "python", "events", "class", "python-2.7" ]
I'm working on my first Python project, and I'm already missing events in my classes. Perhaps it's not even called events in Python, but I would like to create "groups" in my classes to which function references can be added. At some point in my class all function references in my group would execute. Is this built in...
Python doesn't have any sort of event system built-in, but it's could be implemented pretty simply. For example: ``` class ObjectWithEvents(object): callbacks = None def on(self, event_name, callback): if self.callbacks is None: self.callbacks = {} if event_name not in self.callba...
Pip using system python osx
6,158,839
7
2011-05-28T00:22:59Z
6,160,949
11
2011-05-28T10:03:54Z
[ "python", "osx", "packages", "macports", "pip" ]
I installed python26 using macports, so the correct python on my system is `/opt/local/bin/python` However, when I do ``` sudo pip install <packagename> ``` It gives me ``` sudo pip install <somepackage> Exception: Traceback (most recent call last): File "/Library/Python...
Remove pip from /usr/local/bin with `sudo rm /usr/local/bin/pip`. If you have installed pip with macports, `which pip` should then show `/opt/local/bin/pip`. If not, install pip again by following the instructions [here](http://www.pip-installer.org/en/latest/installing.html). As long as `which python` shows the `/opt...
Pip using system python osx
6,158,839
7
2011-05-28T00:22:59Z
14,920,433
13
2013-02-17T11:08:30Z
[ "python", "osx", "packages", "macports", "pip" ]
I installed python26 using macports, so the correct python on my system is `/opt/local/bin/python` However, when I do ``` sudo pip install <packagename> ``` It gives me ``` sudo pip install <somepackage> Exception: Traceback (most recent call last): File "/Library/Python...
Summarizing the above, installing pip using Macports with: ``` sudo port install py27-pip ``` results in an installation of a package named py27-pip. However, no `/opt/local/bin/pip` is installed and `port select pip` or `port select py27-pip` both fail (in contrast to a `port select python`). Changing things in the...
What does Python treat as reference types?
6,158,907
7
2011-05-28T00:36:43Z
6,158,918
14
2011-05-28T00:39:16Z
[ "python", "sequences", "value-type", "reference-type" ]
I assumed sequence types in Python were value types. It turns out they're reference types (Meaning that the value of a variable won't be copied when assigned to a new variable, but referenced). So now I'm wondering, what are the value types in Python? That is, what types in Python can I assign to new variables without ...
*All* values in Python are references. What you need to worry about is if a type is **mutable**. The basic numeric and string types, as well as `tuple` and `frozenset` are immutable; names that are bound to an object of one of those types can only be rebound, not mutated. ``` >>> t = 1, 2, 3 >>> t[1] = 42 Traceback (m...
Can Python test the membership of multiple values in a list?
6,159,313
44
2011-05-28T02:30:54Z
6,159,329
71
2011-05-28T02:35:38Z
[ "python" ]
I want to test if two or more values have membership on a list, but I'm getting an unexpected result: ``` >>> 'a','b' in ['b', 'a', 'foo', 'bar'] ('a', True) ``` So, Can Python test the membership of multiple values at once in a list? What does that result mean?
This does what you want: ``` >>> all(x in ['b', 'a', 'foo', 'bar'] for x in ['a', 'b']) True ``` Your result happens because python interprets your expression as a tuple: ``` >>> 'a', 'b' ('a', 'b') >>> 'a', 5 + 2 ('a', 7) >>> 'a', 'x' in 'xerxes' ('a', True) ```
Can Python test the membership of multiple values in a list?
6,159,313
44
2011-05-28T02:30:54Z
6,159,331
8
2011-05-28T02:36:31Z
[ "python" ]
I want to test if two or more values have membership on a list, but I'm getting an unexpected result: ``` >>> 'a','b' in ['b', 'a', 'foo', 'bar'] ('a', True) ``` So, Can Python test the membership of multiple values at once in a list? What does that result mean?
I'm pretty sure `in` is having higher precedence than `,` so your statement is being interpreted as 'a', ('b' in ['b' ...]), which then evaluates to 'a',True since 'b' is in the array. See previous answer for how to do what you want.
Can Python test the membership of multiple values in a list?
6,159,313
44
2011-05-28T02:30:54Z
6,159,356
33
2011-05-28T02:44:55Z
[ "python" ]
I want to test if two or more values have membership on a list, but I'm getting an unexpected result: ``` >>> 'a','b' in ['b', 'a', 'foo', 'bar'] ('a', True) ``` So, Can Python test the membership of multiple values at once in a list? What does that result mean?
Another way to do it: ``` >>> set(['a','b']).issubset( ['b','a','foo','bar'] ) True ```
How do you mock the User service in App Engine?
6,159,396
20
2011-05-28T03:01:03Z
6,175,422
17
2011-05-30T11:01:10Z
[ "python", "google-app-engine" ]
I am using the Google App Engine `testbed` framework to write test cases with mock objects. This is documented [here](https://code.google.com/appengine/docs/python/tools/localunittesting.html). I've got my datastore tests working nicely using the mock database (`Testbed.init_datastore_v3_stub`), and this lets my test c...
Well I don't think there is an official way to do it, but I have been reading the source code and I found a "hack" way to do it that is working well so far. (Normally I'd be worried about using undocumented behaviour, but it's a test suite so it only matters if it works on the dev server.) The dev server figures out t...
How do you mock the User service in App Engine?
6,159,396
20
2011-05-28T03:01:03Z
16,144,793
11
2013-04-22T10:26:29Z
[ "python", "google-app-engine" ]
I am using the Google App Engine `testbed` framework to write test cases with mock objects. This is documented [here](https://code.google.com/appengine/docs/python/tools/localunittesting.html). I've got my datastore tests working nicely using the mock database (`Testbed.init_datastore_v3_stub`), and this lets my test c...
**Here is what worked for me to simulate a logged in user:** ``` self.testbed.setup_env(USER_EMAIL='usermail@gmail.com',USER_ID='1', USER_IS_ADMIN='0') self.testbed.init_user_stub() ```
How do you mock the User service in App Engine?
6,159,396
20
2011-05-28T03:01:03Z
21,139,805
9
2014-01-15T14:18:46Z
[ "python", "google-app-engine" ]
I am using the Google App Engine `testbed` framework to write test cases with mock objects. This is documented [here](https://code.google.com/appengine/docs/python/tools/localunittesting.html). I've got my datastore tests working nicely using the mock database (`Testbed.init_datastore_v3_stub`), and this lets my test c...
In addition to [Bijan](http://stackoverflow.com/users/306478/)'s answer: The actual check in `google.appengine.api.users` looks like this: ``` def is_current_user_admin(): return (os.environ.get('USER_IS_ADMIN', '0')) == '1' ``` The key is thus to set the environment variable `USER_IS_ADMIN` to `'1'`. This can b...
Module import works on interpreter but not on a script
6,159,523
3
2011-05-28T03:46:17Z
6,159,877
9
2011-05-28T05:36:48Z
[ "python", "import", "interpreter", "elementtree" ]
i was beggining to follow a tutorial on elementtree in this site <http://www.bigfatalien.com/?p=223> so as usual i typed the reference scripts on the interpreter and i went ``` import xml.etree.ElementTree as xml ``` And the interpreter run that command just fine and using "xml" in the intrepreter with no problems my...
A really silly question: did you name your script file `xml.py`? If so, DON'T DO THAT ... `import xml.anything` will be looking in your script file! It's never a good idea to give a script file the same name as a module that you are going to import. **Update** Tracebacks are your friends. Lead to read them carefully. ...
How to clear the whole cache when using django's page_cache decorator
6,159,841
9
2011-05-28T05:25:37Z
6,740,194
8
2011-07-18T22:28:22Z
[ "python", "django", "caching" ]
I've got a pretty simple site where I'm using the `page_cache` decorator. I have a cronjob that checks for new data and processes it if it's available. (This is run using management commands executed with crontab) I want to then clear all the page caches when new data is processed. I'm looking at the documentation he...
I've had this problem with an SQLite database cache - the `clear()` method doesn't clear the cache although it works fine with a MySQL database cache. It seems that a SQLite cache needs a call to `django.db.transation.commit_unless_managed()` after the `DELETE from [table]` statement is run. I have been using multiple...
Correct way to write line to file in Python
6,159,900
481
2011-05-28T05:44:53Z
6,159,910
37
2011-05-28T05:48:14Z
[ "python", "file-io" ]
I'm used to doing `print >>f, "hi there"` However, it seems that `print >>` is getting deprecated. What is the recommended way to do the line above? **Update**: Regarding all those answers with `"\n"`...is this universal or Unix-specific? IE, should I be doing `"\r\n"` on Windows?
I do not think there is a "correct" way. I would use: ``` with open ('myfile', 'a') as f: f.write ('hi there\n') ``` In memoriam [Tim Toady](http://en.wikipedia.org/wiki/There%27s_more_than_one_way_to_do_it).
Correct way to write line to file in Python
6,159,900
481
2011-05-28T05:44:53Z
6,159,912
646
2011-05-28T05:48:38Z
[ "python", "file-io" ]
I'm used to doing `print >>f, "hi there"` However, it seems that `print >>` is getting deprecated. What is the recommended way to do the line above? **Update**: Regarding all those answers with `"\n"`...is this universal or Unix-specific? IE, should I be doing `"\r\n"` on Windows?
You should use the new print() statement, available with Python 2.6+ ``` from __future__ import print_function print("hi there", file=f) ``` The alternative would be to use: ``` f = open('myfile','w') f.write('hi there\n') # python will convert \n to os.linesep f.close() # you can omit in most cases as the destructo...
Correct way to write line to file in Python
6,159,900
481
2011-05-28T05:44:53Z
6,159,915
13
2011-05-28T05:49:25Z
[ "python", "file-io" ]
I'm used to doing `print >>f, "hi there"` However, it seems that `print >>` is getting deprecated. What is the recommended way to do the line above? **Update**: Regarding all those answers with `"\n"`...is this universal or Unix-specific? IE, should I be doing `"\r\n"` on Windows?
In Python 3 it is a function, but in Python 2 you can add this to the top of the source file: ``` from __future__ import print_function ``` Then you do ``` print("hi there", file=f) ```
Correct way to write line to file in Python
6,159,900
481
2011-05-28T05:44:53Z
6,160,082
324
2011-05-28T06:36:52Z
[ "python", "file-io" ]
I'm used to doing `print >>f, "hi there"` However, it seems that `print >>` is getting deprecated. What is the recommended way to do the line above? **Update**: Regarding all those answers with `"\n"`...is this universal or Unix-specific? IE, should I be doing `"\r\n"` on Windows?
This should be as simple as: ``` >>> with open('somefile.txt', 'a') as the_file: ... the_file.write('Hello\n') ``` From The Documentation: > Do not use `os.linesep` as a line terminator when writing files opened in text mode (the default); use a single '\n' instead, on all platforms. Some useful reading: * [Th...
Correct way to write line to file in Python
6,159,900
481
2011-05-28T05:44:53Z
6,165,711
62
2011-05-29T03:02:48Z
[ "python", "file-io" ]
I'm used to doing `print >>f, "hi there"` However, it seems that `print >>` is getting deprecated. What is the recommended way to do the line above? **Update**: Regarding all those answers with `"\n"`...is this universal or Unix-specific? IE, should I be doing `"\r\n"` on Windows?
**Regarding os.linesep:** Here is an exact unedited Python 2.7.1 interpreter session on Windows: ``` Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.linesep '\r\n' >>> f = open('myfile','w...
Correct way to write line to file in Python
6,159,900
481
2011-05-28T05:44:53Z
12,871,858
58
2012-10-13T09:37:19Z
[ "python", "file-io" ]
I'm used to doing `print >>f, "hi there"` However, it seems that `print >>` is getting deprecated. What is the recommended way to do the line above? **Update**: Regarding all those answers with `"\n"`...is this universal or Unix-specific? IE, should I be doing `"\r\n"` on Windows?
The [python docs](http://docs.python.org/tutorial/inputoutput.html) recommend this way: ``` with open('file_to_write', 'w') as f: f.write('file contents') ``` So this is the way I do it do :) Statement from [docs.python.org](http://docs.python.org/tutorial/inputoutput.html): > It is good practice to use the **'...
Python multiple classes
6,160,705
2
2011-05-28T09:12:54Z
6,160,742
7
2011-05-28T09:20:00Z
[ "python" ]
I want to create multiple bots with all their own unique id. But how can do this automatically for numerous bots and have all an other id? I can use bot1, bot2 but what if i want to use this with 100 bots? ``` class newbot: id = randomid() bot1 = newbot() bot2 = newbot() print bot1.id print bot2.id #all th...
The `id` member ends up being shared among all instances of your class because it's defined as a class member instead of an instance member. You probably should write: ``` class newbot(object): def __init__(self): self.id = randomid() bot1 = newbot() bot2 = newbot() # The two ids should be different,...
Python MySQLdb 'not all arguments converted during string formatting'
6,161,697
2
2011-05-28T12:40:01Z
6,161,723
10
2011-05-28T12:44:17Z
[ "python", "mysql" ]
I'm doing a task for uni, where we take a text file with a list of student IDs and their favourite movies, games, tv shows, et cetera, and populating a MySQL database with it. The text files are formatted like so: ``` 1 Fight Club 1 Pootie Tang 3 The Lord Of The Rings Trilogy 3 Ocean's Eleven 3 The Italian J...
Its must be the typo, remove the $ and replace it with % Error code: ``` cursor.executemany('''INSERT INTO popularity VALUES (%s, %s, $s)''', entries_list) ``` Corrected code: ``` cursor.executemany('''INSERT INTO popularity VALUES (%s, %s, %s)''', entries_list) ```
Sort list by nested tuple values
6,162,823
4
2011-05-28T16:13:24Z
6,162,837
7
2011-05-28T16:16:26Z
[ "python", "sorting", "tuples" ]
Is there a better way to sort a list by a nested tuple values than writing an itemgetter alternative that extracts the nested tuple value: ``` def deep_get(*idx): def g(t): for i in idx: t = t[i] return t return g >>> l = [((2,1), 1),((1,3), 1),((3,6), 1),((4,5), 2)] >>> sorted(l, key=deep_get(0,0)) [...
Yes, you could just use a `key=lambda x: x[0][1]`
Turn an application or script into a shell command
6,163,087
4
2011-05-28T17:04:30Z
6,163,113
7
2011-05-28T17:07:35Z
[ "python", "shell", "command-line" ]
When I want to run my python applications from commandline (under ubuntu) I have to be in the directory where is the source code app.py and run the application with command `python app.py` How can I make it (how is it conventionally done) to run the application from arbitrary directory with the command: `app` ? Simil...
1. Add a [shebang line](http://en.wikipedia.org/wiki/Shebang_%28Unix%29) at the beginning of your file: ``` #!/usr/bin/env python ``` 2. Make your file executable by calling ``` chmod +x app.py ``` in the shell. 3. Move it to some location included in the `PATH` environment variable and rename i...
binning data in python with scipy/numpy
6,163,334
54
2011-05-28T17:43:00Z
6,163,403
80
2011-05-28T17:53:58Z
[ "python", "numpy", "scipy", "scientific-computing" ]
is there a more efficient way to take an average of an array in prespecified bins? for example, i have an array of numbers and an array corresponding to bin start and end positions in that array, and I want to just take the mean in those bins? I have code that does it below but i am wondering how it can be cut down and...
It's probably faster and easier to use [`numpy.digitize()`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.digitize.html): ``` import numpy data = numpy.random.random(100) bins = numpy.linspace(0, 1, 10) digitized = numpy.digitize(data, bins) bin_means = [data[digitized == i].mean() for i in range(1, len(bi...
binning data in python with scipy/numpy
6,163,334
54
2011-05-28T17:43:00Z
21,712,136
13
2014-02-11T20:17:50Z
[ "python", "numpy", "scipy", "scientific-computing" ]
is there a more efficient way to take an average of an array in prespecified bins? for example, i have an array of numbers and an array corresponding to bin start and end positions in that array, and I want to just take the mean in those bins? I have code that does it below but i am wondering how it can be cut down and...
Not sure why this thread got necroed; but here is a 2014 approved answer, which should be far faster: ``` import numpy as np data = np.random.rand(100) bins = 10 slices = np.linspace(0, 100, bins+1, True).astype(np.int) counts = np.diff(slices) mean = np.add.reduceat(data, slices[:-1]) / counts print mean ```
binning data in python with scipy/numpy
6,163,334
54
2011-05-28T17:43:00Z
26,884,483
16
2014-11-12T10:19:26Z
[ "python", "numpy", "scipy", "scientific-computing" ]
is there a more efficient way to take an average of an array in prespecified bins? for example, i have an array of numbers and an array corresponding to bin start and end positions in that array, and I want to just take the mean in those bins? I have code that does it below but i am wondering how it can be cut down and...
The Scipy (>=0.11) function [scipy.stats.binned\_statistic](http://docs.scipy.org/doc/scipy-dev/reference/generated/scipy.stats.binned_statistic.html) specifically addresses the above question. For the same example as in the previous answers, the Scipy solution would be ``` import numpy as np from scipy.stats import ...
Python package structure, setup.py for running unit tests
6,164,004
52
2011-05-28T19:51:46Z
6,165,054
38
2011-05-28T23:42:33Z
[ "python", "testing", "setuptools" ]
I'm not sure I'm organizing my package structure correctly or am using the right options in setup.py because I'm getting errors when I try to run unit tests. I have a structure like this: ``` /project /bin /src /pkgname __init__.py module1.py module2.py /test...
Through some trial and error, I found the cause of this problem. Test names should match module names. If there is a "foo\_test.py" test, there needs to be a corresponding module foo.py. I found some [guidelines on organizing package structure](http://python-packaging-user-guide.readthedocs.org), which helped me reorg...
Make Python Sublists from a list using a Separator
6,164,313
7
2011-05-28T20:57:27Z
6,164,322
13
2011-05-28T20:59:49Z
[ "python", "split", "sublist" ]
I have for example the following list: ``` ['|', u'MOM', u'DAD', '|', u'GRAND', '|', u'MOM', u'MAX', u'JULES', '|'] ``` and want it to be split by the "|" so the result would look like: ``` [[u'MOM', u'DAD'],[ u'GRAND'], [u'MOM', u'MAX', u'JULES']] ``` How can I do this? I only find examples of sublists on the net ...
``` >>> [list(x[1]) for x in itertools.groupby(['|', u'MOM', u'DAD', '|', u'GRAND', '|', u'MOM', u'MAX', u'JULES', '|'], lambda x: x=='|') if not x[0]] [[u'MOM', u'DAD'], [u'GRAND'], [u'MOM', u'MAX', u'JULES']] ```
iterating through a list with an if statement
6,164,443
5
2011-05-28T21:28:22Z
6,164,481
8
2011-05-28T21:36:16Z
[ "python", "list", "loops", "if-statement" ]
I have a list that I am looping through with a "for" loop and am running each value in the list through an if statement. My problem is that I am trying to only have the program do something if all the values in the list pass the if statement and if one doesn't pass, I want it to move along to the next value in the list...
Python gives you loads of options to deal with such a situation. If you have example code we could narrow that down for you. One option you could look at is the [`all`](http://docs.python.org/library/functions.html#all) operator: ``` >>> all([1,2,3,4]) True >>> all([1,2,3,False]) False ``` You could also check for t...
Getting two strings in variable from URL in Django
6,164,540
6
2011-05-28T21:47:40Z
6,169,429
22
2011-05-29T18:00:26Z
[ "python", "django", "url" ]
I'm having some trouble sending along more than one variable to the view. my urls.py is as follows: ``` urlpatterns = patterns('', url(r'^rss/(?P<anything>[^/]+)/$', 'rss.rssama.views.makerss', name='anything'), url(r'^$', 'rss.rssama.views.home'), ) ``` views.py ``` def maakrss(request, anything): ``` ...
To begin with, the regex part should look like this: ``` r'^/rss/(?P<anynumber>\d+)/(?P<anystring>.+)/$' ``` Those strings inside the `<...>` parts allow you to give a name to whatever the regex matches. Django will then use that name to pass the value to your function. Therefore your function must have an argument w...
How can I use both a key and an index for the same dictionary value?
6,164,973
10
2011-05-28T23:22:11Z
6,164,999
7
2011-05-28T23:27:24Z
[ "python", "python-2.7" ]
I need an array of data that has a numeric index, but also a human readable index. I need the latter because the numeric indices may change in the future, and I need the numeric indices as a part of a fixed length socket message. My imagination suggests something like this: ``` ACTIONS = { (0, "ALIVE") : (1, 4, F...
The simplest way to achieve this is to have *two* dictionaries: One mapping the indices to your values, and one mapping the string keys to the same objects: ``` >> actions = {"alive": (1, 4, False), "dead": (2, 1, True)} >> indexed_actions = {0: actions["alive"], 2: actions["dead"]} >> actions["alive"] (1, 4, False) >...
Python meta-circular evaluator
6,165,177
5
2011-05-29T00:17:40Z
6,171,266
7
2011-05-30T00:04:17Z
[ "python", "self-interpreter" ]
It's not uncommon for an intro programming class to write a Lisp metacircular evaluator. Has there been any attempt at doing this for Python? Yes, I know that Lisp's structure and syntax lends itself nicely to a metacircular evaluator, etc etc. Python will most likely be more difficult. I am just curious as to whether...
For those who don't know what a *meta-circular evaluator* is, it is an interpreter which is written in the language to be interpreted. For example: a Lisp interpreter written in Lisp, or in our case, a Python interpreter written in Python. For more information, [read this chapter from SICP](http://mitpress.mit.edu/sicp...
shrink parents widgets after child size changed
6,166,484
3
2011-05-29T07:34:27Z
6,166,585
7
2011-05-29T07:57:10Z
[ "python", "qt", "pyqt" ]
How can I make all widgets shrink, if one of their children changed height? They expand if new height is bigger, but don't shrink if smaller. I tried `updateGeometry()`, but it changed nothing. Here is example, after child element shran, parents' height don't change: ![enter image description here](http://i.stack...
You should call the [`adjustSize()`](http://doc.qt.nokia.com/latest/qwidget.html#adjustSize) method on your "toplevel" widget (your `MainWindow` in this case). You'll need to propagate that call up the widget hierarchy yourself for more complex layouts than your sample. In C++, you could do something like this: ``` Q...
How to put multiple statements in one line?
6,167,127
51
2011-05-29T10:14:14Z
6,167,200
9
2011-05-29T10:32:04Z
[ "python" ]
I wasn't sure under what title to ponder this question exactly, coding golf seems appropriate if a bit unspecific. I know a little bit of comprehensions in python but they seem very hard to 'read'. The way I see it, a comprehension might accomplish the same as the following code: ``` for i in range(10): if i == 9: pr...
## Do not do this! What you are describing is *not* a comprehension. It's incomprehensible! From [PEP 8 Style Guide for Python Code](http://www.python.org/dev/peps/pep-0008/), which is essential reading for every Python developer: > * Compound statements (multiple statements on the same line) are generally discourag...
How to put multiple statements in one line?
6,167,127
51
2011-05-29T10:14:14Z
6,167,353
48
2011-05-29T11:00:03Z
[ "python" ]
I wasn't sure under what title to ponder this question exactly, coding golf seems appropriate if a bit unspecific. I know a little bit of comprehensions in python but they seem very hard to 'read'. The way I see it, a comprehension might accomplish the same as the following code: ``` for i in range(10): if i == 9: pr...
Unfortunately, what you want is not possible with Python (which makes Python close to useless for command-line one-liner programs). Even explicit use of parens does not avoid the syntax exception. You can get ayway with a sequence of simple statments, separated by semi-colon: ``` for i in range(10): print "foo"; print...
How to put multiple statements in one line?
6,167,127
51
2011-05-29T10:14:14Z
24,451,002
20
2014-06-27T11:43:51Z
[ "python" ]
I wasn't sure under what title to ponder this question exactly, coding golf seems appropriate if a bit unspecific. I know a little bit of comprehensions in python but they seem very hard to 'read'. The way I see it, a comprehension might accomplish the same as the following code: ``` for i in range(10): if i == 9: pr...
You could use the built-in exec statement, eg.: ``` exec("try: \n \t if sam[0] != 'harry': \n \t\t print('hello', sam) \nexcept: pass") ``` Where `\n` is a newline and `\t` is used as indentation (a tab). Also, you should count the spaces you use, so your indentation matches exactly. However, as all the other ans...
What does [:] in Python mean
6,167,238
45
2011-05-29T10:41:03Z
6,167,245
8
2011-05-29T10:42:08Z
[ "python", "arrays", "syntax", "slice" ]
I'm analyzing some Python code and I don't know what ``` pop = population[:] ``` means. Is it something like array lists in Java or like a bi-dimensional array? Could appreciate some help, thanks.
It is a [slice](http://docs.python.org/tutorial/introduction.html#lists) from the beginning of the sequence to the end, usually producing a shallow copy. (Well, it's [more than that](http://docs.python.org/reference/datamodel.html#object.__getitem__), but you don't need to care yet.)
What does [:] in Python mean
6,167,238
45
2011-05-29T10:41:03Z
6,167,246
75
2011-05-29T10:42:13Z
[ "python", "arrays", "syntax", "slice" ]
I'm analyzing some Python code and I don't know what ``` pop = population[:] ``` means. Is it something like array lists in Java or like a bi-dimensional array? Could appreciate some help, thanks.
It's a slicing, and what it does depends on the type of `population`. If `population` is a list, this line will create a copy of the list. For an object of type `tuple` or a `str`, it will do nothing (the line will do the same without `[:]`), and for a (say) NumPy array, it will create a new view to the same data.
What does [:] in Python mean
6,167,238
45
2011-05-29T10:41:03Z
6,167,394
18
2011-05-29T11:07:10Z
[ "python", "arrays", "syntax", "slice" ]
I'm analyzing some Python code and I don't know what ``` pop = population[:] ``` means. Is it something like array lists in Java or like a bi-dimensional array? Could appreciate some help, thanks.
It might also help to know that a list slice in general makes a copy of part of the list. E.g. `population[2:4]` will return a list containing population[2] and population[3] (slicing is right-exclusive). Leaving away the left and right index, as in `population[:]` they default to 0 and length(population) respectively,...
What does [:] in Python mean
6,167,238
45
2011-05-29T10:41:03Z
14,881,308
12
2013-02-14T18:11:19Z
[ "python", "arrays", "syntax", "slice" ]
I'm analyzing some Python code and I don't know what ``` pop = population[:] ``` means. Is it something like array lists in Java or like a bi-dimensional array? Could appreciate some help, thanks.
well... this really depends on the context. Ultimately, it passes a [`slice`](http://docs.python.org/2/library/functions.html#slice) object (`slice(None,None,None)`) to one of the following methods: [`__getitem__`](http://docs.python.org/2/reference/datamodel.html#object.__getitem__), [`__setitem__`](http://docs.python...
Python : Correct way to strip <p> and </p> from string?
6,167,366
2
2011-05-29T11:01:53Z
6,167,467
11
2011-05-29T11:22:18Z
[ "python", "string" ]
I want to strip out `<p>` and `</p>` from a string (lets say `s`). Right now I am doing this : ``` s.strip('"<p>""</p>"') ``` I am not really sure if what I am doing is correct, but this has been effective enough with most of the strings that I have used. Except, I still get the following string : `Here goes..</p>`...
If you're dealing with a lot of HTML/XML, you might want to use a parser to easily and safely manipulate it instead of using basic string manipulation functions. I really like [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) for this kind of work. It works with invalid markup and has a really elegant API....
The logging.handlers: How to rollover after time or maxBytes?
6,167,587
12
2011-05-29T11:53:04Z
6,347,764
8
2011-06-14T17:47:45Z
[ "python", "logging", "handlers" ]
I do struggle with the logging a bit. I'd like to roll over the logs after certain period of time and also after reaching certain size. Rollover after a period of time is made by [`TimedRotatingFileHandler`](http://docs.python.org/library/logging.handlers.html#logging.handlers.TimedRotatingFileHandler), and rollover a...
So I made a small hack to `TimedRotatingFileHandler` to be able to do rollover after both, time and size. I had to modify `__init__`, `shouldRollover`, `doRollover` and `getFilesToDelete` (see below). This is the result, when I set up when='M', interval=2, backupCount=20, maxBytes=1048576: ``` -rw-r--r-- 1 user group ...
How to parse this format (Praat TextGrid)
6,167,630
4
2011-05-29T12:05:29Z
6,193,059
9
2011-05-31T20:16:40Z
[ "python", "parsing", "text" ]
TextGrid is the "segmentation" file used by Praat program. I'd like to write a parser that will then verify the data. My question is: How would you write a parser for this format? Read it line by line or something else? Is this a known format? ``` File type = "ooTextFile" Object class = "TextGrid" xmin = 0 xmax = 9...
TextGrid parser already exists and it is a part of NLTK Toolkit. The Python file is here: <http://nltk.googlecode.com/svn/trunk/nltk_contrib/nltk_contrib/textgrid.py> Updated link: <https://github.com/nltk/nltk_contrib/blob/master/nltk_contrib/textgrid.py>
Printing list elements on separated lines in Python
6,167,731
25
2011-05-29T12:32:10Z
6,167,735
58
2011-05-29T12:33:08Z
[ "python" ]
I am trying to print out Python path folders using this: ``` import sys print sys.path ``` The output is like this: ``` >>> print sys.path ['.', '/usr/bin', '/home/student/Desktop', '/home/student/my_modules', '/usr/lib/pyth on2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', '/usr/lib/pyth on2.6/...
``` print("\n".join(sys.path)) ``` (The outer parens are included for Python 3 compatibility and usually omitted in Python 2.)
Printing list elements on separated lines in Python
6,167,731
25
2011-05-29T12:32:10Z
6,168,004
11
2011-05-29T13:33:52Z
[ "python" ]
I am trying to print out Python path folders using this: ``` import sys print sys.path ``` The output is like this: ``` >>> print sys.path ['.', '/usr/bin', '/home/student/Desktop', '/home/student/my_modules', '/usr/lib/pyth on2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', '/usr/lib/pyth on2.6/...
``` for path in sys.path: print path ```
Printing list elements on separated lines in Python
6,167,731
25
2011-05-29T12:32:10Z
6,168,360
7
2011-05-29T14:43:42Z
[ "python" ]
I am trying to print out Python path folders using this: ``` import sys print sys.path ``` The output is like this: ``` >>> print sys.path ['.', '/usr/bin', '/home/student/Desktop', '/home/student/my_modules', '/usr/lib/pyth on2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', '/usr/lib/pyth on2.6/...
Use the print function (python 3.x) or import it (python 2.6+) ``` from __future__ import print_function print(*sys.path, sep='\n') ```
Python Bencoding using BitTorrent-bencode 5.0.8.1
6,167,823
2
2011-05-29T12:51:53Z
6,167,987
10
2011-05-29T13:30:01Z
[ "python" ]
I'm new to python and bencoding. I need to read and write torrent files for my project using python. I have already imported the module and here's my code to parse the torrent: Here's the link to my module <http://paste2.org/p/1442120> which is a mod of <http://pypi.python.org/pypi/BitTorrent-bencode/5.0.8.1> ``` ...
The problem is that Bencoded files are not line oriented files. What you're doing is like taking a report, putting it through the shredder, and handing it to your boss one shred at a time. Here is the correct way to decode a Bencoded file: ``` import bencode print bencode.bdecode(open('file.torrent', 'rb').read()) ```
Block scope in Python
6,167,923
38
2011-05-29T13:14:27Z
6,167,932
25
2011-05-29T13:16:08Z
[ "python", "scope" ]
When you code in other languages, you will sometimes create a block scope, like this: ``` statement ... statement { statement ... statement } statement ... statement ``` One purpose (of many) is to improve code readability: to show that certain statements form a logical unit or that certain local variable...
The idiomatic way in Python is to keep your functions short. If you think you need this, refactor your code! :) Python creates a new scope for each module, class, function or generator expression (in Python 3.x also for list comprehensions). Apart from this, there are no nested scopes inside of functions.
Block scope in Python
6,167,923
38
2011-05-29T13:14:27Z
6,167,952
38
2011-05-29T13:20:28Z
[ "python", "scope" ]
When you code in other languages, you will sometimes create a block scope, like this: ``` statement ... statement { statement ... statement } statement ... statement ``` One purpose (of many) is to improve code readability: to show that certain statements form a logical unit or that certain local variable...
No, there is no language support for creating block scope. The only means to create scope is functions, classes or modules.
Python Random Slice Idiom
6,168,787
6
2011-05-29T16:07:24Z
6,168,815
12
2011-05-29T16:12:07Z
[ "python", "random", "slice" ]
Is there a pythonic way to slice a sequence type such that the returned slice is of **random length** and in **random order**? For example, something like: ``` >>> l=["a","b","c","d","e"] >>> rs=l[*:*] >>> rs ['e','c'] ```
How about... ``` random.sample(l, random.randint(1, len(l))) ``` Quick link to docs for the random module can be found [here](http://docs.python.org/library/random.html).
Replace console output in Python
6,169,217
35
2011-05-29T17:25:17Z
6,169,274
54
2011-05-29T17:34:41Z
[ "python" ]
I'm wondering how I could create one of those nifty console counters in Python as in certain C/C++-programs. I've got a loop doing things and the current output is along the lines of: ``` Doing thing 0 Doing thing 1 Doing thing 2 ... ``` what would be neater would be to just have the last line update; ``` X things ...
An easy solution is just writing `"\r"` before the string and not adding a newline; if the string never gets shorter this is sufficient... ``` sys.stdout.write("\rDoing thing %i" % i) sys.stdout.flush() ``` Slightly more sophisticated is a progress bar... this is something I am using: ``` def startProgress(title): ...
Replace console output in Python
6,169,217
35
2011-05-29T17:25:17Z
6,169,341
7
2011-05-29T17:45:38Z
[ "python" ]
I'm wondering how I could create one of those nifty console counters in Python as in certain C/C++-programs. I've got a loop doing things and the current output is along the lines of: ``` Doing thing 0 Doing thing 1 Doing thing 2 ... ``` what would be neater would be to just have the last line update; ``` X things ...
The other answer may be better, but here's what I was doing. First, I made a function called progress which prints off the backspace character: ``` def progress(x): out = '%s things done' % x # The output bs = '\b' * 1000 # The backspace print bs, print out, ``` Then I called it in a loop ...
partition string in python and get value of last segment after colon
6,169,324
16
2011-05-29T17:43:43Z
6,169,342
7
2011-05-29T17:45:48Z
[ "python", "string" ]
I need to get the value after the last colon in this example 1234567 ``` client:user:username:type:1234567 ``` I don't need anything else from the string just the last id value.
Use this: ``` "client:user:username:type:1234567".split(":")[-1] ```
partition string in python and get value of last segment after colon
6,169,324
16
2011-05-29T17:43:43Z
6,169,348
13
2011-05-29T17:46:37Z
[ "python", "string" ]
I need to get the value after the last colon in this example 1234567 ``` client:user:username:type:1234567 ``` I don't need anything else from the string just the last id value.
``` foo = "client:user:username:type:1234567" last = foo.split(':')[-1] ```
partition string in python and get value of last segment after colon
6,169,324
16
2011-05-29T17:43:43Z
6,169,363
30
2011-05-29T17:49:03Z
[ "python", "string" ]
I need to get the value after the last colon in this example 1234567 ``` client:user:username:type:1234567 ``` I don't need anything else from the string just the last id value.
``` result = mystring.rpartition(':')[2] ``` If you string does not have any `:`, the result will contain the original string. An alternative that is supposed to be a little bit slower is: ``` result = mystring.split(':')[-1] ```
no module named zlib
6,169,522
31
2011-05-29T18:16:40Z
6,169,902
22
2011-05-29T19:27:11Z
[ "python", "virtualenv", "zlib", "ubuntu-10.10" ]
First, please bear with me. I have hard time telling others my problem and this is a long thread... I am using pythonbrew to run multiple versions of python in Ubuntu 10.10. For installing pythonbrew and how it works, please refers to this link below <http://www.howopensource.com/2011/05/how-to-install-and-manage-dif...
Sounds like you need to install the devel package for zlib, probably want to do something like `sudo apt-get install zlib1g-dev` (I don't use ubuntu so you'll want to double-check the package). Instead of using python-brew you might want to consider just compiling by hand, it's not very hard. Just download the source, ...
no module named zlib
6,169,522
31
2011-05-29T18:16:40Z
9,486,138
14
2012-02-28T16:49:00Z
[ "python", "virtualenv", "zlib", "ubuntu-10.10" ]
First, please bear with me. I have hard time telling others my problem and this is a long thread... I am using pythonbrew to run multiple versions of python in Ubuntu 10.10. For installing pythonbrew and how it works, please refers to this link below <http://www.howopensource.com/2011/05/how-to-install-and-manage-dif...
By default when you configuring Python source, zlib module is disabled, so you can enable it using option **--with-zlib** when you configure it. So it becomes ``` ./configure --with-zlib ```
no module named zlib
6,169,522
31
2011-05-29T18:16:40Z
11,097,335
14
2012-06-19T08:35:06Z
[ "python", "virtualenv", "zlib", "ubuntu-10.10" ]
First, please bear with me. I have hard time telling others my problem and this is a long thread... I am using pythonbrew to run multiple versions of python in Ubuntu 10.10. For installing pythonbrew and how it works, please refers to this link below <http://www.howopensource.com/2011/05/how-to-install-and-manage-dif...
For the case I met, I found there are missing modules after make. So I did the following: 1. install zlib-devel 2. make and install python again.
How do I use matplotlib autopct?
6,170,246
19
2011-05-29T20:30:28Z
6,170,354
35
2011-05-29T20:53:17Z
[ "python", "matplotlib" ]
I'd like to create a matplotlib pie chart which has the value of each wedge written on top of the wedge. The [documentation](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.pie) suggests I should use `autopct` to do this. > autopct: [ None | format string | > format function ] > If not None, i...
`autopct` enables you to display the percent value using Python string formatting. For example, if `autopct='%.2f'`, then for each pie wedge, the format string is `'%.2f'` and the numerical percent value for that wedge is `pct`, so the wedge label is set to the string `'%.2f'%pct`. ``` import matplotlib.pyplot as plt ...
Django {% if forloop.first %} question
6,170,259
11
2011-05-29T20:32:34Z
6,170,306
10
2011-05-29T20:43:01Z
[ "python", "django" ]
I have the following code in my template: ``` {% for object in object_list %} {% with game=object.game %} {% for category in object.game.objectmeta.categories.all %} {% if category.name|title == 'Puzzle' %} {% if forloop.first %} <div class='side_header' id='dark_gamelink_side'> <a class='actionheader' h...
Edited: I have never used these variables but I think `forloop.parentloop.first` should do it. If not blame me to have misunderstand the Django [docs](https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#for). ;-) You should check if you are within the parentloop and and then within the first ne...
Is there predefined class for URL in Python?
6,170,295
8
2011-05-29T20:39:50Z
6,170,402
13
2011-05-29T21:02:06Z
[ "python", "url", "urlparse" ]
I am looking for something like [java.net.URL](http://download.oracle.com/javase/6/docs/api/java/net/URL.html) in python-modules, Django, Zope or wherever in Python. I want it preferably from the semantics **reason**, because the result of analysis of concerned program implies that the URL plays an essential role in it...
`urlparse` *does* encapsulate URLs into a class, called `ParseResult`, so it can be considered a factory function for these. Straight from the Python docs: ``` >>> urlparse('http://www.cwi.nl:80/%7Eguido/Python.html') ParseResult(scheme='http', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html', params='...