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 |
|---|---|---|---|---|---|---|---|---|---|
Doubling binary digits | 2,928,886 | 8 | 2010-05-28T12:23:26Z | 2,929,198 | 20 | 2010-05-28T13:11:51Z | [
"python",
"algorithm",
"math",
"binary"
] | How to double a number of binary digits in an integer? For example, if bin(x)="1001" then bin(y) must be "11000011". Is there any smart and fast algorithm ?
UPDATE: Here is an elegant solution:
```
''.join([''.join(i) for i in zip(X,X)])
```
where X is bin(int\_x)[2:]
However, I am interested in a more faster way a... | Here's one way that should be reasonably fast: convert your number to a binary string, then reinterpret the result as being in base 4. Now to make sure that all the '1's are doubled properly, multiply the result by 3.
```
>>> x = 9
>>> bin(x)
'0b1001'
>>> y = int(bin(x)[2:], 4)*3
>>> bin(y)
'0b11000011'
``` |
Doubling binary digits | 2,928,886 | 8 | 2010-05-28T12:23:26Z | 2,929,404 | 16 | 2010-05-28T13:34:54Z | [
"python",
"algorithm",
"math",
"binary"
] | How to double a number of binary digits in an integer? For example, if bin(x)="1001" then bin(y) must be "11000011". Is there any smart and fast algorithm ?
UPDATE: Here is an elegant solution:
```
''.join([''.join(i) for i in zip(X,X)])
```
where X is bin(int\_x)[2:]
However, I am interested in a more faster way a... | (Reference <http://graphics.stanford.edu/~seander/bithacks.html#Interleave64bitOps>):
If your number is below 256, you may use
```
@magic
def double_digits_holger8(x):
m = (x * 0x0101010101010101 & 0x8040201008040201) * 0x0102040810204081
return ((m >> 49) & 0x5555) | ((m >> 48) & 0xAAAA)
```
and if it is be... |
Cross platform /dev/null in Python | 2,929,899 | 57 | 2010-05-28T14:34:08Z | 2,929,946 | 93 | 2010-05-28T14:40:07Z | [
"python"
] | I'm using the following code to hide stderr on Linux/OSX for a Python library I do not control that writes to stderr by default:
```
f = open("/dev/null","w")
zookeeper.set_log_stream(f)
```
Is there an easy cross platform alternative to /dev/null? Ideally it would not consume memory since this is a long running proc... | How about [os.devnull](http://docs.python.org/library/os.html#os.devnull) ?
```
import os
f = open(os.devnull,"w")
zookeeper.set_log_stream(f)
``` |
Cross platform /dev/null in Python | 2,929,899 | 57 | 2010-05-28T14:34:08Z | 2,929,954 | 37 | 2010-05-28T14:40:57Z | [
"python"
] | I'm using the following code to hide stderr on Linux/OSX for a Python library I do not control that writes to stderr by default:
```
f = open("/dev/null","w")
zookeeper.set_log_stream(f)
```
Is there an easy cross platform alternative to /dev/null? Ideally it would not consume memory since this is a long running proc... | ```
class Devnull(object):
def write(self, *_): pass
zookeeper.set_log_stream(Devnull())
```
Opening `os.devnull` is fine too of course, but this way every output operation occurs (as a noop) "in process" -- no context switch to the OS and back, and also no buffering (while some buffering is normally used by an `... |
Python help reading csv file failing due to line-endings | 2,930,673 | 8 | 2010-05-28T16:16:29Z | 2,933,928 | 20 | 2010-05-29T05:26:04Z | [
"python",
"csv",
"universal",
"line-endings"
] | I'm trying to create this script that will check the computer host name then search a master list for the value to return a corresponding value in the csv file. Then open another file and do a find an replace. I know this should be easy but haven't done so much in python before. Here is what I have so far...
```
maste... | The two occurrences of '\xD5' in line 194 and the last line have nothing to do with the problem.
The problem appears to be a bug, or a misleading error message, or incorrect/vague documentation, in the Python 2.6 csv module.
In the file, the lines are terminated by '\x0D' aka '\r' in the Classic Mac tradition. The la... |
Pickling an unbound method in Python 3 | 2,930,792 | 9 | 2010-05-28T16:32:37Z | 2,931,464 | 7 | 2010-05-28T18:13:11Z | [
"python",
"methods",
"python-3.x",
"pickle"
] | I would like to pickle an unbound method in Python 3.x. I'm getting this error:
```
>>> class A:
... def m(self):
... pass
>>> import pickle
>>> pickle.dumps(A.m)
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
pickle.dumps(A.m)
File "C:\Python31\lib\pickle.py", line 1358... | This cannot be done directly because in Python 3 unbound method type is gone: it is just a function:
```
>>> print (type (A.m))
<class 'function'>
```
Python functions are not bound to a class, so it is impossible to tell what class `A.m` belongs to just by looking at the expression result.
Depending on what exactly... |
Fastest way to find the rotation of a vector | 2,930,942 | 2 | 2010-05-28T16:56:24Z | 2,931,016 | 12 | 2010-05-28T17:06:49Z | [
"python",
"optimization",
"math"
] | I have two 2D vectors, say u and v, defined by cartesian coordinates.
Imagine that vectors are needles of a clock. I'm looking for the fastest way to find out, using python, if v is after or before u (or in other words find out in wich half plane is v, regarding to position of u). For the purpose of the problem if vec... | ```
def after(u, v):
# return sign of cross product
return u[0]*v[1]<u[1]*v[0]
```
don't know if it's fast, but it is terse |
JavaScript cookie value can't be retrieved in Django | 2,931,324 | 3 | 2010-05-28T17:53:02Z | 2,931,437 | 8 | 2010-05-28T18:09:35Z | [
"javascript",
"python",
"django",
"cookies"
] | I am trying to build a web site in both English and Bulgarian using the Django framework. My idea is the user should click on a button, the page will reload and the language will be changed. This is how I am trying to do it:
In my html I hava a the button tag `<button id='btn' onclick="changeLanguage();" type="button"... | The session is not the same as a cookie.
Sessions are an internal Django database table, the key to which is stored in a cookie. However the rest of the data apart from the key is stored in the database.
If you want to access an actual cookie that's been set by the client, you need to use the `request.COOKIES` dictio... |
What is the cleanest way to do a sort plus uniq on a Python list? | 2,931,672 | 25 | 2010-05-28T18:46:48Z | 2,931,683 | 49 | 2010-05-28T18:47:58Z | [
"python"
] | Consider a Python list `my_list` containing `['foo', 'foo', 'bar']`.
What is the most Pythonic way to uniqify:ing and sorting and the list (think `cat my_list | sort | uniq`)?
This is how I currently do it and while it works I'm sure there are better ways to do it.
```
my_list = []
...
my_list.append("foo")
my_list.... | ```
my_list = sorted(set(my_list))
``` |
finding max in python as per some custom criterion | 2,931,985 | 7 | 2010-05-28T19:42:22Z | 2,932,026 | 10 | 2010-05-28T19:50:30Z | [
"python"
] | I can do max(s) to find the max of a sequence. But suppose I want to compute max according to my own function , something like so -
```
currmax = 0
def mymax(s) :
for i in s :
#assume arity() attribute is present
currmax = i.arity() if i.arity() > currmax else currmax
```
Is there a clean pythonic way of do... | For instance,
```
max (i.arity() for i in s)
``` |
finding max in python as per some custom criterion | 2,931,985 | 7 | 2010-05-28T19:42:22Z | 2,932,027 | 19 | 2010-05-28T19:50:36Z | [
"python"
] | I can do max(s) to find the max of a sequence. But suppose I want to compute max according to my own function , something like so -
```
currmax = 0
def mymax(s) :
for i in s :
#assume arity() attribute is present
currmax = i.arity() if i.arity() > currmax else currmax
```
Is there a clean pythonic way of do... | ```
max(s, key=operator.methodcaller('arity'))
```
or
```
max(s, key=lambda x: x.arity())
``` |
Change array that might contain None to an array that contains "" in python | 2,932,304 | 4 | 2010-05-28T20:30:42Z | 2,932,320 | 11 | 2010-05-28T20:32:53Z | [
"python",
"string"
] | I have a python function that gets an array called row.
Typically row contains things like:
```
["Hello","goodbye","green"]
```
And I print it with:
```
print "\t".join(row)
```
Unfortunately, sometimes it contains:
```
["Hello",None,"green"]
```
Which generates this error:
```
TypeError: sequence item 2: expec... | You can use a [conditional expression](http://docs.python.org/reference/expressions.html#conditional-expressions):
```
>>> l = ["Hello", None, "green"]
>>> [(x if x is not None else '') for x in l]
['Hello', '', 'green']
```
A slightly shorter way is:
```
>>> [x or '' for x in l]
```
But note that the second method... |
Server-side SVG to PNG (or some other image format) in python | 2,932,408 | 9 | 2010-05-28T20:44:37Z | 2,932,454 | 11 | 2010-05-28T20:52:38Z | [
"python",
"png",
"svg"
] | Currently I'm using rsvg to load the svg (from a string, not from a file) and drawing to cairo. Anyone know a better way? I use PIL elsewhere in my application, but I don't know of a way to do this with PIL. | Here's what I currently have:
```
import cairo
import rsvg
def convert(data, ofile, maxwidth=0, maxheight=0):
svg = rsvg.Handle(data=data)
x = width = svg.props.width
y = height = svg.props.height
print "actual dims are " + str((width, height))
print "converting to " + str((maxwidth, maxheight))... |
Letter Count on a string | 2,932,511 | 7 | 2010-05-28T21:04:07Z | 2,932,525 | 9 | 2010-05-28T21:06:06Z | [
"python"
] | Python newb here. I m trying to count the number of letter "a"s in a given string. Code is below. It keeps returning 1 instead 3 in string "banana". Any input appreciated.
```
def count_letters(word, char):
count = 0
while count <= len(word):
for char in word:
if char == word[count]:
... | One problem is that you are using `count` to refer both to the position in the word that you are checking, and the number of `char` you have seen, and you are using `char` to refer both to the input character you are checking, and the current character in the string. Use separate variables instead.
Also, move the `ret... |
Letter Count on a string | 2,932,511 | 7 | 2010-05-28T21:04:07Z | 2,932,539 | 20 | 2010-05-28T21:07:52Z | [
"python"
] | Python newb here. I m trying to count the number of letter "a"s in a given string. Code is below. It keeps returning 1 instead 3 in string "banana". Any input appreciated.
```
def count_letters(word, char):
count = 0
while count <= len(word):
for char in word:
if char == word[count]:
... | The other answers show what's wrong with your code. But there's also a built-in way to do this, if you weren't just doing this for an exercise:
```
>>> 'banana'.count('a')
3
```
---
Danben gave this corrected version:
```
def count_letters(word, char):
count = 0
for c in word:
if char == c:
count += 1... |
How do I use a string as a keyword argument? | 2,932,648 | 29 | 2010-05-28T21:26:41Z | 2,932,658 | 45 | 2010-05-28T21:29:25Z | [
"python",
"django"
] | Specifically, I'm trying to use a string to arbitrairly filter the ORM. I've tried exec and eval solutions, but I'm running into walls. The code below doesn't work, but it's the best way I know how to explain where I'm trying to go
```
from gblocks.models import Image
f = 'image__endswith="jpg"' # Would be scripted in... | ```
d = Image.objects.filter(**{'image__endswith': "jpg"})
``` |
How to write an XML file without header in Python? | 2,933,262 | 5 | 2010-05-29T00:28:41Z | 2,933,326 | 11 | 2010-05-29T00:56:43Z | [
"python",
"xml"
] | when using Python's stock XML tools such as `xml.dom.minidom` for XML writing, a file would always start off like
`<?xml version="1.0"?>`
`[...]`
While this is perfectly legal XML code, and it's even recommended to use the header, I'd like to get rid of it as one of the programs I'm working with has problems here.
... | Unfortunately `minidom` does not give you the option to omit the XML Declaration.
But you can always serialise the document content yourself by calling `toxml()` on the document's root element instead of the `document`. Then you won't get an XML Declaration:
```
xml= document.documentElement.toxml('utf-8')
```
...bu... |
How to set time limit on input | 2,933,399 | 16 | 2010-05-29T01:30:04Z | 2,933,402 | 8 | 2010-05-29T01:32:22Z | [
"python",
"time",
"input",
"timeout",
"user-input"
] | in python, is there a way to, while waiting for a user input, count time so that after, say 30 seconds, the `raw_input()` function is automatically skipped? | I found a solution to this problem [in a blog post](http://www.garyrobinson.net/2009/10/non-blocking-raw_input-for-python.html). Here's the code from that blog post:
```
import signal
class AlarmException(Exception):
pass
def alarmHandler(signum, frame):
raise AlarmException
def nonBlockingRawInput(prompt='... |
How to set time limit on input | 2,933,399 | 16 | 2010-05-29T01:30:04Z | 2,933,423 | 25 | 2010-05-29T01:41:29Z | [
"python",
"time",
"input",
"timeout",
"user-input"
] | in python, is there a way to, while waiting for a user input, count time so that after, say 30 seconds, the `raw_input()` function is automatically skipped? | The [signal.alarm](http://docs.python.org/library/signal.html?highlight=signal#signal.alarm) function, on which @jer's recommended solution is based, is unfortunately Unix-only. If you need a cross-platform or Windows-specific solution, you can base it on [threading.Timer](http://docs.python.org/library/threading.html?... |
Strengths and weaknesses of JIT compilers for Python | 2,933,434 | 11 | 2010-05-29T01:49:47Z | 2,933,453 | 10 | 2010-05-29T01:59:42Z | [
"python",
"compiler-construction",
"project"
] | I'm currently aware of the following Python JIT compilers: Psyco, PyPy and Unladen Swallow.
Basically, I'd like to ask for your personal experiences on the strengths and weaknesses of these compilers - and if there are any others worth looking into.
Thanks in advance,
Az | Christian Perone has an excellent [article](http://blog.christianperone.com/?p=1189) from just a few days ago where he claims (with supporting benchmark data) that `PyPy` is now the fastest, running the benchmark in 145 seconds vs 300 for Unladen Swallow and 374 for CPython (Psyco doesn't help, actually PsycoV2 slows t... |
How do I call setattr() on the current module? | 2,933,470 | 86 | 2010-05-29T02:07:22Z | 2,933,481 | 125 | 2010-05-29T02:11:38Z | [
"python",
"module",
"global-variables",
"getattr",
"setattr"
] | What do I pass as the first parameter "`object`" to the function `setattr(object, name, value)`, to set variables on the current module?
For example:
```
setattr(object, "SOME_CONSTANT", 42);
```
giving the same effect as:
```
SOME_CONSTANT = 42
```
within the module containing these lines (with the correct `objec... | ```
import sys
thismodule = sys.modules[__name__]
setattr(thismodule, name, value)
```
or, without using `setattr` (which breaks the letter of the question but satisfies the same practical purposes;-):
```
globals()[name] = value
```
**Note**: at module scope, the latter is equivalent to:
```
vars()[name] = value... |
Python os.path.walk() method | 2,934,281 | 10 | 2010-05-29T07:56:24Z | 2,934,293 | 10 | 2010-05-29T08:00:57Z | [
"python"
] | I'm currently using the `walk` method in a uni assignment. It's all working fine, but I was hoping that someone could explain something to me.
in the example below, what is the `a` parameter used for on the `myvisit` method?
```
>>> from os.path import walk
>>> def myvisit(a, dir, files):
... print dir,": %d files"... | It's the argument you gave to walk, None in the example in your question |
Python os.path.walk() method | 2,934,281 | 10 | 2010-05-29T07:56:24Z | 2,934,515 | 21 | 2010-05-29T09:35:21Z | [
"python"
] | I'm currently using the `walk` method in a uni assignment. It's all working fine, but I was hoping that someone could explain something to me.
in the example below, what is the `a` parameter used for on the `myvisit` method?
```
>>> from os.path import walk
>>> def myvisit(a, dir, files):
... print dir,": %d files"... | The first argument to your callback function is the last argument of the `os.path.walk` function. Its most obvious use is to allow you to keep state between the successive calls to the helper function (in your case, `myvisit`).
`os.path.walk` is a deprecated function. You really should use `os.walk`, which has no need... |
matplotlib.pyplot, preserve aspect ratio of the plot | 2,934,878 | 28 | 2010-05-29T11:48:15Z | 2,935,000 | 51 | 2010-05-29T12:22:29Z | [
"python",
"matplotlib"
] | Assuming we have a polygon coordinates as polygon = [(x1, y1), (x2, y2), ...], the following code displays the polygon:
```
import matplotlib.pyplot as plt
plt.fill(*zip(*polygon))
plt.show()
```
By default it is trying to adjust the aspect ratio so that the polygon (or whatever other diagram) fits inside the window,... | Does it help to use:
```
plt.axis('equal')
``` |
matplotlib.pyplot, preserve aspect ratio of the plot | 2,934,878 | 28 | 2010-05-29T11:48:15Z | 3,848,235 | 16 | 2010-10-03T01:57:49Z | [
"python",
"matplotlib"
] | Assuming we have a polygon coordinates as polygon = [(x1, y1), (x2, y2), ...], the following code displays the polygon:
```
import matplotlib.pyplot as plt
plt.fill(*zip(*polygon))
plt.show()
```
By default it is trying to adjust the aspect ratio so that the polygon (or whatever other diagram) fits inside the window,... | There is, I'm sure, a way to set this directly as part of your plot command, but I don't remember the trick. To do it after the fact you can use the current axis and set it's aspect ratio with "set\_aspect('equal')". In your example:
```
import matplotlib.pyplot as plt
plt.fill(*zip(*polygon))
plt.axes().set_aspect('e... |
Are there any Python reference counting/garbage collection gotchas when dealing with C code? | 2,935,186 | 5 | 2010-05-29T13:13:58Z | 2,935,356 | 7 | 2010-05-29T14:08:35Z | [
"python",
"garbage-collection",
"scheme",
"reference-counting",
"python-c-api"
] | Just for the sheer heck of it, I've decided to create a [Scheme binding to libpython](http://github.com/jasonbaker/pyscheme) so you can embed Python in Scheme programs. I'm already able to call into Python's C API, but I haven't really thought about memory management.
The way mzscheme's FFI works is that I can call a ... | Your link to <http://docs.python.org/extending/extending.html#reference-counts> is the right place. The Extending and Embedding and Python/C API sections of the documentation are the ones that will explain how to use the C API.
Reference counting is one of the annoying parts of using the C API. The main gotcha is keep... |
Web hooks in Python: Any particular library? | 2,935,596 | 5 | 2010-05-29T15:19:48Z | 2,935,801 | 7 | 2010-05-29T16:38:34Z | [
"python",
"hook"
] | I wanted to implement web hooks in python. Both at server end and client end. Is there any particular library for implementing web hooks? Or does django or twisted python handle this? | You should probably mention that "web hooks" is a specific concept -- as explained at [webhooks.org](http://webhooks.org/) -- to avoid getting generic answers about the web, as I see you already have. It's hardly a popular or widespread concept, so the answerers' utter confusion is not surprising but easily predictable... |
efficiently convert string (or tuple) to ctypes array | 2,935,616 | 5 | 2010-05-29T15:27:22Z | 2,935,678 | 7 | 2010-05-29T15:51:56Z | [
"python",
"python-imaging-library",
"ctypes"
] | I've got code that takes a PIL image and converts it to a ctypes array to pass out to a C function:
```
w_px, h_px = img.size
pixels = struct.unpack('%dI'%(w_px*h_px), img.convert('RGBA').tostring())
pixels_array = (ctypes.c_int * len(pixels))(*pixels)
```
But I'm dealing with big images, and unpacking that many item... | You can first build an uninitialized array:
```
pixarray = (ctypes.c_int * (w_px * h_px))()
```
and then copy the image's contents into it:
```
# dylib in MacOSX, cdll.wincrt in Win, libc.so.? in Unix, ...
clib = ctypes.CDLL('libc.dylib')
_ = clib.memcpy(pixarray, im.tostring(), w_px * h_px * 4)
```
The return val... |
BeautifulSoup: Get the contents of a specific table | 2,935,658 | 7 | 2010-05-29T15:41:56Z | 2,935,713 | 15 | 2010-05-29T16:05:25Z | [
"python",
"html",
"table",
"beautifulsoup"
] | [My local airport](http://www.iaa.gov.il/Rashat/he-IL/Airports/BenGurion/informationForTravelers/OnlineFlights.aspx?flightsType=arr) disgracefully blocks users without IE, and looks awful. I want to write a Python scripts that would get the contents of the Arrival and Departures pages every few minutes, and show them i... | This is not the specific code you need, just a demo of how to work with BeautifulSoup. It finds the table who's id is "Table1" and gets all of its tr elements.
```
html = urllib2.urlopen(url).read()
bs = BeautifulSoup(html)
table = bs.find(lambda tag: tag.name=='table' and tag.has_key('id') and tag['id']=="Table1")
r... |
Running shell commands without a shell window | 2,935,704 | 6 | 2010-05-29T16:01:07Z | 2,935,727 | 20 | 2010-05-29T16:10:46Z | [
"python",
"windows",
"shell",
"subprocess"
] | With either `subprocess.call` or `subprocess.Popen`, executing a shell command makes a shell window quicky appear and disappear.
How can I run the shell command without the shell window? | I imagine your observation is limited to Windows, since that, I believe, is the only platform on which you'll get that "console flash" issue. If so, then the [docs](http://docs.python.org/library/subprocess.html?highlight=subprocess#subprocess.Popen) offer the following semi-helpful paragraph:
> The startupinfo and cr... |
All minimum spanning trees implementation | 2,935,754 | 19 | 2010-05-29T16:17:22Z | 2,936,973 | 8 | 2010-05-29T23:38:47Z | [
"python",
"algorithm",
"language-agnostic",
"graph-theory",
"minimum-spanning-tree"
] | I've been looking for an implementation (I'm using [networkx](http://networkx.lanl.gov/) library.) that will find all the minimum spanning trees (MST) of an undirected weighted graph.
I can only find implementations for Kruskal's Algorithm and Prim's Algorithm both of which will only return a single MST.
I've seen pa... | I don't know if this is **the** solution, but it's **a** solution (it's the graph version of a brute force, I would say):
1. Find the MST of the graph using kruskal's or prim's algorithm. This should be O(E log V).
2. Generate all spanning trees. This can be done in `O(Elog(V) + V + n) for n = number of spanning trees... |
All minimum spanning trees implementation | 2,935,754 | 19 | 2010-05-29T16:17:22Z | 8,374,043 | 8 | 2011-12-04T07:57:59Z | [
"python",
"algorithm",
"language-agnostic",
"graph-theory",
"minimum-spanning-tree"
] | I've been looking for an implementation (I'm using [networkx](http://networkx.lanl.gov/) library.) that will find all the minimum spanning trees (MST) of an undirected weighted graph.
I can only find implementations for Kruskal's Algorithm and Prim's Algorithm both of which will only return a single MST.
I've seen pa... | Rubys gives a good general answer. But writing efficient code to generate all spanning trees of a graph is a beast of a challenge.
Half way down [this page](http://www-cs-staff.stanford.edu/~uno/musings.html), at around Dec 2003, you'll find an CWEB implementation of Knuth's algorithm that finds all spanning trees of ... |
can a python script know that another instance of the same script is running... and then talk to it? | 2,935,836 | 9 | 2010-05-29T16:46:00Z | 2,935,868 | 9 | 2010-05-29T16:54:09Z | [
"python",
"multithreading",
"command-line",
"ipc",
"interprocess"
] | I'd like to prevent multiple instances of the same long-running python command-line script from running at the same time, and I'd like the new instance to be able to send data to the original instance before the new instance commits suicide. How can I do this in a cross-platform way?
Specifically, I'd like to enable t... | The general approach is to have the script, on startup, set up a communication channel in a way that's guaranteed to be exclusive (other attempts to set up the same channel fail in a predictable way) so that further instances of the script can detect the first one's running *and* talk to it.
Your requirements for cros... |
can a python script know that another instance of the same script is running... and then talk to it? | 2,935,836 | 9 | 2010-05-29T16:46:00Z | 2,936,108 | 7 | 2010-05-29T18:16:10Z | [
"python",
"multithreading",
"command-line",
"ipc",
"interprocess"
] | I'd like to prevent multiple instances of the same long-running python command-line script from running at the same time, and I'd like the new instance to be able to send data to the original instance before the new instance commits suicide. How can I do this in a cross-platform way?
Specifically, I'd like to enable t... | The Alex Martelli approach of setting up a communications channel is the appropriate one. I would use a multiprocessing.connection.Listener to create a listener, in your choice. Documentation at:
<http://docs.python.org/library/multiprocessing.html#multiprocessing-listeners-clients>
Rather than using AF\_INET (sockets... |
Is it possible to find and delete orphaned blobs in the app engine blobstore? | 2,935,980 | 5 | 2010-05-29T17:30:54Z | 2,948,541 | 13 | 2010-06-01T09:24:10Z | [
"python",
"google-app-engine",
"blobstore"
] | I'm using the python api and have created a few orphaned blobs during testing.
Because of a bug in the dashboard, I can't currently delete these, and in any case going forward I would like to be able to do this programmatically since it will be unfeasible to do it manually once the number of entities goes up. | If your BlobReferenceProperty field is indexed, then yes, it's quite possible.
The [BlobInfo](http://code.google.com/appengine/docs/python/blobstore/blobinfoclass.html) class provides the same set of fields as a regular model, so you can do it something like this:
```
blobs = BlobInfo.all().fetch(500)
for blob in blo... |
Python - counting sign changes | 2,936,834 | 2 | 2010-05-29T22:42:54Z | 2,936,859 | 11 | 2010-05-29T22:51:32Z | [
"python",
"list"
] | I have a list of numbers I am reading left to right. Anytime I encounter a sign change when reading the sequence I want to count it.
```
X = [-3,2,7,-4,1,-1,1,6,-1,0,-2,1]
X = [-, +, +, -, +, -, +, +, -, -,-,+]
```
So, in this list there are 8 sign changes.
When Item `[0]` (in this case -3) is negative it is consid... | You can use [`itertools.groupby`](http://docs.python.org/library/itertools.html#itertools.groupby) to count the groups of positive and non-positive numbers:
```
>>> x = [-3,2,7,-4,1,-1,1,6,-1,0,-2,1]
>>> import itertools
>>> len(list(itertools.groupby(x, lambda x: x > 0)))
```
Result:
```
8
```
In your question y... |
Python: Implementing slicing in __getitem__ | 2,936,863 | 53 | 2010-05-29T22:52:27Z | 2,936,876 | 59 | 2010-05-29T22:56:39Z | [
"python",
"slice",
"python-datamodel"
] | I am trying to implement slice functionality for a class I am making that creates a vector representation.
I have this code so far, which I believe will properly implement the slice but whenever I do a call like `v[4]` where v is a vector python returns an error about not having enough parameters. So I am trying to fi... | The `__getitem__()` method will receive a `slice` object when the object is sliced. Simply look at the `start`, `stop`, and `step` members of the `slice` object in order to get the components for the slice.
```
>>> class C(object):
... def __getitem__(self, val):
... print val
...
>>> c = C()
>>> c[3]
3
>>> c[3... |
Python: Implementing slicing in __getitem__ | 2,936,863 | 53 | 2010-05-29T22:52:27Z | 9,951,672 | 40 | 2012-03-30T23:43:03Z | [
"python",
"slice",
"python-datamodel"
] | I am trying to implement slice functionality for a class I am making that creates a vector representation.
I have this code so far, which I believe will properly implement the slice but whenever I do a call like `v[4]` where v is a vector python returns an error about not having enough parameters. So I am trying to fi... | I have a "synthetic" list (one where the data is larger than you would want to create in memory) and my `__getitem__` looks like this:
```
def __getitem__( self, key ) :
if isinstance( key, slice ) :
#Get the start, stop, and step from the slice
return [self[ii] for ii in xrange(*key.indices(len(se... |
How to parse a directory tree in python? | 2,936,909 | 5 | 2010-05-29T23:10:44Z | 2,936,955 | 8 | 2010-05-29T23:27:32Z | [
"python"
] | I have a directory called "notes" within the notes I have categories which are named "science", "maths" ... within those folder are sub-categories, such as "Quantum Mechanics", "Linear Algebra".
```
./notes
--> ./notes/maths
------> ./notes/maths/linear_algebra
--> ./notes/physics/
------> ./notes/physics/quantum_mech... | You could utilize [`os.walk`](http://docs.python.org/library/os.html#os.walk).
```
#!/usr/bin/env python
import os
for root, dirs, files in os.walk('notes'):
print root, dirs, files
```
---
Naive two level traversing:
```
import os
from os.path import isdir, join
def cats_and_subs(root='notes'):
"""
C... |
Python: check if an object is a sequence | 2,937,114 | 27 | 2010-05-30T00:43:25Z | 2,937,122 | 38 | 2010-05-30T00:46:43Z | [
"python",
"if-statement",
"sequence",
"sequences"
] | In python is there an easy way to tell if something is not a sequence? I tried to just do:
`if x is not sequence` but python did not like that | `iter(x)` will raise a `TypeError` if `x` cannot be iterated on -- but that check "accepts" sets and dictionaries, though it "rejects" other non-sequences such as `None` and numbers.
On the other hands, strings (which most applications want to consider "single items" rather than sequences) *are* in fact sequences (so,... |
Python: check if an object is a sequence | 2,937,114 | 27 | 2010-05-30T00:43:25Z | 2,937,160 | 7 | 2010-05-30T01:03:12Z | [
"python",
"if-statement",
"sequence",
"sequences"
] | In python is there an easy way to tell if something is not a sequence? I tried to just do:
`if x is not sequence` but python did not like that | The [Python 2.6.5 documentation](http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-buffer-xrange) describes the following sequence types: string, Unicode string, list, tuple, buffer, and xrange.
```
def isSequence(obj):
return type(obj) in [str, unicode, list, tuple, buffer, xrange... |
large amount of data in many text files - how to process? | 2,937,619 | 30 | 2010-05-30T05:06:28Z | 2,937,630 | 12 | 2010-05-30T05:12:11Z | [
"python",
"sql",
"large-files",
"large-data-volumes"
] | I have large amounts of data (a few terabytes) and accumulating... They are contained in many tab-delimited flat text files (each about 30MB). Most of the task involves reading the data and aggregating (summing/averaging + additional transformations) over observations/rows based on a series of predicate statements, and... | (3) is not necessarily a bad idea -- Python makes it easy to process "CSV" file (and despite the C standing for Comma, tab as a separator is just as easy to handle) and of course gets just about as much bandwidth in I/O ops as any other language. As for other recommendations, `numpy`, besides fast computation (which yo... |
large amount of data in many text files - how to process? | 2,937,619 | 30 | 2010-05-30T05:06:28Z | 2,939,975 | 13 | 2010-05-30T19:28:18Z | [
"python",
"sql",
"large-files",
"large-data-volumes"
] | I have large amounts of data (a few terabytes) and accumulating... They are contained in many tab-delimited flat text files (each about 30MB). Most of the task involves reading the data and aggregating (summing/averaging + additional transformations) over observations/rows based on a series of predicate statements, and... | Ok, so just to be different, why not R?
* You seem to know R so you may get to working code quickly
* 30 mb per file is not large on standard workstation with a few gb of ram
* the `read.csv()` variant of `read.table()` can be very efficient if you specify the types of columns via the `colClasses` argument: instead of... |
Update model instance with dynamic field names | 2,937,661 | 3 | 2010-05-30T05:27:58Z | 2,937,665 | 11 | 2010-05-30T05:31:04Z | [
"python",
"django"
] | What I want to do is pretty simple:
```
f=Foobar.objects.get(id=1)
foo='somefield'
bar='somevalue'
f.foo=bar
f.save()
```
This doesn't work as it tries to update the f object's 'foo' field, which of course doesn't exist. How can I accomplish this? | You can use [`setattr`](http://docs.python.org/library/functions.html#setattr):
```
f = Foobar.objects.get(id=1)
foo = 'somefield'
bar = 'somevalue'
setattr(f, foo, bar) # f.foo=bar
f.save()
```
> [`setattr`] is the counterpart of `getattr()`. The arguments are an object, a string and an arbitrary value. The string m... |
Scrapy - Follow RSS links | 2,939,050 | 6 | 2010-05-30T14:40:51Z | 3,747,337 | 7 | 2010-09-19T20:29:13Z | [
"python",
"web-crawler",
"scrapy"
] | I was wondering if anyone ever tried to extract/follow RSS item links using
SgmlLinkExtractor/CrawlSpider. I can't get it to work...
I am using the following rule:
```
rules = (
Rule(SgmlLinkExtractor(tags=('link',), attrs=False),
follow=True,
callback='parse_article'),
)
```
(... | CrawlSpider rules don't work that way. You'll probably need to subclass BaseSpider and implement your own link extraction in your spider callback. For example:
```
from scrapy.spider import BaseSpider
from scrapy.http import Request
from scrapy.selector import XmlXPathSelector
class MySpider(BaseSpider):
name = '... |
Pure python implementation of greenlet API | 2,939,678 | 19 | 2010-05-30T17:52:59Z | 2,941,050 | 10 | 2010-05-31T02:05:59Z | [
"python",
"ironpython",
"jython"
] | The [greenlet](http://codespeak.net/py/0.9.2/greenlet.html) package is used by gevent and eventlet for asynchronous IO. It is written as a C-extension and therefore doesn't work with Jython or IronPython. If performance is of no concern, what is the easiest approach to implementing the greenlet API in pure Python.
A s... | It's not possible to implement greenlet in pure Python.
**UPDATE:**
* faking greenlet API with threads could be indeed doable, even if completely useless for all practical purposes
* generators cannot be used for this as they only save the state of a single frame. Greenlets save the whole stack. This means gevent can... |
Pure python implementation of greenlet API | 2,939,678 | 19 | 2010-05-30T17:52:59Z | 2,989,390 | 11 | 2010-06-07T12:23:55Z | [
"python",
"ironpython",
"jython"
] | The [greenlet](http://codespeak.net/py/0.9.2/greenlet.html) package is used by gevent and eventlet for asynchronous IO. It is written as a C-extension and therefore doesn't work with Jython or IronPython. If performance is of no concern, what is the easiest approach to implementing the greenlet API in pure Python.
A s... | This kind of thing can be achieved with co-routines which have been built-in to the standard Python distribution since version 2.5. If IronPython and co are fully compliant with all Python 2.5 features (I believe they are) you should be able to use this idiom.
See [this post](http://www.dabeaz.com/coroutines/) for mor... |
Python __import__ parameter confusion | 2,939,854 | 6 | 2010-05-30T18:45:24Z | 2,939,872 | 7 | 2010-05-30T18:49:58Z | [
"python",
"import",
"global"
] | I'm trying to import a module, while passing some global variables, but it does not seem to work:
File test\_1:
```
test_2 = __import__("test_2", {"testvar": 1})
```
File test\_2:
```
print testvar
```
This seems like it should work, and print a 1, but I get the following error when I run test\_1:
```
Traceback (... | As [the docs](http://docs.python.org/library/functions.html?highlight=__import__#__import__) explain, the `globals` parameter to `__import__` does **not** "inject" extra globals into the imported module, as you appear to believe -- indeed, what's normally passed there is the `globals()` of the *importing* module, so su... |
Parsing an RDF file in python | 2,940,454 | 4 | 2010-05-30T21:42:40Z | 2,940,495 | 8 | 2010-05-30T21:52:42Z | [
"python",
"xml",
"parsing",
"rdf"
] | Does anyone know how to pars RDF file in Python to get all the values within a specific tag?
thanks | Are you using an RDF library? Otherwise, perhaps you should. For example, see the documentation of three RDF libraries for Python:
* [Redland RDF libraries](http://librdf.org/)
* [RDFLib](http://www.rdflib.net/)
* [RDF/XML parser](http://infomesh.net/2003/rdfparser/) |
PyParsing: What does Combine() do? | 2,940,489 | 4 | 2010-05-30T21:51:04Z | 2,940,844 | 10 | 2010-05-31T00:30:25Z | [
"python",
"parsing",
"nlp",
"pyparsing"
] | What is the difference between:
```
foo = TOKEN1 + TOKEN2
```
and
```
foo = Combine(TOKEN1 + TOKEN2)
```
Thanks.
**UPDATE**: Based on my experimentation, it seems like `Combine()` is for terminals, where you're trying to build an expression to match on, whereas plain `+` is for non-terminals. But I'm not sure. | Combine has 2 effects:
* it concatenates all the tokens into a single string
* it requires the matching tokens to all be adjacent with no intervening whitespace
If you create an expression like
```
realnum = Word(nums) + "." + Word(nums)
```
Then `realnum.parseString("3.14")` will return a list of 3 tokens: the lea... |
Using custom Qt subclasses in Python | 2,940,686 | 3 | 2010-05-30T23:11:30Z | 2,940,781 | 7 | 2010-05-31T00:04:32Z | [
"c++",
"python",
"qt",
"swig"
] | First off: I'm new to both Qt and SWIG. Currently reading documentation for both of these, but this is a time consuming task, so I'm looking for some spoilers. It's good to know up-front whether something just won't work.
I'm attempting to formulate a modular architecture for some in-house software. The core component... | PyQt exposes C++ code to Python via [SIP](http://www.riverbankcomputing.co.uk/software/sip/intro); PySide does so via [Shiboken](http://www.pyside.org/docs/shiboken/). Both have roughly the same capabilities as SWIG (except that they only support "extended C++ to Python", while SWIG has back-ends for Ruby, Perl, Java, ... |
Kill process by name? | 2,940,858 | 48 | 2010-05-31T00:37:31Z | 2,940,864 | 11 | 2010-05-31T00:41:21Z | [
"python",
"process",
"kill"
] | I'm trying to kill a process (specifically iChat). On the command line, I use these commands:
```
ps -A | grep iChat
```
Then:
```
kill -9 PID
```
However, I'm not exactly sure how to translate these commands over to Python. | If you have killall:
```
os.system("killall -9 iChat");
```
Or:
```
os.system("ps -C iChat -o pid=|xargs kill -9")
``` |
Kill process by name? | 2,940,858 | 48 | 2010-05-31T00:37:31Z | 2,940,878 | 48 | 2010-05-31T00:50:04Z | [
"python",
"process",
"kill"
] | I'm trying to kill a process (specifically iChat). On the command line, I use these commands:
```
ps -A | grep iChat
```
Then:
```
kill -9 PID
```
However, I'm not exactly sure how to translate these commands over to Python. | Assuming you're on a Unix-like platform (so that `ps -A` exists),
```
>>> import subprocess, signal
>>> p = subprocess.Popen(['ps', '-A'], stdout=subprocess.PIPE)
>>> out, err = p.communicate()
```
gives you `ps -A`'s output in the `out` variable (a string). You can break it down into lines and loop on them...:
```
... |
Kill process by name? | 2,940,858 | 48 | 2010-05-31T00:37:31Z | 4,230,226 | 97 | 2010-11-19T23:11:16Z | [
"python",
"process",
"kill"
] | I'm trying to kill a process (specifically iChat). On the command line, I use these commands:
```
ps -A | grep iChat
```
Then:
```
kill -9 PID
```
However, I'm not exactly sure how to translate these commands over to Python. | [psutil](https://github.com/giampaolo/psutil) can find process by name and kill it:
```
import psutil
PROCNAME = "python.exe"
for proc in psutil.process_iter():
# check whether the process name matches
if proc.name() == PROCNAME:
proc.kill()
``` |
Kill process by name? | 2,940,858 | 48 | 2010-05-31T00:37:31Z | 11,660,877 | 24 | 2012-07-26T00:54:18Z | [
"python",
"process",
"kill"
] | I'm trying to kill a process (specifically iChat). On the command line, I use these commands:
```
ps -A | grep iChat
```
Then:
```
kill -9 PID
```
However, I'm not exactly sure how to translate these commands over to Python. | If you have to consider the Windows case in order to be cross-platform, then try the following:
```
os.system('taskkill /f /im exampleProcess.exe')
``` |
How do I embed an AppleScript in in a Python script? | 2,940,916 | 7 | 2010-05-31T01:08:23Z | 2,941,735 | 14 | 2010-05-31T06:26:07Z | [
"python",
"osx",
"applescript"
] | I am trying to embed an AppleScript in a Python script. I don't want to have to save the AppleScript as a file and then load it in my Python script. Is there a way to enter the AppleScript as a string in Python and have Python execute the AppleScript? Thanks a bunch.
Here is my script:
import subprocess
import re
impo... | Use [subprocess](http://docs.python.org/library/subprocess.html):
```
from subprocess import Popen, PIPE
scpt = '''
on run {x, y}
return x + y
end run'''
args = ['2', '2']
p = Popen(['osascript', '-'] + args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate(scpt)
print (p.returnco... |
PyParsing: Is this correct use of setParseAction()? | 2,941,029 | 5 | 2010-05-31T01:55:30Z | 2,945,146 | 15 | 2010-05-31T17:44:42Z | [
"python",
"parsing",
"nlp",
"pyparsing"
] | I have strings like this:
```
"MSE 2110, 3030, 4102"
```
I would like to output:
```
[("MSE", 2110), ("MSE", 3030), ("MSE", 4102)]
```
This is my way of going about it, although I haven't quite gotten it yet:
```
def makeCourseList(str, location, tokens):
print "before: %s" % tokens
for index, course_numb... | This solution memorizes the department when parsed, and emits a (dept,coursenum) tuple when a number is found.
```
from pyparsing import Suppress,Word,ZeroOrMore,alphas,nums,delimitedList
data = '''\
MSE 2110, 3030, 4102
CSE 1000, 2000, 3000
'''
def memorize(t):
memorize.dept = t[0]
def token(t):
return (me... |
how to show the right word in my code, my code is : os.urandom(64) | 2,941,070 | 2 | 2010-05-31T02:15:58Z | 2,941,079 | 8 | 2010-05-31T02:20:34Z | [
"python"
] | My code is:
```
print os.urandom(64)
```
which outputs:
```
> "D:\Python25\pythonw.exe" "D:\zjm_code\a.py"
\xd0\xc8=<\xdbD'
\xdf\xf0\xb3>\xfc\xf2\x99\x93
=S\xb2\xcd'\xdbD\x8d\xd0\\xbc{&YkD[\xdd\x8b\xbd\x82\x9e\xad\xd5\x90\x90\xdcD9\xbf9.\xeb\x9b>\xef#n\x84
```
which isn't readable, so I tried this:
```
print os.... | No shortage of choices. Here's a couple:
```
>>> os.urandom(64).encode('hex')
'0bf760072ea10140d57261d2cd16bf7af1747e964c2e117700bd84b7acee331ee39fae5cff6f3f3fc3ee3f9501c9fa38ecda4385d40f10faeb75eb3a8f557909'
>>> os.urandom(64).encode('base64')
'ZuYDN1BiB0ln73+9P8eoQ3qn3Q74QzCXSViu8lqueKAOUYchMXYgmz6WDmgJm1DyTX598zE2l... |
small code redundancy within while-loops (doesn't feel clean) | 2,941,272 | 11 | 2010-05-31T03:47:36Z | 2,941,282 | 31 | 2010-05-31T03:50:43Z | [
"python",
"organization",
"redundancy",
"maintainability"
] | So, in Python (though I think it can be applied to many languages), I find myself with something like this quite often:
```
the_input = raw_input("what to print?\n")
while the_input != "quit":
print the_input
the_input = raw_input("what to print?\n")
```
Maybe I'm being too picky, but I don't like how the lin... | Think **iterators** -- e.g., in this specific case:
```
for the_input in iter(lambda: raw_input('what to print?\n'), 'quit'):
print the_input
```
Most loops in Python, except at the very lowest levels of abstractions, are best implemented as `for` loops with the help of some underling iterator which captures the ... |
How to make "int" parse blank strings? | 2,941,681 | 13 | 2010-05-31T06:10:48Z | 2,941,975 | 19 | 2010-05-31T07:22:48Z | [
"python"
] | I have a parsing system for fixed-length text records based on a layout table:
```
parse_table = [\
('name', type, length),
....
('numeric_field', int, 10), # int example
('textc_field', str, 100), # string example
...
]
```
The idea is that given a table for a message type, I just go through the ... | Use a factory function instead of int or a subclass of int:
```
def mk_int(s):
s = s.strip()
return int(s) if s else 0
``` |
Python: Ignore 'Incorrect padding' error when base64 decoding | 2,941,995 | 42 | 2010-05-31T07:27:15Z | 2,942,022 | 16 | 2010-05-31T07:32:50Z | [
"python",
"base64"
] | I have some data that is base64 encoded that I want to convert back to binary even if there is a padding error in it. If I use
```
base64.decodestring(b64_string)
```
it raises an 'Incorrect padding' error. Is there another way?
UPDATE: Thanks for all the feedback. To be honest, all the methods mentioned sounded a b... | If there's a padding error it probably means your string is corrupted; base64-encoded strings should have a multiple of four length. You can try adding the padding character (`=`) yourself to make the string a multiple of four, but it should already have that unless something is wrong |
Python: Ignore 'Incorrect padding' error when base64 decoding | 2,941,995 | 42 | 2010-05-31T07:27:15Z | 2,942,039 | 12 | 2010-05-31T07:37:09Z | [
"python",
"base64"
] | I have some data that is base64 encoded that I want to convert back to binary even if there is a padding error in it. If I use
```
base64.decodestring(b64_string)
```
it raises an 'Incorrect padding' error. Is there another way?
UPDATE: Thanks for all the feedback. To be honest, all the methods mentioned sounded a b... | Just add padding as required. Heed Michael's warning, however.
```
b64_string += "=" * ((4 - len(b64_string) % 4) % 4) #ugh
``` |
Python: Ignore 'Incorrect padding' error when base64 decoding | 2,941,995 | 42 | 2010-05-31T07:27:15Z | 2,942,127 | 15 | 2010-05-31T07:49:48Z | [
"python",
"base64"
] | I have some data that is base64 encoded that I want to convert back to binary even if there is a padding error in it. If I use
```
base64.decodestring(b64_string)
```
it raises an 'Incorrect padding' error. Is there another way?
UPDATE: Thanks for all the feedback. To be honest, all the methods mentioned sounded a b... | "Incorrect padding" can mean not only "missing padding" but also (believe it or not) "incorrect padding".
If suggested "adding padding" methods don't work, try removing some trailing bytes:
```
lens = len(strg)
lenx = lens - (lens % 4 if lens % 4 else 4)
try:
result = base64.decodestring(strg[:lenx])
except etc
`... |
Python: Ignore 'Incorrect padding' error when base64 decoding | 2,941,995 | 42 | 2010-05-31T07:27:15Z | 9,807,138 | 33 | 2012-03-21T14:57:52Z | [
"python",
"base64"
] | I have some data that is base64 encoded that I want to convert back to binary even if there is a padding error in it. If I use
```
base64.decodestring(b64_string)
```
it raises an 'Incorrect padding' error. Is there another way?
UPDATE: Thanks for all the feedback. To be honest, all the methods mentioned sounded a b... | As said in other responses, there are various ways in which base64 data could be corrupted.
However, as [Wikipedia](https://en.wikipedia.org/wiki/Base64#Padding) says, removing the padding (the '=' characters at the end of base64 encoded data) is "lossless":
> From a theoretical point of view, the padding character i... |
Reading/parsing Excel (xls) files with Python | 2,942,889 | 60 | 2010-05-31T10:28:30Z | 2,942,953 | 37 | 2010-05-31T10:39:46Z | [
"python",
"xls"
] | What is the best way to read Excel (XLS) files with Python (not [CSV](http://en.wikipedia.org/wiki/Comma-separated_values) files).
Is there a built-in package which is supported by default in Python to do this task? | There is no such built-in package that I know of.
But you may find this web page interesting: <http://www.python-excel.org/> |
Reading/parsing Excel (xls) files with Python | 2,942,889 | 60 | 2010-05-31T10:28:30Z | 2,943,487 | 55 | 2010-05-31T12:24:02Z | [
"python",
"xls"
] | What is the best way to read Excel (XLS) files with Python (not [CSV](http://en.wikipedia.org/wiki/Comma-separated_values) files).
Is there a built-in package which is supported by default in Python to do this task? | I highly recommend [xlrd](http://pypi.python.org/pypi/xlrd) for reading `.xls` files.
voyager mentioned the use of COM automation. Having done this myself a few years ago, be warned that doing this is a real PITA. The number of caveats is huge and the documentation is lacking and annoying. I ran into many weird bugs a... |
Python for Windows Extensions - what does it do? | 2,943,739 | 3 | 2010-05-31T13:12:36Z | 2,943,750 | 8 | 2010-05-31T13:14:25Z | [
"python"
] | Can someone explain what this library does? Apparently, one of the things it does is allow automatic detection of SDKs. No, they don't mention what it does on their [website](http://sourceforge.net/projects/pywin32/) :-(. | It provides Python bindings for the Win32 API and for COM. |
nightmare with relative imports, how does pep 366 work? | 2,943,847 | 31 | 2010-05-31T13:34:51Z | 2,944,024 | 7 | 2010-05-31T14:03:16Z | [
"python",
"python-import",
"runpy"
] | I have a "canonical file structure" like that (I'm giving sensible names to ease the reading):
```
mainpack/
__main__.py
__init__.py
- helpers/
__init__.py
path.py
- network/
__init__.py
clientlib.py
server.py
- gui/
__init__.py
mainwindow.py
controllers.py
```
I... | The loading code seems to be something like [this](http://svn.python.org/projects/python/trunk/Lib/ihooks.py):
```
try:
return sys.modules[pkgname]
except KeyError:
if level < 1:
warn("Parent module '%s' not found while handling "
"absolute import" % pkgname, Runtim... |
nightmare with relative imports, how does pep 366 work? | 2,943,847 | 31 | 2010-05-31T13:34:51Z | 6,655,098 | 41 | 2011-07-11T19:03:41Z | [
"python",
"python-import",
"runpy"
] | I have a "canonical file structure" like that (I'm giving sensible names to ease the reading):
```
mainpack/
__main__.py
__init__.py
- helpers/
__init__.py
path.py
- network/
__init__.py
clientlib.py
server.py
- gui/
__init__.py
mainwindow.py
controllers.py
```
I... | The "boilerplate" given in [PEP 366](http://www.python.org/dev/peps/pep-0366/) seems incomplete. Although it sets the `__package__` variable, it doesn't actually import the package, which is also needed to allow relative imports to work. *extraneon*'s solution is on the right track.
Note that it is not enough to simpl... |
Java's equivalent to bisect in python | 2,945,017 | 6 | 2010-05-31T17:18:09Z | 2,945,053 | 7 | 2010-05-31T17:25:07Z | [
"java",
"python",
"bisect"
] | Is there a java's equivalent to python's bisect library? With python's bisect you can do array bisection with directions. For instance bisect.bisect\_left does:
[Locate the proper insertion point for item in list to maintain sorted order. The parameters lo and hi may be used to specify a subset of the list which shoul... | You have two options:
* [`java.util.Arrays.binarySearch`](http://java.sun.com/javase/6/docs/api/java/util/Arrays.html#binarySearch%28int%5B%5D,%20int%29) on arrays
+ (with various overloads for different array types)
* [`java.util.Collections.binarySearch`](http://java.sun.com/javase/6/docs/api/java/util/Collections... |
Python: How best to parse a simple grammar? | 2,945,357 | 14 | 2010-05-31T18:36:29Z | 2,945,415 | 13 | 2010-05-31T18:50:35Z | [
"python",
"parsing",
"nlp",
"pyparsing",
"ply"
] | Ok, so I've asked a bunch of smaller questions about this project, but I still don't have much confidence in the designs I'm coming up with, so I'm going to ask a question on a broader scale.
I am parsing pre-requisite descriptions for a course catalog. The descriptions almost always follow a certain form, which makes... | ```
def parse(astr):
astr=astr.replace(',','')
astr=astr.replace('and','')
tokens=astr.split()
dept=None
number=None
result=[]
option=[]
for tok in tokens:
if tok=='or':
result.append(option)
option=[]
continue
if tok.isalpha():
... |
Simulating python's With statement in java | 2,945,359 | 6 | 2010-05-31T18:36:56Z | 15,768,083 | 13 | 2013-04-02T15:29:04Z | [
"java",
"python",
"connection"
] | Is there something like Python **with** context manager in Java?
For example say I want to do something like the following:
```
getItem(itemID){
Connection c = C.getConnection();
c.open();
try{
Item i = c.query(itemID);
}catch(ALLBunchOfErrors){
c.close();
}
c.close();
return c;
}
```
... | Java 7 has introduced a new feature to address this issue: "try with resources"
<http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html>
[Close resource quietly using try-with-resources](http://stackoverflow.com/questions/6889697/close-resource-quietly-using-try-with-resources)
The syntax ... |
How to backup an AppEngine site? | 2,946,183 | 14 | 2010-05-31T22:06:38Z | 2,946,195 | 7 | 2010-05-31T22:09:34Z | [
"python",
"google-app-engine",
"backup"
] | So, you build a great shiny cloudy 2.0 website on top of AppEngine, with thousands upon thousands of images saved into the datastore and gigs of data at the blobstore. How do you backup them? | use google app engine data export <http://code.google.com/appengine/docs/python/tools/uploadingdata.html> |
does webapp has 'elseif' or 'elif' in template tags | 2,946,826 | 7 | 2010-06-01T01:29:51Z | 2,946,849 | 12 | 2010-06-01T01:40:13Z | [
"python",
"google-app-engine",
"if-statement"
] | my code is :
Hello!~~~
```
{% if user %}
<p>Logged in as {{ user.first_name }} {{ user.last_name }}.</p>
{% elif openid_user%}
<p>Hello, {{openid_user.nickname}}! Do you want to <a href="{{openid_logout_url}}">Log out?</p>
{% else %}
<p><a href="/login?redirect={{ current_url }}">google Log in</a>.</p>
... | **Update**: [as Jeff Bauer says in a comment below](http://stackoverflow.com/questions/2946826/does-webapp-has-elseif-or-elif-in-template-tags/2946849#comment15621678_2946849), Django 1.4 [provides an `elif` tag](https://docs.djangoproject.com/en/dev/releases/1.4/#minor-features).
Original answer as follows:
---
[Th... |
does webapp has 'elseif' or 'elif' in template tags | 2,946,826 | 7 | 2010-06-01T01:29:51Z | 2,946,852 | 14 | 2010-06-01T01:41:47Z | [
"python",
"google-app-engine",
"if-statement"
] | my code is :
Hello!~~~
```
{% if user %}
<p>Logged in as {{ user.first_name }} {{ user.last_name }}.</p>
{% elif openid_user%}
<p>Hello, {{openid_user.nickname}}! Do you want to <a href="{{openid_logout_url}}">Log out?</p>
{% else %}
<p><a href="/login?redirect={{ current_url }}">google Log in</a>.</p>
... | `webapp` per se has no templates, but you can use Django templates - **by default**, those from back in [Django 0.96](http://www.djangoproject.com/documentation/0.96/templates/#if) (as you see from the ancient docs I pointed to, that requires the nested `if` to be physically nested inside the `else` block). You can use... |
Can I program Nvidia's CUDA using only Python or do I have to learn C? | 2,947,211 | 35 | 2010-06-01T04:04:50Z | 2,947,307 | 18 | 2010-06-01T04:42:08Z | [
"python",
"cuda",
"opencl"
] | I guess the question speaks for itself. I'm interested in doing some serious computations but am not a programmer by trade. I can string enough python together to get done what I want. But can I write a program in python and have the GPU execute it using CUDA? Or do I have to use some mix of python and C?
The examples... | I believe that, with PyCUDA, your computational kernels will always have to be written as "CUDA C Code". PyCUDA takes charge of a lot of otherwise-tedious book-keeping, but does not build computational CUDA kernels from Python code. |
Can I program Nvidia's CUDA using only Python or do I have to learn C? | 2,947,211 | 35 | 2010-06-01T04:04:50Z | 2,947,984 | 8 | 2010-06-01T07:40:02Z | [
"python",
"cuda",
"opencl"
] | I guess the question speaks for itself. I'm interested in doing some serious computations but am not a programmer by trade. I can string enough python together to get done what I want. But can I write a program in python and have the GPU execute it using CUDA? Or do I have to use some mix of python and C?
The examples... | [pyopencl](http://mathema.tician.de/software/pyopencl) offers an interesting alternative to PyCUDA. It is described as a "sister project" to PyCUDA. It is a *complete* wrapper around OpenCL's API.
As far as I understand, OpenCL has the advantage of running on GPUs beyond Nvidia's. |
Can I program Nvidia's CUDA using only Python or do I have to learn C? | 2,947,211 | 35 | 2010-06-01T04:04:50Z | 3,077,807 | 20 | 2010-06-20T00:53:32Z | [
"python",
"cuda",
"opencl"
] | I guess the question speaks for itself. I'm interested in doing some serious computations but am not a programmer by trade. I can string enough python together to get done what I want. But can I write a program in python and have the GPU execute it using CUDA? Or do I have to use some mix of python and C?
The examples... | You should take a look at [CUDAmat](http://code.google.com/p/cudamat/) and [Theano](http://deeplearning.net/software/theano). Both are approaches to writing code that executes on the GPU without really having to know much about GPU programming. |
Python: How do you insert into a list by slicing? | 2,947,872 | 24 | 2010-06-01T07:12:12Z | 2,947,881 | 48 | 2010-06-01T07:13:35Z | [
"python",
"list"
] | I was instructed to prevent this from happening in a Python program but frankly I have no idea how this is even possible. Can someone give an example of how you can slice a list and insert something into it to make it bigger? Thanks | ```
>>> a = [1,2,3]
>>> a[:0] = [4]
>>> a
[4, 1, 2, 3]
```
`a[:0]` is the "slice of list `a` beginning before any elements and ending before index 0", which is initially an empty slice (since there are no elements in the original list before index 0). If you set it to be a non-empty list, that will expand the original... |
How to exit a program: sys.stderr.write() or print | 2,949,974 | 24 | 2010-06-01T13:09:25Z | 2,950,027 | 41 | 2010-06-01T13:16:26Z | [
"python"
] | I am writing a small app and I need to quit the program multiple number of times.
Should I use:
`sys.stderr.write('Ok quitting')`
`sys.exit(1)`
Or should I just do a:
`print 'Error!'`
Which is better and why? Note that I need to do this a lot. The program should completely quit. | ```
sys.exit('Error!')
```
Note from [the docs](http://docs.python.org/library/sys.html#sys.exit):
> If another type of object is passed,
> None is equivalent to passing zero,
> and any other object is printed to
> sys.stderr and results in an exit code
> of 1. In particular, sys.exit("some
> error message") is a qui... |
How to exit a program: sys.stderr.write() or print | 2,949,974 | 24 | 2010-06-01T13:09:25Z | 2,950,072 | 8 | 2010-06-01T13:21:31Z | [
"python"
] | I am writing a small app and I need to quit the program multiple number of times.
Should I use:
`sys.stderr.write('Ok quitting')`
`sys.exit(1)`
Or should I just do a:
`print 'Error!'`
Which is better and why? Note that I need to do this a lot. The program should completely quit. | They're two different ways of showing messages.
`print` generally goes to `sys.stdout` and you know where `sys.stderr` is going. It's worth knowing the difference between [stdin, stdout, and stderr](http://en.wikipedia.org/wiki/Standard_streams).
`stdout` should be used for normal program output, whereas `stderr` sho... |
python [lxml] - cleaning out html tags | 2,950,131 | 11 | 2010-06-01T13:28:34Z | 5,332,984 | 11 | 2011-03-16T23:19:36Z | [
"python",
"parsing",
"lxml"
] | ```
from lxml.html.clean import clean_html, Cleaner
def clean(text):
try:
cleaner = Cleaner(scripts=True, embedded=True, meta=True, page_structure=True, links=True, style=True,
remove_tags = ['a', 'li', 'td'])
print (len(cleaner.clean_html(text))- len(te... | Not sure if this method existed around the time you made your question, but if you go through
```
document = lxml.html.document_fromstring(html_text)
raw_text = document.text_content()
```
That should return you all the text content in the html document, minus all the markup. |
Debugging (displaying) SQL command sent to the db by SQLAlchemy | 2,950,385 | 33 | 2010-06-01T14:01:50Z | 2,950,434 | 36 | 2010-06-01T14:07:49Z | [
"python",
"sqlalchemy"
] | I have an ORM class called Person, which wraps around a person table:
After setting up the connection to the db etc, I run the ff statement.
people = session.query(Person).all()
The person table does not contain any data (as yet), so when I print the variable people, I
get an empty list.
I renamed the table referre... | You can see the SQL statements being sent to the DB by passing echo=True when the engine instance is created (usually using the create\_engine() or engine\_from\_config() call in your code).
For example:
```
engine = sqlalchemy.create_engine('postgres://foo/bar', echo=True)
```
By default, logged statements go to st... |
Debugging (displaying) SQL command sent to the db by SQLAlchemy | 2,950,385 | 33 | 2010-06-01T14:01:50Z | 2,950,685 | 79 | 2010-06-01T14:40:38Z | [
"python",
"sqlalchemy"
] | I have an ORM class called Person, which wraps around a person table:
After setting up the connection to the db etc, I run the ff statement.
people = session.query(Person).all()
The person table does not contain any data (as yet), so when I print the variable people, I
get an empty list.
I renamed the table referre... | In addition to `echo` parameter of `create_engine()` there is a more flexible way: configuring `logging` to echo engine statements:
```
import logging
logging.basicConfig()
logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)
```
See [Configuring Logging](http://docs.sqlalchemy.org/en/latest/core/engines.htm... |
strip spaces in python | 2,950,448 | 3 | 2010-06-01T14:10:07Z | 2,950,465 | 10 | 2010-06-01T14:11:51Z | [
"python",
"string"
] | ok I know that this should be simple... anyways say:
```
line = "$W5M5A,100527,142500,730301c44892fd1c,2,686.5 4,333.96,0,0,28.6,123,75,-0.4,1.4*49"
```
I want to strip out the spaces. I thought you would just do this
```
line = line.strip()
```
but now line is still '$W5M5A,100527,142500,730301c44892fd1c,2,686.5 ... | ```
line = line.replace(' ', '')
``` |
Several modules in a package importing one common module | 2,950,557 | 4 | 2010-06-01T14:21:55Z | 2,950,584 | 8 | 2010-06-01T14:24:30Z | [
"python"
] | I am writing a python package. I am using the concept of plugins - where each plugin is a specialization of a Worker class. Each plugin is written as a module (script?) and spawned in a separate process.
Because of the base commonality between the plugins (e.g. all extend a base class 'Worker'), The plugin module gene... | No worry: only the *first* `import` of a module in the course of a program's execution causes it to be loaded. Every further import after that first one just fetches the module object from a "cache" dictionary (`sys.modules`, indexed by module name strings) and therefore it's both very fast *and* bereft of side effects... |
Cross-compiling a Python script on Linux into a Windows executable | 2,950,971 | 27 | 2010-06-01T15:18:31Z | 2,951,046 | 17 | 2010-06-01T15:29:03Z | [
"python",
"windows",
"linux",
"py2exe",
"cross-compiling"
] | I have a Python script that I'd like to compile into a Windows executable. Now, `py2exe` works fine from Windows, but I'd like to be able to run this from Linux. I *do* have Windows on my development machine, but Linux is my primary dev platform and I'm getting kind of sick of rebooting into Windows just to create the ... | Did you look at [PyInstaller](http://www.pyinstaller.org/)?
It seems that 1.4 support cross-compilation
<http://www.pyinstaller.org/browser/tags/1.4/doc/CHANGES.txt> says:
> Add support for cross-compilation: PyInstaller is now able to build Windows executables when running under Linux. See documentation for more de... |
Is it possible to use 'else' in a python list comprehension? | 2,951,701 | 100 | 2010-06-01T16:57:10Z | 2,951,716 | 12 | 2010-06-01T17:00:06Z | [
"python",
"list-comprehension"
] | Here is the code I was trying to turn into a list comprehension:
```
table = ''
for index in xrange(256):
if index in ords_to_keep:
table += chr(index)
else:
table += replace_with
```
Is there a way to add the else statement to this comprehension?
```
table = ''.join(chr(index) for index in x... | If you want an `else` you don't want to filter the list comprehension, you want it to iterate over every value. You can use `true-value if cond else false-value` as the statement instead, and remove the filter from the end:
```
table = ''.join(chr(index) if index in ords_to_keep else replace_with for index in xrange(1... |
Is it possible to use 'else' in a python list comprehension? | 2,951,701 | 100 | 2010-06-01T16:57:10Z | 2,951,722 | 167 | 2010-06-01T17:00:52Z | [
"python",
"list-comprehension"
] | Here is the code I was trying to turn into a list comprehension:
```
table = ''
for index in xrange(256):
if index in ords_to_keep:
table += chr(index)
else:
table += replace_with
```
Is there a way to add the else statement to this comprehension?
```
table = ''.join(chr(index) for index in x... | The syntax `a if b else c` is a ternary operator in Python that evaluates to `a` if the condition `b` is true - otherwise, it evaluates to `c`. It can be used in comprehension statements:
```
>>> [a if a else 2 for a in [0,1,0,3]]
[2, 1, 2, 3]
```
So for your example,
```
table = ''.join(chr(index) if index in ords_... |
Force import module from Python standard library instead of PYTHONPATH default | 2,952,045 | 12 | 2010-06-01T17:56:26Z | 2,952,130 | 11 | 2010-06-01T18:08:24Z | [
"python",
"import",
"module",
"standard-library",
"pythonpath"
] | I have a custom module in one of the directories in my PYTHONPATH with the same name as one of the standard library modules, so that when I `import module_name`, that module gets loaded. If I want to use the original standard library module, is there any way to force Python to import from the standard library rather th... | The ideal solution would be to rename your module to something not in the standard library.
You can also [switch absolute imports on](http://docs.python.org/whatsnew/2.5.html#pep-328-absolute-and-relative-imports) if you're on Python 2.5+:
```
from __future__ import absolute_import
``` |
Force import module from Python standard library instead of PYTHONPATH default | 2,952,045 | 12 | 2010-06-01T17:56:26Z | 2,953,396 | 9 | 2010-06-01T21:15:57Z | [
"python",
"import",
"module",
"standard-library",
"pythonpath"
] | I have a custom module in one of the directories in my PYTHONPATH with the same name as one of the standard library modules, so that when I `import module_name`, that module gets loaded. If I want to use the original standard library module, is there any way to force Python to import from the standard library rather th... | Don't.
If you have accidentally chosen a standard library module name, change your module name to end the conflict. |
Getting "Error loading MySQLdb module: No module named MySQLdb" - have tried previously posted solutions | 2,952,187 | 220 | 2010-06-01T18:18:10Z | 3,782,998 | 7 | 2010-09-23T22:35:03Z | [
"python",
"mysql",
"django",
"virtualenv",
"virtualenvwrapper"
] | This is a much discussed issue for OSX 10.6 users, but I haven't been able to find a solution that works. Here's my setup:
Python 2.6.1 64bit
Django 1.2.1
MySQL 5.1.47 osx10.6 64bit
I create a virtualenvwrapper with --no-site-packages, then installed Django. When I activate the virtualenv and run python manage.py syn... | This issue was the result of an incomplete / incorrect installation of the MySQL for Python adapter. Specifically, I had to edit the path to the mysql\_config file to point to /usr/local/mysql/bin/mysql\_config - discussed in greater detail in this article: <http://dakrauth.com/blog/entry/python-and-django-setup-mac-os... |
Getting "Error loading MySQLdb module: No module named MySQLdb" - have tried previously posted solutions | 2,952,187 | 220 | 2010-06-01T18:18:10Z | 4,169,790 | 298 | 2010-11-12T22:55:07Z | [
"python",
"mysql",
"django",
"virtualenv",
"virtualenvwrapper"
] | This is a much discussed issue for OSX 10.6 users, but I haven't been able to find a solution that works. Here's my setup:
Python 2.6.1 64bit
Django 1.2.1
MySQL 5.1.47 osx10.6 64bit
I create a virtualenvwrapper with --no-site-packages, then installed Django. When I activate the virtualenv and run python manage.py syn... | I had the same error and `pip install MySQL-python` solved it for me.
Alternate installs:
* If you don't have pip, `easy_install MySQL-python` should work.
* If your python is managed by a packaging system, you might have to use
that system (e.g. `sudo apt-get install ...`)
Below, Soli notes that if you receive th... |
Getting "Error loading MySQLdb module: No module named MySQLdb" - have tried previously posted solutions | 2,952,187 | 220 | 2010-06-01T18:18:10Z | 4,881,380 | 55 | 2011-02-02T23:59:36Z | [
"python",
"mysql",
"django",
"virtualenv",
"virtualenvwrapper"
] | This is a much discussed issue for OSX 10.6 users, but I haven't been able to find a solution that works. Here's my setup:
Python 2.6.1 64bit
Django 1.2.1
MySQL 5.1.47 osx10.6 64bit
I create a virtualenvwrapper with --no-site-packages, then installed Django. When I activate the virtualenv and run python manage.py syn... | Running Ubuntu, I had to do:
```
sudo apt-get install python-mysqldb
``` |
Getting "Error loading MySQLdb module: No module named MySQLdb" - have tried previously posted solutions | 2,952,187 | 220 | 2010-06-01T18:18:10Z | 7,031,378 | 49 | 2011-08-11T19:03:23Z | [
"python",
"mysql",
"django",
"virtualenv",
"virtualenvwrapper"
] | This is a much discussed issue for OSX 10.6 users, but I haven't been able to find a solution that works. Here's my setup:
Python 2.6.1 64bit
Django 1.2.1
MySQL 5.1.47 osx10.6 64bit
I create a virtualenvwrapper with --no-site-packages, then installed Django. When I activate the virtualenv and run python manage.py syn... | Adding to other answers, the following helped me finish the installation mysql-python:
[virtualenv, mysql-python, pip: anyone know how?](http://stackoverflow.com/questions/1511661/virtualenv-mysql-python-pip-anyone-know-how)
On Ubuntu...
```
apt-get install libmysqlclient-dev
apt-get install python-dev
pip install m... |
Getting "Error loading MySQLdb module: No module named MySQLdb" - have tried previously posted solutions | 2,952,187 | 220 | 2010-06-01T18:18:10Z | 8,329,935 | 13 | 2011-11-30T17:05:25Z | [
"python",
"mysql",
"django",
"virtualenv",
"virtualenvwrapper"
] | This is a much discussed issue for OSX 10.6 users, but I haven't been able to find a solution that works. Here's my setup:
Python 2.6.1 64bit
Django 1.2.1
MySQL 5.1.47 osx10.6 64bit
I create a virtualenvwrapper with --no-site-packages, then installed Django. When I activate the virtualenv and run python manage.py syn... | ```
pip install mysql-python
```
raised an error:
> EnvironmentError: mysql\_config not found
```
sudo apt-get install python-mysqldb
```
fixed the problem. |
Getting "Error loading MySQLdb module: No module named MySQLdb" - have tried previously posted solutions | 2,952,187 | 220 | 2010-06-01T18:18:10Z | 11,040,568 | 16 | 2012-06-14T20:04:34Z | [
"python",
"mysql",
"django",
"virtualenv",
"virtualenvwrapper"
] | This is a much discussed issue for OSX 10.6 users, but I haven't been able to find a solution that works. Here's my setup:
Python 2.6.1 64bit
Django 1.2.1
MySQL 5.1.47 osx10.6 64bit
I create a virtualenvwrapper with --no-site-packages, then installed Django. When I activate the virtualenv and run python manage.py syn... | `mysql_config` must be on the path. On Mac, do
```
export PATH=$PATH:/usr/local/mysql/bin/
pip install MySQL-python
``` |
Getting "Error loading MySQLdb module: No module named MySQLdb" - have tried previously posted solutions | 2,952,187 | 220 | 2010-06-01T18:18:10Z | 22,215,991 | 8 | 2014-03-06T05:42:23Z | [
"python",
"mysql",
"django",
"virtualenv",
"virtualenvwrapper"
] | This is a much discussed issue for OSX 10.6 users, but I haven't been able to find a solution that works. Here's my setup:
Python 2.6.1 64bit
Django 1.2.1
MySQL 5.1.47 osx10.6 64bit
I create a virtualenvwrapper with --no-site-packages, then installed Django. When I activate the virtualenv and run python manage.py syn... | Try this: This solved the issue for me .
> pip install MySQL-python |
Getting "Error loading MySQLdb module: No module named MySQLdb" - have tried previously posted solutions | 2,952,187 | 220 | 2010-06-01T18:18:10Z | 30,162,838 | 17 | 2015-05-11T08:26:24Z | [
"python",
"mysql",
"django",
"virtualenv",
"virtualenvwrapper"
] | This is a much discussed issue for OSX 10.6 users, but I haven't been able to find a solution that works. Here's my setup:
Python 2.6.1 64bit
Django 1.2.1
MySQL 5.1.47 osx10.6 64bit
I create a virtualenvwrapper with --no-site-packages, then installed Django. When I activate the virtualenv and run python manage.py syn... | Try this the commands below. They work for me:
```
brew install mysql-connector-c
pip install MySQL-python
``` |
Python library to split and join mp3 files | 2,952,309 | 14 | 2010-06-01T18:35:59Z | 19,985,175 | 34 | 2013-11-14T18:13:21Z | [
"python",
"mp3"
] | There are a lot of libs to work with mp3 tags, but I need just 2 functions - split mp3 file in 2 parts and the second one to merge 5 mp3.
Can you suggest anything?
Thanks! | I wrote a library ([pydub](http://pydub.com)) for pretty much this exact use case:
```
from pydub import AudioSegment
sound = AudioSegment.from_mp3("/path/to/file.mp3")
# len() and slicing are in milliseconds
halfway_point = len(sound) / 2
second_half = sound[halfway_point:]
# Concatenation is just adding
second_ha... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.