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
Is a "for" loop necessary if elements of the a numpy vector are dependant upon the previous element?
4,407,984
9
2010-12-10T10:40:18Z
4,408,341
7
2010-12-10T11:27:06Z
[ "python", "numpy" ]
``` T(i) = Tm(i) + (T(i-1)-Tm(i))**(-tau(i)) ``` Tm and tau are numpy vectors of the same length that have been previously calculated and the desire is to create a new vector T. The "i" is included only to indicate the element indexs for what is desired. Is a for loop necessary for this case?
You might think this would work: ``` import numpy as np n = len(Tm) t = np.empty(n) t[0] = 0 # or whatever the initial condition is t[1:] = Tm[1:] + (t[0:n-1] - Tm[1:])**(-tau[1:]) ``` but it doesn't: you can't actually do recursion in numpy this way (since numpy calculates the whole RHS and then assigns it to the...
execute *.sql file with python MySQLdb
4,408,714
13
2010-12-10T12:13:29Z
4,408,760
8
2010-12-10T12:20:11Z
[ "python", "mysql" ]
How can execute sql script stored in \*.sql file using MySQLdb python driver. I was trying ``` cursor.execute(file(PATH_TO_FILE).read()) ``` but this doesn't work because **cursor.execute** can run only one sql command at once. My sql script contains several sql statements instead. Also I was trying ``` cursor.execu...
``` for line in open(PATH_TO_FILE): cursor.execute(line) ``` This assumes you have one SQL statement per line in your file. Otherwise you'll need to write some rules to join lines together.
execute *.sql file with python MySQLdb
4,408,714
13
2010-12-10T12:13:29Z
4,563,950
24
2010-12-30T15:43:01Z
[ "python", "mysql" ]
How can execute sql script stored in \*.sql file using MySQLdb python driver. I was trying ``` cursor.execute(file(PATH_TO_FILE).read()) ``` but this doesn't work because **cursor.execute** can run only one sql command at once. My sql script contains several sql statements instead. Also I was trying ``` cursor.execu...
From python, I start a mysql process to execute the file for me: ``` from subprocess import Popen, PIPE process = Popen(['mysql', db, '-u', user, '-p', passwd], stdout=PIPE, stdin=PIPE) output = process.communicate('source ' + filename)[0] ```
execute *.sql file with python MySQLdb
4,408,714
13
2010-12-10T12:13:29Z
10,989,939
7
2012-06-12T02:41:26Z
[ "python", "mysql" ]
How can execute sql script stored in \*.sql file using MySQLdb python driver. I was trying ``` cursor.execute(file(PATH_TO_FILE).read()) ``` but this doesn't work because **cursor.execute** can run only one sql command at once. My sql script contains several sql statements instead. Also I was trying ``` cursor.execu...
At least `MySQLdb` 1.2.3 seems to allow this out of the box, you just have to call `cursor.nextset()` to cycle through the returned result sets. ``` db = conn.cursor() db.execute('SELECT 1; SELECT 2;') more = True while more: print db.fetchall() more = db.nextset() ``` If you want to be absolutely sure the s...
execute *.sql file with python MySQLdb
4,408,714
13
2010-12-10T12:13:29Z
19,159,041
9
2013-10-03T12:18:07Z
[ "python", "mysql" ]
How can execute sql script stored in \*.sql file using MySQLdb python driver. I was trying ``` cursor.execute(file(PATH_TO_FILE).read()) ``` but this doesn't work because **cursor.execute** can run only one sql command at once. My sql script contains several sql statements instead. Also I was trying ``` cursor.execu...
I also needed to execute a SQL file, but the catch was that there wasn't one statement per line, so the accepted answer didn't work for me. The SQL file I wanted to execute looked like this: ``` -- SQL script to bootstrap the DB: -- CREATE USER 'x'@'%' IDENTIFIED BY 'x'; GRANT ALL PRIVILEGES ON mystore.* TO 'x'@'%'; ...
Python+sqlite: the LIKE query with wildcards
4,409,539
4
2010-12-10T14:05:25Z
4,409,584
8
2010-12-10T14:10:38Z
[ "python", "database", "sqlite" ]
Hi I'm trying to search an SQlite table based on a user input with wildcards. I've tried different methods by I can't get it to work. This is the last thing I tried, it's a solution I found here actually, but it might have changed in python 3. ``` search = input("type name or partial name: ") cur.execute("sele...
Your problem just seems to be that you have supplied a string as the second argument to `cur.execute`, when you probably meant to supply a single-element tuple containing the string. Since a string is a sequence, every character in the string will be interpreted as a separate parameter and that's why you see the "Inco...
Need some Python datetime magic
4,409,549
2
2010-12-10T14:06:31Z
4,409,648
9
2010-12-10T14:15:48Z
[ "python", "datetime" ]
Hey all. I don't think this should be very complicated but I just can't get it. I have a list of `datetime` objects starting at a certain date and ending at one. Some days can be skipped. I can print them out like this: ``` for entry in dates: print entry ``` Which gives me the following output: ``` 2010-11-29 1...
Here is a way to do this by converting your `datetime`s to `date`s. Rather than try to iterate over the dates themselves, we take a `timedelta` of the last date and the first date (this requires your dates to be sorted, I added a `sorted` call in case they aren't). Then we see if the first date plus the number of days ...
How to make text strikethough in Sphinx
4,410,100
2
2010-12-10T15:00:42Z
4,410,376
9
2010-12-10T15:28:52Z
[ "python", "documentation", "python-sphinx", "strikethrough" ]
Is it possible to make text strikethrough in the sphinx documentation generator?
I've done this. Require a .CSS in your conf.py ``` html_style = 'mydoc.css' ``` In the `_static/mydoc.css`, use something like this ``` @import url("default.css"); span.strikethrough { text-decoration: line-through; } ``` In the document, do this. ``` .. role:: strikethrough make text :strikethrough:`striket...
How can I find the union of two Django querysets?
4,411,049
33
2010-12-10T16:32:44Z
4,412,293
92
2010-12-10T18:56:30Z
[ "python", "django", "django-models" ]
I’ve got a Django model with two custom manager methods. Each returns a different subset of the model’s objects, based on a different property of the object. Is there any way to get a queryset, or just a list of objects, that’s the union of the querysets returned by each manager method?
This works and looks a bit cleaner: ``` records = query1 | query2 ```
How can I find the intersection of two Django querysets?
4,411,213
13
2010-12-10T16:47:22Z
4,411,712
31
2010-12-10T17:42:33Z
[ "python", "django", "django-models" ]
I’ve got a Django model with two custom manager methods. Each returns a different subset of the model’s objects, based on a different property of the object. ``` class FeatureManager(models.Manager): def without_test_cases(self): return self.get_query_set().annotate(num_test_cases=models.Count('testca...
In most cases you can just write (exploiting the "Set" part of QuerySet) : ``` intersection = Model.objects.filter(...) & Model.objects.filter(...) ``` This isn't very well documented, but should behave almost exactly like using AND conditions on conditions from both queries. Relevant code: <https://github.com/django...
How can I find the intersection of two Django querysets?
4,411,213
13
2010-12-10T16:47:22Z
18,234,095
13
2013-08-14T14:10:51Z
[ "python", "django", "django-models" ]
I’ve got a Django model with two custom manager methods. Each returns a different subset of the model’s objects, based on a different property of the object. ``` class FeatureManager(models.Manager): def without_test_cases(self): return self.get_query_set().annotate(num_test_cases=models.Count('testca...
You can just do something like this: ``` intersection = queryset1 & queryset2 ``` To do a union just replace `&` by `|`
Python: define multiple variables of same type?
4,411,811
4
2010-12-10T17:55:35Z
4,411,828
10
2010-12-10T17:58:16Z
[ "python" ]
Probably a duplicate, but I can't find the answer by searching with these terms, at least. Is there a quicker way to do this in Python? ``` level1 = {} level2 = {} level3 = {} ``` I've tried ``` level1 = level2 = level3 = {} ``` But that seems to create copies of the object, which isn't what I want. And ``` level...
You could do ``` level1, level2, level3 = {}, {}, {} ```
Python: define multiple variables of same type?
4,411,811
4
2010-12-10T17:55:35Z
4,411,837
14
2010-12-10T17:58:45Z
[ "python" ]
Probably a duplicate, but I can't find the answer by searching with these terms, at least. Is there a quicker way to do this in Python? ``` level1 = {} level2 = {} level3 = {} ``` I've tried ``` level1 = level2 = level3 = {} ``` But that seems to create copies of the object, which isn't what I want. And ``` level...
Your variable naming is a possible sign that your design could be improved. It might be better to use a list instead of three separate variables: ``` levels = [{}, {}, {}] ```
Python: define multiple variables of same type?
4,411,811
4
2010-12-10T17:55:35Z
4,411,863
13
2010-12-10T18:02:06Z
[ "python" ]
Probably a duplicate, but I can't find the answer by searching with these terms, at least. Is there a quicker way to do this in Python? ``` level1 = {} level2 = {} level3 = {} ``` I've tried ``` level1 = level2 = level3 = {} ``` But that seems to create copies of the object, which isn't what I want. And ``` level...
``` level1 = level2 = level3 = {} ``` Doesn’t create copies. It lets reference level{1-3} to the *same* object. You can use a list comprehension instead: ``` level1, level2, level3 = [{} for dummy in range(3)] ``` or more readable: ``` level1, level2, level3 = {}, {}, {} ```
How do I create a web interface to a simple python script?
4,412,476
10
2010-12-10T19:20:55Z
4,412,938
8
2010-12-10T20:19:09Z
[ "python" ]
I am learning python. I have created some scripts that I use to parse various websites that I run daily (as their stats are updated), and look at the output in the Python interpreter. I would like to create a website to display the results. What I want to do is run my script when I go to the site, and display a sortabl...
If you are creating non-interactive pages, you can easily setup any modern web server to execute your python script as a CGI. Instead of loading a static file, your web server will return the output of your python script. This isn't very sophisticated, but if you are simply returning the output without needing browser...
How do I create a web interface to a simple python script?
4,412,476
10
2010-12-10T19:20:55Z
4,412,946
8
2010-12-10T20:20:46Z
[ "python" ]
I am learning python. I have created some scripts that I use to parse various websites that I run daily (as their stats are updated), and look at the output in the Python interpreter. I would like to create a website to display the results. What I want to do is run my script when I go to the site, and display a sortabl...
Have you considered Flask? Like Tornado, it is both a "micro-framework" and a simple web server, so it has everything you need right out of the box. <http://flask.pocoo.org/> This example (right off the homepage) pretty much sums up how simple the code can be: ``` from flask import Flask app = Flask(__name__) @app.r...
Python: How to execute an external program
4,412,852
2
2010-12-10T20:08:38Z
4,412,881
11
2010-12-10T20:12:00Z
[ "python", "subprocess" ]
How do I execute a program from within my program without blocking until the executed program finishes? I have tried: ``` os.system() ``` But it stops my program till the executed program is stopped/closed. Is there a way to allow my program to keep running after the execution of the external program?
Consider using the *subprocess* module. * Python 2: <http://docs.python.org/2/library/subprocess.html> * Python 3: <http://docs.python.org/3/library/subprocess.html> *subprocess* spawns a new process in which your external application is run. Your application continues execution while the other application runs.
python: array default value for index out-of-bounds
4,413,550
5
2010-12-10T21:39:57Z
4,413,618
8
2010-12-10T21:50:52Z
[ "python", "arrays" ]
I need a good way to ask for an array/matrix value, but reporting a default (0) value for out-of-bound index: b[2][4] should return 0 if the 2nd index length is 3, and b[-1][2] also I checked this: [Getting a default value on index out of range in Python](http://stackoverflow.com/questions/2574636/getting-a-defau...
If you want a indefinitely-sized sparse matrix, you can use defautldict: ``` py> matrix=defaultdict(lambda:defaultdict(lambda:0)) py> matrix[2][4] 0 py> matrix[2][4]=8 py> matrix[2][4] 8 py> matrix[-1][2] 0 ```
multiprocessing.Pool example
4,413,821
23
2010-12-10T22:21:33Z
4,415,314
16
2010-12-11T05:09:59Z
[ "python", "multiprocessing" ]
I'm trying to learn how to use [multiprocessing](http://docs.python.org/2/library/multiprocessing.html), and found [the following example](http://forum.openopt.org/viewtopic.php?id=51). I want to sum values as follows: ``` from multiprocessing import Pool from time import time N = 10 K = 50 w = 0 def CostlyFunction...
If you're going to use apply\_async like that, then you have to use some sort of shared memory. Also, you need to put the part that starts the multiprocessing so that it is only done when called by the initial script, not the pooled processes. Here's a way to do it with map. ``` from multiprocessing import Pool from t...
Why is print not a function in python?
4,413,912
8
2010-12-10T22:35:20Z
4,413,915
12
2010-12-10T22:35:46Z
[ "python" ]
Why is `print` a keyword in python and not a function?
Because Guido has decided that he made a mistake. :) It has since been corrected: try Python 3, which dedicates a [section of its release notes](http://docs.python.org/release/3.0.1/whatsnew/3.0.html#print-is-a-function) to describing the change to a function. For the whole background, see [PEP 3105](https://www.pyth...
Why is print not a function in python?
4,413,912
8
2010-12-10T22:35:20Z
4,415,023
7
2010-12-11T03:28:03Z
[ "python" ]
Why is `print` a keyword in python and not a function?
`print` **was** a statement in Python because it was a statement in ABC, the main inspiration for Python (although it was called `WRITE` there). That in turn probably had a statement instead of a function as it was a teaching language and as such inspired by basic. Python on the other hand, turned out to be more than a...
Getting Python's unittest results in a tearDown() method
4,414,234
35
2010-12-10T23:37:36Z
4,414,788
13
2010-12-11T02:01:01Z
[ "python", "unit-testing", "nose" ]
Is it possible to get the results of a test (i.e. whether all assertions have passed) in a tearDown() method? I'm running Selenium scripts, and I'd like to do some reporting from inside tearDown(), however I don't know if this is possible.
CAVEAT: I have no way of double checking the following theory at the moment, being away from a dev box. So this may be a shot in the dark. Perhaps you could check the return value of `sys.exc_info()` inside your tearDown() method, if it returns `(None, None, None)`, you know the test case succeeded. Otherwise, you cou...
Getting Python's unittest results in a tearDown() method
4,414,234
35
2010-12-10T23:37:36Z
4,415,062
27
2010-12-11T03:40:46Z
[ "python", "unit-testing", "nose" ]
Is it possible to get the results of a test (i.e. whether all assertions have passed) in a tearDown() method? I'm running Selenium scripts, and I'd like to do some reporting from inside tearDown(), however I don't know if this is possible.
If you take a look at the implementation of `unittest.TestCase.run`, you can see that all test results are collected in the result object (typically a `unittest.TestResult` instance) passed as argument. No result status is left in the `unittest.TestCase` object. So there isn't much you can do in the `unittest.TestCase...
Getting Python's unittest results in a tearDown() method
4,414,234
35
2010-12-10T23:37:36Z
22,597,494
9
2014-03-23T21:42:53Z
[ "python", "unit-testing", "nose" ]
Is it possible to get the results of a test (i.e. whether all assertions have passed) in a tearDown() method? I'm running Selenium scripts, and I'd like to do some reporting from inside tearDown(), however I don't know if this is possible.
If you are using Python2 you can use the method `_resultForDoCleanups`. This method return a [`TextTestResult`](http://docs.python.org/2/library/unittest.html#unittest.TextTestResult) object: `<unittest.runner.TextTestResult run=1 errors=0 failures=0>` You can use this object to check the result of your tests: ``` d...
Getting Python's unittest results in a tearDown() method
4,414,234
35
2010-12-10T23:37:36Z
23,176,373
8
2014-04-19T22:38:35Z
[ "python", "unit-testing", "nose" ]
Is it possible to get the results of a test (i.e. whether all assertions have passed) in a tearDown() method? I'm running Selenium scripts, and I'd like to do some reporting from inside tearDown(), however I don't know if this is possible.
Following on from amatellanes' answer, if you're on Python3.4, you can't use `_outcomeForDoCleanups`. Here's what I managed to hack together: ``` def _test_has_failed(self): for method, error in self._outcome.errors: if error: return True return False ``` yucky, but it seems to work.
Getting Python's unittest results in a tearDown() method
4,414,234
35
2010-12-10T23:37:36Z
30,280,840
7
2015-05-16T21:15:45Z
[ "python", "unit-testing", "nose" ]
Is it possible to get the results of a test (i.e. whether all assertions have passed) in a tearDown() method? I'm running Selenium scripts, and I'd like to do some reporting from inside tearDown(), however I don't know if this is possible.
It depends what kind of reporting you'd like to produce. In case you'd like to do some actions on failure (such as [generating a screenshots](http://stackoverflow.com/q/12290336/55075)), instead of using `tearDown()`, you may achieve that by overriding `failureException`. For example: ``` @property def failureExcept...
How can I log into a website using python?
4,414,683
7
2010-12-11T01:28:18Z
4,414,710
12
2010-12-11T01:36:25Z
[ "python", "authentication" ]
I've seen this other question: [How to use Python to login to a webpage and retrieve cookies for later usage?](http://stackoverflow.com/questions/189555/how-to-use-python-to-login-to-a-webpage-and-retrieve-cookies-for-later-usage) However, a straightforward modification of that answer did not work for me, so I'm wonde...
Try with [mechanize](http://wwwsearch.sourceforge.net/mechanize/): ``` import mechanize br=mechanize.Browser() br.open('https://mog.com/hp/sign_in') br.select_form(nr=0) br['user[login]']= your_login br['user[password]']= your_password br.submit() br.retrieve('http://mog.com/my_mog/playlists','playlist.html') ``` **...
Python Raw Strings
4,415,259
13
2010-12-11T04:49:08Z
4,415,275
16
2010-12-11T04:54:19Z
[ "python", "string" ]
I have the string U, it's contents are variable. I'd like to make it a raw string. How do I go about this? Something similar to the r'' method. ``` U = str(var) ```
raw strings apply only to string literals. they exist so that you can more conveniently express strings that would be modified by escape sequence processing. This is most especially useful when writing out regular expressions, or other forms of code in string literals. if you want a unicode string without escape proces...
Python Raw Strings
4,415,259
13
2010-12-11T04:49:08Z
4,415,585
32
2010-12-11T06:47:11Z
[ "python", "string" ]
I have the string U, it's contents are variable. I'd like to make it a raw string. How do I go about this? Something similar to the r'' method. ``` U = str(var) ```
Raw strings are **not a different kind of string**. They are a different way of describing a string in your source code. Once the string is created, it is what it is.
Python Raw Strings
4,415,259
13
2010-12-11T04:49:08Z
13,967,409
20
2012-12-20T07:44:06Z
[ "python", "string" ]
I have the string U, it's contents are variable. I'd like to make it a raw string. How do I go about this? Something similar to the r'' method. ``` U = str(var) ```
i believe what you're looking for is the str.encode("string-escape") function. For example, if you have a variable that you want to 'raw string': ``` a = '\x89' a.encode('string-escape') '\\x89' ``` I was searching for a similar solution and found the solution via: [casting raw strings python](http://stackoverflow.co...
python theading.Timer: how to pass argument to the callback?
4,415,672
15
2010-12-11T07:13:02Z
4,415,685
29
2010-12-11T07:18:16Z
[ "python", "timer" ]
My code: ``` import threading def hello(arg, kargs): print arg t = threading.Timer(2, hello, "bb") t.start() while 1: pass ``` The print out put is just: ``` b ``` How can I pass a argument to the callback? What does the kargs mean?
`Timer` takes an array of arguments and a dict of keyword arguments, so you need to pass an array: ``` import threading def hello(arg): print arg t = threading.Timer(2, hello, ["bb"]) t.start() while 1: pass ``` You're seeing "b" because you're not giving it an array, so it treats `"bb"` an an iterable; it...
Can I make my class play nice with the Python '"in" keyword?
4,415,939
2
2010-12-11T08:45:19Z
4,415,948
9
2010-12-11T08:49:15Z
[ "python" ]
I'm heading into hour 5 or so of my experience with Python, and so far I've been pretty impressed with what it can do. My current endeavor is to make a short attempt at a Stream class, the code for which follows: ``` class Stream: """A Basic class implementing the stream abstraction. """ def __init__(self,da...
For iterating as in `for x in object`, you need to provide an `__iter__` method which will return a new iterator. An iterator is an object which has a method `next()` (Python 2) or `__next__` (Python 3) which either returns the next element or raises `StopIteration` exception when there are no more elements. (An itera...
Beautiful Soup [Python] and the extracting of text in a table
4,416,013
5
2010-12-11T09:16:06Z
4,416,083
10
2010-12-11T09:37:02Z
[ "php", "python" ]
i am new to Python and to Beatiful Soup also! I heard about BS. It is told to be a great tool to parse and extract content. So here i am...: I want to take the content of the first td of a table in a html document. For example, i have this table ``` <table class="bp_ergebnis_tab_info"> <tr> <td> ...
First find the table (as you are doing). Using `find` rather than `findall` returns the first item in the list (rather than returning a list of all finds - in which case we'd have to add an extra `[0]` to take the first element of the list): ``` table = soup.find('table' ,attrs={'class':'bp_ergebnis_tab_info'}) ``` T...
Change background color of python shell
4,416,642
4
2010-12-11T12:17:05Z
4,416,689
8
2010-12-11T12:30:30Z
[ "python" ]
Is it possible to change background color of the Python Shell from white to black for example. I did find how to change text color, but can't figure out how to change background color. I'm running it under the Windows. Any suggestions?
if you are refereeing to IDLE i did this simple steps from this link (its for ubuntu but worked in windows as well) <http://ubuntuforums.org/showthread.php?t=657799> and if you are talking about the windows Prompt , you can use the color command or just right click & select properties & edit the color settings
Permission denied when trying to install easy_install on OSX
4,416,984
15
2010-12-11T13:40:01Z
4,416,992
11
2010-12-11T13:41:36Z
[ "python", "osx", "installation", "easy-install" ]
I'm trying to install easy\_install and, well... see for yourself: --- sh setuptools-0.6c11-py2.6.egg Processing setuptools-0.6c11-py2.6.egg Copying setuptools-0.6c11-py2.6.egg to /Library/Python/2.6/site-packages Adding setuptools 0.6c11 to easy-install.pth file Installing easy\_install script to /usr/local/bin ...
Use [sudo](https://secure.wikimedia.org/wikipedia/en/wiki/Sudo). ``` sudo sh setuptools-0.6c11-py2.6.egg ``` I would also investigate [MacPorts](http://www.macports.org/). Edit (5 years later): I now suggest [Homebrew](http://brew.sh/) instead of MacPorts.
Constantly print Subprocess output while process is running
4,417,546
70
2010-12-11T16:03:30Z
4,417,735
97
2010-12-11T16:45:21Z
[ "python", "subprocess" ]
To launch programs from my Python-scripts, I'm using the following method: ``` def execute(command): process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) output = process.communicate()[0] exitCode = process.returncode if (exitCode == 0): return outp...
There is a pattern using [iter](https://docs.python.org/3/library/functions.html#iter) that yields lines as soon as the command generates them: `lines = iter(fd.readline, "")`. A full example: ``` from __future__ import print_function # Python 2.x import subprocess def execute(cmd): popen = subprocess.Popen(cmd, ...
Constantly print Subprocess output while process is running
4,417,546
70
2010-12-11T16:03:30Z
4,418,193
40
2010-12-11T18:16:41Z
[ "python", "subprocess" ]
To launch programs from my Python-scripts, I'm using the following method: ``` def execute(command): process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) output = process.communicate()[0] exitCode = process.returncode if (exitCode == 0): return outp...
Ok i managed to solve it without threads (any suggestions why using threads would be better are appreciated) by using a snippet from this question [Intercepting stdout of a subprocess while it is running](http://stackoverflow.com/questions/527197/intercepting-stdout-of-a-subprocess-while-it-is-running) ``` def execute...
Constantly print Subprocess output while process is running
4,417,546
70
2010-12-11T16:03:30Z
28,319,191
9
2015-02-04T10:36:52Z
[ "python", "subprocess" ]
To launch programs from my Python-scripts, I'm using the following method: ``` def execute(command): process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) output = process.communicate()[0] exitCode = process.returncode if (exitCode == 0): return outp...
To print subprocess' output line-by-line as soon as its stdout buffer is flushed in Python 3: ``` from subprocess import Popen, PIPE with Popen(cmd, stdout=PIPE, bufsize=1, universal_newlines=True) as p: for line in p.stdout: print(line, end='') ``` Notice: you do not need `p.poll()` -- the loop ends whe...
Stop reading process output in Python without hang?
4,417,962
12
2010-12-11T17:27:08Z
4,418,891
17
2010-12-11T20:52:40Z
[ "python", "subprocess", "multiprocessor", "hung" ]
I have a Python program for Linux almost looks like this one : ``` import os import time process = os.popen("top").readlines() time.sleep(1) os.popen("killall top") print process ``` the program hangs in this line : ``` process = os.popen("top").readlines() ``` and that happens in the tools that keep update out...
``` #!/usr/bin/env python """Start process; wait 2 seconds; kill the process; print all process output.""" import subprocess import tempfile import time def main(): # open temporary file (it automatically deleted when it is closed) # `Popen` requires `f.fileno()` so `SpooledTemporaryFile` adds nothing here ...
Wrap all commands entered within a Bash-Shell with a Python script
4,418,378
5
2010-12-11T19:00:20Z
8,893,138
7
2012-01-17T10:36:15Z
[ "python", "linux", "bash" ]
What i'd like to have is a mechanism that all commands i enter on a Bash-Terminal are wrapped by a Python-script. The Python-script executes the entered command, but it adds some additional magic (for example setting "dynamic" environment variables). Is that possible somehow? I'm running Ubuntu and Debian Squeezy. **...
The perfect way to wrap every command that is typed into a Bash Shell is to change the variable `PROMPT_COMMAND` inside the .bashrc. For example, if I want to do some Python stuff before every command, liked asked in my question: .bashrc: ``` # ... PROMPT_COMMAND="python mycoolscript.py; $PROMPT_COMMAND;" export $PRO...
How does the KD-tree nearest neighbor search work?
4,418,450
14
2010-12-11T19:14:25Z
4,420,293
14
2010-12-12T03:33:50Z
[ "python", "machine-learning", "nearest-neighbor", "kdtree" ]
I am looking at the Wikipedia page for KD trees. As an example, I implemented, in python, the algorithm for building a kd tree listed. The algorithm for doing KNN search with a KD tree, however, switches languages and isn't totally clear. The English explanation starts making sense, but parts of it (such as the area w...
This [book introduction](http://people.csail.mit.edu/gregory/annbook/introduction.pdf), page 3: > Given a set of n points in a d-dimensional space, the kd-tree is constructed > recursively as follows. First, one finds a median of the values of the ith > coordinates of the points (initially, i = 1). That is, a value M ...
How does the KD-tree nearest neighbor search work?
4,418,450
14
2010-12-11T19:14:25Z
5,255,382
9
2011-03-10T04:13:06Z
[ "python", "machine-learning", "nearest-neighbor", "kdtree" ]
I am looking at the Wikipedia page for KD trees. As an example, I implemented, in python, the algorithm for building a kd tree listed. The algorithm for doing KNN search with a KD tree, however, switches languages and isn't totally clear. The English explanation starts making sense, but parts of it (such as the area w...
I've just spend some time puzzling out the [Wikipedia](http://en.wikipedia.org/wiki/Kd-tree) description of the algorithm myself, and came up with the following Python implementation that may help: <https://gist.github.com/863301> The first phase of `closest_point` is a simple depth first search to find the best match...
I'm able to use a mutable object as a dictionary key in python. Is this not disallowed?
4,418,741
11
2010-12-11T20:20:12Z
4,418,757
16
2010-12-11T20:24:08Z
[ "python", "dictionary" ]
``` class A(object): x = 4 i = A() d = {} d[i] = 2 print d i.x = 10 print d ``` I thought only immutable objects can be dictionary keys, but the object i above is mutable.
Any object with a [\_\_hash\_\_](http://docs.python.org/reference/datamodel.html#object.__hash__) method can be a dictionary key. For classes you write, this method defaults to returning a value based off id(self), and if equality is not determined by identity for those classes, you may be surprised by using them as ke...
How to run 'python setup.py install' from within Python?
4,419,752
6
2010-12-12T00:17:34Z
4,419,876
8
2010-12-12T00:56:21Z
[ "python" ]
I'm trying to create a generic python script for starting up a python app and I would like to install any dependent python modules if they are missing from the target system. How can I run the equivalent of the command line command 'python setup.py install' from within Python itself? I feel like this should be pretty e...
Read this: <http://docs.python.org/distutils/apiref.html#distutils.core.run_setup> It's pretty well documented.
How to see function signature in Python?
4,419,829
10
2010-12-12T00:42:43Z
4,419,873
12
2010-12-12T00:55:55Z
[ "python", "introspection" ]
Is there a way to introspect a function so that it shows me information on the arguments it takes (like number of args, type if possible, name of arguments if named) and the return value? `dir()` doesn't seem to do what I want. The `__doc__` string sometimes includes method/function arguments, but often doesn't.
`help(the_funcion)` should give you all of that information. Sample: ``` >>> help(enumerate) Help on class enumerate in module __builtin__: class enumerate(object) | enumerate(iterable[, start]) -> iterator for index, value of iterable | | Return an enumerate object. iterable must be another object that suppor...
See anything wrong with my attempt to get Flask running? (mod_wsgi + virtualenv)
4,420,218
13
2010-12-12T03:01:27Z
4,420,536
8
2010-12-12T05:32:23Z
[ "python", "apache2", "mod-wsgi", "virtualenv", "flask" ]
I have a VPS running a fresh install of Ubuntu 10.04 LTS. I'm trying to set up a live application using the Flask microframework, but it's giving me trouble. I took notes while I tried to get it running and here's my play-by-play in an effort to pinpoint exactly where I went wrong. # INSTALLATION <http://flask.pocoo....
Obviously, it cannot find your "`myapp`" package. You should add it to the path in your `myapp.wsgi` file like this: ``` import sys sys.path.append(DIRECTORY_WHERE_YOUR_PACKAGE_IS_LOCATED) from myapp import app ``` Also, if `myapp` module is a package, you should put and empty `__init__.py` file into its directory.
How to account for column-contiguous array when extending numpy with C
4,420,622
9
2010-12-12T06:52:23Z
4,422,476
7
2010-12-12T15:53:23Z
[ "python", "c", "numpy", "cython" ]
I have a C-function to normalize the rows of an array in log-space (this prevents numerical underflow). The prototype of my C-function is as follows: ``` void normalize_logspace_matrix(size_t nrow, size_t ncol, double* mat); ``` You can see that it takes a pointer to an array and modifies it in place. The C-code of ...
If you want to support arrays in C and Fortran order without ever copying, your C function needs to be flexible enough to support both orderings. This can be achieved by passing the strides of the NumPy array to the C function: Change the prototype to ``` void normalize_logspace_matrix(size_t nrow, size_t ncol, ...
how to get module location
4,421,061
4
2010-12-12T09:46:11Z
4,421,125
9
2010-12-12T10:03:31Z
[ "python" ]
when i import module using ``` import module_name ``` is it possible to see where in my hard disk is that module located?
It is worth mentioning that packages have `__file__` attribute which points to `__init__.py`, they also have [`__path__`](http://docs.python.org/tutorial/modules.html#packages-in-multiple-directories) which points to the package directory. So you can use `hasattr(module_name, '__path__') and module_name.__path__[0] or ...
Making HTTP HEAD request with urllib2 from Python 2
4,421,170
21
2010-12-12T10:16:59Z
4,421,485
52
2010-12-12T11:56:34Z
[ "python", "python-2.7", "urllib2", "head" ]
I'm trying to do a HEAD request of a page using Python 2. I am trying ``` import misc_urllib2 ..... opender = urllib2.build_opener([misc_urllib2.MyHTTPRedirectHandler(), misc_urllib2.HeadRequest()]) ``` with `misc_urllib2.py` containing ``` class HeadRequest(urllib2.Request): def get_method(self): retur...
This works just fine: ``` import urllib2 request = urllib2.Request('http://localhost:8080') request.get_method = lambda : 'HEAD' response = urllib2.urlopen(request) print response.info() ``` Tested with quick and dirty HTTPd hacked in python: ``` Server: BaseHTTP/0.3 Python/2.6.6 Date: Sun, 12 Dec 2010 11:52:33 GMT...
Compiling Python to C using Cython
4,421,832
9
2010-12-12T13:18:20Z
4,421,869
11
2010-12-12T13:24:31Z
[ "python", "c", "linux", "gcc", "cython" ]
I'm trying to compile `python` source code foo.py to C using [`cython`](http://cython.org/). In `foo.py`: ``` print "Hello World" ``` The command I'm running is `cython foo.py`. The problem is that when compiling foo.c using [`gcc`](https://gcc.gnu.org/), I get the error: `undefined reference to 'main'`.
Read the Cython documentation. This will also (hopefully) teach you what Cython is and what it isn't. Cython is for creating python extensions (not a general-purpose Python-to-C-compiler), which are shared objects/dlls. Dynamically loaded libraries don't have a `main` function like standalone programs, but compilers as...
Compiling Python to C using Cython
4,421,832
9
2010-12-12T13:18:20Z
4,422,286
17
2010-12-12T15:07:04Z
[ "python", "c", "linux", "gcc", "cython" ]
I'm trying to compile `python` source code foo.py to C using [`cython`](http://cython.org/). In `foo.py`: ``` print "Hello World" ``` The command I'm running is `cython foo.py`. The problem is that when compiling foo.c using [`gcc`](https://gcc.gnu.org/), I get the error: `undefined reference to 'main'`.
when converting the code from python to c (using Cython) it converts it to c code which can be compiled into a shared object. in order to make it executable, you should add "--embed" to cython conversion command. this flag adds the 'main' function you need, so you could compile the c code into executable file. please n...
Reading an entire binary file into Python
4,423,647
8
2010-12-12T19:47:04Z
4,423,726
9
2010-12-12T20:02:58Z
[ "python", "numpy" ]
I need to import a binary file from Python -- the contents are signed 16-bit integers, big endian. The following Stack Overflow questions suggest how to pull in several bytes at a time, but is this the way to scale up to read in a whole file? * *[Reading some binary file in Python](http://stackoverflow.com/questions/...
Use `numpy.fromfile`.
Using Beautiful Soup to strip html tags from a string
4,423,953
5
2010-12-12T20:48:44Z
4,424,139
7
2010-12-12T21:27:36Z
[ "python", "beautifulsoup" ]
Does anyone have some sample code that illustrates how to use Python's Beautiful Soup to strip all html tags, except some, from a string of text? I want to strip all javascript and html tags everything except: ``` <a></a> <b></b> <i></i> ``` And also things like: ``` <a onclick=""></a> ``` Thanks for helping -- I ...
``` import BeautifulSoup doc = '''<html><head><title>Page title</title></head><body><p id="firstpara" align="center">This is <i>paragraph</i> <a onclick="">one</a>.<p id="secondpara" align="blah">This is <i>paragraph</i> <b>two</b>.</html>''' soup = BeautifulSoup.BeautifulSoup(doc) for tag in soup.recursiveChildGener...
simple python list comprehension question
4,424,283
2
2010-12-12T21:54:27Z
4,424,295
10
2010-12-12T21:55:48Z
[ "python", "list-comprehension" ]
i am trying to select the elements of a list without the very first element. the following code works but it kinda look ugly to me ``` [s[i] for i in range(len(s)) if i>0] ``` is there a better way to write it? thanks
Use the slicing notation: ``` s[1:] ``` Alternatively, you can avoid copying the list thus: ``` itertools.islice(s, 1, None) ``` The result isn't a list — it doesn't support random access, for instance — but you can pass it to anything that accepts an iterator.
Generating a list of functions in python
4,425,954
5
2010-12-13T05:07:19Z
4,426,004
8
2010-12-13T05:17:53Z
[ "python", "list", "lambda" ]
I have the following python code that generates a list of anonymous functions: ``` basis = [ (lambda x: n*x) for n in [0, 1, 2] ] print basis[0](1) ``` I would have expected it to be equivalent to ``` basis = [ (lambda x: 0*x), (lambda x: 1*x), (lambda x: 2*x) ] print basis[0](1) ``` However, whereas the secon...
You can use a default parameter to create a closure on n ``` >>> basis = [ (lambda x,n=n: n*x) for n in [0, 1, 2] ] >>> print basis[0](1) 0 ```
How can I output what SUDs is generating/receiving?
4,426,204
41
2010-12-13T06:03:47Z
6,034,831
11
2011-05-17T17:39:21Z
[ "python", "xml", "soap", "suds" ]
I have the following code: ``` from suds.client import Client import logging logging.basicConfig(level=logging.INFO) logging.getLogger('suds.client').setLevel(logging.DEBUG) logging.getLogger('suds.transport').setLevel(logging.DEBUG) logging.getLogger('suds.xsd.schema').setLevel(logging.DEBUG) logging.getLogger('suds...
Suds supports internal logging, as you have been doing. I am setting info levels like you: ``` logging.getLogger('suds.client').setLevel(logging.DEBUG) logging.getLogger('suds.transport').setLevel(logging.DEBUG) # MUST BE THIS? logging.getLogger('suds.xsd.schema').setLevel(logging.DEBUG) logging.getLogger('suds.wsdl'...
How can I output what SUDs is generating/receiving?
4,426,204
41
2010-12-13T06:03:47Z
6,069,053
60
2011-05-20T07:59:04Z
[ "python", "xml", "soap", "suds" ]
I have the following code: ``` from suds.client import Client import logging logging.basicConfig(level=logging.INFO) logging.getLogger('suds.client').setLevel(logging.DEBUG) logging.getLogger('suds.transport').setLevel(logging.DEBUG) logging.getLogger('suds.xsd.schema').setLevel(logging.DEBUG) logging.getLogger('suds...
SUDS provides some convenience methods to do just that: ``` client.last_sent() client.last_received() ``` These should provide you with what you need. I use them for error logging. [The API doc](http://jortel.fedorapeople.org/suds/doc/suds.client.Client-class.html) for Client class should have any extra info you ne...
How can I output what SUDs is generating/receiving?
4,426,204
41
2010-12-13T06:03:47Z
24,064,760
15
2014-06-05T15:53:14Z
[ "python", "xml", "soap", "suds" ]
I have the following code: ``` from suds.client import Client import logging logging.basicConfig(level=logging.INFO) logging.getLogger('suds.client').setLevel(logging.DEBUG) logging.getLogger('suds.transport').setLevel(logging.DEBUG) logging.getLogger('suds.xsd.schema').setLevel(logging.DEBUG) logging.getLogger('suds...
You can use the MessagePlugin to do this (this will work on the newer Jurko fork where last\_sent and last\_received have been removed) ``` from suds.plugin import MessagePlugin class LogPlugin(MessagePlugin): def sending(self, context): print(str(context.envelope)) def received(self, context): print(str(...
String Manipulation in Python
4,426,397
3
2010-12-13T06:47:26Z
4,426,411
11
2010-12-13T06:49:40Z
[ "python", "string" ]
I have a string in python and I'd like to take off the last three characters. How do I go about this? So turn something like 'hello' to 'he'.
``` >>> s = "hello" >>> print(s[:-3]) he ``` For an explanation of how this works, see the question: [good primer for python slice notation](http://stackoverflow.com/q/509211/893).
Python library to do jQuery-like text extraction?
4,426,504
6
2010-12-13T07:08:25Z
4,426,863
11
2010-12-13T08:06:38Z
[ "jquery", "python", "css-selectors", "beautifulsoup" ]
I've got html that contains entries like this: ``` <div class="entry"> <h3 class="foo"> <a href="http://www.example.com/blog-entry-slug" rel="bookmark">Blog Entry</a> </h3> ... </div> ``` and I would like to extract the text "Blog Entry" (and a number of other attributes, so I'm looking for a generic an...
You might want to take a look at [lxml](http://codespeak.net/lxml/dev/index.html)'s [CSSSelector](http://codespeak.net/lxml/dev/cssselect.html) class which tries to implement CSS selectors as described in the w3c specification. As a side note, [many](http://stackoverflow.com/questions/1922032/parsing-html-in-python-lxm...
Python EOF for multi byte requests of file.read()
4,426,581
7
2010-12-13T07:23:45Z
4,433,813
18
2010-12-13T21:48:28Z
[ "python", "eof" ]
The Python docs on [file.read()](http://docs.python.org/library/stdtypes.html#file.read) state that `An empty string is returned when EOF is encountered immediately.` The documentation further states: > Note that this method may call the > underlying C function fread() more > than once in an effort to acquire as > clo...
You are not thinking with your snake skin on... Python is not C. First, a review: * st=f.read() reads to EOF, or if opened as a binary, to the last byte; * st=f.read(n) *attempts* to reads `n` bytes and in no case more than `n` bytes; * st=f.readline() reads a line at a time, the line ends with '\n' or EOF; * st=f.re...
How do I remove the first Item from a Python list?
4,426,663
272
2010-12-13T07:38:38Z
4,426,683
19
2010-12-13T07:40:53Z
[ "python", "list" ]
> **Possible Duplicate:** > [good primer for python slice notation](http://stackoverflow.com/questions/509211/good-primer-for-python-slice-notation) I have the list `[0, 1, 2, 3, 4]` I'd like to make it into `[1, 2, 3, 4]`. How do I go about this?
``` >>> x = [0, 1, 2, 3, 4] >>> x.pop(0) 0 ``` More on this [here](http://docs.python.org/tutorial/datastructures.html#more-on-lists).
How do I remove the first Item from a Python list?
4,426,663
272
2010-12-13T07:38:38Z
4,426,693
80
2010-12-13T07:41:37Z
[ "python", "list" ]
> **Possible Duplicate:** > [good primer for python slice notation](http://stackoverflow.com/questions/509211/good-primer-for-python-slice-notation) I have the list `[0, 1, 2, 3, 4]` I'd like to make it into `[1, 2, 3, 4]`. How do I go about this?
Slicing: ``` x = [0,1,2,3,4] x = x[1:] ``` Which would actually return a subset of the original but not modify it.
How do I remove the first Item from a Python list?
4,426,663
272
2010-12-13T07:38:38Z
4,426,696
11
2010-12-13T07:41:49Z
[ "python", "list" ]
> **Possible Duplicate:** > [good primer for python slice notation](http://stackoverflow.com/questions/509211/good-primer-for-python-slice-notation) I have the list `[0, 1, 2, 3, 4]` I'd like to make it into `[1, 2, 3, 4]`. How do I go about this?
With list slicing, see the Python tutorial about [lists](http://docs.python.org/tutorial/introduction.html#lists) for more details: ``` >>> l = [0, 1, 2, 3, 4] >>> l[1:] [1, 2, 3, 4] ```
How do I remove the first Item from a Python list?
4,426,663
272
2010-12-13T07:38:38Z
4,426,706
15
2010-12-13T07:43:24Z
[ "python", "list" ]
> **Possible Duplicate:** > [good primer for python slice notation](http://stackoverflow.com/questions/509211/good-primer-for-python-slice-notation) I have the list `[0, 1, 2, 3, 4]` I'd like to make it into `[1, 2, 3, 4]`. How do I go about this?
you would just do this ``` l = [0, 1, 2, 3, 4] l.pop(0) ``` or `l = l[1:]` Pros and Cons Using pop you can retrieve the value say `x = l.pop(0)` `x` would be `0`
How do I remove the first Item from a Python list?
4,426,663
272
2010-12-13T07:38:38Z
4,426,727
440
2010-12-13T07:45:58Z
[ "python", "list" ]
> **Possible Duplicate:** > [good primer for python slice notation](http://stackoverflow.com/questions/509211/good-primer-for-python-slice-notation) I have the list `[0, 1, 2, 3, 4]` I'd like to make it into `[1, 2, 3, 4]`. How do I go about this?
[Python List](http://docs.python.org/tutorial/datastructures.html) **list.pop(index)** ``` >>> l = [0, 1, 2, 3, 4] >>> l.pop(0) 0 >>> l [1, 2, 3, 4] ``` **del list[index]** ``` >>> l = [0, 1, 2, 3, 4] >>> del l[0] >>> l [1, 2, 3, 4] ``` These both modify your original list. Others have suggested using slicing: *...
How do I remove the first Item from a Python list?
4,426,663
272
2010-12-13T07:38:38Z
4,426,740
8
2010-12-13T07:47:57Z
[ "python", "list" ]
> **Possible Duplicate:** > [good primer for python slice notation](http://stackoverflow.com/questions/509211/good-primer-for-python-slice-notation) I have the list `[0, 1, 2, 3, 4]` I'd like to make it into `[1, 2, 3, 4]`. How do I go about this?
Then just delete it: ``` x = [0, 1, 2, 3, 4] del x[0] print x # [1, 2, 3, 4] ```
Python re "bogus escape error"
4,427,174
4
2010-12-13T08:59:15Z
4,428,605
7
2010-12-13T12:04:04Z
[ "python", "regex", "tkinter" ]
I've been messing around with the python re modules **.search** method. **cur** is the input from a Tkinter entry widget. Whenever I enter a "\" into the entry widget, it throws this error. I'm not all to sure what the error is or how to deal with it. Any insight would be much appreciated. **cur** is a string **tup[0...
"bogus escape (end of line)" means that your pattern ends with a backslash. This has nothing to do with Tkinter. You can duplicate the error pretty easily in an interactive shell: ``` >>> import re >>> pattern="foobar\\" >>> re.search(pattern, "foobar") Traceback (most recent call last): File "<stdin>", line 1, in <...
Python re "bogus escape error"
4,427,174
4
2010-12-13T08:59:15Z
8,692,622
7
2012-01-01T09:59:40Z
[ "python", "regex", "tkinter" ]
I've been messing around with the python re modules **.search** method. **cur** is the input from a Tkinter entry widget. Whenever I enter a "\" into the entry widget, it throws this error. I'm not all to sure what the error is or how to deal with it. Any insight would be much appreciated. **cur** is a string **tup[0...
The solution to this issue is to use a raw string as the replacement text. The following won't work: ``` re.sub('this', 'This \\', 'this is a text') ``` It will throw the error: bogus escape (end of line) But the following will work just fine: ``` re.sub('this', r'This \\', 'this is a text') ``` Now, the question ...
How to do sed like text replace with python?
4,427,542
18
2010-12-13T09:47:20Z
4,427,835
29
2010-12-13T10:22:35Z
[ "python", "regex", "linux" ]
I would like to enable all apt repositories in this file ``` cat /etc/apt/sources.list ## Note, this file is written by cloud-init on first boot of an instance ## modifications made here will not survive a re-bu...
You can do that like this: ``` with open("/etc/apt/sources.list", "r") as sources: lines = sources.readlines() with open("/etc/apt/sources.list", "w") as sources: for line in lines: sources.write(re.sub(r'^# deb', 'deb', line)) ``` The with statement ensures that the file is closed correctly, and re-o...
How to do sed like text replace with python?
4,427,542
18
2010-12-13T09:47:20Z
4,428,373
11
2010-12-13T11:31:18Z
[ "python", "regex", "linux" ]
I would like to enable all apt repositories in this file ``` cat /etc/apt/sources.list ## Note, this file is written by cloud-init on first boot of an instance ## modifications made here will not survive a re-bu...
This is such a different approach, I don't want to edit my other answer. Nested `with` since I don't use 3.1 (Where `with A() as a, B() as b:` works). Might be a bit overkill to change sources.list, but I want to put it out there for future searches. ``` #!/usr/bin/env python from shutil import move from tempfile i...
How to do sed like text replace with python?
4,427,542
18
2010-12-13T09:47:20Z
11,332,274
8
2012-07-04T15:50:58Z
[ "python", "regex", "linux" ]
I would like to enable all apt repositories in this file ``` cat /etc/apt/sources.list ## Note, this file is written by cloud-init on first boot of an instance ## modifications made here will not survive a re-bu...
massedit.py (<http://github.com/elmotec/massedit>) does the scaffolding for you leaving just the regex to write. It's still in beta but we are looking for feedback. ``` python -m massedit -e "re.sub(r'^# deb', 'deb', line)" /etc/apt/sources.list ``` will show the differences (before/after) in diff format. Add the -w...
How to do sed like text replace with python?
4,427,542
18
2010-12-13T09:47:20Z
31,499,114
14
2015-07-19T07:56:08Z
[ "python", "regex", "linux" ]
I would like to enable all apt repositories in this file ``` cat /etc/apt/sources.list ## Note, this file is written by cloud-init on first boot of an instance ## modifications made here will not survive a re-bu...
Authoring a homegrown `sed` replacement in pure Python with *no* external commands or additional dependencies is a noble task laden with noble landmines. Who would have thought? **Nonetheless, it is feasible.** It's also desirable. We've all been there, people: "I need to munge some plaintext files, but I only have Py...
RDFLib: Namespace prefixes in XML serialization
4,427,607
2
2010-12-13T09:54:45Z
4,428,390
7
2010-12-13T11:33:20Z
[ "python", "namespaces", "rdflib" ]
In a Python script using [RDFLib 3.0](http://www.rdflib.net/), I get the following XML-Output when serializing my triples: ``` <rdf:RDF xmlns:_3="http://www.my-example.intra/ontologies/ci.owl#" > ``` How can I define specific namespace prefixes for those anonymous \_x-prefixes automatically assigned by RDFLib (or i...
I eventually found a solution to this by looking at some (quite messily distributed) rdflib doc files. For the (Conjunctive)Graph storing the triples, call ``` mygraph.bind(prefix, URIRef(url)) ``` i.e. ``` mygraph.bind('ex', URIRef('http://www.my-example.intra/ontologies/ci.owl#')) ``` Passing 'False' as 3rd argum...
Reading back a datetime in sqlite3
4,429,788
7
2010-12-13T14:29:00Z
4,430,061
13
2010-12-13T14:55:59Z
[ "python", "datetime", "sqlite3", "timestamp" ]
I am using Python to create an in-memory sqlite3 database with a timestamp column. When I use min() or max() on this column in my query, the column is returned as a string rather than a Python datetime object. I read a [previous question on Stackoverflow](http://stackoverflow.com/questions/1829872/read-datetime-back-fr...
You have to set detect\_types to sqlite.PARSE\_COLNAMES and use `as "foo [timestamp]"` like this: ``` import sqlite3 import datetime db = sqlite3.connect(':memory:', detect_types = sqlite3.PARSE_COLNAMES) c = db.cursor() c.execute('create table foo (bar integer, baz timestamp)') c.execute('insert into foo values(?, ?...
How to make a python script "pipeable" in bash?
4,429,966
28
2010-12-13T14:45:37Z
4,429,980
10
2010-12-13T14:47:15Z
[ "python", "pipe" ]
I wrote a script and I want it to be *pipeable* in bash. Something like: ``` echo "1stArg" | myscript.py ``` Is it possible? How?
In your Python script you simply [read from `stdin`](http://stackoverflow.com/questions/1450393/how-do-you-read-from-stdin-in-python).
How to make a python script "pipeable" in bash?
4,429,966
28
2010-12-13T14:45:37Z
4,430,047
43
2010-12-13T14:55:08Z
[ "python", "pipe" ]
I wrote a script and I want it to be *pipeable* in bash. Something like: ``` echo "1stArg" | myscript.py ``` Is it possible? How?
See this simple `echo.py`: ``` import sys if __name__ == "__main__": for line in sys.stdin: sys.stderr.write("DEBUG: got line: " + line) sys.stdout.write(line) ``` running: ``` ls | python echo.py 2>debug_output.txt | sort ``` output: ``` echo.py test.py test.sh ``` debug\_output.txt content:...
How to make a python script "pipeable" in bash?
4,429,966
28
2010-12-13T14:45:37Z
4,430,066
13
2010-12-13T14:56:23Z
[ "python", "pipe" ]
I wrote a script and I want it to be *pipeable* in bash. Something like: ``` echo "1stArg" | myscript.py ``` Is it possible? How?
Other answers already pointed to `sys.stdin`, so I'll complement them with a `grep` example that uses [fileinput](http://docs.python.org/library/fileinput.html) to implement the typical behaviour of UNIX tools (many input files can be sent as arguments and `-` means *stdin*): ``` import fileinput import re import sys ...
python on win32: how to get absolute timing / CPU cycle-count
4,430,227
4
2010-12-13T15:10:53Z
4,430,736
7
2010-12-13T16:01:07Z
[ "python", "winapi", "api", "performancecounter" ]
I have a python script that calls a USB-based data-acquisition C# dotnet executable. The main python script does many other things, e.g. it controls a stepper motor. We would like to check the relative timing of various operations, for that purpose the dotnet exe generates a log with timestamps from C# Stopwatch.GetTim...
Have you tried using ctypes? ``` from ctypes import * val = c_int64() windll.Kernel32.QueryPerformanceCounter(byref(val)) print val.value ```
python function call with variable
4,431,216
3
2010-12-13T16:50:36Z
4,431,253
14
2010-12-13T16:53:35Z
[ "python" ]
``` def test(): print 'test' def test2(): print 'test2' test = {'test':'blabla','test2':'blabla2'} for key, val in test.items(): key() # Here i want to call the function with the key name, how can i do so? ```
You could use the actual function objects themselves as keys, rather than the names of the functions. Functions are first class objects in Python, so it's cleaner and more elegant to use them directly rather than their names. ``` test = {test:'blabla', test2:'blabla2'} for key, val in test.items(): key() ```
Frequency detection from a sound file
4,431,481
8
2010-12-13T17:15:16Z
4,431,666
7
2010-12-13T17:34:29Z
[ "python", "audio", "numpy", "fft", "frequency" ]
What I am trying to achieve is the following: I need the frequency values of a sound file (.wav) for analysis. I know a lot of programs will give a visual graph (spectrogram) of the values but I need to raw data. I know this can be done with FFT and should be fairly easily scriptable in python but not sure how to do it...
I'm not sure if this is what you want, if you just want the FFT: ``` import scikits.audiolab, scipy x, fs, nbits = scikits.audiolab.wavread(filename) X = scipy.fft(x) ``` If you want the magnitude response: ``` import pylab Xdb = 20*scipy.log10(scipy.absolute(X)) f = scipy.linspace(0, fs, len(Xdb)) pylab.plot(f, Xdb...
Python: Split list in array
4,432,067
2
2010-12-13T18:16:05Z
4,432,163
10
2010-12-13T18:26:22Z
[ "python", "list", "dictionary", "split" ]
Just beginning with python and know enough to know I know nothing. I would like to find alternative ways of splitting a list into a list of dicts. Example list: ``` data = ['**adjective:**', 'nice', 'kind', 'fine', '**noun:**', 'benefit', 'profit', 'advantage', 'avail', 'welfare', 'use', 'weal', '**ad...
This might be as close at it gets to what you have asked: ``` d = collections.defaultdict(list) for s in data: if s.endswith(":"): key = s[:-1] else: d[key].append(s) print d # defaultdict(<type 'list'>, # {'adjective': ['nice', 'kind', 'fine'], # 'noun': ['benefit', 'profit', 'advan...
How does % work in Python?
4,432,208
59
2010-12-13T18:31:15Z
4,432,228
16
2010-12-13T18:33:20Z
[ "python", "syntax", "operators", "modulo" ]
What does the `%` in a calculation? I can't seem to work out what it does. Does it work out a percent of the calculation for example: `3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6` is apparently equal to 7. How?
An expression like 'x % y' evaluates to the remainder of 'x / y'. Precedence rules are like '/' and '\*'. ``` >>> 9 / 2 4 >>> 9 % 2 1 ``` * 9 divided by 2 is equal to 4. * 4 times 2 is 8 * 9 minus 8 is 1 - the remainder. **Python gotcha**: depending on the Python version you are using, `%` is also the (deprecated) s...
How does % work in Python?
4,432,208
59
2010-12-13T18:31:15Z
4,432,235
82
2010-12-13T18:34:00Z
[ "python", "syntax", "operators", "modulo" ]
What does the `%` in a calculation? I can't seem to work out what it does. Does it work out a percent of the calculation for example: `3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6` is apparently equal to 7. How?
> The % (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type. A zero right argument raises the ZeroDivisionError exception. The arguments may be floating point numbers, e.g., 3.14%0.7 equals 0.34 (since 3.14 equals 4\*0....
How does % work in Python?
4,432,208
59
2010-12-13T18:31:15Z
4,432,236
7
2010-12-13T18:34:29Z
[ "python", "syntax", "operators", "modulo" ]
What does the `%` in a calculation? I can't seem to work out what it does. Does it work out a percent of the calculation for example: `3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6` is apparently equal to 7. How?
In most languages % is used for [modulus](http://en.wikipedia.org/wiki/Modular_arithmetic). Python is no exception.
How does % work in Python?
4,432,208
59
2010-12-13T18:31:15Z
4,432,299
9
2010-12-13T18:40:03Z
[ "python", "syntax", "operators", "modulo" ]
What does the `%` in a calculation? I can't seem to work out what it does. Does it work out a percent of the calculation for example: `3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6` is apparently equal to 7. How?
Python - Basic Operators <http://www.tutorialspoint.com/python/python_basic_operators.htm> > Modulus - Divides left hand operand by right hand operand and returns remainder a = 10 and b = 20 b % a = 0
How does % work in Python?
4,432,208
59
2010-12-13T18:31:15Z
14,886,799
47
2013-02-15T00:58:08Z
[ "python", "syntax", "operators", "modulo" ]
What does the `%` in a calculation? I can't seem to work out what it does. Does it work out a percent of the calculation for example: `3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6` is apparently equal to 7. How?
Somewhat off topic, the `%` is also used in string formatting operations like `%=` to substitute values into a string: ``` >>> x = 'abc_%(key)s_' >>> x %= {'key':'value'} >>> x 'abc_value_' ``` Again, off topic, but it seems to be a little documented feature which took me awhile to track down, *and* I thought it was...
How does % work in Python?
4,432,208
59
2010-12-13T18:31:15Z
19,524,230
11
2013-10-22T17:11:27Z
[ "python", "syntax", "operators", "modulo" ]
What does the `%` in a calculation? I can't seem to work out what it does. Does it work out a percent of the calculation for example: `3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6` is apparently equal to 7. How?
The modulus is a mathematical operation, sometimes described as "clock arithmetic." I find that describing it as simply a remainder is misleading and confusing because it masks the real reason it is used so much in computer science. It really is used to wrap around cycles. Think of a clock: Suppose you look at a clock...
How to display date format using Python logging module
4,433,157
14
2010-12-13T20:25:39Z
4,433,190
22
2010-12-13T20:29:03Z
[ "python", "logging", "format" ]
I am trying to setup a format for logging in python: ``` import logging,logging.handlers FORMAT = "%(asctime)-15s %(message)s" logging.basicConfig(format=FORMAT,level=logging.INFO) logger = logging.getLogger("twitter") handler = logging.handlers.RotatingFileHandler('/var/log/twitter_search/message.log', maxBytes=10240...
You can add the `datefmt` parameter to `basicConfig`: ``` logging.basicConfig(format=FORMAT,level=logging.INFO,datefmt='%Y-%m-%d %H:%M:%S') ``` Or, to set the format for the Rotating FileHandler: ``` fmt = logging.Formatter(FORMAT,datefmt='%Y-%m-%d') handler.setFormatter(fmt) ```
USB Barcode scanner research
4,434,959
11
2010-12-14T00:55:14Z
4,435,005
10
2010-12-14T01:03:03Z
[ "python", "barcode", "barcode-scanner" ]
I'm doing some feasibility research with regards to a (large) book cataloging project. Any help would w/r/t good sources of information would be appreciated but the things I would specifically like to know are: 1.)does python have any modules for use with barcode readers (preferably USB)? What other programs are avail...
1. You don't need any - most USB barcode scanners emulate a keyboard - if you scan a barcode it simply sends a series of key presses representing the numbers (or text if it's a more advanced barcode encoding) encoded in the barcode. Most scanners are pretty configurable so you could configure it to send a special chara...
python about multiple %s in a string
4,435,152
7
2010-12-14T01:36:12Z
4,435,165
20
2010-12-14T01:40:08Z
[ "python", "string" ]
``` str = 'I love %s and %s, he loves %s and %s.' ``` I want to use this format to display I love apple and pitch, he loves apple and pitch. Only add two variable please, but need a way to use it twice in one sentence.
Use a dict: ``` >>> s = 'I love %(x)s and %(y)s, he loves %(x)s and %(y)s.' >>> s % {"x" : "apples", "y" : "oranges"} 'I love apples and oranges, he loves apples and oranges.' ``` Or use the newer [`format`](http://docs.python.org/library/stdtypes.html#str.format) function, which was introduced in 2.6: ``` >>> s = '...
Good way to append to a string
4,435,169
319
2010-12-14T01:41:29Z
4,435,176
7
2010-12-14T01:42:49Z
[ "python", "string" ]
I want an efficient way to append string to another. Is there any good built-in method to use?
If you need to do many append operations to build a large string, you can use [StringIO](http://docs.python.org/library/stringio.html) or cStringIO. The interface is like a file. ie: you `write` to append text to it. If you're just appending two strings then just use `+`.
Good way to append to a string
4,435,169
319
2010-12-14T01:41:29Z
4,435,179
14
2010-12-14T01:42:55Z
[ "python", "string" ]
I want an efficient way to append string to another. Is there any good built-in method to use?
``` str1 = "Hello" str2 = "World" newstr = " ".join((str1, str2)) ``` That joins str1 and str2 with a space as separators. You can also do `"".join(str1, str2, ...)`. `str.join()` takes an iterable, so you'd have to put the strings in a list or a tuple. That's about as efficient as it gets for a builtin method.
Good way to append to a string
4,435,169
319
2010-12-14T01:41:29Z
4,435,194
167
2010-12-14T01:45:11Z
[ "python", "string" ]
I want an efficient way to append string to another. Is there any good built-in method to use?
Don't prematurely optimize. If you have no reason to believe there's a speed bottleneck caused by string concatenations then just stick with `+` and `+=`: ``` s = 'foo' s += 'bar' s += 'baz' ``` That said, if you're aiming for something like Java's StringBuilder, the canonical Python idiom is to add items to a list ...
Good way to append to a string
4,435,169
319
2010-12-14T01:41:29Z
4,435,282
28
2010-12-14T02:06:59Z
[ "python", "string" ]
I want an efficient way to append string to another. Is there any good built-in method to use?
Don't. That is, for most cases you are better off generating the whole string in one go rather then appending to an existing string. For example, don't do: `obj1.name + ":" + str(obj1.count)` Instead: use `"%s:%d" % (obj1.name, obj1.count)` That will be easier to read and more efficient.
Good way to append to a string
4,435,169
319
2010-12-14T01:41:29Z
4,435,752
299
2010-12-14T04:01:52Z
[ "python", "string" ]
I want an efficient way to append string to another. Is there any good built-in method to use?
If you only have one reference to a string and you concatenate another string to the end, CPython now special cases this and tries to extend the string in place. The end result is that the operation is amortized O(n) eg ``` s = "" for i in range(n): s+=str(n) ``` used to be O(n^2), but now it is O(n) From the ...
Is this common practice to avoid key not found in a dictionary
4,436,070
10
2010-12-14T05:07:37Z
4,436,082
29
2010-12-14T05:09:45Z
[ "python" ]
I was wondering, whether the following style is a common practice to avoid key not found in a dictionary? ``` # default is 0 value = my_dic[100] if 100 in my_dic else 0 ```
``` value = my_dic.get(100, 0) ```
Confirming the difference between import * and from xxx import *
4,436,401
9
2010-12-14T06:10:38Z
4,436,753
13
2010-12-14T07:11:49Z
[ "python", "python-import" ]
I was surprised to find out that ``` import foo ``` and ``` from foo import * ``` had different effects on global members. I wanted to confirm that my experiments are the correct behavior. In the first example, changing a member in module foo will reflect in all code that imports foo. However, changing that member...
Yes, your observations are correct. This is a consequence of the way that binding works in Python. When one does ``` import foo ``` then `foo` becomes a global name that references the module `foo`. When one does ``` foo.bar = 7 ``` Then the reference is followed and the object `foo` is loaded. Then `7` is stored ...
Pythonic difference between two dates in years?
4,436,957
16
2010-12-14T07:50:21Z
8,971,809
21
2012-01-23T12:43:45Z
[ "python", "datetime" ]
Is there a more efficient way of doing this below? I want to have the difference in years between two dates as a single scalar. Any suggestions are welcome. ``` from datetime import datetime start_date = datetime(2010,4,28,12,33) end_date = datetime(2010,5,5,23,14) difference = end_date - start_date difference_in_yea...
If you want precise results, I recommend using the [dateutil](http://labix.org/python-dateutil) library. ``` from dateutil.relativedelta import relativedelta difference_in_years = relativedelta(end_date, start_date).years ``` This is for complete years (e.g. a person's age). If you want fractional years, then add mon...
Choose list variable given probability of each variable
4,437,250
6
2010-12-14T08:34:54Z
4,437,286
8
2010-12-14T08:39:38Z
[ "python", "probability" ]
I've been trying to code a program that uses the softmax activation function in the middle. Right now, I have a list of probabilities like this: ``` P[0.10,0.25,0.60,0.05] ``` The sum of all the variables in P is always 1. I wanted a way to pick the index of the list given the probability attached to it. Or, in oth...
Hmm interesting, how about... 1. Generate a number between 0 and 1. 2. Walk the list substracting the probability of each item from your number. 3. Pick the item that, after substraction, took your number down to 0 or below. That's simple, O(n) and should work :)