content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
Why subprocess.Popen doesn't work when args is sequence?
I'm having a problem with subprocess.Popen when args parameter is given as sequence.
For example:
import subprocess
maildir = "/home/support/Maildir"
This works (it prints the correct size of /home/support/Maildir dir):
size = subprocess.Popen(["du -s -b " ... | Why subprocess.Popen doesn't work when args is sequence? | I'm having a problem with subprocess.Popen when args parameter is given as sequence.
For example:
import subprocess
maildir = "/home/support/Maildir"
This works (it prints the correct size of /home/support/Maildir dir):
size = subprocess.Popen(["du -s -b " + maildir], shell=True,
stdout=subproc... | [
"From the documentation\n\nOn Unix, with shell=True: […] If args is a sequence, the first item specifies the\n command string, and any additional items will be treated as additional arguments to\n the shell itself. That is to say, Popen does the equivalent of:\nPopen(['/bin/sh', '-c', args[0], args[1], ...])\n\n\... | [
12,
5,
1
] | [] | [] | [
"python",
"subprocess"
] | stackoverflow_0002400878_python_subprocess.txt |
Q:
Why does this python queue code process items multiple times?
The following is a testcase I created. Why does every process print the number 1 to 5 and are the numbers not divided over the processes?
code:
#!/usr/bin/python
from subprocess import *
from Queue import Queue
from Queue import Empty
import multiproc... | Why does this python queue code process items multiple times? | The following is a testcase I created. Why does every process print the number 1 to 5 and are the numbers not divided over the processes?
code:
#!/usr/bin/python
from subprocess import *
from Queue import Queue
from Queue import Empty
import multiprocessing
from multiprocessing import Process
def main():
r = Run... | [
"The Queue package is not process aware, it only works for threads. The following happens in your example:\n\nCreate Queue and fill with numbers\nFork 4 processes. This copies the memory content into each subprocess, including the filled Queue\nEach process empties its copy of the queue\n\nYou have to use the Queue... | [
8
] | [] | [] | [
"multithreading",
"python",
"queue"
] | stackoverflow_0002401117_multithreading_python_queue.txt |
Q:
Importing Python module from Bash
I am launching a Python script from the command line (Bash) under Linux. I need to open Python, import a module, and then have lines of code interpreted. The console must then remain in Python (not quit it). How do I do that?
I have tried an alias like this one:
alias program="cd ... | Importing Python module from Bash | I am launching a Python script from the command line (Bash) under Linux. I need to open Python, import a module, and then have lines of code interpreted. The console must then remain in Python (not quit it). How do I do that?
I have tried an alias like this one:
alias program="cd /home/myname/programs/; python; import ... | [
"An easy way to do this is with the \"code\" module:\npython -c \"import code; code.interact(local=locals())\"\n\nThis will drop you into an interactive shell when code.interact() is called. The local keyword argument to interact is used to prepopulate the default namespace for the interpreter that gets created; w... | [
16,
9,
3
] | [] | [] | [
"alias",
"bash",
"linux",
"python"
] | stackoverflow_0002401305_alias_bash_linux_python.txt |
Q:
How to run python scripts on your server?
I have mod_python installed on my server, but if I want to acceses a python script - let's say httü://site.com/something.py the script doesn't run, the download box "pops up"
Any solutions?
A:
I would consider a lightweight framework such as http://werkzeug.pocoo.org/ as... | How to run python scripts on your server? | I have mod_python installed on my server, but if I want to acceses a python script - let's say httü://site.com/something.py the script doesn't run, the download box "pops up"
Any solutions?
| [
"I would consider a lightweight framework such as http://werkzeug.pocoo.org/ as it isn't very practical in the modern day to have CGI-style python scripts.\nAnd I would use mod_wsgi instead of mod_python as the latter is a bit outdated.\n",
"This should be on ServerFault. By the way, mod_python is deprecated, use... | [
1,
0,
0
] | [] | [] | [
"apache",
"python",
"unix"
] | stackoverflow_0002401602_apache_python_unix.txt |
Q:
Generator speed in python 3
I am going through a link about generators that someone posted. In the beginning he compares the two functions below. On his setup he showed a speed increase of 5% with the generator.
I'm running windows XP, python 3.1.1, and cannot seem to duplicate the results. I keep showing the "ol... | Generator speed in python 3 | I am going through a link about generators that someone posted. In the beginning he compares the two functions below. On his setup he showed a speed increase of 5% with the generator.
I'm running windows XP, python 3.1.1, and cannot seem to duplicate the results. I keep showing the "old way"(logs1) as being slightly f... | [
"For what it's worth, the main purpose of the speed comparison in the presentation was to point out that using generators does not introduce a huge performance overhead. Many programmers, when first seeing generators, might start wondering about the hidden costs. For example, is there all sorts of fancy magic goi... | [
9,
1,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0002399308_python_python_3.x.txt |
Q:
Python: getting \\u00bd correctly in editor
I would like to do the following:
1) Serialize my class
2) Also manually edit the serialization dump file to remove certain objects of my class which I find unnecessary.
I am currently using python with simplejson. As you know, simplejson converts all characters to unicd... | Python: getting \\u00bd correctly in editor | I would like to do the following:
1) Serialize my class
2) Also manually edit the serialization dump file to remove certain objects of my class which I find unnecessary.
I am currently using python with simplejson. As you know, simplejson converts all characters to unicde. As a result, when I dump a particular object w... | [
"I don't know anything about simplejson or the Serialisation part of the question, but you asked about converting \"\\u00bd\" to 好 in Vim. Here are some vim tips for working with unicode:\n\nYou'll need the correct encoding set up in vim, see:\n:help 'encoding'\n:help 'fileencoding'\n\nEntering unicode characters ... | [
1,
0
] | [] | [] | [
"python",
"vim"
] | stackoverflow_0002400088_python_vim.txt |
Q:
Convert list in tuple to numpy array?
I have tuple of lists. One of these lists is a list of scores. I want to convert the list of scores to a numpy array to take advantage of the pre-built stats that scipy provides.
In this case the tuple is called 'data'
In [12]: type data[2]
-------> type(data[2])
Out[12]: <typ... | Convert list in tuple to numpy array? | I have tuple of lists. One of these lists is a list of scores. I want to convert the list of scores to a numpy array to take advantage of the pre-built stats that scipy provides.
In this case the tuple is called 'data'
In [12]: type data[2]
-------> type(data[2])
Out[12]: <type 'list'>
In [13]: type data[2][1]
-------... | [
"The command numpy.asarray will turn a number of pre-set iterable containers (list, tuple, etc) into a numpy array.\n"
] | [
47
] | [] | [] | [
"arrays",
"numpy",
"python",
"scipy",
"tuples"
] | stackoverflow_0002402575_arrays_numpy_python_scipy_tuples.txt |
Q:
Python: Help with counters and writing files
Possible Duplicate:
Python: How do I create sequential file names?
I was suggested to use a separate file as a counter to give my files sequential file names, but I don't understand how I would do that. I need my file names to have sequential numbers, like file1.txt, ... | Python: Help with counters and writing files |
Possible Duplicate:
Python: How do I create sequential file names?
I was suggested to use a separate file as a counter to give my files sequential file names, but I don't understand how I would do that. I need my file names to have sequential numbers, like file1.txt, file2.txt, file3.txt. Any help is appreciated!
Ed... | [
"More information probably is needed, but if you want to sequentially name files to avoid name clashes etc you don't necessarily need a separate file to record the current number. I'm assuming you want to write a new file from time to time, numbering to keep track of things?\nSo given a set of files, you want to k... | [
4,
0,
0,
0
] | [] | [] | [
"filesystems",
"python"
] | stackoverflow_0002401235_filesystems_python.txt |
Q:
django: caching passwords for custom authentication
I am authenticating users in ldap, but this happens only once, when user is logging in. Afterwards I need to keep username and password, because before every ldap operation I need to make bind on ldap server before every operation. What is the safe way to cache t... | django: caching passwords for custom authentication | I am authenticating users in ldap, but this happens only once, when user is logging in. Afterwards I need to keep username and password, because before every ldap operation I need to make bind on ldap server before every operation. What is the safe way to cache this password (I can't store in the database or cookies) f... | [
"You may cache authentication credentials in sessions. If you are afraid that they may \"leak\" to disk, i.e. be cached in database, you may use memory based sessions.\nWith cache session engine (Using cached sessions) and memory based sessions this should be accomplished easily. \n",
"solution 1:\nmaybe the most... | [
2,
1
] | [] | [] | [
"caching",
"django",
"ldap",
"passwords",
"python"
] | stackoverflow_0002402694_caching_django_ldap_passwords_python.txt |
Q:
Python instances and attributes: is this a bug or i got it totally wrong?
Suppose you have something like this:
class intlist:
def __init__(self,l = []):
self.l = l
def add(self,a):
self.l.append(a)
def appender(a):
obj = intlist()
obj.add(a)
... | Python instances and attributes: is this a bug or i got it totally wrong? | Suppose you have something like this:
class intlist:
def __init__(self,l = []):
self.l = l
def add(self,a):
self.l.append(a)
def appender(a):
obj = intlist()
obj.add(a)
print obj.l
if __name__ == "__main__":
for i in range(5):
... | [
"Ah, you've hit one of the common Python gotchas: default values are computed once, then re-used. So, every time __init__ is called, the same list is being used.\nThis is the Pythonic way of doing what you want:\ndef __init__(self, l=None):\n self.l = [] if l is None else l\n\nFor a bit more information, check o... | [
14,
4,
3,
1,
1,
1,
0
] | [] | [] | [
"attributes",
"class",
"instance",
"python"
] | stackoverflow_0002402887_attributes_class_instance_python.txt |
Q:
GAE Task Queue oddness
I have been testing the taskqueue with mixed success. Currently I am
using the default queue, in default settings etc etc....
I have a test URL setup which inserts about 8 tasks into the queue.
With short order, all 8 are completed properly. So far so good.
The problem comes up when I re-loa... | GAE Task Queue oddness | I have been testing the taskqueue with mixed success. Currently I am
using the default queue, in default settings etc etc....
I have a test URL setup which inserts about 8 tasks into the queue.
With short order, all 8 are completed properly. So far so good.
The problem comes up when I re-load that URL twice under say a... | [
"When a task-queue ends in error : I believe it stays in your queue ..\nCheck that\n"
] | [
0
] | [] | [] | [
"google_app_engine",
"python",
"task_queue"
] | stackoverflow_0002308050_google_app_engine_python_task_queue.txt |
Q:
What would be the most efficient way to do this search (mysql or text)?
Suppose I have 500 rows of data, each with a paragraph of text (like this paragraph). That's it.I want to do a search that matches part of words. (%LIKE%, not FULL_TEXT)
What would be faster?
SELECT * FROM ...WHERE LIKE "%query%"; This would ... | What would be the most efficient way to do this search (mysql or text)? | Suppose I have 500 rows of data, each with a paragraph of text (like this paragraph). That's it.I want to do a search that matches part of words. (%LIKE%, not FULL_TEXT)
What would be faster?
SELECT * FROM ...WHERE LIKE "%query%"; This would put load on the database server.
Select all. Then, go through each one and do... | [
"This is very hard for us to determine without knowing:\n\nthe amount of text to search\nthe load and configuration on the database server\nthe load and configuration on on the webserver\netc etc ...\n\nWith that said i would conceptually definitely go for the first scenario. It should be lightening-fast when searc... | [
1,
0
] | [] | [] | [
"database",
"mysql",
"python",
"regex",
"search"
] | stackoverflow_0002401508_database_mysql_python_regex_search.txt |
Q:
Python: Get values (objects) from a dictionary of objects in which one of the object's field matches a value (or condition)
I have a python dictionary whose keys are strings and the values are objects.
For instance, an object with one string and one int
class DictItem:
def __init__(self, field1, field2):
... | Python: Get values (objects) from a dictionary of objects in which one of the object's field matches a value (or condition) | I have a python dictionary whose keys are strings and the values are objects.
For instance, an object with one string and one int
class DictItem:
def __init__(self, field1, field2):
self.field1 = str(field1)
self.field2 = int(field2)
and the dictionary:
myDict = dict()
myDict["sampleKey1"] = DictItem("t... | [
"To make a dict from your dict,\nsubdict = dict((k, v) for k, v in myDict.iteritems() if v.field2 >= 2)\n\n",
"mySubList = [dict((k,v) for k,v in myDict.iteritems() if v.field2 >= 2)]\n\nDocumentation:\nlist-comprehensions, iteritems()\n",
"You should keep your various records - that is \"DicItem\" instances - ... | [
8,
4,
3,
2,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0002403372_dictionary_python.txt |
Q:
Best web application language for Delphi Developers
I'm Delphi developer, and I would like to build few web applications, I know about Intraweb, but I think it's not a real tool for web development, maybe for just intranet applications
so I'm considering PHP, Python or ruby, I prefer python because it's better syn... | Best web application language for Delphi Developers | I'm Delphi developer, and I would like to build few web applications, I know about Intraweb, but I think it's not a real tool for web development, maybe for just intranet applications
so I'm considering PHP, Python or ruby, I prefer python because it's better syntax than other( I feel it closer to Delphi), also I want ... | [
"Try Morfik http://www.morfik.com/\nP.S.\nIt looked promising a few years ago, but after I digged it deeper I must admit that it's quite limited web development environment for a very basic web development.\n",
"Why should an answer be different if the question was asked by a Delphi programmer, than a programmer ... | [
7,
6,
4,
4,
2,
2,
1,
1,
0,
0
] | [] | [] | [
"delphi",
"php",
"python",
"ruby"
] | stackoverflow_0002400605_delphi_php_python_ruby.txt |
Q:
How do I create a set of image files from a PowerPoint file file?
I'm creating a "slideshow room" web page. The user will upload a PowerPoint file that my server will use to generate a set of .jpg image files representing the slides to present in a custom "gallery viewer".
I'm an experienced Python developer but I... | How do I create a set of image files from a PowerPoint file file? | I'm creating a "slideshow room" web page. The user will upload a PowerPoint file that my server will use to generate a set of .jpg image files representing the slides to present in a custom "gallery viewer".
I'm an experienced Python developer but I cannot find anything useful.
How can I do that?
| [
"Off the top of my head, the way I'd do it:\n\nUse OpenOffice.org to convert the .ppt file into a PDF. (OO.o has a very rich Java API. Rich and bloody difficult to use, mind, but once you figure out how to get it to do the task you need, you're all set. Dunno if you can do anything useful with it via Python; not... | [
4,
0,
0
] | [] | [] | [
"jpeg",
"powerpoint",
"python"
] | stackoverflow_0002403041_jpeg_powerpoint_python.txt |
Q:
Google App Engine UI Widgets
Are there any UI widgets available to the python side of Google App Engine? I'd like something like the collapsed/expanded views of Google Groups threads. Are these type things limited to the GWT side?
A:
Why not simply use jQueryUI? It's a tested and very solid library, and will be... | Google App Engine UI Widgets | Are there any UI widgets available to the python side of Google App Engine? I'd like something like the collapsed/expanded views of Google Groups threads. Are these type things limited to the GWT side?
| [
"Why not simply use jQueryUI? It's a tested and very solid library, and will be easier to pick up than anything else at the current stage.\nCheers\n",
"ToscaWidgets, in the version 2 that's currently in alpha test, is said to support App Engine (at least for the tw2.core part). I've also seen posts showing ways ... | [
9,
5,
3
] | [] | [] | [
"google_app_engine",
"python",
"user_interface"
] | stackoverflow_0002402128_google_app_engine_python_user_interface.txt |
Q:
python: Writing Application- Different modules/Licenses and impact on Proprietary application
I've written an application using wxPython and various other small modules (xlrd, xlwrt, pyserial, etc.) xlrd/xlwt i believe use a BSD license, and wxPython..
""Being a wrapper, wxPython uses the same free software li... | python: Writing Application- Different modules/Licenses and impact on Proprietary application | I've written an application using wxPython and various other small modules (xlrd, xlwrt, pyserial, etc.) xlrd/xlwt i believe use a BSD license, and wxPython..
""Being a wrapper, wxPython uses the same free software licence
used by wxWidgets (wxWindows License)—which is approved by Free
Software Foundation and Ope... | [
"\"GPL-compatible\" only matters if you're writing GPLed or LGPLed code. When writing a proprietary application the biggest concern is \"closed-source-incompatible\", although a proprietary app does not necessarily need to be closed-source. BSD and LGPL (among others) are closed-source-compatible; GPL is not.\n"
] | [
0
] | [] | [] | [
"commercial_application",
"licensing",
"python"
] | stackoverflow_0002404637_commercial_application_licensing_python.txt |
Q:
Does filehandle get closed automatically in Python after it goes out of scope?
If I do the following, does filehandle get closed automatically as it goes out of scope in Python:
def read_contents(file_path):
return file(file_path).read()
If it doesn't, how can I write this function to close the scope automatica... | Does filehandle get closed automatically in Python after it goes out of scope? | If I do the following, does filehandle get closed automatically as it goes out of scope in Python:
def read_contents(file_path):
return file(file_path).read()
If it doesn't, how can I write this function to close the scope automatically?
| [
"To expand on FogleBird's answer, if you do not explicitly close it then the file will be closed automatically when the file object is destroyed. In CPython this will happen as soon as there are no more references to it, e.g. if it is a local variable in a function and the function ends. However if an exception i... | [
41,
21
] | [] | [] | [
"file",
"python",
"scope"
] | stackoverflow_0002404430_file_python_scope.txt |
Q:
wanting to move up from ms access, thinking .net? visual studio?
So I wrote a project-management program for a small business using Microsoft Access 2007.
Now they've requested lots of additional features (timekeeping, privileged data tiers ...)
I personally use Linux, but the whole office uses Windows.
I'm relati... | wanting to move up from ms access, thinking .net? visual studio? | So I wrote a project-management program for a small business using Microsoft Access 2007.
Now they've requested lots of additional features (timekeeping, privileged data tiers ...)
I personally use Linux, but the whole office uses Windows.
I'm relatively new to programming but like to teach myself using projects like t... | [
"In an environment like that, you can't go wrong with VB/C#. Try the various VS Express editions.\nIf you want something that will translate to Linux a little more, Python and just about any cross-platform GUI framework(QT, or wxpython) would work.\nEDIT:\nThen there's the database. I would probably suggest sqlite ... | [
5,
3,
2,
1,
1,
1,
1,
0,
0,
0
] | [] | [] | [
".net",
"database",
"ms_access",
"python"
] | stackoverflow_0002402814_.net_database_ms_access_python.txt |
Q:
How do I watch a folder for changes and when changes are done using Python?
i need to watch a folder for incoming files. i did that with the following help:
How do I watch a file for changes?
the problem is that the files that are being moved are pretty big (10gb)
and i want to be notified when all files are done ... | How do I watch a folder for changes and when changes are done using Python? | i need to watch a folder for incoming files. i did that with the following help:
How do I watch a file for changes?
the problem is that the files that are being moved are pretty big (10gb)
and i want to be notified when all files are done moving.
i tried comparing the size of the folder every 20 seconds but the file sh... | [
"You should take a look at this link:\nhttp://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html\nThere you can see the comparison of the method you are speaking about (simple polling) with two other windows-specific techniques which, in my opinion, offers a really better solution to your proble... | [
2,
0,
0,
0,
0
] | [] | [] | [
"monitoring",
"python",
"pywin32",
"watch"
] | stackoverflow_0002404087_monitoring_python_pywin32_watch.txt |
Q:
Vectorization of index operation for a scipy.sparse matrix
The following code runs too slowly even though everything seems to be vectorized.
from numpy import *
from scipy.sparse import *
n = 100000;
i = xrange(n); j = xrange(n);
data = ones(n);
A=csr_matrix((data,(i,j)));
x = A[i,j]
The problem seems to be t... | Vectorization of index operation for a scipy.sparse matrix | The following code runs too slowly even though everything seems to be vectorized.
from numpy import *
from scipy.sparse import *
n = 100000;
i = xrange(n); j = xrange(n);
data = ones(n);
A=csr_matrix((data,(i,j)));
x = A[i,j]
The problem seems to be that the indexing operation is implemented as a python function, ... | [
"You can use A.diagonal() to retrieve the diagonal much more quickly (0.0009 seconds vs. 3.8 seconds on my machine) . However, if you want to do arbitary indexing then that is a more complicated question because you aren't using slices so much as a list of indices. The _get_single_element function is being called 1... | [
7,
0
] | [] | [] | [
"indexing",
"python",
"scipy",
"sparse_matrix"
] | stackoverflow_0002404437_indexing_python_scipy_sparse_matrix.txt |
Q:
Fastest way to convert file from latin1 to utf-8 in python
I need fastest way to convert files from latin1 to utf-8 in python. The files are large ~ 2G. ( I am moving DB data ). So far I have
import codecs
infile = codecs.open(tmpfile, 'r', encoding='latin1')
outfile = codecs.open(tmpfile1, 'w', encoding='utf-8')
... | Fastest way to convert file from latin1 to utf-8 in python | I need fastest way to convert files from latin1 to utf-8 in python. The files are large ~ 2G. ( I am moving DB data ). So far I have
import codecs
infile = codecs.open(tmpfile, 'r', encoding='latin1')
outfile = codecs.open(tmpfile1, 'w', encoding='utf-8')
for line in infile:
outfile.write(line)
infile.close()
outf... | [
"I would go with iconv and a system call.\n",
"You could use blocks larger than one line, and do binary I/O -- each might speed thinks up a bit (though on Linux binary I/O won't, as it's identical to text I/O):\n BLOCKSIZE = 1024*1024\n with open(tmpfile, 'rb') as inf:\n with open(tmpfile, 'wb') as ouf:\n w... | [
6,
4,
2
] | [] | [] | [
"python"
] | stackoverflow_0002404855_python.txt |
Q:
Why would memcached refuse to store data with some keys?
I use the memcache extension for python, and I have a very strange problem. Memcached refuses to store the exact same data with some keys, and succeeds in caching some others.
>>> import memcache
>>> conn = memcache.Client('121.0.0.1:11211', debug=0)
>>> con... | Why would memcached refuse to store data with some keys? | I use the memcache extension for python, and I have a very strange problem. Memcached refuses to store the exact same data with some keys, and succeeds in caching some others.
>>> import memcache
>>> conn = memcache.Client('121.0.0.1:11211', debug=0)
>>> conn.set('138b9c95d693760840aab85ee5591d2', 'test');
True
>>> con... | [
"The first param should be a list\nconn = memcache.Client(['127.0.0.1:11211'], debug=0)\n\n"
] | [
1
] | [] | [] | [
"memcached",
"python",
"ubuntu"
] | stackoverflow_0002405621_memcached_python_ubuntu.txt |
Q:
Python: Indexing list for element in nested list
I know what I'm looking for. I want python to tell me which list it's in.
Here's some pseudocode:
item = "a"
nested_list = [["a", "b"], ["c", "d"]]
list.index(item) #obviously this doesn't work
here I would want python to return 0 (because "a" is an element in t... | Python: Indexing list for element in nested list | I know what I'm looking for. I want python to tell me which list it's in.
Here's some pseudocode:
item = "a"
nested_list = [["a", "b"], ["c", "d"]]
list.index(item) #obviously this doesn't work
here I would want python to return 0 (because "a" is an element in the first sub-list in the bigger list). I don't care w... | [
"In Python 2.6 or better,\nnext((i for i, sublist in enumerate(nested_list) if \"a\" in sublist), -1)\n\nassuming e.g. you want a -1 result if 'a' is present in none of the sublists.\nOf course it can be done in older versions of Python, too, but not quite as handily, and since you don't specify which Python versio... | [
12,
1,
0,
0
] | [] | [] | [
"indexing",
"list",
"nested",
"python"
] | stackoverflow_0002405928_indexing_list_nested_python.txt |
Q:
Use of infix operator hack in production code (Python)
What is your opinion of using the infix operator hack in production code? Issues:
The effect this will have on speed.
The potential for a clashes with an object with these operators already defined. This seems particularly dangerous with generic code that is ... | Use of infix operator hack in production code (Python) | What is your opinion of using the infix operator hack in production code? Issues:
The effect this will have on speed.
The potential for a clashes with an object with these operators already defined. This seems particularly dangerous with generic code that is intended to handle objects of any type.
It is a shame that ... | [
"It will be measurably slower than more Pythonic code, fragile (e.g. in the way you suggest), and baffling to every expert Python programmer that comes upon such code for the first time.\nIf you want to turn Python into one of the very few languages that allow user-defined infix operators (such as Haskell), you're ... | [
6,
1
] | [] | [] | [
"python"
] | stackoverflow_0002405936_python.txt |
Q:
Processing a log to fix a malformed IP address ?.?.?.x
I would like to replace the first character 'x' with the number '7' on every line of a log file using a shell script. Example of the log file:
216.129.119.x [01/Mar/2010:00:25:20 +0100] "GET /etc/....
74.131.77.x [01/Mar/2010:00:25:37 +0100] "GET /etc/....
222... | Processing a log to fix a malformed IP address ?.?.?.x | I would like to replace the first character 'x' with the number '7' on every line of a log file using a shell script. Example of the log file:
216.129.119.x [01/Mar/2010:00:25:20 +0100] "GET /etc/....
74.131.77.x [01/Mar/2010:00:25:37 +0100] "GET /etc/....
222.168.17.x [01/Mar/2010:00:27:10 +0100] "GET /etc/....
My hu... | [
"since everyone is posting their alternative solutions i'm going to post one that i think is very simple:\nsed s/\\.x/\\.7/ input_file > output_file\n\nreplace any string \".x\" by \".7\"\nhope it helps! :)\n",
"The following perl one-liner should do the trick:\n\nperl -p -i -e 's/\\.x/\\.7/' foo.log\n\nIt'll sub... | [
3,
2,
2,
0,
0
] | [] | [] | [
"bash",
"perl",
"python",
"shell",
"string"
] | stackoverflow_0002402553_bash_perl_python_shell_string.txt |
Q:
Get the last '/' or '\\' character in Python
If I have a string that looks like either
./A/B/c.d
OR
.\A\B\c.d
How do I get just the "./A/B/" part? The direction of the slashes can be the same as they are passed.
This problem kinda boils down to: How do I get the last of a specific character in a string?
Basicall... | Get the last '/' or '\\' character in Python | If I have a string that looks like either
./A/B/c.d
OR
.\A\B\c.d
How do I get just the "./A/B/" part? The direction of the slashes can be the same as they are passed.
This problem kinda boils down to: How do I get the last of a specific character in a string?
Basically, I want the path of a file without the file part... | [
"Normally os.path.dirname() is used for this.\n",
"I believe you are looking for os.path.split. It splits the path into head and tail... tail being the file, head being the path up to the file.\n",
">>> p=\"./A/B/c.d\"\n>>> import os\n>>> os.path.split(p)\n('./A/B', 'c.d')\n>>> os.path.split(p)[0]\n'./A/B'\n>>... | [
7,
4,
2
] | [] | [] | [
"python",
"string"
] | stackoverflow_0002406032_python_string.txt |
Q:
Detecting circular imports
I'm working with a project that contains about 30 unique modules. It wasn't designed too well, so it's common that I create circular imports when adding some new functionality to the project.
Of course, when I add the circular import, I'm unaware of it. Sometimes it's pretty obvious I've... | Detecting circular imports | I'm working with a project that contains about 30 unique modules. It wasn't designed too well, so it's common that I create circular imports when adding some new functionality to the project.
Of course, when I add the circular import, I'm unaware of it. Sometimes it's pretty obvious I've made a circular import when I g... | [
"To avoid having to alter every module, you could stick your import-tracking functionality in a import hook, or in a customized __import__ you could stick in the built-ins -- the latter, for once, might work better, because __import__ gets called even if the module getting imported is already in sys.modules, which ... | [
10,
1,
1,
0
] | [] | [] | [
"circular_dependency",
"python"
] | stackoverflow_0002406007_circular_dependency_python.txt |
Q:
HTTPS post login form
Trying to find a way to send a POST HTTPS request from Python to a web page form
A:
httplib is for the job, and you may refer to the example code at the bottom of the document. and google for the httplib sample code.
| HTTPS post login form | Trying to find a way to send a POST HTTPS request from Python to a web page form
| [
"httplib is for the job, and you may refer to the example code at the bottom of the document. and google for the httplib sample code.\n"
] | [
5
] | [] | [] | [
"https",
"python"
] | stackoverflow_0002406196_https_python.txt |
Q:
How can I turn off registry redirection on Python?
My program is trying to create an key on the
HKLM\Software\Microsoft\Shared Tools\MSCONFIG\startupreg\test\
but instead the key is created on the
HKLM\Wow6432node\Software\Microsoft\Shared Tools\MSCONFIG\startupreg\test\
and don't work properly... Why? How can I... | How can I turn off registry redirection on Python? | My program is trying to create an key on the
HKLM\Software\Microsoft\Shared Tools\MSCONFIG\startupreg\test\
but instead the key is created on the
HKLM\Wow6432node\Software\Microsoft\Shared Tools\MSCONFIG\startupreg\test\
and don't work properly... Why? How can I solve it?
| [
"The docs on reflection-key features in winreg are scarce (and bits and pieces are missing). You really need this patch, but until it's applied and a new micro-release of Python is made with these fixes, at least you can try the DisableReflectionKey etc route according to the docs that patch adds (here's the RST f... | [
2,
0
] | [] | [] | [
"64_bit",
"python",
"registry",
"windows"
] | stackoverflow_0002404595_64_bit_python_registry_windows.txt |
Q:
Getting readline to block on a FIFO
I create a fifo:
mkfifo tofetch
I run this python code:
fetchlistfile = file("tofetch", "r")
while 1:
nextfetch = fetchlistfile.readline()
print nextfetch
It stalls on readline, as I would hope. I run:
echo "test" > tofetch
And my program doesn't stall anymore. It rea... | Getting readline to block on a FIFO | I create a fifo:
mkfifo tofetch
I run this python code:
fetchlistfile = file("tofetch", "r")
while 1:
nextfetch = fetchlistfile.readline()
print nextfetch
It stalls on readline, as I would hope. I run:
echo "test" > tofetch
And my program doesn't stall anymore. It reads the line, and then continues looping f... | [
"According to the documentation for readline, it returns the empty string if and only if you're at end-of-file. Closed isn't the same as end-of-file. The file object will only be closed when you call .close(). When your code reaches the end of the file, readline() keeps returning the empty string.\nIf you just u... | [
5
] | [] | [] | [
"fifo",
"pipe",
"python"
] | stackoverflow_0002406365_fifo_pipe_python.txt |
Q:
Adding an object to another module's globals in python
I know this is very evil, but is it possible to add an object to another module's globals, something like:
#module dog.py
import cat
cat.globals.addVar('name','mittens')
and
#module cat.py
print name #mittens
A:
setattr(cat, 'name', 'mittens')
or
cat.name... | Adding an object to another module's globals in python | I know this is very evil, but is it possible to add an object to another module's globals, something like:
#module dog.py
import cat
cat.globals.addVar('name','mittens')
and
#module cat.py
print name #mittens
| [
"setattr(cat, 'name', 'mittens')\n\nor\ncat.name = 'mittens'\n\n"
] | [
2
] | [] | [] | [
"global",
"python"
] | stackoverflow_0002406586_global_python.txt |
Q:
Why can you reference an imported module using the importing module in python
I am trying to understand why any import can be referenced using the importing module, e.g
#module master.py
import slave
and then
>>>import master
>>>print master.slave
gives
<module 'slave' from 'C:\Documents and Settings....'>
What ... | Why can you reference an imported module using the importing module in python | I am trying to understand why any import can be referenced using the importing module, e.g
#module master.py
import slave
and then
>>>import master
>>>print master.slave
gives
<module 'slave' from 'C:\Documents and Settings....'>
What is the purpose of the feature? I can see how it can be helpful in a package's __ini... | [
"It's a side effect, but it can be used purposefully, e.g. os.py imports either posixpath or ntpath as path in order to create os.path.\n"
] | [
1
] | [] | [] | [
"import",
"module",
"namespaces",
"python"
] | stackoverflow_0002406722_import_module_namespaces_python.txt |
Q:
Javascript equivalent of Python's iterkeys() dictionary method
In Python I can use the iterkeys() method to iterate over the keys of a dictionary. For example:
mydict = {'a': [3,5,6,43,3,6,3,],
'b': [87,65,3,45,7,8],
'c': [34,57,8,9,9,2],}
for k in mydict.iterkeys():
print k
gives me:
a
c
... | Javascript equivalent of Python's iterkeys() dictionary method | In Python I can use the iterkeys() method to iterate over the keys of a dictionary. For example:
mydict = {'a': [3,5,6,43,3,6,3,],
'b': [87,65,3,45,7,8],
'c': [34,57,8,9,9,2],}
for k in mydict.iterkeys():
print k
gives me:
a
c
b
How can I do something similar in Javascript?
| [
"var mydict = {\n 'a': [3,5,6,43,3,6,3,],\n 'b': [87,65,3,45,7,8],\n 'c': [34,57,8,9,9,2],\n};\nfor (var key in mydict) {\n alert(key);\n}\n\n",
"for(k in mydict){\n alert(k)\n}\n\n"
] | [
4,
0
] | [] | [] | [
"javascript",
"python"
] | stackoverflow_0002406916_javascript_python.txt |
Q:
I want to scrape a site using GAE and post the results into a Google Entity
I want to scrape this URL : https://www.xstreetsl.com/modules.php?searchSubmitImage_x=0&searchSubmitImage_y=0&SearchLocale=0&name=Marketplace&SearchKeyword=business&searchSubmitImage.x=0&searchSubmitImage.y=0&SearchLocale=0&SearchPriceMin=... | I want to scrape a site using GAE and post the results into a Google Entity | I want to scrape this URL : https://www.xstreetsl.com/modules.php?searchSubmitImage_x=0&searchSubmitImage_y=0&SearchLocale=0&name=Marketplace&SearchKeyword=business&searchSubmitImage.x=0&searchSubmitImage.y=0&SearchLocale=0&SearchPriceMin=&SearchPriceMax=&SearchRatingMin=&SearchRatingMax=&sort=&dir=asc
Go into each of ... | [
"There are several nice screen scraping libraries you can use in Python. \nPerhaps the easiest to knock up an advanced scraper with is scrapy. It relies on Twisted to implement the main engine but provides a very easy to use interface for implementing custom scraping code.\nOtherwise you can look at doing it more... | [
3,
3
] | [] | [] | [
"google_app_engine",
"python",
"screen_scraping"
] | stackoverflow_0002406428_google_app_engine_python_screen_scraping.txt |
Q:
Why does concatenating a boolean value return an integer?
In python, you can concatenate boolean values, and it would return an integer. Example:
>>> True
True
>>> True + True
2
>>> True + False
1
>>> True + True + True
3
>>> True + True + False
2
>>> False + False
0
Why? Why does this make sense?
I understand th... | Why does concatenating a boolean value return an integer? | In python, you can concatenate boolean values, and it would return an integer. Example:
>>> True
True
>>> True + True
2
>>> True + False
1
>>> True + True + True
3
>>> True + True + False
2
>>> False + False
0
Why? Why does this make sense?
I understand that True is often represented as 1, whereas False is represented... | [
"Because In Python, bool is the subclass/subtype of int.\n>>> issubclass(bool,int)\nTrue\n\nUpdate:\nFrom boolobject.c\n/* Boolean type, a subtype of int */\n\n/* We need to define bool_print to override int_print */\nbool_print\n fputs(self->ob_ival == 0 ? \"False\" : \"True\", fp);\n\n/* We define bool_repr to... | [
21,
7,
2
] | [] | [] | [
"python"
] | stackoverflow_0002406959_python.txt |
Q:
Preferred way of defining properties in Python: property decorator or lambda?
Which is the preferred way of defining class properties in Python and why? Is it Ok to use both in one class?
@property
def total(self):
return self.field_1 + self.field_2
or
total = property(lambda self: self.field_1 + self.field_2... | Preferred way of defining properties in Python: property decorator or lambda? | Which is the preferred way of defining class properties in Python and why? Is it Ok to use both in one class?
@property
def total(self):
return self.field_1 + self.field_2
or
total = property(lambda self: self.field_1 + self.field_2)
| [
"For read-only properties I use the decorator, else I usually do something like this:\nclass Bla(object):\n def sneaky():\n def fget(self):\n return self._sneaky\n def fset(self, value):\n self._sneaky = value\n return locals()\n sneaky = property(**sneaky())\n\nupda... | [
51,
22,
5
] | [] | [] | [
"decorator",
"lambda",
"properties",
"python"
] | stackoverflow_0002406567_decorator_lambda_properties_python.txt |
Q:
fastest calculation of largest prime factor of 512 bit number in python
i am simulating my crypto scheme in python, i am a new user to it.
p = 512 bit number and i need to calculate largest prime factor for it, i am looking for two things:
Fastest code to process this large prime factorization
Code that can take ... | fastest calculation of largest prime factor of 512 bit number in python | i am simulating my crypto scheme in python, i am a new user to it.
p = 512 bit number and i need to calculate largest prime factor for it, i am looking for two things:
Fastest code to process this large prime factorization
Code that can take 512 bit of number as input and can handle it.
I have seen different implemen... | [
"For a Python-based solution, you might want to look at pyecm On a system with gmpy installed also, pyecm found the following factors:\n101, 521, 3121, 9901, 36479, 300623, 53397071018461, 1900381976777332243781\nThere still is a 98 digit unfactored composite:\n602525071745682437589111511878284384468144476539868422... | [
3,
2,
1
] | [
"('''==============================================================================='''\n> ''' CALCULATE HIGHEST PRIME\n> FACTOR '''\n>\n> '''===============================================================================''')\n>\n> #!/usr/bin/env python\n> def h... | [
-1
] | [
"factorization",
"primes",
"python"
] | stackoverflow_0002403578_factorization_primes_python.txt |
Q:
Convert mysql timestamp to epoch time in python
Convert mysql timestamp to epoch time in python - is there an easy way to do this?
A:
Why not let MySQL do the hard work?
select unix_timestamp(fieldname) from tablename;
A:
converting mysql time to epoch:
>>> import time
>>> import calendar
>>> mysql_time = "201... | Convert mysql timestamp to epoch time in python | Convert mysql timestamp to epoch time in python - is there an easy way to do this?
| [
"Why not let MySQL do the hard work?\nselect unix_timestamp(fieldname) from tablename;\n\n",
"converting mysql time to epoch:\n>>> import time\n>>> import calendar\n>>> mysql_time = \"2010-01-02 03:04:05\"\n>>> mysql_time_struct = time.strptime(mysql_time, '%Y-%m-%d %H:%M:%S')\n>>> print mysql_time_struct\n(2010,... | [
28,
9,
5,
1
] | [] | [] | [
"mysql",
"python",
"time",
"timestamp"
] | stackoverflow_0000115866_mysql_python_time_timestamp.txt |
Q:
What does the term "blocking" mean in programming?
Could someone provide a layman definition and use case?
A:
"Blocking" means that the caller waits until the callee finishes its processing. For instance, a "blocking read" from a socket waits until there is data to return; a "non-blocking" read does not, it just... | What does the term "blocking" mean in programming? | Could someone provide a layman definition and use case?
| [
"\"Blocking\" means that the caller waits until the callee finishes its processing. For instance, a \"blocking read\" from a socket waits until there is data to return; a \"non-blocking\" read does not, it just returns an indication (usually a count) of whether there was something read.\nYou hear the term mostly ar... | [
34,
5
] | [] | [] | [
"api",
"blocking",
"python"
] | stackoverflow_0002407589_api_blocking_python.txt |
Q:
Change sound output
Is there a way in windows by which I can toggle the audio output between a built-in speaker and the headphone jack using a python library.
I am thinking someone with .NET experience would be able to give me some pointers (I could use IronPython if there is a .NET library to do that).
I have no ... | Change sound output | Is there a way in windows by which I can toggle the audio output between a built-in speaker and the headphone jack using a python library.
I am thinking someone with .NET experience would be able to give me some pointers (I could use IronPython if there is a .NET library to do that).
I have no idea where to start. Any ... | [
"The device selected for output in the Control Panel is just a default, each application can choose to output through that device or select a new one. You can get a handle to the device you want to output through, and subsequently use it for playback, by using the Win32 API for multimedia (winmm.dll). Some of those... | [
0
] | [
"Please read http://alvasnet.blogspot.com/2010/01/communicate-with-aliens-on-ironpython.html article\n"
] | [
-1
] | [
".net",
"audio",
"python"
] | stackoverflow_0001965155_.net_audio_python.txt |
Q:
Creating a list of lists with consecutive numbers
I am looking for a convenient way to create a list of lists for which the lists within the list have consecutive numbers. So far I only came up with a very unsatisfying brute-typing force solution (yeah right, I just use python for a few weeks now):
block0 = []
...... | Creating a list of lists with consecutive numbers | I am looking for a convenient way to create a list of lists for which the lists within the list have consecutive numbers. So far I only came up with a very unsatisfying brute-typing force solution (yeah right, I just use python for a few weeks now):
block0 = []
...
block4 = []
blocks = [block0,block1,block2,block3,blo... | [
"It's not clear what consecutive numbers you're talking about, but your code translates into the following idiomatic Python:\n[[] for _ in range(4)] # use xrange in python-2.x\n\n",
"Don't do it this way. Put it in blocks in the first place:\nblocks = [\n [ ... ],\n [ ... ],\n [ ... ],\n [ ... ]\n]\n... | [
5,
0
] | [] | [] | [
"python"
] | stackoverflow_0002408452_python.txt |
Q:
Why can't I find `len(list)` in Python?
I'm new to Python. I have a method that begins:
def foo(self, list):
length = len(list)
I've called len() successfully in other cases, but here I get:
TypeError: object of type 'type' has no len()
How do I convince Python that this object passed in is a list? What am... | Why can't I find `len(list)` in Python? | I'm new to Python. I have a method that begins:
def foo(self, list):
length = len(list)
I've called len() successfully in other cases, but here I get:
TypeError: object of type 'type' has no len()
How do I convince Python that this object passed in is a list? What am I missing?
| [
"Because list is the name of the list type.\nUse a different name.\ndef foo(self, lst):\n length = len(lst)\n\nAnd make sure you didn't call foo like this:\nFoo.foo(list)\n\n",
"you're shadowing built-in. The value that you're passing to foo method is not a list object, but rather a list type, that doesn't hav... | [
5,
5,
2
] | [] | [] | [
"python"
] | stackoverflow_0002408575_python.txt |
Q:
How can I tell if waiting on Event has timed out?
import threading
event = threading.Event()
event.set()
print event.wait(1)
None
event.clear()
print event.wait(1)
None
So it basically returns None both when condition was True and False. How can I distinguish the ... | How can I tell if waiting on Event has timed out? |
import threading
event = threading.Event()
event.set()
print event.wait(1)
None
event.clear()
print event.wait(1)
None
So it basically returns None both when condition was True and False. How can I distinguish the case of timeouting from the one with no waiting at... | [
"Yes, you're missing next sentence in documentation which writes:\n\nChanged in version 2.7: Previously,\n the method always returned None.\n\n",
"From the docs for threading.Event.wait:\n\nThis method returns the internal flag on exit, so it will always return True except if a timeout is given and the operation... | [
3,
2
] | [] | [] | [
"events",
"multithreading",
"python"
] | stackoverflow_0002408882_events_multithreading_python.txt |
Q:
standalone application in python
I wanted to know how can I make standalone application in python.
Basically what I am doing right now is I have a template.tex file and my script generate the pdf by giving some input values.
So I have to make exe file for windows and same for linux.
I can use cx_freeze for creatin... | standalone application in python | I wanted to know how can I make standalone application in python.
Basically what I am doing right now is I have a template.tex file and my script generate the pdf by giving some input values.
So I have to make exe file for windows and same for linux.
I can use cx_freeze for creating exe file.
But my problem is most of ... | [
"You could write a installer (using NSIS or something) that does two things : \n\ninstall LateX (or make sure there is an installation of latex available), potentially by calling another installer\nthen install your python script (which can assume latex is now available)\n\n",
"Sounds like you need a decent insta... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0002409168_python.txt |
Q:
Google App Engine: Users API acting oddly
I think I'm using the Users API incorrectly:
class BaseHandler(webapp.RequestHandler):
user = users.get_current_user()
def header(self, title):
if self.user:
render('Views/link.html', self, {'text': 'Log out', 'href': users.create_logout_url('/')})
... | Google App Engine: Users API acting oddly | I think I'm using the Users API incorrectly:
class BaseHandler(webapp.RequestHandler):
user = users.get_current_user()
def header(self, title):
if self.user:
render('Views/link.html', self, {'text': 'Log out', 'href': users.create_logout_url('/')})
else:
render('Views/link.html', self, ... | [
"You are storing the result of users.get_current_user() in the variable called user, but then your if checks the value of self.user, which is not the same variable.\nUse the same variable name and all should be fine!\n"
] | [
1
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0002406424_django_google_app_engine_python.txt |
Q:
Cross-site json rpc : Python server side and Mozilla extension using Javascript client side
I am building a Mozilla extension that contacts a Python application on a remote server to send and receive data. The Python application can be called using xml-rpc from a Python console. I am attempting to design a JSON-RP... | Cross-site json rpc : Python server side and Mozilla extension using Javascript client side | I am building a Mozilla extension that contacts a Python application on a remote server to send and receive data. The Python application can be called using xml-rpc from a Python console. I am attempting to design a JSON-RPC that would contact the same application. Developing the Python server side, which can be access... | [
"You can use http://mimic-xmlrpc.sourceforge.net/ js library, or just XMLHttpRequest. I'm just with the same problem, and i'm an absolute newby with js :(\nmimic seems grat, even if i'm having problems parsing the data returned.. \n"
] | [
0
] | [] | [] | [
"javascript",
"json",
"mozilla",
"python",
"rpc"
] | stackoverflow_0002399516_javascript_json_mozilla_python_rpc.txt |
Q:
python unicode implementation (using external programs: cygnative plink ssh rsync)
I have a backup applications in python that needs to work on Windows. It needs UTF compatibility (to be able to backup directories that contain UTF characters like italian accents). The problem is it uses external programs (plink, c... | python unicode implementation (using external programs: cygnative plink ssh rsync) | I have a backup applications in python that needs to work on Windows. It needs UTF compatibility (to be able to backup directories that contain UTF characters like italian accents). The problem is it uses external programs (plink, cygwin, ssh and rsync) and I can't get them working. The prototype is 32 lines long, plea... | [
"\nDon't use shell=True. EVER. It needlessy invokes a shell to call your program.\nPass the parameters as a list instead of a string.\n\nThis example should work, provided the parameters are right and the rsync.exe is in current folder (or PATH):\n# -*- coding: utf-8 -*-\nimport subprocess\n\ndef execute(command):\... | [
1,
0
] | [] | [] | [
"cygwin",
"plink",
"python",
"rsync",
"utf_8"
] | stackoverflow_0002408695_cygwin_plink_python_rsync_utf_8.txt |
Q:
seleniumRC: Problems with browser starting on OS X
I am trying to start simple selenium test on OSX (just downloaded the latest version of RC), with a python client driver. But the browser can't start (it crashes).
The error which I see in console is
15:33:32.867 INFO - Preparing Firefox profile...
dyld: Libr... | seleniumRC: Problems with browser starting on OS X | I am trying to start simple selenium test on OSX (just downloaded the latest version of RC), with a python client driver. But the browser can't start (it crashes).
The error which I see in console is
15:33:32.867 INFO - Preparing Firefox profile...
dyld: Library not loaded: /System/Library/Frameworks/ApplicationSe... | [
"It appears as if ImageIO is interfering with the loading of Firefox when it is creating its new Firefox profile on creation.\nTry create your own firefox profile and then start Selenium RC with the -firefoxProfileTemplate argument\njava -jar selenium-server.jar -firefoxProfileTemplate </path/to/template/>\n\nAnd s... | [
0
] | [] | [] | [
"python",
"selenium",
"selenium_rc"
] | stackoverflow_0002409353_python_selenium_selenium_rc.txt |
Q:
Python methods on an object - which is better?
Hopefully an easy question. If I have an object and I want to call a method on it which is the better approach, A or B?
class foo(object):
def bar():
print 'bar'
# approach A
f = foo()
f.bar()
# approach B
foo().bar()
A:
A is more readable.
So, A :)
... | Python methods on an object - which is better? | Hopefully an easy question. If I have an object and I want to call a method on it which is the better approach, A or B?
class foo(object):
def bar():
print 'bar'
# approach A
f = foo()
f.bar()
# approach B
foo().bar()
| [
"A is more readable. \nSo, A :)\n",
"If your sole intent is to call bar() on a foo object, B is okay.\nBut if you actually plan to do something with the object later, you must go with A as B doesn't leave you any references to the created object.\n",
"Approach B doesn't keep the object around. If method bar() r... | [
2,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0002409668_python.txt |
Q:
django python - generic views and cookies
I made in my web a menu using generic_view - simple 'django.views.generic.list_detail.object_list' in urls.py file.
I would like to set a cookies each time when user chooses one of element of this list [HttpResponse.set_cookie(...)].
What is the best solution? Should I wri... | django python - generic views and cookies | I made in my web a menu using generic_view - simple 'django.views.generic.list_detail.object_list' in urls.py file.
I would like to set a cookies each time when user chooses one of element of this list [HttpResponse.set_cookie(...)].
What is the best solution? Should I write function in views.py or have you got more si... | [
"Generic views are simple views that handle a couple of common cases, for example rendering a template when no view logic is needed. In your case, you want to add functionality to your view (i.e. setting a cookie) so you will need to write your custom view. In addition, you should not add view logic in your urls.py... | [
1
] | [] | [] | [
"django",
"django_generic_views",
"python"
] | stackoverflow_0002408514_django_django_generic_views_python.txt |
Q:
How do I do this regex in Python?
Suppose I have a string of text, of all characters Latin-based. With punctuation.
How do I "find" all the characters and put <strong> tags around it?
hay = The fox jumped up the tree.
needle = "umpe"
In this case, part of the word "jumped" would be highlighted.
A:
Without regex... | How do I do this regex in Python? | Suppose I have a string of text, of all characters Latin-based. With punctuation.
How do I "find" all the characters and put <strong> tags around it?
hay = The fox jumped up the tree.
needle = "umpe"
In this case, part of the word "jumped" would be highlighted.
| [
"Without regex (may be a bit more verbose but also easier to understand):\nhay = \"The fox jumped up the tree.\"\nneedle = \"umpe\"\n\nprint hay.replace(needle, \"<strong>%s<strong>\" % needle)\n\nEDIT after extra specification: if you want case insensitive replace (which a regular string replace can't do):\nimport... | [
4,
3,
1,
1,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0002409636_python_regex.txt |
Q:
Python: How expensive is to create a small list many times?
I encounter the following small annoying dilemma over and over again in Python:
Option 1:
cleaner but slower(?) if called many times since a_list get re-created for each call of do_something()
def do_something():
a_list = ["any", "think", "whatever"... | Python: How expensive is to create a small list many times? | I encounter the following small annoying dilemma over and over again in Python:
Option 1:
cleaner but slower(?) if called many times since a_list get re-created for each call of do_something()
def do_something():
a_list = ["any", "think", "whatever"]
# read something from a_list
Option 2:
Uglier but more e... | [
"What's ugly about it?\nAre the contents of the list always constants, as in your example? If so: recent versions of Python (since 2.4) will optimise that by evaluating the constant expression and keeping the result but only if it's a tuple. So you could change it to being a tuple. Or you could stop worrying about ... | [
16,
4,
4,
3,
2,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0002409472_python.txt |
Q:
How to separate comma separated data from csv file?
I have opened a csv file and I want to sort each string which is comma separated and are in same line:
ex:: file :
name,sal,dept
tom,10000,it
o/p :: each string in string variable
I have a file which is already open, so I can not use "open" API, I have to use "... | How to separate comma separated data from csv file? | I have opened a csv file and I want to sort each string which is comma separated and are in same line:
ex:: file :
name,sal,dept
tom,10000,it
o/p :: each string in string variable
I have a file which is already open, so I can not use "open" API, I have to use "csv.reader" which have to read one line at a time.
| [
"If the file open for reading is bound to a variable name, say fin; and assuming you're using Python 2.6, and you know the file's not empty (has at least the row with headers):\n import csv\n\n rd = csv.reader(fin)\n headers = next(rd)\n for data in rd:\n ...process data and headers...\n\nIn Python 2.5, use heade... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0002408338_python.txt |
Q:
Where to put the separation between a stateful object and a stateless calculation in Python?
Which of the following code snippets is the most "pythonic"? The calculation is trivial in this example but could be assumed to be complex in real life.
class A(object):
"""Freely mix state and calcs - no good I presum... | Where to put the separation between a stateful object and a stateless calculation in Python? | Which of the following code snippets is the most "pythonic"? The calculation is trivial in this example but could be assumed to be complex in real life.
class A(object):
"""Freely mix state and calcs - no good I presume"""
def __init__(self, state):
self.state = state
def calc_with_state(self, x):
... | [
"As written, A, by a longshot. The issue, quite simply, is \n\nFlat is better than nested.\n\nLook: separating state from calculations is a good design principle, but it doesn't mean what you think, at least not what I can infer you think from this example. We want to make sure that state doesn't change in order ... | [
6,
1,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0002410265_python.txt |
Q:
Python: how to switch between workspaces using Xlib?
How do I switch between my window manager's workspaces using Python with Xlib module?
This is my most promising attempt:
#!/usr/bin/python
from Xlib import X, display, error, Xatom, Xutil
import Xlib.protocol.event
screen = Xlib.display.Display().screen()
root... | Python: how to switch between workspaces using Xlib? | How do I switch between my window manager's workspaces using Python with Xlib module?
This is my most promising attempt:
#!/usr/bin/python
from Xlib import X, display, error, Xatom, Xutil
import Xlib.protocol.event
screen = Xlib.display.Display().screen()
root = screen.root
def sendEvent(win, ctype, data, mask=No... | [
"Apparently you need to work on the same Display object and then flush it at the end. Something like:\ndisplay = Xlib.display.Display()\nscreen = display.screen()\nroot = screen.root\n\n# ...\n\nsendEvent(root, display.intern_atom(\"_NET_CURRENT_DESKTOP\"), [1, X.CurrentTime])\ndisplay.flush()\n\nCredit: Idea from ... | [
5
] | [] | [] | [
"pygtk",
"python",
"window",
"xlib"
] | stackoverflow_0002405738_pygtk_python_window_xlib.txt |
Q:
GAE db.Model getting property instead of a string value
I have a db.Model which has a string property on it, email_type. Now I've the values for type defined in a readonly class. When I save this to the datastore I get the string instead of "Register", it also raises a BadValueError. How do I get it to save as a ... | GAE db.Model getting property instead of a string value | I have a db.Model which has a string property on it, email_type. Now I've the values for type defined in a readonly class. When I save this to the datastore I get the string instead of "Register", it also raises a BadValueError. How do I get it to save as a string, not as a property.
Here's the (slimmed down) code:
cl... | [
"What happens if you change your EmailTypes class to look like this:\nclass EmailTypes(object):\n Register = 'Register'\n NewsLetter = 'NewsLetter'\n\nand use it like:\ne.email_type = EmailTypes.Register\n\nDoes that make your simplified example work?\n"
] | [
3
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0002411138_google_app_engine_python.txt |
Q:
Template extraction in python/php
Are there existing template extract libraries in either python or php? Perl has Template::Extract, but I haven't been able to find a similar implementation in either python or php.
The only thing close in python that I could find is TemplateMaker (http://code.google.com/p/templat... | Template extraction in python/php | Are there existing template extract libraries in either python or php? Perl has Template::Extract, but I haven't been able to find a similar implementation in either python or php.
The only thing close in python that I could find is TemplateMaker (http://code.google.com/p/templatemaker/), but that's not really a templ... | [
"After digging around some more I found a solution to exactly what I was looking for. filippo posted a list of python solutions for screen scraping in this post: Options for HTML scraping? among which is a package called scrapemark ( http://arshaw.com/scrapemark/ ).\nHope this helps anyone else who is looking for t... | [
2,
1,
0
] | [] | [] | [
"extract",
"php",
"python",
"templates"
] | stackoverflow_0002152786_extract_php_python_templates.txt |
Q:
pymssql connect function
i have this function
pymssql.connect(host="my host",user="my user",password="my pass",database="mydb")
I want to read the user and password from the user and put them there is that possible or named arguments lvalue should not be variable and if yes then how could i do that ?
i.e is it po... | pymssql connect function | i have this function
pymssql.connect(host="my host",user="my user",password="my pass",database="mydb")
I want to read the user and password from the user and put them there is that possible or named arguments lvalue should not be variable and if yes then how could i do that ?
i.e is it possible to call this function l... | [
"Your question is worded... strangely. Are you having trouble with setting default arguments in a function definition? \n>>> def f(arg1=\"hello\", arg2=\"goodbye\"):\n print \"arg1 is\", arg1\n print \"arg2 is\", arg2\n\n\n>>> f()\narg1 is hello\narg2 is goodbye\n>>> f(arg2=\"two\")\narg1 is hello\narg2 is ... | [
3,
0
] | [] | [] | [
"python",
"sql_server"
] | stackoverflow_0002411203_python_sql_server.txt |
Q:
Function to create in-memory zip file and return as http response
I am avoiding the creation of files on disk, this is what I have got so far:
def get_zip(request):
import zipfile, StringIO
i = open('picture.jpg', 'rb').read()
o = StringIO.StringIO()
zf = zipfile.ZipFile(o, mode='w')
zf.writest... | Function to create in-memory zip file and return as http response | I am avoiding the creation of files on disk, this is what I have got so far:
def get_zip(request):
import zipfile, StringIO
i = open('picture.jpg', 'rb').read()
o = StringIO.StringIO()
zf = zipfile.ZipFile(o, mode='w')
zf.writestr('picture.jpg', i)
zf.close()
o.seek(0)
response = HttpRes... | [
"For StringIO you should generally use o.getvalue() to get the result. Also, if you want to add a normal file to the zip file, you can use zf.write('picture.jpg'). You don't need to manually read it.\n",
"Avoiding disk files can slow your server to a crawl, but it will certainly work.\nYou'll exhaust memory if yo... | [
12,
4
] | [] | [] | [
"python",
"stringio",
"zip"
] | stackoverflow_0002411514_python_stringio_zip.txt |
Q:
How to get an item from a set of Queues?
Say there are two empty Queues. Is there a way to get an item from the queue that gets it first?
So I have a queue of high anonymous proxies, queues of anonymous and transparent ones. Some threads may need only high anon. proxies, while others may accept both high anon. and... | How to get an item from a set of Queues? | Say there are two empty Queues. Is there a way to get an item from the queue that gets it first?
So I have a queue of high anonymous proxies, queues of anonymous and transparent ones. Some threads may need only high anon. proxies, while others may accept both high anon. and just anon. proxies. That's why I can't put th... | [
"You could check both queues in turn, each time using a short timeout. That way you would most likely read from the first queue that receives data. However, this solution is prone to race conditions if you will be getting many items on a regular basis.\nIf that is the case, do you have a good reason for not just wr... | [
0,
0
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0002411306_multithreading_python.txt |
Q:
Regex - Special alpha characters? - Python
I have a list of simple names such as Márquez,
because of the á (?< name >[a-zA-Z]+) doesn't seem to be working!
Help would be very much appreciated!
A:
you could use
\w+
with the unicode flag. I assume there's no risk of having digits or underscore in your names.
>>... | Regex - Special alpha characters? - Python | I have a list of simple names such as Márquez,
because of the á (?< name >[a-zA-Z]+) doesn't seem to be working!
Help would be very much appreciated!
| [
"you could use \n\\w+\n\nwith the unicode flag. I assume there's no risk of having digits or underscore in your names.\n>>> re.findall('\\w+', 'Márquez', re.U)\n['Márquez']\n\nYou also seem to be missing P after the question mark: (?P< name >[a-zA-Z]+)\n",
"For Python < 3 you may want to enable locale:\nimport lo... | [
3,
0
] | [] | [] | [
"ascii",
"python",
"regex"
] | stackoverflow_0002411759_ascii_python_regex.txt |
Q:
Python Socket Send Buffer Vs. Str
I am trying to get a basic server (copied from Beginning Python) to send a str.
The error:
c.send( "XXX" )
TypeError: must be bytes or buffer, not str
It seems to work when pickling an object. All of the examples I found, seem to be able to send a string no problem.
Any help woul... | Python Socket Send Buffer Vs. Str | I am trying to get a basic server (copied from Beginning Python) to send a str.
The error:
c.send( "XXX" )
TypeError: must be bytes or buffer, not str
It seems to work when pickling an object. All of the examples I found, seem to be able to send a string no problem.
Any help would be appreciated,
Stephen
import socket... | [
"It seems you try to use Python 2.x examples in Python 3 and you hit one of the main differences between those Python version.\nFor Python < 3 'strings' are in fact binary strings and 'unicode objects' are the right text objects (as they can contain any Unicode characters).\nIn Python 3 unicode strings are the 'reg... | [
22,
12
] | [] | [] | [
"python",
"send",
"sockets",
"string"
] | stackoverflow_0002411864_python_send_sockets_string.txt |
Q:
Getting information from scripts/command line calls in C#
I've been writing a couple of apps which use C# as the Gui, but under the hood do all the work via scripts (which may be Python, Ruby etc.).
To pass information from the script back to the GUI (for example error reporting etc.) I've usually resorted to ca... | Getting information from scripts/command line calls in C# | I've been writing a couple of apps which use C# as the Gui, but under the hood do all the work via scripts (which may be Python, Ruby etc.).
To pass information from the script back to the GUI (for example error reporting etc.) I've usually resorted to calling the script via Process and either
Redirected the input (... | [
"Using ProcessStartInfo.RedirectStandardInput, ProcessStartInfo.RedirectStandardOutput and ProcessStartInfo.RedirectStandardError (as well as Process.ExitCode) is perfectly fine, especially when your scripts rigorously follow a certain convention:\n\nwarnings and error descriptions go to stderr\nin case of errors e... | [
4
] | [] | [] | [
"c#",
"python",
"ruby",
"scripting"
] | stackoverflow_0002412141_c#_python_ruby_scripting.txt |
Q:
List of Dicts comparision to match between lists and detect value changes in Python
I have a list of dictionaries that I get back from a web service call,
listA = [{'name':'foo', 'val':'x'},
{'name':'bar', 'val':'1'},
{'name':'alice','val':'2'}]
I need to compare the results from the previous c... | List of Dicts comparision to match between lists and detect value changes in Python | I have a list of dictionaries that I get back from a web service call,
listA = [{'name':'foo', 'val':'x'},
{'name':'bar', 'val':'1'},
{'name':'alice','val':'2'}]
I need to compare the results from the previous call to the service and pull out changes. So on the next call I may get:
listB = [{'name':... | [
"I'd build an auxiliary dict to store listA's information more sensibly:\nauxdict = dict((d['name'], d['val']) for d in listA)\n\nthen the task becomes very easy:\nchanged = [d['name'] for d in listB \n if d['name'] in auxdict and d['val'] != auxdict[d['name']]]\n\n",
"First off, please turn that braind... | [
6,
0
] | [] | [] | [
"comparison",
"dictionary",
"list",
"python"
] | stackoverflow_0002412562_comparison_dictionary_list_python.txt |
Q:
Python program doesn't quit when finished
I have the following script 186.py:
S=[]
study=set([524287])
tmax=10**7
D={}
DF={}
dudcount=0
callcount=0
def matchval(t1,t2):
if t1==t2:
global dudcount
dudcount+=1
else:
global callcount
callcount+=1
D.setdefault(t1,set([... | Python program doesn't quit when finished | I have the following script 186.py:
S=[]
study=set([524287])
tmax=10**7
D={}
DF={}
dudcount=0
callcount=0
def matchval(t1,t2):
if t1==t2:
global dudcount
dudcount+=1
else:
global callcount
callcount+=1
D.setdefault(t1,set([]))
D.setdefault(t2,set([]))
D[... | [
"I ran the same code on my 2 GHz dual-core laptop with 2GB RAM and it took about 1 1/2 minutes in Cygwin. The memory usage got up over 600 MB before the program quit and it took about 2-4 seconds after Done appeared for the prompt to come up and the memory to be released. However, I didn't see any memory increase a... | [
7,
0
] | [] | [] | [
"linux",
"memory_leaks",
"python"
] | stackoverflow_0002412715_linux_memory_leaks_python.txt |
Q:
Python - file contents to nested list
I have a file in tab delimited format with trailing newline characters, e.g.,
123 abc
456 def
789 ghi
I wish to write function to convert the contents of the file into a nested list. To date I have tried:
def ls_platform_ann():
keyword = []
for line in open( "fi... | Python - file contents to nested list | I have a file in tab delimited format with trailing newline characters, e.g.,
123 abc
456 def
789 ghi
I wish to write function to convert the contents of the file into a nested list. To date I have tried:
def ls_platform_ann():
keyword = []
for line in open( "file", "r" ).readlines():
for value i... | [
"You want the csv module.\nimport csv\n\nsource = \"123\\tabc\\n456\\tdef\\n789\\tghi\"\nlines = source.split(\"\\n\")\n\nreader = csv.reader(lines, delimiter='\\t')\n\nprint [word for word in [row for row in reader]]\n\nOutput:\n[['123', 'abc'], ['456', 'def'], ['789', 'ghi']]\n\nIn the code above Ive put the cont... | [
8,
3,
3
] | [] | [] | [
"file",
"list",
"newline",
"python",
"tabs"
] | stackoverflow_0002410619_file_list_newline_python_tabs.txt |
Q:
problem with editing labels in wx list control
do you guys have any idea how to edit the the labels in the second column in a wx.ListCtrl
here is the code that i used to create that list .. Note that the first column is the only editable one . how can i make the other one editable too?
self.lCUsers=wx.ListCtrl(s... | problem with editing labels in wx list control | do you guys have any idea how to edit the the labels in the second column in a wx.ListCtrl
here is the code that i used to create that list .. Note that the first column is the only editable one . how can i make the other one editable too?
self.lCUsers=wx.ListCtrl(self,style=wx.LC_EDIT_LABELS | wx.LC_REPORT |wx.LC_V... | [
"You can use the TextEditMixin\nimport wx\nfrom wx.lib.mixins.listctrl import TextEditMixin\n\nclass EditableTextListCtrl(wx.ListCtrl, TextEditMixin):\n def __init__(self, parent, ID, pos=wx.DefaultPosition,\n size=wx.DefaultSize, style=0):\n wx.ListCtrl.__init__(self, parent, ID, pos, size... | [
2
] | [] | [] | [
"python",
"wxpython",
"wxwidgets"
] | stackoverflow_0002274217_python_wxpython_wxwidgets.txt |
Q:
Circular import issues with Django apps that have dependencies on each other
I am writing a couple of django apps which by design are coupled together. But I get circular import problems. I know it might be bad design, so please give examples of better solutions. I can't seem to find a better suited design, so if ... | Circular import issues with Django apps that have dependencies on each other | I am writing a couple of django apps which by design are coupled together. But I get circular import problems. I know it might be bad design, so please give examples of better solutions. I can't seem to find a better suited design, so if there isn't a better design, how to solve this one?
It is basically two django app... | [
"Both models do not need many-to-many fields.\nDo not put both sides of a many-to-many relationship in your model.\nWhen you put in one many-to-many relationship, Django inserts the other side of the relationship for you. \nhttp://docs.djangoproject.com/en/1.1/topics/db/queries/#many-to-many-relationships\n\nBoth e... | [
7
] | [] | [] | [
"design_patterns",
"django",
"import",
"python"
] | stackoverflow_0002412995_design_patterns_django_import_python.txt |
Q:
Mercurial Issue when updating
I am trying to do a terminal update and I keep getting this error, no matter what.
/Volumes/www/working/.hg/wlock.break
/Library/Python/2.6/site-packages/mercurial/dispatch.py:157: DeprecationWarning: use lock.release instead of del lock
return -1
Any ideas as to what this is?
Out o... | Mercurial Issue when updating | I am trying to do a terminal update and I keep getting this error, no matter what.
/Volumes/www/working/.hg/wlock.break
/Library/Python/2.6/site-packages/mercurial/dispatch.py:157: DeprecationWarning: use lock.release instead of del lock
return -1
Any ideas as to what this is?
Out of date versions?
I am running Snow ... | [
"What version of mercurial are you running? It looks like a lot of these (harmless warning) messages have been cleaned up according to the mercurial bug tracker.\n"
] | [
1
] | [] | [] | [
"mercurial",
"python"
] | stackoverflow_0002412043_mercurial_python.txt |
Q:
Python Socket Getting Connection Reset
I created a threaded socket listener that stores newly accepted connections in a queue. The socket threads then read from the queue and respond. For some reason, when doing benchmarking with 'ab' (apache benchmark) using a concurrency of 2 or more, I always get a connection r... | Python Socket Getting Connection Reset | I created a threaded socket listener that stores newly accepted connections in a queue. The socket threads then read from the queue and respond. For some reason, when doing benchmarking with 'ab' (apache benchmark) using a concurrency of 2 or more, I always get a connection reset before it's able to complete the benchm... | [
"Is there a reason why you're not using SocketServer which comes with Python? This would handle the situation a lot better. If you're looking to do HTTP stuff, the BaseHTTPServer also provides a framework for this. \n"
] | [
0
] | [] | [] | [
"multithreading",
"python",
"sockets"
] | stackoverflow_0002411290_multithreading_python_sockets.txt |
Q:
Error when using astWCS trying to create WCS object
I'm running python2.5 and trying to use the astLib library to analyse WCS information in astronomical images. I try and get the object instanciated with the following skeleton code:
from astLib import astWCS
w = astWCS.WCS('file.fits') # error here
where file.f... | Error when using astWCS trying to create WCS object | I'm running python2.5 and trying to use the astLib library to analyse WCS information in astronomical images. I try and get the object instanciated with the following skeleton code:
from astLib import astWCS
w = astWCS.WCS('file.fits') # error here
where file.fits is a string pointing to a valid fits file.
I have tr... | [
"Just found out the updated version of this library has fixed the problem, thanks for everyone's help\n",
"Oh sorry, I should have seen. Looking at the pastebin in more detail, the only error I can think of is that, for some reason the header has unicode in it. It can't be converted to char *, and you get the er... | [
1,
0
] | [] | [] | [
"astronomy",
"fits",
"python"
] | stackoverflow_0002048166_astronomy_fits_python.txt |
Q:
Good ways to sort a queryset? - Django
what I'm trying to do is this:
get the 30 Authors with highest score ( Author.objects.order_by('-score')[:30] )
order the authors by last_name
Any suggestions?
A:
What about
import operator
auths = Author.objects.order_by('-score')[:30]
ordered = sorted(auths, key=operat... | Good ways to sort a queryset? - Django | what I'm trying to do is this:
get the 30 Authors with highest score ( Author.objects.order_by('-score')[:30] )
order the authors by last_name
Any suggestions?
| [
"What about\nimport operator\n\nauths = Author.objects.order_by('-score')[:30]\nordered = sorted(auths, key=operator.attrgetter('last_name'))\n\nIn Django 1.4 and newer you can order by providing multiple fields.\nReference: https://docs.djangoproject.com/en/dev/ref/models/querysets/#order-by\norder_by(*fields)\nBy... | [
248,
16,
6
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0002412770_django_django_models_python.txt |
Q:
Python package with compiled code
I'm looking into releasing a python package which includes an existing fortran or C program. The fortran/C program is compiled by running
./configure
make
The python code calls the resulting binary through subprocess calls (i.e. the code is not really wrapped as such). What I wou... | Python package with compiled code | I'm looking into releasing a python package which includes an existing fortran or C program. The fortran/C program is compiled by running
./configure
make
The python code calls the resulting binary through subprocess calls (i.e. the code is not really wrapped as such). What I would like is that when the user types
pyt... | [
"Don't make this too complex.\nJust provide them as separate items with a README that says -- basically -- what you said in the question.\n\nBuild the Fortran/C with ./configure; make; make install.\nSetup Python with python setup.py install.\n\nIt doesn't appear to be rocket science. Trying to over-simplify the i... | [
2,
0
] | [] | [] | [
"package",
"python"
] | stackoverflow_0002414045_package_python.txt |
Q:
How do I make this sorting case insensitive?
def sortProfiles(p):
return sorted(p, key=itemgetter('first_name'))
I have a list with dictionaries. This function allows me to sort them by their first_name. However, it's case-sensitive.
A:
>>> from operator import itemgetter
>>> p = [{'fn':'bill'}, {'fn':'Bob... | How do I make this sorting case insensitive? | def sortProfiles(p):
return sorted(p, key=itemgetter('first_name'))
I have a list with dictionaries. This function allows me to sort them by their first_name. However, it's case-sensitive.
| [
">>> from operator import itemgetter\n>>> p = [{'fn':'bill'}, {'fn':'Bob'}, {'fn':'bobby'}]\n>>> sorted(p, key=itemgetter('fn'))\n[{'fn': 'Bob'}, {'fn': 'bill'}, {'fn': 'bobby'}]\n>>> sorted(p, key=lambda x: x['fn'].lower())\n[{'fn': 'bill'}, {'fn': 'Bob'}, {'fn': 'bobby'}]\n>>>\n\n",
"Here's a way:\nreturn sorte... | [
10,
2,
1,
1,
1,
1
] | [] | [] | [
"dictionary",
"list",
"python",
"sorting"
] | stackoverflow_0002414201_dictionary_list_python_sorting.txt |
Q:
How regex a empty string in python?
I want that find empty tags, here is a example
txt ="<lol1><><lol2>"
rgx = "<([a-zA-Z_0-9]+)>"
print re.findall(rgex, txt)
I get this
['lol1', 'lol2']
I want
['lol1', '', 'lol2']
How I can do this with regex?
A:
Use rgx = "<([a-zA-Z_0-9]*)>"
The key point is using *, whi... | How regex a empty string in python? | I want that find empty tags, here is a example
txt ="<lol1><><lol2>"
rgx = "<([a-zA-Z_0-9]+)>"
print re.findall(rgex, txt)
I get this
['lol1', 'lol2']
I want
['lol1', '', 'lol2']
How I can do this with regex?
| [
"Use rgx = \"<([a-zA-Z_0-9]*)>\"\nThe key point is using *, which means \"zero or more of the preceding\", where you're using +, which means \"one or more\".\n",
"no need regex\n>>> s=\"txt =\"<lol1><><lol2>\"\n>>> for i in txt.split(\">\"):\n... if \"<\" in i:\n... print i[i.find(\"<\")+1:]\n...\nlol1... | [
8,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0002414472_python_regex.txt |
Q:
Creating subtree from tree which is represented in xml - python
I have an XML (in the form of tree), I require to create sub-tree out of it.
For ex:
<a>
<b>
<c>Hello</c>
<d>
<e>Hi</e>
</a>
Subtree would be
<root>
<a>
<b>
<c>Hello</c>
</b>
</a>
<a>
<d>
<e>Hi</e>
</d>
</a>
</root>
Wh... | Creating subtree from tree which is represented in xml - python | I have an XML (in the form of tree), I require to create sub-tree out of it.
For ex:
<a>
<b>
<c>Hello</c>
<d>
<e>Hi</e>
</a>
Subtree would be
<root>
<a>
<b>
<c>Hello</c>
</b>
</a>
<a>
<d>
<e>Hi</e>
</d>
</a>
</root>
What is the best XML library in python to do it? Any algorithm that alr... | [
"ElementTree is good and simple for both \"reading\" and \"writing\".\nYour first XML example (I edited your question just to add formatting so it would be readable!) is invalid, I assume missing close-tags for b and d as appear in what you call \"the subtree\" (which looks nothing like a subtree to me, but does lo... | [
4
] | [] | [] | [
"parsing",
"python",
"subtree",
"tree",
"xml"
] | stackoverflow_0002414458_parsing_python_subtree_tree_xml.txt |
Q:
How do I do this "order by" in Django, if I have foreign keys?
Suppose my model is this:
class Ego(models.Model):
event = models.ForeignKey(Event)
user = models.ForeignKey(User)
As you can see, this table has 2 columns, and they're both foreign keys.
How do I "order by" User.first_name?
Is this it? But i... | How do I do this "order by" in Django, if I have foreign keys? | Suppose my model is this:
class Ego(models.Model):
event = models.ForeignKey(Event)
user = models.ForeignKey(User)
As you can see, this table has 2 columns, and they're both foreign keys.
How do I "order by" User.first_name?
Is this it? But it doesn't look like it.
Ego.objects.all().order_by("User.first_name"... | [
"Solved.\nI did this:\nEgo.objects.all().select_related.order_by(\"auth_user.first_name\")\n\n"
] | [
3
] | [] | [] | [
"database",
"django",
"mysql",
"python"
] | stackoverflow_0002414369_database_django_mysql_python.txt |
Q:
Where is the full JID value when using xmpppy?
Where do I find the full JID value after connecting and authenticating against a Jabber server when using the xmpppy library?
I need the full JID for a subsequent Iq call to the server. Specifying the bare JID (user@domain.com) results in the following error:
If set... | Where is the full JID value when using xmpppy? | Where do I find the full JID value after connecting and authenticating against a Jabber server when using the xmpppy library?
I need the full JID for a subsequent Iq call to the server. Specifying the bare JID (user@domain.com) results in the following error:
If set, the 'from' attribute must be set to the user's ful... | [
"Use the non-underbar versions:\nc = xmpp.client.Client(...)\n# connect\njid = xmpp.JID(node=c.User, domain=c.Server, resource=c.Resource)\n\nHowever, there is no need to set a from address. The server will do this for you for all of the stanzas you send.\n",
"I don't see the JID being stored as such either, but... | [
2,
1
] | [] | [] | [
"python",
"xmpp",
"xmpppy"
] | stackoverflow_0002393011_python_xmpp_xmpppy.txt |
Q:
Sort by key of dictionary inside a dictionary in Python
How to sort the following dictionary by the value of "remaining_pcs" or "discount_ratio"?
promotion_items = {
'one': {'remaining_pcs': 100, 'discount_ratio': 10},
'two': {'remaining_pcs': 200, 'discount_ratio': 20},
}
EDIT
What I mean is getting a so... | Sort by key of dictionary inside a dictionary in Python | How to sort the following dictionary by the value of "remaining_pcs" or "discount_ratio"?
promotion_items = {
'one': {'remaining_pcs': 100, 'discount_ratio': 10},
'two': {'remaining_pcs': 200, 'discount_ratio': 20},
}
EDIT
What I mean is getting a sorted list of above dictionary, not to sort the dictionary its... | [
"You can only sort the keys (or items or values) of a dictionary, into a separate list (as I wrote years ago in the recipe that @Andrew's quoting). E.g., to sort keys according to your stated criteria:\npromotion_items = {\n 'one': {'remaining_pcs': 100, 'discount_ratio': 10},\n 'two': {'remaining_pcs': 200, ... | [
5,
2,
0
] | [] | [] | [
"dictionary",
"python",
"sorting"
] | stackoverflow_0002414763_dictionary_python_sorting.txt |
Q:
Concepts and tools required to scale up algorithms
I'd like to begin thinking about how I can scale up my algorithms that I write for data analysis so that they can be applied to arbitrarily large sets of data. I wonder what are the relevant concepts (threads, concurrency, immutable data structures, recursion) and... | Concepts and tools required to scale up algorithms | I'd like to begin thinking about how I can scale up my algorithms that I write for data analysis so that they can be applied to arbitrarily large sets of data. I wonder what are the relevant concepts (threads, concurrency, immutable data structures, recursion) and tools (Hadoop/MapReduce, Terracota, and Eucalyptus) to ... | [
"While languages and associated technologies/frameworks are important for scaling, they tend to pale in comparison to the importance of the algorithms, data structure, and architectures. Forget threads: the number of cores you can exploit that way is just too limited -- you want separate processes exchanging messa... | [
9,
3
] | [] | [] | [
"concurrency",
"hadoop",
"multithreading",
"python",
"r"
] | stackoverflow_0002414915_concurrency_hadoop_multithreading_python_r.txt |
Q:
What is the fastest way to check whether a folder size is greater than a specific size?
What will be the fastest way to check whether a folder size is beyond a specific size say 10 MB, 1 Gb , 10 GB etc, without actually calculating the folder size. Something like quota. A Pythonic solution will be great, but stand... | What is the fastest way to check whether a folder size is greater than a specific size? | What will be the fastest way to check whether a folder size is beyond a specific size say 10 MB, 1 Gb , 10 GB etc, without actually calculating the folder size. Something like quota. A Pythonic solution will be great, but standard UNIX utilities also welcome
| [
"import os\nfrom os.path import join, getsize\n\ndef getsize_limited(directory, limit):\n total_size = 0\n for root, dirs, files in os.walk(directory, topdown=False):\n for name in files:\n total_size += getsize(join(root, name))\n if total_size > limit:\n ... | [
4,
2,
2,
1
] | [] | [] | [
"linux",
"python",
"shell"
] | stackoverflow_0002414917_linux_python_shell.txt |
Q:
Add directory to PYTHONPATH ( multiple drives ), for auto-complete
I have 2 hard-drives, C:\ and D:\
Django imports correctly (which is in my C drive), but my application is on my D drive. I can't move it to the C drive because of some back-up software I'm running/
I'm trying to get auto-complete to work in Komodo... | Add directory to PYTHONPATH ( multiple drives ), for auto-complete | I have 2 hard-drives, C:\ and D:\
Django imports correctly (which is in my C drive), but my application is on my D drive. I can't move it to the C drive because of some back-up software I'm running/
I'm trying to get auto-complete to work in Komodo Edit 5 which works fine for Django, but not for my application. There a... | [
"Have you tried adding Additional import directories in Edit/Preferences/ under Languages/Python in Komodo?\nEdit: I think you can also add a .pth file in [komodo-install-dir]/lib/mozilla/python/ or C:\\[PythonVersion]\\Lib\\site-packages\\ containing all other path you might want to be available. Not sure wich way... | [
2
] | [] | [] | [
"autocomplete",
"python",
"pythonpath"
] | stackoverflow_0002415014_autocomplete_python_pythonpath.txt |
Q:
How to install python modules and dependents easily?
Are there any easy installation tools like "perl -MCPAN -e shell;" to install python modules and its dependents???
A:
pip is the most up to date tool to do this: you use it by issuing the command
pip install <packagename>
The "old" way of doing the same is to... | How to install python modules and dependents easily? | Are there any easy installation tools like "perl -MCPAN -e shell;" to install python modules and its dependents???
| [
"pip is the most up to date tool to do this: you use it by issuing the command \npip install <packagename>\nThe \"old\" way of doing the same is to easy_install:\neasy_install <packagename>\n\nIf you have easy_install already on your system, it is advisable to run easy_install pip to upgrade to pip\nBoth of these i... | [
6
] | [] | [] | [
"python"
] | stackoverflow_0002415166_python.txt |
Q:
How to make script/program to make it so an application is always running?
I have a simple .exe that needs to be running continuously.
Unfortunately, sometimes it crashes unexpectedly, and there's nothing that can be done for this.
I'm thinking of like a C# program that scans the running application tree on a time... | How to make script/program to make it so an application is always running? | I have a simple .exe that needs to be running continuously.
Unfortunately, sometimes it crashes unexpectedly, and there's nothing that can be done for this.
I'm thinking of like a C# program that scans the running application tree on a timer and if the process stops running it re-launches it... ? Not sure how to do th... | [
"It's fairly easy to do that, but the \"crashes unexpectedly, and there's nothing that can be done for this\" sounds highly suspect to me. Perhaps you mean the program in question is from a third party, and you need to work around problems they can't/won't fix?\nIn any case, there's quite a bit of sample code to do... | [
2,
1,
0,
0,
0
] | [] | [] | [
"c#",
"c++",
"python"
] | stackoverflow_0002414616_c#_c++_python.txt |
Q:
Suggestions required for generating this logging file structure in django project
Can anyone please suggest how to generate log files having following directory-file structure using python logging in django project.
logs/2009-03-09
/errors.log
/warnings.log
/info.log
/emai... | Suggestions required for generating this logging file structure in django project | Can anyone please suggest how to generate log files having following directory-file structure using python logging in django project.
logs/2009-03-09
/errors.log
/warnings.log
/info.log
/emails.log
/messages.log
logs/2009-03-08
/errors.log
/warni... | [
"\nSet up FileHandler instances with Filter instances which match the criteria for those files.\nAdd the handlers to the root logger.\nProfit ;-)\n\nSee this other answer for an example of a filter which matches a specific level. You can use that as an example to create your own custom filters for 'emails' and 'mes... | [
3
] | [] | [] | [
"django",
"logging",
"python"
] | stackoverflow_0002408800_django_logging_python.txt |
Q:
python ConfigParser module
I have the following ini file
[Section]
value=test
When i use the ConfigParser Module :
import ConfigParser
config = ConfigParser.ConfigParser()
config.read('config.ini')
str=config.get('Section', 'value')
if str == 'test':
print 1
else :
print 0
it always print 0 could someo... | python ConfigParser module | I have the following ini file
[Section]
value=test
When i use the ConfigParser Module :
import ConfigParser
config = ConfigParser.ConfigParser()
config.read('config.ini')
str=config.get('Section', 'value')
if str == 'test':
print 1
else :
print 0
it always print 0 could someone help
| [
"try \nprint str\n\nand see what the value is.\n"
] | [
0
] | [] | [] | [
"configparser",
"python"
] | stackoverflow_0002415586_configparser_python.txt |
Q:
"Broken" unicode strings encoded in UTF-8?
I have been studying unicode and its Python implementation now for two days, and I think I'm getting a glimpse of what it is about. Just to get confident, I'm asking if my assumptions for my current problems are correct.
In Django, forms give me unicode strings which I su... | "Broken" unicode strings encoded in UTF-8? | I have been studying unicode and its Python implementation now for two days, and I think I'm getting a glimpse of what it is about. Just to get confident, I'm asking if my assumptions for my current problems are correct.
In Django, forms give me unicode strings which I suspect to be "broken". Unicode strings in Python ... | [
"u'f\\xa4hre'is a unicode string, not encoded as anything. The unicode codepoint 0xa4 is the character ä. It is not really important that ä would also be encoded as byte 0xa4 in ISO-8859-1.\nThe unicode string can contain any unicode characters without encoding them in some way. For example 轮渡 would be represented ... | [
4,
1
] | [] | [] | [
"django",
"python",
"unicode",
"utf_8"
] | stackoverflow_0002415628_django_python_unicode_utf_8.txt |
Q:
Send AT-command through bluetooth from python application
hai guyz,
how can i send AT-command through bluetooth from a python application?
OS:fedora 8
Any one please healp me with the code?
which package i need to import?
from where can i download it?
A:
To get a connection over bluetooth to your IP modem, you ... | Send AT-command through bluetooth from python application | hai guyz,
how can i send AT-command through bluetooth from a python application?
OS:fedora 8
Any one please healp me with the code?
which package i need to import?
from where can i download it?
| [
"To get a connection over bluetooth to your IP modem, you want to use the bluetooth\nrfcomm driver:\nmichael@challenger:~> cat /etc/bluetooth/rfcomm.conf \nrfcomm0 {\n # Automatically bind the device at startup\n bind yes;\n # Bluetooth address of the device\n device 00:1C:CC:XX:XX:XX;\... | [
1,
1
] | [] | [] | [
"at_command",
"fedora",
"python",
"sms"
] | stackoverflow_0002161365_at_command_fedora_python_sms.txt |
Q:
Error in gui programming in python using tkinter
#!/usr/bin/python
# -*- coding: iso-8859-1 -*-
import Tkinter
class simpleapp_tk(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent=parent
def initialize(self):
self.grid()
self.entry=Tkint... | Error in gui programming in python using tkinter | #!/usr/bin/python
# -*- coding: iso-8859-1 -*-
import Tkinter
class simpleapp_tk(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent=parent
def initialize(self):
self.grid()
self.entry=Tkinter.Entry(self)
self.entry.grid(column=0,row=0,... | [
"The main issue was that you forgot to call app.initialize(), but you also had a couple of typos. I've pointed out where in the comments in this fixed version.\nimport Tkinter\n\nclass simpleapp_tk(Tkinter.Tk):\n def __init__(self,parent):\n Tkinter.Tk.__init__(self,parent)\n self.parent=parent\n ... | [
4
] | [] | [] | [
"python"
] | stackoverflow_0002415950_python.txt |
Q:
Allow user to select a file or a folder in QFileDialog
In PyQt you can do something like the following to allow the user to select a file
filename = QtGui.QFileDialog.getOpenFileName(self, "Choose file..")
However I would like a QFileDialog to open in which the user would be able to select either a file or a dire... | Allow user to select a file or a folder in QFileDialog | In PyQt you can do something like the following to allow the user to select a file
filename = QtGui.QFileDialog.getOpenFileName(self, "Choose file..")
However I would like a QFileDialog to open in which the user would be able to select either a file or a directory. I'm sure I've seen this feature in PyQt applications ... | [
"From what I remember you need to write your own QFileDialog and set proper mode. I believe this should be QFileDialog.ExistingFile & QFileDialog.Directory.\nYou can try to write your own static method basing on the getExisitingDirectory (from C++ repository):\nQString QFileDialog::getExistingDirectory(QWidget *par... | [
0
] | [] | [] | [
"pyqt",
"python"
] | stackoverflow_0002413692_pyqt_python.txt |
Q:
SQLAlchemy with multiple primary keys does not automatically set any
I had a simple table:
class test(Base):
__tablename__ = 'test'
id = Column(Integer, primary_key=True)
title = Column(String)
def __init__(self, title):
self.title = title
When using this table, id was set automatically. ... | SQLAlchemy with multiple primary keys does not automatically set any | I had a simple table:
class test(Base):
__tablename__ = 'test'
id = Column(Integer, primary_key=True)
title = Column(String)
def __init__(self, title):
self.title = title
When using this table, id was set automatically. I want to add another field that is unique and efficient to search, so I ... | [
"I have few problems here\n1) What is a purpose of your hand-made __init__? If it does just what you wrote, you can omit constructor completely since SQLAlchemy machinery generates exactly the same constructor for all your models automagically. Although if you take some additional actions and thus have to override ... | [
7
] | [] | [] | [
"database",
"primary_key",
"python",
"sqlalchemy"
] | stackoverflow_0002415842_database_primary_key_python_sqlalchemy.txt |
Q:
Error while posting a Twitter message through a python app
#!/usr/bin/python
# -*- coding: iso-8859-1 -*-
import Tkinter
import twitter
class simpleapp_tk(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent = parent
self.initialize()
def initializ... | Error while posting a Twitter message through a python app | #!/usr/bin/python
# -*- coding: iso-8859-1 -*-
import Tkinter
import twitter
class simpleapp_tk(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent = parent
self.initialize()
def initialize(self):
self.grid()
api=twitter.api()(username='-... | [
"The error message is clear, isn't it? The twitter module has no attribute named \"api\".\nA quick google showed me some examples that have a \".Api()\" method (capital A). Maybe that is your problem.\n"
] | [
3
] | [] | [] | [
"python",
"tkinter",
"twitter"
] | stackoverflow_0002416548_python_tkinter_twitter.txt |
Q:
How to join the same table in sqlalchemy
I'm trying to join the same table in sqlalchemy. This is a minimial version of what I tried:
#!/usr/bin/env python
import sqlalchemy as sa
from sqlalchemy import create_engine
from sqlalchemy.orm import mapper, sessionmaker, aliased
engine = create_engine('sqlite:///:memor... | How to join the same table in sqlalchemy | I'm trying to join the same table in sqlalchemy. This is a minimial version of what I tried:
#!/usr/bin/env python
import sqlalchemy as sa
from sqlalchemy import create_engine
from sqlalchemy.orm import mapper, sessionmaker, aliased
engine = create_engine('sqlite:///:memory:', echo=True)
metadata = sa.MetaData()
devi... | [
"For query.[outer]join, you specify as list of joins (which is different to expression.[outer]join.) So I needed to put the 2 elements of the join, the table and the onclause in a tuple, like this:\nq = db_session.query(Device, ParentDevice)\\\n .outerjoin(\n (ParentDevice, Device.parent_device_... | [
8,
3
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0002416454_python_sqlalchemy.txt |
Q:
Django and "get() returned more than one Model name" error in multi-threaded program
Django's get_or_create function always cause "get() returned more than one Model name" error in a multi-threaded program.
I even tried to put get_or_create statement inside a lock.acquire() and lock.release() block but still didn'... | Django and "get() returned more than one Model name" error in multi-threaded program | Django's get_or_create function always cause "get() returned more than one Model name" error in a multi-threaded program.
I even tried to put get_or_create statement inside a lock.acquire() and lock.release() block but still didn't work.
The program only works when I set thread_count=1
The database is on InnoDB engine.... | [
"This is not caused by multithreading, but because there are more than one object in database, that satisfies your query. You must select exactly one object from the database using get, otherwise it will raise an exception.\n"
] | [
2
] | [] | [] | [
"database",
"insert",
"multithreading",
"mysql",
"python"
] | stackoverflow_0002416819_database_insert_multithreading_mysql_python.txt |
Q:
Python __init__ issue: unbound method __init__() must be called with Bank instance as first argument (got int instance instead)
class Teller(object):
def __init__(self):
self.occupied = False
self.timeLeft = 0
self.totTime
def occupy(self, timeOcc):
self.occupied = True
... | Python __init__ issue: unbound method __init__() must be called with Bank instance as first argument (got int instance instead) | class Teller(object):
def __init__(self):
self.occupied = False
self.timeLeft = 0
self.totTime
def occupy(self, timeOcc):
self.occupied = True
self.timeLeft = timeOcc
def nextMin(self):
self.timeLeft -= 1
self.totTime += 1
if self.timeLeft ==... | [
"2 points to make here:\n\nYou shouldn't be calling __init__ directly, it's a magic method which is invoked when you construct an object like this:\nvirtBank = Bank(3, 7)\n\nThe instance is implicitly passed to the constructor, but it must be explicitly received, like this:\ndef __init__(self, numTellers, hoursOpen... | [
8
] | [] | [] | [
"init",
"methods",
"python"
] | stackoverflow_0002417192_init_methods_python.txt |
Q:
Finding a module's directory
How can I find what directory a module has been imported from, as it needs to load a data file which is in the same directory.
edit:
combining several answers:
module_path = os.path.dirname(imp.find_module(self.__module__)[1])
got me what i wanted
A:
This would work:
yourmodule.__fi... | Finding a module's directory | How can I find what directory a module has been imported from, as it needs to load a data file which is in the same directory.
edit:
combining several answers:
module_path = os.path.dirname(imp.find_module(self.__module__)[1])
got me what i wanted
| [
"This would work:\nyourmodule.__file__\n\nand if you want to find the module an object was imported from:\nmyobject.__module__\n\n",
"The path to the module's file is in module.__file__. You can use that with os.path.dirname to get the directory.\n",
"Using the re module as an example:\n>>> import re\n>>> path ... | [
1,
1,
1,
1
] | [] | [] | [
"dirname",
"module",
"python"
] | stackoverflow_0002417215_dirname_module_python.txt |
Q:
How to convert this regular expression into Python
I want to use this regular expression in Python:
<(?:"[^"]*"['"]*|'[^']*'['"]*|[^'">])+>
(from RegEx match open tags except XHTML self-contained tags)
def removeHtmlTags(page):
p = re.compile(r'XXXX')
return p.sub('', page)
It seems that I cannot direct... | How to convert this regular expression into Python | I want to use this regular expression in Python:
<(?:"[^"]*"['"]*|'[^']*'['"]*|[^'">])+>
(from RegEx match open tags except XHTML self-contained tags)
def removeHtmlTags(page):
p = re.compile(r'XXXX')
return p.sub('', page)
It seems that I cannot directly substitute the complex regular expression into the ab... | [
"Works fine here. You're probably having trouble because of the quotes. Just triple-quote it:\ndef removeHtmlTags(page):\n p = re.compile(r'''<(?:\"[^\"]*\"['\"]*|'[^']*'['\"]*|[^'\">])+>''')\n return p.sub('', page)\n\n",
"If you need to remove HTML tags, this should do it:\nimport re\n\ndef removeHtmlTags... | [
3,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0002417330_python_regex.txt |
Q:
How to use lazy_gettext with Pylons and setup.py
Just a quick question. When I use the _() function provided by the Pylons i18n module, everything works just as expected.
My problem is with the lazy version of this function, lazy_gettext. When I run :
python setup.py extract_messages
I get in the POT file the str... | How to use lazy_gettext with Pylons and setup.py | Just a quick question. When I use the _() function provided by the Pylons i18n module, everything works just as expected.
My problem is with the lazy version of this function, lazy_gettext. When I run :
python setup.py extract_messages
I get in the POT file the strings to be translated with the _() function, but not t... | [
"In the modules where you use lazy_gettext(), just assign _ = lazy_gettext and use _() instead.\n"
] | [
2
] | [] | [] | [
"internationalization",
"pylons",
"python"
] | stackoverflow_0002417479_internationalization_pylons_python.txt |
Q:
How to check with python if a table is empty?
Using python and MySQLdb, how can I check if there are any records in a mysql table (innodb)?
A:
Just select a single row. If you get nothing back, it's empty! (Example from the MySQLdb site)
import MySQLdb
db = MySQLdb.connect(passwd="moonpie", db="thangs")
results... | How to check with python if a table is empty? | Using python and MySQLdb, how can I check if there are any records in a mysql table (innodb)?
| [
"Just select a single row. If you get nothing back, it's empty! (Example from the MySQLdb site)\nimport MySQLdb\ndb = MySQLdb.connect(passwd=\"moonpie\", db=\"thangs\")\nresults = db.query(\"\"\"SELECT * from mytable limit 1\"\"\")\nif not results:\n print \"This table is empty!\"\n\n",
"Something like\nimpor... | [
6,
2
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0002417545_mysql_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.