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:
What to do with “urlopen error” in python?
How do I rectify the error "urlopen error (11001, 'getaddrinfo failed" in python?
also i use a socks
A:
So urlopen cannot find the URL you desire. What socks proxy are you using -- socksipy, for example? Maybe you haven't integrated it correctly in your use of (I imagine) urllib2.
This SO question shows and points to some approaches for using a socks proxy with Python (pycurl is the way I'd choose to do it, if it was up to me).
| What to do with “urlopen error” in python? | How do I rectify the error "urlopen error (11001, 'getaddrinfo failed" in python?
also i use a socks
| [
"So urlopen cannot find the URL you desire. What socks proxy are you using -- socksipy, for example? Maybe you haven't integrated it correctly in your use of (I imagine) urllib2.\nThis SO question shows and points to some approaches for using a socks proxy with Python (pycurl is the way I'd choose to do it, if it was up to me).\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0002845602_python.txt |
Q:
PyQt4: Why does Python crash on close when using QTreeWidgetItem?
I'm using Python 3.1.1 and PyQt4 (not sure how to get that version number?). Python is crashing whenever I exit my application. I've seen this before as a garbage collection issue, but this time I'm not sure how to correct the problem.
This code crashes:
import sys
from PyQt4 import QtGui
class MyWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.tree = QtGui.QTreeWidget(self)
self.setCentralWidget(self.tree)
QtGui.QTreeWidgetItem(self.tree) # This line is the problem
self.show()
app = QtGui.QApplication(sys.argv)
mw = MyWindow()
sys.exit(app.exec_())
If I remove the commented line, the code exits without a problem. If I remove the 'self.tree' parent from the initialization, the code exits without a problem. If I try to use self.tree.addTopLevelItem, the code crashes again.
What could be the problem?
A:
It does not crash with a recent SIP/PyQt version.
| PyQt4: Why does Python crash on close when using QTreeWidgetItem? | I'm using Python 3.1.1 and PyQt4 (not sure how to get that version number?). Python is crashing whenever I exit my application. I've seen this before as a garbage collection issue, but this time I'm not sure how to correct the problem.
This code crashes:
import sys
from PyQt4 import QtGui
class MyWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.tree = QtGui.QTreeWidget(self)
self.setCentralWidget(self.tree)
QtGui.QTreeWidgetItem(self.tree) # This line is the problem
self.show()
app = QtGui.QApplication(sys.argv)
mw = MyWindow()
sys.exit(app.exec_())
If I remove the commented line, the code exits without a problem. If I remove the 'self.tree' parent from the initialization, the code exits without a problem. If I try to use self.tree.addTopLevelItem, the code crashes again.
What could be the problem?
| [
"It does not crash with a recent SIP/PyQt version.\n"
] | [
1
] | [] | [] | [
"pyqt4",
"python",
"python_sip"
] | stackoverflow_0002803704_pyqt4_python_python_sip.txt |
Q:
How to add dll's using py2exe?
I use a c++ dll in python. That dll uses other dlls.
I want to know if it's possible to include all the dll's in my .exe using py2exe without calling them directlly. If so, how can I do it?
Thanks in advance :)
A:
You may need a data_files= referencing all of those DLLs, perhaps with a wildcard. See the docs for an example (about specifically the MS runtime DLL). Note, as the docs say a million times, that you need legal rights to redistribute DLLs and those need to be obtained from the DLL's authors/owners -- don't just assume it's legally OK to redistribute them!-)
| How to add dll's using py2exe? | I use a c++ dll in python. That dll uses other dlls.
I want to know if it's possible to include all the dll's in my .exe using py2exe without calling them directlly. If so, how can I do it?
Thanks in advance :)
| [
"You may need a data_files= referencing all of those DLLs, perhaps with a wildcard. See the docs for an example (about specifically the MS runtime DLL). Note, as the docs say a million times, that you need legal rights to redistribute DLLs and those need to be obtained from the DLL's authors/owners -- don't just assume it's legally OK to redistribute them!-)\n"
] | [
3
] | [] | [] | [
"py2exe",
"python"
] | stackoverflow_0002845386_py2exe_python.txt |
Q:
QFileDialog and german umlaute within a path
i am working on a project, which i am developing with Python and PyQT4. I have stumbled upon a somewhat odd behaviour of the QFileDialog, that is not occuring when running the project within in my IDE (Eclipse).
The problem is that QFileDialog in ExistingFiles-mode does fail to return the list of selected files, when one of the file paths is containing a german umlaut (ä,ü,ö, etc.)
The QFileDialog is not offering options or parameters to make it sensible regarding this scenario.
Does anyone have any ideas of how to tackle this issue?
edit: my deployment scenario in which the error occurs is looking like the following. i am building an executable with Py2Exe and then make it distributable with Inno Setup. don't know if this may have been giving birth to the problem but the more info the better i think.
edit2:
I don't have the exact code accessable until friday, but we're having an if-statement waiting for the dialog to compplete. like this:
fileDialog = QFileDialog(...)
if fileDialog.exec_():
# get the choosen files
fileNames = fileDialog.getSelectedFiles()
# test if if-statement is entered
print fileNames
# convert from QStringList to normal list of Strings
fileNames = list(map(lambda x: str(x), fileNames))
# to suffice as an example print each
for fileName in fileNames:
print fileName
The first print command does get executed the second doesn't. As if something in between is not willing to terminate and Python is handling the exception somehow quietly. The QFileDialog however is closing as supposed after choosing the files and clicking "Open" or double clicking a file.
A:
Try to use lambda x: x.toUtf8(), or toLocal8Bit() or set TextCodec to any codepage you want, it should help. These methods return properly encoded python strings. Avoid using str() on QString, it is unaware of charmap you want.
What is getSelectedFiles()? There is no such method in Qt 4.5 or higher in QFileDialog class. I assumed, that it was typo or some old Qt version, and changed it to selectedFiles() in my test code.
Why don't you use convenience methods of QFileDialog for file choosing:
getExistingDirectory()
getOpenFileName()
getOpenFileNames()
getSaveFileName()
?
A:
You should use unicode() (not str()) to convert QString into Python unicode strings.
| QFileDialog and german umlaute within a path | i am working on a project, which i am developing with Python and PyQT4. I have stumbled upon a somewhat odd behaviour of the QFileDialog, that is not occuring when running the project within in my IDE (Eclipse).
The problem is that QFileDialog in ExistingFiles-mode does fail to return the list of selected files, when one of the file paths is containing a german umlaut (ä,ü,ö, etc.)
The QFileDialog is not offering options or parameters to make it sensible regarding this scenario.
Does anyone have any ideas of how to tackle this issue?
edit: my deployment scenario in which the error occurs is looking like the following. i am building an executable with Py2Exe and then make it distributable with Inno Setup. don't know if this may have been giving birth to the problem but the more info the better i think.
edit2:
I don't have the exact code accessable until friday, but we're having an if-statement waiting for the dialog to compplete. like this:
fileDialog = QFileDialog(...)
if fileDialog.exec_():
# get the choosen files
fileNames = fileDialog.getSelectedFiles()
# test if if-statement is entered
print fileNames
# convert from QStringList to normal list of Strings
fileNames = list(map(lambda x: str(x), fileNames))
# to suffice as an example print each
for fileName in fileNames:
print fileName
The first print command does get executed the second doesn't. As if something in between is not willing to terminate and Python is handling the exception somehow quietly. The QFileDialog however is closing as supposed after choosing the files and clicking "Open" or double clicking a file.
| [
"\nTry to use lambda x: x.toUtf8(), or toLocal8Bit() or set TextCodec to any codepage you want, it should help. These methods return properly encoded python strings. Avoid using str() on QString, it is unaware of charmap you want.\nWhat is getSelectedFiles()? There is no such method in Qt 4.5 or higher in QFileDialog class. I assumed, that it was typo or some old Qt version, and changed it to selectedFiles() in my test code.\nWhy don't you use convenience methods of QFileDialog for file choosing:\ngetExistingDirectory()\ngetOpenFileName()\ngetOpenFileNames()\ngetSaveFileName()\n\n?\n",
"You should use unicode() (not str()) to convert QString into Python unicode strings.\n"
] | [
0,
0
] | [] | [] | [
"diacritics",
"path",
"pyqt",
"pyqt4",
"python"
] | stackoverflow_0002585694_diacritics_path_pyqt_pyqt4_python.txt |
Q:
Python: How do I create a reference to a reference?
I am traditionally a Perl and C++ programmer, so apologies in advance if I am misunderstanding something trivial about Python!
I would like to create a reference to a reference.
Huh? Ok. All objects in Python are actually references to the real object.
So, how do I create a reference to this reference?
Why do I need/want this? I am overriding sys.stdout and sys.stderr to create a logging library. I would like a (second-level) reference to sys.stdout.
If I could create a reference to a reference, then I could create a generic logger class where the init function receives a reference to a file handle reference that will be overrided, e.g., sys.stdout or sys.stderr. Currently, I must hard-code both values.
Cheers,
Kevin
A:
Easier done than said:
ostream = sys.stdout
print >> ostream, 'hi mom!'
ostream = sys.stderr
print >> ostream, 'hi mom!'
ostream = open('mylog.txt', 'a')
...
And look at the standard logging module when you have some more Python under your belt.
This answer was based on the presumption, from the level of the question, of what was really needed. The concept of a reference to a reference is not needed in Python, you can multiplex through a list or a dict if you want:
outputs = [sys.stderr, my_open_file_object_which_is_really_a_reference]
print >> outputs[0], 'hi dad!'
outputs = {'terminal': sys.stderr, 'logfile': file_object}
print >> outputs['logfile'], 'goodbye world!'
and so on.
A:
You can't create references to references in python. You can however override the stderr and stdout files with custom classes with write etc methods to allow your own logging systems:
import sys
class MyLogger:
def __init__(self, f):
self.f = f
def __getattr__(self, name):
# forward e.g. flush() calls to the original file
return getattr(self.f, name)
def write(self, data):
# log the data here!
# ...
# And write to the original file
self.f.write(data)
sys.stdout = MyLogger(sys.stdout)
sys.stderr = MyLogger(sys.stderr)
A:
As the other answers say, there is no true "references of references" in python, but there are ways of getting nearly the same effect:
>>> reference1 = "Some Data"
>>> reference2 = (reference1,)
>>> def f(data):
print data
>>> f(reference2)
('Some Data',)
>>> f(*reference2)
Some Data
A:
This can't be done. Pass the desired attribute as a string and use getattr() and setattr().
A:
Firstly, there is already a logging module, so you probably should just use that. Secondly, while there is no such thing as a reference to a reference, you can achieve that indirection via a wrapper or function. For example, if you were to create a getter and setter function for assigning the object, like:
class StdOutWrapper(object):
def __init__(self):
self.original = sys.stdout
@property
def value(self):
return sys.stdout
@value.setter
def value(self,val):
sys.stdout = val
You could then pass an instance of this object to your logger to assign/dereference sys.stdout.
| Python: How do I create a reference to a reference? | I am traditionally a Perl and C++ programmer, so apologies in advance if I am misunderstanding something trivial about Python!
I would like to create a reference to a reference.
Huh? Ok. All objects in Python are actually references to the real object.
So, how do I create a reference to this reference?
Why do I need/want this? I am overriding sys.stdout and sys.stderr to create a logging library. I would like a (second-level) reference to sys.stdout.
If I could create a reference to a reference, then I could create a generic logger class where the init function receives a reference to a file handle reference that will be overrided, e.g., sys.stdout or sys.stderr. Currently, I must hard-code both values.
Cheers,
Kevin
| [
"Easier done than said:\nostream = sys.stdout\nprint >> ostream, 'hi mom!'\nostream = sys.stderr\nprint >> ostream, 'hi mom!'\nostream = open('mylog.txt', 'a')\n...\n\nAnd look at the standard logging module when you have some more Python under your belt.\nThis answer was based on the presumption, from the level of the question, of what was really needed. The concept of a reference to a reference is not needed in Python, you can multiplex through a list or a dict if you want:\noutputs = [sys.stderr, my_open_file_object_which_is_really_a_reference]\nprint >> outputs[0], 'hi dad!'\noutputs = {'terminal': sys.stderr, 'logfile': file_object}\nprint >> outputs['logfile'], 'goodbye world!'\n\nand so on.\n",
"You can't create references to references in python. You can however override the stderr and stdout files with custom classes with write etc methods to allow your own logging systems:\nimport sys\n\nclass MyLogger:\n def __init__(self, f):\n self.f = f\n\n def __getattr__(self, name):\n # forward e.g. flush() calls to the original file\n return getattr(self.f, name)\n\n def write(self, data):\n # log the data here!\n # ...\n\n # And write to the original file\n self.f.write(data)\n\nsys.stdout = MyLogger(sys.stdout)\nsys.stderr = MyLogger(sys.stderr)\n\n",
"As the other answers say, there is no true \"references of references\" in python, but there are ways of getting nearly the same effect:\n>>> reference1 = \"Some Data\"\n>>> reference2 = (reference1,)\n>>> def f(data):\n print data\n\n>>> f(reference2)\n('Some Data',)\n>>> f(*reference2)\nSome Data\n\n",
"This can't be done. Pass the desired attribute as a string and use getattr() and setattr().\n",
"Firstly, there is already a logging module, so you probably should just use that. Secondly, while there is no such thing as a reference to a reference, you can achieve that indirection via a wrapper or function. For example, if you were to create a getter and setter function for assigning the object, like:\n class StdOutWrapper(object):\n def __init__(self):\n self.original = sys.stdout\n\n @property\n def value(self):\n return sys.stdout\n\n @value.setter\n def value(self,val):\n sys.stdout = val\n\nYou could then pass an instance of this object to your logger to assign/dereference sys.stdout.\n"
] | [
6,
1,
1,
0,
0
] | [] | [] | [
"python",
"reference",
"stdout"
] | stackoverflow_0002846308_python_reference_stdout.txt |
Q:
Python: Repeat elements in a list comprehension?
I have the following list comprehension which returns a list of coordinate objects for each location.
coordinate_list = [Coordinates(location.latitude, location.longitude)
for location in locations]
This works.
Now suppose the location object has a number_of_times member. I want a list comprehension to generate n Coordinate objects where n is the number_of_times for the particular location. So if a location has number_of_times = 5 then the coordinates for that location will be repeated 5 times in the list. (Maybe this is a case for a for-loop but I'm curious if it can be done via list comprehensions)
A:
coordinate_list = [x for location in locations
for x in [Coordinates(location.latitude,
location.longitude)
] * location.number_of_times]
Edit: the OP suggests a loop may be clearer, which, given the length of the identifiers, is definitely a possibility. The equivalent code would then be something like:
coordinate_list = [ ]
for location in locations:
coord = Coordinates(location.latitude, location.longitude)
coordinate_list.extend([coord] * location.number_of_times)
The loop does look fine, partly because the extend method of lists works nicely here, and partly because you get to give a name to the Coordinate instance you're extending with.
A:
Try
coordinate_list = [Coordinates(location.latitude, location.longitude)
for location in locations
for i in range(location.number_of_times)]
A:
You can multiply a sequence by the number_of_times value. So [1,2]*3 will equal [1, 2, 1, 2, 1, 2] . If you get your coordinates in a list then multiply the list by the number of repeats, your result should be [coord, coord, coord].
def coordsFor(location):
return coord = [Coordinates(location.latitude, location.longitude) ]*location.number_of_times
Concatenate the coordsFor of each element in the list.
reduce(operator.add, map(coordsFor, locations), [])
| Python: Repeat elements in a list comprehension? | I have the following list comprehension which returns a list of coordinate objects for each location.
coordinate_list = [Coordinates(location.latitude, location.longitude)
for location in locations]
This works.
Now suppose the location object has a number_of_times member. I want a list comprehension to generate n Coordinate objects where n is the number_of_times for the particular location. So if a location has number_of_times = 5 then the coordinates for that location will be repeated 5 times in the list. (Maybe this is a case for a for-loop but I'm curious if it can be done via list comprehensions)
| [
"coordinate_list = [x for location in locations\n for x in [Coordinates(location.latitude,\n location.longitude)\n ] * location.number_of_times]\n\nEdit: the OP suggests a loop may be clearer, which, given the length of the identifiers, is definitely a possibility. The equivalent code would then be something like:\ncoordinate_list = [ ]\nfor location in locations:\n coord = Coordinates(location.latitude, location.longitude)\n coordinate_list.extend([coord] * location.number_of_times)\n\nThe loop does look fine, partly because the extend method of lists works nicely here, and partly because you get to give a name to the Coordinate instance you're extending with.\n",
"Try\ncoordinate_list = [Coordinates(location.latitude, location.longitude)\n for location in locations \n for i in range(location.number_of_times)]\n\n",
"You can multiply a sequence by the number_of_times value. So [1,2]*3 will equal [1, 2, 1, 2, 1, 2] . If you get your coordinates in a list then multiply the list by the number of repeats, your result should be [coord, coord, coord].\ndef coordsFor(location):\n return coord = [Coordinates(location.latitude, location.longitude) ]*location.number_of_times\n\nConcatenate the coordsFor of each element in the list.\nreduce(operator.add, map(coordsFor, locations), [])\n\n"
] | [
7,
6,
0
] | [] | [] | [
"list_comprehension",
"python"
] | stackoverflow_0002846536_list_comprehension_python.txt |
Q:
Passing an argument to create a window using wxpython?
I am trying to learn how to make a GUI in Python. Following an online tutorial, I found that the following code 'works' in creating an empty window:
import wx
from sys import argv
class bucky(wx.Frame):
def __init__(self, parent, id):
wx.Frame.__init__(self, parent, id, 'Frame aka window', size=(300, 200))
if __name__=='__main__':
app=wx.PySimpleApp()
frame=bucky(parent=None,id=-1)
frame.Show()
app.MainLoop()
That gives me a window, which is great. However, what if I want to get an argument passed onto the program to determine the window size? I thought something like this ought to do the trick:
import wx
from sys import argv
script, x, y = argv
class mywindow(wx.Frame):
def __init__(self, parent, id):
wx.Frame.__init__(self, parent, id, 'Frame aka window', size=(x, y))
if __name__=='__main__':
app=wx.PySimpleApp()
frame=mywindow(parent=None,id=-1)
frame.Show()
app.MainLoop()
But, alas, that does not work! I keep getting the following error:
Traceback <most recent call last):
File "C:\DOCUME~1\OWNER\DESKTOP\pw2.py", line 12, in <module>
frame=mywindow(parent=None, id=-1)
File "C:\DOCUME~1\OWNER\DESKTOP\pw2.py", line 8, in __init__
wx.Frame.__init))(self.parent, id, 'Frame aka window', size=(x, y))
File "C:\Python26\lib\site-packagaes\wx-2.8-msw-unicode\wx\_widows.py", line 5
05, in __init__
_windows_.Frame_swiginit(self, _windows_.new_Frame(*args, **kwargs))
TypeError: Expected a 2-tuple of integers or a wxSize object.
How do I create a window depending on user input as I've tried to above?
A:
The elements of sys.argv are strings; you need to convert them to integers before using them. Consider passing them to the constructor though, instead of relying on global state.
| Passing an argument to create a window using wxpython? | I am trying to learn how to make a GUI in Python. Following an online tutorial, I found that the following code 'works' in creating an empty window:
import wx
from sys import argv
class bucky(wx.Frame):
def __init__(self, parent, id):
wx.Frame.__init__(self, parent, id, 'Frame aka window', size=(300, 200))
if __name__=='__main__':
app=wx.PySimpleApp()
frame=bucky(parent=None,id=-1)
frame.Show()
app.MainLoop()
That gives me a window, which is great. However, what if I want to get an argument passed onto the program to determine the window size? I thought something like this ought to do the trick:
import wx
from sys import argv
script, x, y = argv
class mywindow(wx.Frame):
def __init__(self, parent, id):
wx.Frame.__init__(self, parent, id, 'Frame aka window', size=(x, y))
if __name__=='__main__':
app=wx.PySimpleApp()
frame=mywindow(parent=None,id=-1)
frame.Show()
app.MainLoop()
But, alas, that does not work! I keep getting the following error:
Traceback <most recent call last):
File "C:\DOCUME~1\OWNER\DESKTOP\pw2.py", line 12, in <module>
frame=mywindow(parent=None, id=-1)
File "C:\DOCUME~1\OWNER\DESKTOP\pw2.py", line 8, in __init__
wx.Frame.__init))(self.parent, id, 'Frame aka window', size=(x, y))
File "C:\Python26\lib\site-packagaes\wx-2.8-msw-unicode\wx\_widows.py", line 5
05, in __init__
_windows_.Frame_swiginit(self, _windows_.new_Frame(*args, **kwargs))
TypeError: Expected a 2-tuple of integers or a wxSize object.
How do I create a window depending on user input as I've tried to above?
| [
"The elements of sys.argv are strings; you need to convert them to integers before using them. Consider passing them to the constructor though, instead of relying on global state.\n"
] | [
1
] | [] | [] | [
"python",
"winapi",
"wxpython",
"wxwidgets"
] | stackoverflow_0002846523_python_winapi_wxpython_wxwidgets.txt |
Q:
Java or Python distributed compute job (on a student budget)?
I have a large dataset (c. 40G) that I want to use for some NLP (largely embarrassingly parallel) over a couple of computers in the lab, to which i do not have root access, and only 1G of user space.
I experimented with hadoop, but of course this was dead in the water-- the data is stored on an external usb hard drive, and i cant load it on to the dfs because of the 1G user space cap.
I have been looking into a couple of python based options (as I'd rather use NLTK instead of Java's lingpipe if I can help it), and it seems distributed compute options look like:
Ipython
DISCO
After my hadoop experience, i am trying to make sure i try and make an informed choice -- any help on what might be more appropriate would be greatly appreciated.
Amazon's EC2 etc not really an option, as i have next to no budget.
A:
Speak with the IT dept at your school (especially if you are in college), if it is for an assignment or research I bet they would be more than happy to give you more disk space.
A:
no actual answers; i'd have put this as a comment but on this site you're forced to only answer if you're still a noob
if it's genuinely as parallel as that, and it's only a couple of computers, could you not split the dataset up manually ahead of time?
have you confirmed that there isn't going to be a firewall or similar stopping you using something like that anyway?
you may only have 1GB of user space, but, if linux, what about /tmp ? (if windows, what about %temp% ? )
A:
Definitely speak with the IT department at your school. It's not a good idea to utilize computer resources that don't belong to you.
I found JPPF, which enables applications with large processing power requirements to be run on any number of computers. I'm not sure if you need to install software on the client machines, but certain ports need to be open on the client machines.
A:
If more resources in your computing department are a no go, you're going to have to consider breaking down your data set into manageable chunks before you do any work on it, ad reduce the results down into a meaningful set.
More resources from IT would be the way to go.
Good luck !
Ben
| Java or Python distributed compute job (on a student budget)? | I have a large dataset (c. 40G) that I want to use for some NLP (largely embarrassingly parallel) over a couple of computers in the lab, to which i do not have root access, and only 1G of user space.
I experimented with hadoop, but of course this was dead in the water-- the data is stored on an external usb hard drive, and i cant load it on to the dfs because of the 1G user space cap.
I have been looking into a couple of python based options (as I'd rather use NLTK instead of Java's lingpipe if I can help it), and it seems distributed compute options look like:
Ipython
DISCO
After my hadoop experience, i am trying to make sure i try and make an informed choice -- any help on what might be more appropriate would be greatly appreciated.
Amazon's EC2 etc not really an option, as i have next to no budget.
| [
"Speak with the IT dept at your school (especially if you are in college), if it is for an assignment or research I bet they would be more than happy to give you more disk space.\n",
"no actual answers; i'd have put this as a comment but on this site you're forced to only answer if you're still a noob\nif it's genuinely as parallel as that, and it's only a couple of computers, could you not split the dataset up manually ahead of time?\nhave you confirmed that there isn't going to be a firewall or similar stopping you using something like that anyway?\nyou may only have 1GB of user space, but, if linux, what about /tmp ? (if windows, what about %temp% ? )\n",
"Definitely speak with the IT department at your school. It's not a good idea to utilize computer resources that don't belong to you.\nI found JPPF, which enables applications with large processing power requirements to be run on any number of computers. I'm not sure if you need to install software on the client machines, but certain ports need to be open on the client machines.\n",
"If more resources in your computing department are a no go, you're going to have to consider breaking down your data set into manageable chunks before you do any work on it, ad reduce the results down into a meaningful set.\nMore resources from IT would be the way to go.\nGood luck !\nBen\n"
] | [
3,
1,
1,
0
] | [] | [] | [
"hadoop",
"java",
"nlp",
"nltk",
"python"
] | stackoverflow_0002844105_hadoop_java_nlp_nltk_python.txt |
Q:
Summary count for Python logging
At the end of my Python program, I'd like to be able to get a summary of the number of items logged through the standard logging module. I'd specifically like to be able to get a count for each specified name (and possibly its children). E.g. if I have:
input_logger = getLogger('input')
input_logger.debug("got input1")
input_logger.debug("got input2")
input_logger.debug("got input3")
network_input_logger = getLogger('input.network')
network_input_logger.debug("got network input1")
network_input_logger.debug("got network input2")
getLogger('output')
output_logger.debug("sent output1")
Then at the end I'd like to get a summary such as:
input: 5
input.network: 2
output: 1
I'm thinking, by calling a getcount() method for a logger or a handler.
What would be a good way to achieve this? I imagine it would involve a sub-class of one of the classes in the logging module, but I'm not sure what would be the best way to go.
A:
Using a decorator could be pretty elegant, I haven't tested this but something like this could work:
class myDecorator(object):
def __init__(self, inner):
self.inner = inner
self.log = {}
def __getattr__(self,name):
self.log[name] = self.log.get(name,0)+1
return getattr(self.inner,name)
def __setattr__(self,name,value):
setattr(self.inner,name,value)
I am realizing that you didn't want to log the number of calls to each method but calls to each different logger. All the same I think a decorator could be pretty elegant.
I don't think I've had enough sleep, the idea would be to wrap calls to your logger, I am mixing the use of a decorator with the decorator pattern. (Actually a mix of the pattern and the syntax would be a great answer)
Here is a more complete solution. I'm sorry I realized I was the someone that was wrong on the internet.
class LoggerLogger(object):
def __init__(self,inner,name):
self.inner = inner
self.calls = 0
def __call__(self,*args,**kwargs):
self.calls += 1
return self.inner(*args,**kwargs)
def loggerDecorator(func):
def inner(name):
logger = func(name)
logger.debug = LoggerLogger(logger.debug,name)
return inner
getLogger = loggerDecorator(getLogger)
A:
I think the decorator pattern might be the cleanest method to implement this.
You will pass an instance of Logger into the LoggerDecorator which will have the same interface as the logger. When one of the methods are called then increment a member variable as appropriate. Then implementing the getCount() method will be trivial.
Here is a reference on implementing decorator in Python:
http://wiki.python.org/moin/DecoratorPattern
| Summary count for Python logging | At the end of my Python program, I'd like to be able to get a summary of the number of items logged through the standard logging module. I'd specifically like to be able to get a count for each specified name (and possibly its children). E.g. if I have:
input_logger = getLogger('input')
input_logger.debug("got input1")
input_logger.debug("got input2")
input_logger.debug("got input3")
network_input_logger = getLogger('input.network')
network_input_logger.debug("got network input1")
network_input_logger.debug("got network input2")
getLogger('output')
output_logger.debug("sent output1")
Then at the end I'd like to get a summary such as:
input: 5
input.network: 2
output: 1
I'm thinking, by calling a getcount() method for a logger or a handler.
What would be a good way to achieve this? I imagine it would involve a sub-class of one of the classes in the logging module, but I'm not sure what would be the best way to go.
| [
"Using a decorator could be pretty elegant, I haven't tested this but something like this could work:\nclass myDecorator(object):\n def __init__(self, inner):\n self.inner = inner\n self.log = {}\n\n def __getattr__(self,name):\n self.log[name] = self.log.get(name,0)+1\n return getattr(self.inner,name)\n\n def __setattr__(self,name,value):\n setattr(self.inner,name,value)\n\nI am realizing that you didn't want to log the number of calls to each method but calls to each different logger. All the same I think a decorator could be pretty elegant. \nI don't think I've had enough sleep, the idea would be to wrap calls to your logger, I am mixing the use of a decorator with the decorator pattern. (Actually a mix of the pattern and the syntax would be a great answer)\nHere is a more complete solution. I'm sorry I realized I was the someone that was wrong on the internet.\nclass LoggerLogger(object):\n def __init__(self,inner,name):\n self.inner = inner\n self.calls = 0\n def __call__(self,*args,**kwargs):\n self.calls += 1\n return self.inner(*args,**kwargs)\n\n\ndef loggerDecorator(func):\n def inner(name):\n logger = func(name)\n logger.debug = LoggerLogger(logger.debug,name)\n return inner\n\ngetLogger = loggerDecorator(getLogger)\n\n",
"I think the decorator pattern might be the cleanest method to implement this. \nYou will pass an instance of Logger into the LoggerDecorator which will have the same interface as the logger. When one of the methods are called then increment a member variable as appropriate. Then implementing the getCount() method will be trivial.\nHere is a reference on implementing decorator in Python:\nhttp://wiki.python.org/moin/DecoratorPattern\n"
] | [
3,
2
] | [] | [] | [
"logging",
"python"
] | stackoverflow_0002847282_logging_python.txt |
Q:
Dynamically setting the queryset of a ModelMultipleChoiceField to a custom recordset
I've seen all the howtos about how you can set a ModelMultipleChoiceField to use a custom queryset and I've tried them and they work. However, they all use the same paradigm: the queryset is just a filtered list of the same objects.
In my case, I'm trying to get the admin to draw a multiselect form that instead of using usernames as the text portion of the , I'd like to use the name field from my account class.
Here's a breakdown of what I've got:
# models.py
class Account(models.Model):
name = models.CharField(max_length=128,help_text="A display name that people understand")
user = models.ForeignKey(User, unique=True) # Tied to the User class in settings.py
class Organisation(models.Model):
administrators = models.ManyToManyField(User)
# admin.py
from django.forms import ModelMultipleChoiceField
from django.contrib.auth.models import User
class OrganisationAdminForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
from ethico.accounts.models import Account
self.base_fields["administrators"] = ModelMultipleChoiceField(
queryset=User.objects.all(),
required=False
)
super(OrganisationAdminForm, self).__init__(*args, **kwargs)
class Meta:
model = Organisation
This works, however, I want queryset above to draw a selectbox with the Account.name property and the User.id property. This didn't work:
queryset=Account.objects.all().order_by("name").values_list("user","name")
It failed with this error:
'tuple' object has no attribute 'pk'
I figured that this would be easy, but it's turned into hours of dead-ends. Anyone care to shed some light?
A:
You can use a custom widget, override its render method. Here's what I had done for a text field :
class UserToAccount(forms.widgets.TextInput):
def render(self, name, value, attrs=None):
if isinstance(value, User) :
value = Account.objects.get(user=value).name
return super (UserToAccount, self).render(name, value, attrs=None)
Then of course, use the widget parameter of your administrator field, in order to use your custom widget.
I don't know if it can be adapted for a select, but you can try out.
A:
The queryset needs to be a QuerySet, when you do values_list you get a list so that won't work.
If you want to change the default display of models, just override __unicode__. See http://docs.djangoproject.com/en/dev/ref/models/instances/#unicode
For example:
def __unicode__(self):
return u"%s for %s" % (self.name, self.user)
Django will use __unicode__ whenever you asks it to print a model. For testing you can just load up a model in the shell and do print my_instance.
A:
Taking a queue from sebpiq, I managed to figure it out:
class OrganisationAdminForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
from django.forms import MultipleChoiceField
from ethico.accounts.models import Account
self.base_fields["administrators"] = MultipleChoiceField(
choices=tuple([(a.user_id, a.name) for a in Account.objects.all().order_by("name")]),
widget=forms.widgets.SelectMultiple,
required=False
)
super(OrganisationAdminForm, self).__init__(*args, **kwargs)
class Meta:
model = Organisation
class OrganisationAdmin(admin.ModelAdmin):
form = OrganisationAdminForm
admin.site.register(Organisation, OrganisationAdmin)
The key was abandoning the queryset altogether. Once I went with a fixed choices= parameter, everything just worked. Thanks everyone!
| Dynamically setting the queryset of a ModelMultipleChoiceField to a custom recordset | I've seen all the howtos about how you can set a ModelMultipleChoiceField to use a custom queryset and I've tried them and they work. However, they all use the same paradigm: the queryset is just a filtered list of the same objects.
In my case, I'm trying to get the admin to draw a multiselect form that instead of using usernames as the text portion of the , I'd like to use the name field from my account class.
Here's a breakdown of what I've got:
# models.py
class Account(models.Model):
name = models.CharField(max_length=128,help_text="A display name that people understand")
user = models.ForeignKey(User, unique=True) # Tied to the User class in settings.py
class Organisation(models.Model):
administrators = models.ManyToManyField(User)
# admin.py
from django.forms import ModelMultipleChoiceField
from django.contrib.auth.models import User
class OrganisationAdminForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
from ethico.accounts.models import Account
self.base_fields["administrators"] = ModelMultipleChoiceField(
queryset=User.objects.all(),
required=False
)
super(OrganisationAdminForm, self).__init__(*args, **kwargs)
class Meta:
model = Organisation
This works, however, I want queryset above to draw a selectbox with the Account.name property and the User.id property. This didn't work:
queryset=Account.objects.all().order_by("name").values_list("user","name")
It failed with this error:
'tuple' object has no attribute 'pk'
I figured that this would be easy, but it's turned into hours of dead-ends. Anyone care to shed some light?
| [
"You can use a custom widget, override its render method. Here's what I had done for a text field :\nclass UserToAccount(forms.widgets.TextInput):\n def render(self, name, value, attrs=None):\n if isinstance(value, User) :\n value = Account.objects.get(user=value).name\n return super (UserToAccount, self).render(name, value, attrs=None) \n\nThen of course, use the widget parameter of your administrator field, in order to use your custom widget.\nI don't know if it can be adapted for a select, but you can try out.\n",
"The queryset needs to be a QuerySet, when you do values_list you get a list so that won't work.\nIf you want to change the default display of models, just override __unicode__. See http://docs.djangoproject.com/en/dev/ref/models/instances/#unicode\nFor example:\ndef __unicode__(self):\n return u\"%s for %s\" % (self.name, self.user)\n\nDjango will use __unicode__ whenever you asks it to print a model. For testing you can just load up a model in the shell and do print my_instance.\n",
"Taking a queue from sebpiq, I managed to figure it out:\nclass OrganisationAdminForm(forms.ModelForm):\n\n def __init__(self, *args, **kwargs):\n\n from django.forms import MultipleChoiceField\n from ethico.accounts.models import Account\n\n self.base_fields[\"administrators\"] = MultipleChoiceField(\n choices=tuple([(a.user_id, a.name) for a in Account.objects.all().order_by(\"name\")]),\n widget=forms.widgets.SelectMultiple,\n required=False\n )\n\n super(OrganisationAdminForm, self).__init__(*args, **kwargs)\n\n class Meta:\n model = Organisation\n\n\nclass OrganisationAdmin(admin.ModelAdmin):\n form = OrganisationAdminForm\n\n\nadmin.site.register(Organisation, OrganisationAdmin)\n\nThe key was abandoning the queryset altogether. Once I went with a fixed choices= parameter, everything just worked. Thanks everyone!\n"
] | [
1,
0,
0
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0002846879_django_django_admin_python.txt |
Q:
what's faster: merging lists or dicts in python?
I'm working with an app that is cpu-bound more than memory bound, and I'm trying to merge two things whether they be lists or dicts.
Now the thing is i can choose either one, but I'm wondering if merging dicts would be faster since it's all in memory? Or is it always going to be O(n), n being the size of the smaller list.
The reason I asked about dicts rather than sets is because I can't convert a set to json, because that results in {key1, key2, key3} and json needs a key/value pair, so I am using a dict so json dumps returns {key1:1, key2:1, key3:1}. Yes this is wasteful, but if it proves to be faster then I'm okay with it.
Edit: My question is the difference in using dict and list for merging, I originally and mistakenly had dict and set listed.
dict1 = {"the" : {"1":1, "3":1, "10":1}
dict2 = {"the" : {"11":1, "13":1}}
after merging
dict3 = {"the" : {"1":1, "3":1, "10":1, "11":1, "13":1}
A:
If you are looking for duplicate elimination, sets are very, very fast.
>>> x = set(range(1000000,2000000))
>>> y = set(range(1900000,2900000))
the following happened in ~0.020s
>>> z = set.intersection(x,y)
>>> len(z)
100000
Regarding output to json, just convert to a list...
json_encode(list(z))
A:
You can use the timeit module to measure the speed of your code, but I'm going to guess that they'll be practically the same (since a set is probably implemented using a dictionary).
A:
Dicts and sets will be just as fast (and O(N), as you surmise). Lists, which you only mention in your Q's title and never in its text, might be slower, depending what you mean by "merging".
Given the json downstream requirements, dicts with values all set to 1 will be fastest overall -- not for the merging, but for the JSON serialization.
A:
I'd be more worried about correctness. If you have duplicate keys, the list will duplicate your keys and values. A dictionary will only keep one of the values. Also, a list will keep the order consistent. Which do you prefer?
My gut reaction is that if you are searching for keys the dictionary will be faster. But how will you deal with duplication?
A:
as Michael said, it's probably easiest to use the timeit module and see for yourself. It's very easy to do:
import timeit
def test():
# do your thing here
# including conversion to json
pass
result = timeit.repeat(test, repeat=10, number=10000)
print '{0:.2}s per 10000 test runs.'.format(min(result))
Hope that helps.
| what's faster: merging lists or dicts in python? | I'm working with an app that is cpu-bound more than memory bound, and I'm trying to merge two things whether they be lists or dicts.
Now the thing is i can choose either one, but I'm wondering if merging dicts would be faster since it's all in memory? Or is it always going to be O(n), n being the size of the smaller list.
The reason I asked about dicts rather than sets is because I can't convert a set to json, because that results in {key1, key2, key3} and json needs a key/value pair, so I am using a dict so json dumps returns {key1:1, key2:1, key3:1}. Yes this is wasteful, but if it proves to be faster then I'm okay with it.
Edit: My question is the difference in using dict and list for merging, I originally and mistakenly had dict and set listed.
dict1 = {"the" : {"1":1, "3":1, "10":1}
dict2 = {"the" : {"11":1, "13":1}}
after merging
dict3 = {"the" : {"1":1, "3":1, "10":1, "11":1, "13":1}
| [
"If you are looking for duplicate elimination, sets are very, very fast.\n>>> x = set(range(1000000,2000000))\n>>> y = set(range(1900000,2900000))\n\nthe following happened in ~0.020s \n>>> z = set.intersection(x,y)\n>>> len(z)\n100000\n\nRegarding output to json, just convert to a list...\njson_encode(list(z))\n\n",
"You can use the timeit module to measure the speed of your code, but I'm going to guess that they'll be practically the same (since a set is probably implemented using a dictionary). \n",
"Dicts and sets will be just as fast (and O(N), as you surmise). Lists, which you only mention in your Q's title and never in its text, might be slower, depending what you mean by \"merging\".\nGiven the json downstream requirements, dicts with values all set to 1 will be fastest overall -- not for the merging, but for the JSON serialization.\n",
"I'd be more worried about correctness. If you have duplicate keys, the list will duplicate your keys and values. A dictionary will only keep one of the values. Also, a list will keep the order consistent. Which do you prefer?\nMy gut reaction is that if you are searching for keys the dictionary will be faster. But how will you deal with duplication? \n",
"as Michael said, it's probably easiest to use the timeit module and see for yourself. It's very easy to do:\nimport timeit\ndef test():\n # do your thing here\n # including conversion to json\n pass\n\nresult = timeit.repeat(test, repeat=10, number=10000)\nprint '{0:.2}s per 10000 test runs.'.format(min(result))\n\nHope that helps.\n"
] | [
2,
1,
1,
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0002846431_list_python.txt |
Q:
"With" statement in Python with multiple files to handle
How do i use the with statement in this case?
f_spam = open(spam,'r')
f_bar = open(eggs,'r')
...
do something with these files
...
f_spam.close()
f_bar.close()
Files number could be greater than two.
A:
You can also do:
from contextlib import nested
with nested(open(spam), open(eggs)) as (f_spam, f_eggs):
# do something
In Python 2.7 and 3.1+ you don't need the nested function because with supports the following syntax:
with open(spam) as f_spam, open(eggs) as f_eggs:
# do something
A:
with open(spam,'r') as f_spam:
with open(eggs,'r') as f_bar:
#do stuff with each
| "With" statement in Python with multiple files to handle | How do i use the with statement in this case?
f_spam = open(spam,'r')
f_bar = open(eggs,'r')
...
do something with these files
...
f_spam.close()
f_bar.close()
Files number could be greater than two.
| [
"You can also do:\nfrom contextlib import nested\n\nwith nested(open(spam), open(eggs)) as (f_spam, f_eggs):\n # do something\n\nIn Python 2.7 and 3.1+ you don't need the nested function because with supports the following syntax:\nwith open(spam) as f_spam, open(eggs) as f_eggs:\n # do something\n\n",
"with open(spam,'r') as f_spam:\n with open(eggs,'r') as f_bar:\n #do stuff with each\n\n"
] | [
18,
3
] | [] | [] | [
"python"
] | stackoverflow_0002847939_python.txt |
Q:
Catch clearly defined exception from sub.submodule in python
I have 3 files. xxx which imports xxx2 and xxx2 imports xxx3 which one raises OppsError exception.
xxx3.py:
class OppsError(Exception):pass
def go():
raise OppsError()
xxx2.py:
import xxx3
xxx3.go()
xxx.py:
try:
import xxx2
except xxx3.OppsError:
print 'ops'
When i run xxx.py i get error NameError: name 'xxx3' is not defined. Is importing xxx3 inside xxx only way to catch OppsError?
A:
As far as I know, it is (unless you are willing to replace OppsError with a built-in exception that is already known to xxx or to catch a more general exception instead of OppsError from which OppsError is derived).
| Catch clearly defined exception from sub.submodule in python | I have 3 files. xxx which imports xxx2 and xxx2 imports xxx3 which one raises OppsError exception.
xxx3.py:
class OppsError(Exception):pass
def go():
raise OppsError()
xxx2.py:
import xxx3
xxx3.go()
xxx.py:
try:
import xxx2
except xxx3.OppsError:
print 'ops'
When i run xxx.py i get error NameError: name 'xxx3' is not defined. Is importing xxx3 inside xxx only way to catch OppsError?
| [
"As far as I know, it is (unless you are willing to replace OppsError with a built-in exception that is already known to xxx or to catch a more general exception instead of OppsError from which OppsError is derived).\n"
] | [
1
] | [] | [] | [
"exception",
"python"
] | stackoverflow_0002848049_exception_python.txt |
Q:
In Python 2.x, using backticks to get decimal string from int object is Horrible?
In Python 2.x, using backticks to get decimal string from int object is Horrible?
Because backticks are repr(), not str()? I have noticed that when I answering this question.
In Python source, they have same function in Python source, intobject.c
(reprfunc)int_to_decimal_string, /* tp_repr */
....
(reprfunc)int_to_decimal_string, /* tp_str */
What do you think?
A:
Well, I wouldn't say it's "horrible", but I feel it isn't right for at least four reasons:
str(my_number) states your intent more clearly than surrounding my_number by backticks. (See "Readability counts" in the Zen of Python).
The implementation of Python in C is just one possible implementation; there is Jython, IronPython, PyPy and so on, and unless there is an explicit statement in the Python specification somewhere that repr() and str() is the same for integer objects, I wouldn't to rely on that behaviour.
Backticks are gone in Python 3.x.
If your number happens to be so large that it cannot be represented by an int, Python promotes it automatically to a long integer, and for that, repr() and str() differs.
See this example:
>>> x = 1234567890
>>> y = x ** 3
>>> `y`
'1881676371789154860897069000L'
>>> str(y)
'1881676371789154860897069000'
A:
Yes. Using backticks for anything is horrible.
You've got str(i), you've got '%d' % i, you've got .format(i); if you want the repr then say so directly with repr() or %r or whatever.
There was never a good reason to use backticks, they just made code less readable and much harder to parse. They are gone in Python 3.
A:
2.X: Using backticks for anything is horrible. Use repr() or str() as required.
3.X: Backticks have vanished! Three cheers!!
| In Python 2.x, using backticks to get decimal string from int object is Horrible? | In Python 2.x, using backticks to get decimal string from int object is Horrible?
Because backticks are repr(), not str()? I have noticed that when I answering this question.
In Python source, they have same function in Python source, intobject.c
(reprfunc)int_to_decimal_string, /* tp_repr */
....
(reprfunc)int_to_decimal_string, /* tp_str */
What do you think?
| [
"Well, I wouldn't say it's \"horrible\", but I feel it isn't right for at least four reasons:\n\nstr(my_number) states your intent more clearly than surrounding my_number by backticks. (See \"Readability counts\" in the Zen of Python).\nThe implementation of Python in C is just one possible implementation; there is Jython, IronPython, PyPy and so on, and unless there is an explicit statement in the Python specification somewhere that repr() and str() is the same for integer objects, I wouldn't to rely on that behaviour.\nBackticks are gone in Python 3.x.\nIf your number happens to be so large that it cannot be represented by an int, Python promotes it automatically to a long integer, and for that, repr() and str() differs.\n\nSee this example:\n>>> x = 1234567890\n>>> y = x ** 3\n>>> `y`\n'1881676371789154860897069000L'\n>>> str(y)\n'1881676371789154860897069000'\n\n",
"Yes. Using backticks for anything is horrible.\nYou've got str(i), you've got '%d' % i, you've got .format(i); if you want the repr then say so directly with repr() or %r or whatever.\nThere was never a good reason to use backticks, they just made code less readable and much harder to parse. They are gone in Python 3.\n",
"2.X: Using backticks for anything is horrible. Use repr() or str() as required. \n3.X: Backticks have vanished! Three cheers!!\n"
] | [
7,
2,
0
] | [] | [] | [
"backticks",
"python",
"python_2.x"
] | stackoverflow_0002848090_backticks_python_python_2.x.txt |
Q:
python socket.socket.recv with hidden input
Is there any way to have socket.socket.recv run with hidden input. For example, if I was asking for a password I would want the input to be hidden, as if I were running the "sudo" bash command.
Edit:
socket.socket.recv asks for data on the remote end. When you are connected to the server it will ask you for text and when you type it in it will be shown in your console. Now when you use the sudo command it asks for the password and you can't see the text you type. I want something like this that would work for socket.sock.recv, so you wouldn't see the password you type.
Edit 2:
When I said socket.socket.recv I actually meant something like socket._socketobject.recv which would look like this in my program: client.recv(BUF_SIZE).
Edit 3:
I am making a telnet server. client.recv(BUF_SIZE) is like running raw_input on the clients computer. So is there anything that is similar to running getpass.getpass on the clients computer?
A:
socket.recv() returns data from a socket, what you do with that data is up to you.
I guess you are doing something like this:
s.connect(...)
while True:
print s.recv(4096)
In which case your problem is the remote end where someone is presumably typing input.
Can you clarify your question please? recv() never displays data by itself.
A:
(In response to the questioner's clarification)
If you want to be able to obtain input from the user at a console (text-mode) prompt without it being displayed, you probably want to use the getpass.
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from getpass import getpass
>>> p = getpass("Enter some text now: ")
Enter some text now:
>>> print p
secret
>>>
However, this has absolutely nothing to do with sockets and networking. The variable p above contains the user's entered text (i.e. their password). If you send this down a network with socket.sendall(p) the remote end will receive this data. At that point it is up to the receiving script to decide what to do with the data...
A:
(In response to edit 2)
Here is a simple example of how you can encode whether some data is secret or not, and pass that data between functions:
Python 2.6.2 (r262:71600, Sep 22 2009, 18:29:26)
[GCC 3.4.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def capture(secret=False):
... if secret:
... from getpass import getpass
... return chr(0) + getpass("Enter some secret text now: ")
... else:
... return raw_input("Enter some text now: ")
...
>>> def display(data):
... if data[0] == chr(0):
... print "(Secret text hidden)"
... else:
... print data
...
>>> display( capture() )
Enter some text now: Hello
Hello
>>> display( capture(secret=True) )
Enter some secret text now:
(Secret text hidden)
>>>
If you are using sockets, you will need to use s.sendall( capture() ) at one end, and display( s.recv4096) ) at the other.
| python socket.socket.recv with hidden input | Is there any way to have socket.socket.recv run with hidden input. For example, if I was asking for a password I would want the input to be hidden, as if I were running the "sudo" bash command.
Edit:
socket.socket.recv asks for data on the remote end. When you are connected to the server it will ask you for text and when you type it in it will be shown in your console. Now when you use the sudo command it asks for the password and you can't see the text you type. I want something like this that would work for socket.sock.recv, so you wouldn't see the password you type.
Edit 2:
When I said socket.socket.recv I actually meant something like socket._socketobject.recv which would look like this in my program: client.recv(BUF_SIZE).
Edit 3:
I am making a telnet server. client.recv(BUF_SIZE) is like running raw_input on the clients computer. So is there anything that is similar to running getpass.getpass on the clients computer?
| [
"socket.recv() returns data from a socket, what you do with that data is up to you.\nI guess you are doing something like this:\ns.connect(...)\nwhile True:\n print s.recv(4096)\n\nIn which case your problem is the remote end where someone is presumably typing input.\nCan you clarify your question please? recv() never displays data by itself.\n",
"(In response to the questioner's clarification)\nIf you want to be able to obtain input from the user at a console (text-mode) prompt without it being displayed, you probably want to use the getpass.\nPython 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) \n[GCC 4.4.3] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> from getpass import getpass\n>>> p = getpass(\"Enter some text now: \")\nEnter some text now: \n>>> print p\nsecret\n>>> \n\nHowever, this has absolutely nothing to do with sockets and networking. The variable p above contains the user's entered text (i.e. their password). If you send this down a network with socket.sendall(p) the remote end will receive this data. At that point it is up to the receiving script to decide what to do with the data...\n",
"(In response to edit 2)\nHere is a simple example of how you can encode whether some data is secret or not, and pass that data between functions:\nPython 2.6.2 (r262:71600, Sep 22 2009, 18:29:26)\n[GCC 3.4.2] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> def capture(secret=False):\n... if secret:\n... from getpass import getpass\n... return chr(0) + getpass(\"Enter some secret text now: \")\n... else:\n... return raw_input(\"Enter some text now: \")\n...\n>>> def display(data):\n... if data[0] == chr(0):\n... print \"(Secret text hidden)\"\n... else:\n... print data\n...\n>>> display( capture() )\nEnter some text now: Hello\nHello\n>>> display( capture(secret=True) )\nEnter some secret text now:\n(Secret text hidden)\n>>>\n\nIf you are using sockets, you will need to use s.sendall( capture() ) at one end, and display( s.recv4096) ) at the other.\n"
] | [
1,
1,
1
] | [] | [] | [
"passwords",
"python",
"recv",
"sockets"
] | stackoverflow_0002831542_passwords_python_recv_sockets.txt |
Q:
How do you extend python with C++?
I've successfully extended python with C, thanks to this handy skeleton module. But I can't find one for C++, and I have circular dependency trouble when trying to fix the errors that C++ gives when I compile this skeleton module.
How do you extend Python with C++?
I'd rather not depend on Boost (or SWIP or other libraries) if I don't have to. Dependencies are a pain in the butt. Best case scenario, I find a skeleton file that already compiles with C++.
Here's the edited skeleton I've made for C++:
#include <Python.h>
#include "Flp.h"
static PyObject * ErrorObject;
typedef struct {
PyObject_HEAD
PyObject * x_attr; // attributes dictionary
} FlpObject;
static void Flp_dealloc(FlpObject * self);
static PyObject * Flp_getattr(FlpObject * self, char * name);
static int Flp_setattr(FlpObject * self, char * name, PyObject * v);
DL_EXPORT(void) initflp();
static PyTypeObject Flp_Type = {
/* The ob_type field must be initialized in the module init function
* to be portable to Windows without using C++. */
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
"Flp", /*tp_name*/
sizeof(FlpObject), /*tp_basicsize*/
0, /*tp_itemsize*/
/* methods */
(destructor)Flp_dealloc, /*tp_dealloc*/
0, /*tp_print*/
(getattrfunc)Flp_getattr, /*tp_getattr*/
(setattrfunc)Flp_setattr, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash*/
};
#define FlpObject_Check(v) ((v)->ob_type == &Flp_Type)
static FlpObject * newFlpObject(PyObject * arg)
{
FlpObject * self;
self = PyObject_NEW(FlpObject, &Flp_Type);
if (self == NULL)
return NULL;
self->x_attr = NULL;
return self;
}
// Flp methods
static void Flp_dealloc(FlpObject * self)
{
Py_XDECREF(self->x_attr);
PyMem_DEL(self);
}
static PyObject * Flp_demo(FlpObject * self, PyObject * args)
{
if (! PyArg_ParseTuple(args, ""))
return NULL;
Py_INCREF(Py_None);
return Py_None;
}
static PyMethodDef Flp_methods[] = {
{"demo", (PyCFunction)Flp_demo, 1},
{NULL, NULL} // sentinel
};
static PyObject * Flp_getattr(FlpObject * self, char * name)
{
if (self->x_attr != NULL) {
PyObject * v = PyDict_GetItemString(self->x_attr, name);
if (v != NULL) {
Py_INCREF(v);
return v;
}
}
return Py_FindMethod(Flp_methods, (PyObject *)self, name);
}
static int Flp_setattr(FlpObject * self, char * name, PyObject * v)
{
if (self->x_attr == NULL) {
self->x_attr = PyDict_New();
if (self->x_attr == NULL)
return -1;
}
if (v == NULL) {
int rv = PyDict_DelItemString(self->x_attr, name);
if (rv < 0)
PyErr_SetString(PyExc_AttributeError,
"delete non-existing Flp attribute");
return rv;
}
else
return PyDict_SetItemString(self->x_attr, name, v);
}
/* --------------------------------------------------------------------- */
/* Function of two integers returning integer */
static PyObject * flp_foo(PyObject * self, PyObject * args)
{
long i, j;
long res;
if (!PyArg_ParseTuple(args, "ll", &i, &j))
return NULL;
res = i+j; /* flpX Do something here */
return PyInt_FromLong(res);
}
/* Function of no arguments returning new Flp object */
static PyObject * flp_new(PyObject * self, PyObject * args)
{
FlpObject *rv;
if (!PyArg_ParseTuple(args, ""))
return NULL;
rv = newFlpObject(args);
if ( rv == NULL )
return NULL;
return (PyObject *)rv;
}
/* Example with subtle bug from extensions manual ("Thin Ice"). */
static PyObject * flp_bug(PyObject * self, PyObject * args)
{
PyObject *list, *item;
if (!PyArg_ParseTuple(args, "O", &list))
return NULL;
item = PyList_GetItem(list, 0);
/* Py_INCREF(item); */
PyList_SetItem(list, 1, PyInt_FromLong(0L));
PyObject_Print(item, stdout, 0);
printf("\n");
/* Py_DECREF(item); */
Py_INCREF(Py_None);
return Py_None;
}
/* Test bad format character */
static PyObject * flp_roj(PyObject * self, PyObject * args)
{
PyObject *a;
long b;
if (!PyArg_ParseTuple(args, "O#", &a, &b))
return NULL;
Py_INCREF(Py_None);
return Py_None;
}
/* List of functions defined in the module */
static PyMethodDef flp_methods[] = {
{"roj", flp_roj, 1},
{"foo", flp_foo, 1},
{"new", flp_new, 1},
{"bug", flp_bug, 1},
{NULL, NULL} /* sentinel */
};
/* Initialization function for the module (*must* be called initflp) */
DL_EXPORT(void) initflp()
{
PyObject *m, *d;
/* Initialize the type of the new type object here; doing it here
* is required for portability to Windows without requiring C++. */
Flp_Type.ob_type = &PyType_Type;
/* Create the module and add the functions */
m = Py_InitModule("flp", flp_methods);
/* Add some symbolic constants to the module */
d = PyModule_GetDict(m);
ErrorObject = PyErr_NewException("flp.error", NULL, NULL);
PyDict_SetItemString(d, "error", ErrorObject);
}
This compiles fine for me, but when I test it:
$ python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import flp
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: dynamic module does not define init function (initflp)
>>>
A:
First of all, even though you don't want to introduce an additional dependency, I suggest you to have a look at PyCXX. Quoting its webpage:
CXX/Objects is a set of C++ facilities to make it easier to write Python extensions. The chief way in which PyCXX makes it easier to write Python extensions is that it greatly increases the probability that your program will not make a reference-counting error and will not have to continually check error returns from the Python C API. CXX/Objects integrates Python with C++ in these ways:
C++ exception handling is relied on to detect errors and clean up. In a complicated function this is often a tremendous problem when writing in C. With PyCXX, we let the compiler keep track of what objects need to be dereferenced when an error occurs.
The Standard Template Library (STL) and its many algorithms plug and play with Python containers such as lists and tuples.
The optional CXX/Extensions facility allows you to replace the clumsy C tables with objects and method calls that define your modules and extension objects.
I think PyCXX is licensed under the BSD license, which means that you can just as well include the whole source code of PyCXX in the distributed tarball of your extension if your extension will be released under a similar license.
If you really and absolutely don't want to depend on PyCXX or any other third-party library, I think you only have to wrap functions that will be called by the Python interpreter in extern "C" { and } to avoid name mangling.
Here's the corrected code:
#include <Python.h>
#include "Flp.h"
static PyObject * ErrorObject;
typedef struct {
PyObject_HEAD
PyObject * x_attr; // attributes dictionary
} FlpObject;
extern "C" {
static void Flp_dealloc(FlpObject * self);
static PyObject * Flp_getattr(FlpObject * self, char * name);
static int Flp_setattr(FlpObject * self, char * name, PyObject * v);
DL_EXPORT(void) initflp();
}
static PyTypeObject Flp_Type = {
/* The ob_type field must be initialized in the module init function
* to be portable to Windows without using C++. */
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
"Flp", /*tp_name*/
sizeof(FlpObject), /*tp_basicsize*/
0, /*tp_itemsize*/
/* methods */
(destructor)Flp_dealloc, /*tp_dealloc*/
0, /*tp_print*/
(getattrfunc)Flp_getattr, /*tp_getattr*/
(setattrfunc)Flp_setattr, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash*/
};
#define FlpObject_Check(v) ((v)->ob_type == &Flp_Type)
static FlpObject * newFlpObject(PyObject * arg)
{
FlpObject * self;
self = PyObject_NEW(FlpObject, &Flp_Type);
if (self == NULL)
return NULL;
self->x_attr = NULL;
return self;
}
// Flp methods
static void Flp_dealloc(FlpObject * self)
{
Py_XDECREF(self->x_attr);
PyMem_DEL(self);
}
static PyObject * Flp_demo(FlpObject * self, PyObject * args)
{
if (! PyArg_ParseTuple(args, ""))
return NULL;
Py_INCREF(Py_None);
return Py_None;
}
static PyMethodDef Flp_methods[] = {
{"demo", (PyCFunction)Flp_demo, 1},
{NULL, NULL} // sentinel
};
static PyObject * Flp_getattr(FlpObject * self, char * name)
{
if (self->x_attr != NULL) {
PyObject * v = PyDict_GetItemString(self->x_attr, name);
if (v != NULL) {
Py_INCREF(v);
return v;
}
}
return Py_FindMethod(Flp_methods, (PyObject *)self, name);
}
static int Flp_setattr(FlpObject * self, char * name, PyObject * v)
{
if (self->x_attr == NULL) {
self->x_attr = PyDict_New();
if (self->x_attr == NULL)
return -1;
}
if (v == NULL) {
int rv = PyDict_DelItemString(self->x_attr, name);
if (rv < 0)
PyErr_SetString(PyExc_AttributeError,
"delete non-existing Flp attribute");
return rv;
}
else
return PyDict_SetItemString(self->x_attr, name, v);
}
/* --------------------------------------------------------------------- */
/* Function of two integers returning integer */
static PyObject * flp_foo(PyObject * self, PyObject * args)
{
long i, j;
long res;
if (!PyArg_ParseTuple(args, "ll", &i, &j))
return NULL;
res = i+j; /* flpX Do something here */
return PyInt_FromLong(res);
}
/* Function of no arguments returning new Flp object */
static PyObject * flp_new(PyObject * self, PyObject * args)
{
FlpObject *rv;
if (!PyArg_ParseTuple(args, ""))
return NULL;
rv = newFlpObject(args);
if ( rv == NULL )
return NULL;
return (PyObject *)rv;
}
/* Example with subtle bug from extensions manual ("Thin Ice"). */
static PyObject * flp_bug(PyObject * self, PyObject * args)
{
PyObject *list, *item;
if (!PyArg_ParseTuple(args, "O", &list))
return NULL;
item = PyList_GetItem(list, 0);
/* Py_INCREF(item); */
PyList_SetItem(list, 1, PyInt_FromLong(0L));
PyObject_Print(item, stdout, 0);
printf("\n");
/* Py_DECREF(item); */
Py_INCREF(Py_None);
return Py_None;
}
/* Test bad format character */
static PyObject * flp_roj(PyObject * self, PyObject * args)
{
PyObject *a;
long b;
if (!PyArg_ParseTuple(args, "O#", &a, &b))
return NULL;
Py_INCREF(Py_None);
return Py_None;
}
/* List of functions defined in the module */
static PyMethodDef flp_methods[] = {
{"roj", flp_roj, 1},
{"foo", flp_foo, 1},
{"new", flp_new, 1},
{"bug", flp_bug, 1},
{NULL, NULL} /* sentinel */
};
/* Initialization function for the module (*must* be called initflp) */
DL_EXPORT(void) initflp()
{
PyObject *m, *d;
/* Initialize the type of the new type object here; doing it here
* is required for portability to Windows without requiring C++. */
Flp_Type.ob_type = &PyType_Type;
/* Create the module and add the functions */
m = Py_InitModule("flp", flp_methods);
/* Add some symbolic constants to the module */
d = PyModule_GetDict(m);
ErrorObject = PyErr_NewException("flp.error", NULL, NULL);
PyDict_SetItemString(d, "error", ErrorObject);
}
A:
use extern C to wrap all the function names that get called from python. Because C++ compilers use something called 'name mangling' (necessary for dealing with overloading), python can't read c++ libraries. But extern C will solve your problems. Do it like this:
// most of your code can go whereever
void cpp_function() {}
extern "C" {
// all functions that python calls directly must go in here
void python_function() {}
}
Make extra sure you put every function python needs inside the extern block. You can still use c++ features inside the functions, it's just that the names will be exported without 'name mangling'.
A:
What about Boost::Python?
EDIT: sorry, I did oversee that you don't want to depend on boost but I think it might still be one of the best options.
| How do you extend python with C++? | I've successfully extended python with C, thanks to this handy skeleton module. But I can't find one for C++, and I have circular dependency trouble when trying to fix the errors that C++ gives when I compile this skeleton module.
How do you extend Python with C++?
I'd rather not depend on Boost (or SWIP or other libraries) if I don't have to. Dependencies are a pain in the butt. Best case scenario, I find a skeleton file that already compiles with C++.
Here's the edited skeleton I've made for C++:
#include <Python.h>
#include "Flp.h"
static PyObject * ErrorObject;
typedef struct {
PyObject_HEAD
PyObject * x_attr; // attributes dictionary
} FlpObject;
static void Flp_dealloc(FlpObject * self);
static PyObject * Flp_getattr(FlpObject * self, char * name);
static int Flp_setattr(FlpObject * self, char * name, PyObject * v);
DL_EXPORT(void) initflp();
static PyTypeObject Flp_Type = {
/* The ob_type field must be initialized in the module init function
* to be portable to Windows without using C++. */
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
"Flp", /*tp_name*/
sizeof(FlpObject), /*tp_basicsize*/
0, /*tp_itemsize*/
/* methods */
(destructor)Flp_dealloc, /*tp_dealloc*/
0, /*tp_print*/
(getattrfunc)Flp_getattr, /*tp_getattr*/
(setattrfunc)Flp_setattr, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash*/
};
#define FlpObject_Check(v) ((v)->ob_type == &Flp_Type)
static FlpObject * newFlpObject(PyObject * arg)
{
FlpObject * self;
self = PyObject_NEW(FlpObject, &Flp_Type);
if (self == NULL)
return NULL;
self->x_attr = NULL;
return self;
}
// Flp methods
static void Flp_dealloc(FlpObject * self)
{
Py_XDECREF(self->x_attr);
PyMem_DEL(self);
}
static PyObject * Flp_demo(FlpObject * self, PyObject * args)
{
if (! PyArg_ParseTuple(args, ""))
return NULL;
Py_INCREF(Py_None);
return Py_None;
}
static PyMethodDef Flp_methods[] = {
{"demo", (PyCFunction)Flp_demo, 1},
{NULL, NULL} // sentinel
};
static PyObject * Flp_getattr(FlpObject * self, char * name)
{
if (self->x_attr != NULL) {
PyObject * v = PyDict_GetItemString(self->x_attr, name);
if (v != NULL) {
Py_INCREF(v);
return v;
}
}
return Py_FindMethod(Flp_methods, (PyObject *)self, name);
}
static int Flp_setattr(FlpObject * self, char * name, PyObject * v)
{
if (self->x_attr == NULL) {
self->x_attr = PyDict_New();
if (self->x_attr == NULL)
return -1;
}
if (v == NULL) {
int rv = PyDict_DelItemString(self->x_attr, name);
if (rv < 0)
PyErr_SetString(PyExc_AttributeError,
"delete non-existing Flp attribute");
return rv;
}
else
return PyDict_SetItemString(self->x_attr, name, v);
}
/* --------------------------------------------------------------------- */
/* Function of two integers returning integer */
static PyObject * flp_foo(PyObject * self, PyObject * args)
{
long i, j;
long res;
if (!PyArg_ParseTuple(args, "ll", &i, &j))
return NULL;
res = i+j; /* flpX Do something here */
return PyInt_FromLong(res);
}
/* Function of no arguments returning new Flp object */
static PyObject * flp_new(PyObject * self, PyObject * args)
{
FlpObject *rv;
if (!PyArg_ParseTuple(args, ""))
return NULL;
rv = newFlpObject(args);
if ( rv == NULL )
return NULL;
return (PyObject *)rv;
}
/* Example with subtle bug from extensions manual ("Thin Ice"). */
static PyObject * flp_bug(PyObject * self, PyObject * args)
{
PyObject *list, *item;
if (!PyArg_ParseTuple(args, "O", &list))
return NULL;
item = PyList_GetItem(list, 0);
/* Py_INCREF(item); */
PyList_SetItem(list, 1, PyInt_FromLong(0L));
PyObject_Print(item, stdout, 0);
printf("\n");
/* Py_DECREF(item); */
Py_INCREF(Py_None);
return Py_None;
}
/* Test bad format character */
static PyObject * flp_roj(PyObject * self, PyObject * args)
{
PyObject *a;
long b;
if (!PyArg_ParseTuple(args, "O#", &a, &b))
return NULL;
Py_INCREF(Py_None);
return Py_None;
}
/* List of functions defined in the module */
static PyMethodDef flp_methods[] = {
{"roj", flp_roj, 1},
{"foo", flp_foo, 1},
{"new", flp_new, 1},
{"bug", flp_bug, 1},
{NULL, NULL} /* sentinel */
};
/* Initialization function for the module (*must* be called initflp) */
DL_EXPORT(void) initflp()
{
PyObject *m, *d;
/* Initialize the type of the new type object here; doing it here
* is required for portability to Windows without requiring C++. */
Flp_Type.ob_type = &PyType_Type;
/* Create the module and add the functions */
m = Py_InitModule("flp", flp_methods);
/* Add some symbolic constants to the module */
d = PyModule_GetDict(m);
ErrorObject = PyErr_NewException("flp.error", NULL, NULL);
PyDict_SetItemString(d, "error", ErrorObject);
}
This compiles fine for me, but when I test it:
$ python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import flp
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: dynamic module does not define init function (initflp)
>>>
| [
"First of all, even though you don't want to introduce an additional dependency, I suggest you to have a look at PyCXX. Quoting its webpage:\n\nCXX/Objects is a set of C++ facilities to make it easier to write Python extensions. The chief way in which PyCXX makes it easier to write Python extensions is that it greatly increases the probability that your program will not make a reference-counting error and will not have to continually check error returns from the Python C API. CXX/Objects integrates Python with C++ in these ways:\n\nC++ exception handling is relied on to detect errors and clean up. In a complicated function this is often a tremendous problem when writing in C. With PyCXX, we let the compiler keep track of what objects need to be dereferenced when an error occurs.\nThe Standard Template Library (STL) and its many algorithms plug and play with Python containers such as lists and tuples.\nThe optional CXX/Extensions facility allows you to replace the clumsy C tables with objects and method calls that define your modules and extension objects.\n\n\nI think PyCXX is licensed under the BSD license, which means that you can just as well include the whole source code of PyCXX in the distributed tarball of your extension if your extension will be released under a similar license.\nIf you really and absolutely don't want to depend on PyCXX or any other third-party library, I think you only have to wrap functions that will be called by the Python interpreter in extern \"C\" { and } to avoid name mangling.\nHere's the corrected code:\n#include <Python.h>\n\n#include \"Flp.h\"\n\nstatic PyObject * ErrorObject;\n\ntypedef struct {\n PyObject_HEAD\n PyObject * x_attr; // attributes dictionary\n} FlpObject;\n\nextern \"C\" {\n static void Flp_dealloc(FlpObject * self);\n static PyObject * Flp_getattr(FlpObject * self, char * name);\n static int Flp_setattr(FlpObject * self, char * name, PyObject * v);\n DL_EXPORT(void) initflp();\n}\n\nstatic PyTypeObject Flp_Type = {\n /* The ob_type field must be initialized in the module init function\n * to be portable to Windows without using C++. */\n PyObject_HEAD_INIT(NULL)\n 0, /*ob_size*/\n \"Flp\", /*tp_name*/\n sizeof(FlpObject), /*tp_basicsize*/\n 0, /*tp_itemsize*/\n /* methods */\n (destructor)Flp_dealloc, /*tp_dealloc*/\n 0, /*tp_print*/\n (getattrfunc)Flp_getattr, /*tp_getattr*/\n (setattrfunc)Flp_setattr, /*tp_setattr*/\n 0, /*tp_compare*/\n 0, /*tp_repr*/\n 0, /*tp_as_number*/\n 0, /*tp_as_sequence*/\n 0, /*tp_as_mapping*/\n 0, /*tp_hash*/\n};\n\n#define FlpObject_Check(v) ((v)->ob_type == &Flp_Type)\n\nstatic FlpObject * newFlpObject(PyObject * arg)\n{\n FlpObject * self;\n self = PyObject_NEW(FlpObject, &Flp_Type);\n if (self == NULL)\n return NULL;\n self->x_attr = NULL;\n return self;\n}\n\n// Flp methods\n\nstatic void Flp_dealloc(FlpObject * self)\n{\n Py_XDECREF(self->x_attr);\n PyMem_DEL(self);\n}\n\nstatic PyObject * Flp_demo(FlpObject * self, PyObject * args)\n{\n if (! PyArg_ParseTuple(args, \"\"))\n return NULL;\n Py_INCREF(Py_None);\n return Py_None;\n}\n\nstatic PyMethodDef Flp_methods[] = {\n {\"demo\", (PyCFunction)Flp_demo, 1},\n {NULL, NULL} // sentinel\n};\n\nstatic PyObject * Flp_getattr(FlpObject * self, char * name)\n{\n if (self->x_attr != NULL) {\n PyObject * v = PyDict_GetItemString(self->x_attr, name);\n if (v != NULL) {\n Py_INCREF(v);\n return v;\n }\n }\n return Py_FindMethod(Flp_methods, (PyObject *)self, name);\n}\n\nstatic int Flp_setattr(FlpObject * self, char * name, PyObject * v)\n{\n if (self->x_attr == NULL) {\n self->x_attr = PyDict_New();\n if (self->x_attr == NULL)\n return -1;\n }\n if (v == NULL) {\n int rv = PyDict_DelItemString(self->x_attr, name);\n if (rv < 0)\n PyErr_SetString(PyExc_AttributeError,\n \"delete non-existing Flp attribute\");\n return rv;\n }\n else\n return PyDict_SetItemString(self->x_attr, name, v);\n}\n/* --------------------------------------------------------------------- */\n\n/* Function of two integers returning integer */\n\nstatic PyObject * flp_foo(PyObject * self, PyObject * args)\n{\n long i, j;\n long res;\n if (!PyArg_ParseTuple(args, \"ll\", &i, &j))\n return NULL;\n res = i+j; /* flpX Do something here */\n return PyInt_FromLong(res);\n}\n\n\n/* Function of no arguments returning new Flp object */\n\nstatic PyObject * flp_new(PyObject * self, PyObject * args)\n{\n FlpObject *rv;\n \n if (!PyArg_ParseTuple(args, \"\"))\n return NULL;\n rv = newFlpObject(args);\n if ( rv == NULL )\n return NULL;\n return (PyObject *)rv;\n}\n\n/* Example with subtle bug from extensions manual (\"Thin Ice\"). */\n\nstatic PyObject * flp_bug(PyObject * self, PyObject * args)\n{\n PyObject *list, *item;\n \n if (!PyArg_ParseTuple(args, \"O\", &list))\n return NULL;\n \n item = PyList_GetItem(list, 0);\n /* Py_INCREF(item); */\n PyList_SetItem(list, 1, PyInt_FromLong(0L));\n PyObject_Print(item, stdout, 0);\n printf(\"\\n\");\n /* Py_DECREF(item); */\n \n Py_INCREF(Py_None);\n return Py_None;\n}\n\n/* Test bad format character */\n\nstatic PyObject * flp_roj(PyObject * self, PyObject * args)\n{\n PyObject *a;\n long b;\n if (!PyArg_ParseTuple(args, \"O#\", &a, &b))\n return NULL;\n Py_INCREF(Py_None);\n return Py_None;\n}\n\n\n/* List of functions defined in the module */\n\nstatic PyMethodDef flp_methods[] = {\n {\"roj\", flp_roj, 1},\n {\"foo\", flp_foo, 1},\n {\"new\", flp_new, 1},\n {\"bug\", flp_bug, 1},\n {NULL, NULL} /* sentinel */\n};\n\n\n/* Initialization function for the module (*must* be called initflp) */\n\nDL_EXPORT(void) initflp()\n{\n PyObject *m, *d;\n\n /* Initialize the type of the new type object here; doing it here\n * is required for portability to Windows without requiring C++. */\n Flp_Type.ob_type = &PyType_Type;\n\n /* Create the module and add the functions */\n m = Py_InitModule(\"flp\", flp_methods);\n\n /* Add some symbolic constants to the module */\n d = PyModule_GetDict(m);\n ErrorObject = PyErr_NewException(\"flp.error\", NULL, NULL);\n PyDict_SetItemString(d, \"error\", ErrorObject);\n}\n\n",
"use extern C to wrap all the function names that get called from python. Because C++ compilers use something called 'name mangling' (necessary for dealing with overloading), python can't read c++ libraries. But extern C will solve your problems. Do it like this:\n\n// most of your code can go whereever\nvoid cpp_function() {}\nextern \"C\" {\n // all functions that python calls directly must go in here\n void python_function() {}\n}\n\nMake extra sure you put every function python needs inside the extern block. You can still use c++ features inside the functions, it's just that the names will be exported without 'name mangling'.\n",
"What about Boost::Python?\nEDIT: sorry, I did oversee that you don't want to depend on boost but I think it might still be one of the best options.\n"
] | [
14,
7,
1
] | [] | [] | [
"c++",
"python"
] | stackoverflow_0002847617_c++_python.txt |
Q:
How to check a file saving is complete using Python?
I am trying to automate a downloading process. In this I want to know, whether a particular file's save is completed or not. The scenario is like this.
Open a site address using either Chrome or Firefox (any browser)
Save the page to disk using 'Crtl + S' (I work on windows)
Now if the page is very big, then it takes few seconds to save. I want to parse the html once the save is complete.
Since I don't have control on the browser save functionality, I don't know whether the save has completed or not.
One idea I thought, is to get the md5sum of the file using a while loop, and check against the previous one calculated, and continue the while loop till the md5 sum from the previous and current one matches. This doesn't works I guess, as it seems browser first attempts to save the file in a tmp file and then copies the content to the specified file (or just renames the file).
Any ideas? I use python for the automation, hence any idea which can be implemented using python is welcome.
Thanks
Indrajith
A:
On Windows you can try to open file in exclusive access mode to check if it's being used (read or written) by some other program. I've used this to wait for complete FTP uploads server-side, here's the code:
def check_file_ready(self, path):
'''Check if file is not opened by another process.'''
handle = None
try:
handle = win32file.CreateFile(
path,
win32file.GENERIC_WRITE,
0,
None,
win32file.OPEN_EXISTING,
win32file.FILE_ATTRIBUTE_NORMAL,
None)
return True
except pywintypes.error, e:
if e[0] == winerror.ERROR_SHARING_VIOLATION:
# Note: other possible error codes include
# winerror.ERROR_FILE_NOT_FOUND
# winerror.ERROR_PATH_NOT_FOUND
# winerror.ERROR_ACCESS_DENIED.
return False
raise
finally:
if handle:
win32file.CloseHandle(handle)
Note: this functions re-raises all win32 errors except sharing violation. You should check for file existence beforehead or check for additional error codes in the function (see comment on line 15).
| How to check a file saving is complete using Python? | I am trying to automate a downloading process. In this I want to know, whether a particular file's save is completed or not. The scenario is like this.
Open a site address using either Chrome or Firefox (any browser)
Save the page to disk using 'Crtl + S' (I work on windows)
Now if the page is very big, then it takes few seconds to save. I want to parse the html once the save is complete.
Since I don't have control on the browser save functionality, I don't know whether the save has completed or not.
One idea I thought, is to get the md5sum of the file using a while loop, and check against the previous one calculated, and continue the while loop till the md5 sum from the previous and current one matches. This doesn't works I guess, as it seems browser first attempts to save the file in a tmp file and then copies the content to the specified file (or just renames the file).
Any ideas? I use python for the automation, hence any idea which can be implemented using python is welcome.
Thanks
Indrajith
| [
"On Windows you can try to open file in exclusive access mode to check if it's being used (read or written) by some other program. I've used this to wait for complete FTP uploads server-side, here's the code:\ndef check_file_ready(self, path):\n '''Check if file is not opened by another process.'''\n handle = None\n try:\n handle = win32file.CreateFile(\n path,\n win32file.GENERIC_WRITE,\n 0,\n None,\n win32file.OPEN_EXISTING,\n win32file.FILE_ATTRIBUTE_NORMAL,\n None)\n return True\n except pywintypes.error, e:\n if e[0] == winerror.ERROR_SHARING_VIOLATION:\n # Note: other possible error codes include\n # winerror.ERROR_FILE_NOT_FOUND\n # winerror.ERROR_PATH_NOT_FOUND\n # winerror.ERROR_ACCESS_DENIED.\n return False\n raise\n finally:\n if handle:\n win32file.CloseHandle(handle)\n\nNote: this functions re-raises all win32 errors except sharing violation. You should check for file existence beforehead or check for additional error codes in the function (see comment on line 15).\n"
] | [
6
] | [] | [] | [
"python",
"pywin",
"save",
"windows"
] | stackoverflow_0002848008_python_pywin_save_windows.txt |
Q:
How to identify a broadcasted message?
Sometimes I have to send a message to a specific IP and sometimes I have to broadcast the message to all the IP's in my network. At the other end I have to distinguish between a broadcast and a normal one, but recvfrom() just returns the address the message came from;
there is no difference between them. Can anyone help me distinguish them?
UDP is the protocol.
A:
I don't think it's possible with Python's socket module. UDP is a very minimalistic protocol, and the only way to distinguish between a broadcast and a non-broadcast UDP packet is by looking at the destination address. However, you cannot inspect that part of the packet with the BSD socket API (if I remember it correctly), and the socket module exposes the BSD socket API only. Your best bet would probably be to use the first byte of the message to denote whether it is a broadcast or a unicast message.
| How to identify a broadcasted message? | Sometimes I have to send a message to a specific IP and sometimes I have to broadcast the message to all the IP's in my network. At the other end I have to distinguish between a broadcast and a normal one, but recvfrom() just returns the address the message came from;
there is no difference between them. Can anyone help me distinguish them?
UDP is the protocol.
| [
"I don't think it's possible with Python's socket module. UDP is a very minimalistic protocol, and the only way to distinguish between a broadcast and a non-broadcast UDP packet is by looking at the destination address. However, you cannot inspect that part of the packet with the BSD socket API (if I remember it correctly), and the socket module exposes the BSD socket API only. Your best bet would probably be to use the first byte of the message to denote whether it is a broadcast or a unicast message.\n"
] | [
5
] | [] | [] | [
"python"
] | stackoverflow_0002848098_python.txt |
Q:
To convert PyBytesObject type to PyUnicodeObject type in python3
How to convert pyunicodeobject type to pybytesobject type?
Example:
function(PyBytesObject* byteobj){
....operation..
}
PyUnicodeObject* Uniobj;
function((PyBytesObject*) Uniobj);
got a bus error as a result.
A:
You need to encode it just as you would if you were doing it in Python. For utf-8 use:
PyObject* PyUnicode_AsUTF8String(PyObject *unicode)
Return value: New reference.
Encode a Unicode object using UTF-8 and return the result as Python bytes object. Error handling is “strict”. Return NULL if an exception was raised by the codec.
Or if you want it in utf-16 or some other encoding there are api's for those too. See the docs at http://docs.python.org/py3k/c-api/unicode.html (search for functions beginning with PyUnicode_As).
Don't forget to check the return code when you do the encoding, and release the reference to the bytes object when you're done with it.
| To convert PyBytesObject type to PyUnicodeObject type in python3 | How to convert pyunicodeobject type to pybytesobject type?
Example:
function(PyBytesObject* byteobj){
....operation..
}
PyUnicodeObject* Uniobj;
function((PyBytesObject*) Uniobj);
got a bus error as a result.
| [
"You need to encode it just as you would if you were doing it in Python. For utf-8 use:\n\nPyObject* PyUnicode_AsUTF8String(PyObject *unicode)\n\nReturn value: New reference.\n Encode a Unicode object using UTF-8 and return the result as Python bytes object. Error handling is “strict”. Return NULL if an exception was raised by the codec.\n\nOr if you want it in utf-16 or some other encoding there are api's for those too. See the docs at http://docs.python.org/py3k/c-api/unicode.html (search for functions beginning with PyUnicode_As).\nDon't forget to check the return code when you do the encoding, and release the reference to the bytes object when you're done with it.\n"
] | [
2
] | [] | [] | [
"cpython",
"python",
"python_3.x",
"python_c_api"
] | stackoverflow_0002848569_cpython_python_python_3.x_python_c_api.txt |
Q:
threading.local equivalent for twisted.web?
In asynchronous environments, threading.local is not guaranteed to be context-local anymore, because several contexts may coexist within a single thread. Most asynchronous frameworks (gevent, eventlet) provide a get_current_context() functionality to identify the current context. Some offer a way to monkey-patch threading.local so it is local to 'greenthreads' or other framework-specific contexts. I cannot find such a functionality in the twisted documentation. How do I do this?
A:
I'm assuming you want this API in order to save and retrieve per-request state. If not, then you might want to clarify your question.
Twisted Web doesn't offer any API along these lines. Since you're in control for the completely lifetime of the request, it's possible for you to store any per-request state yourself: on Resource instances, in locals, in arguments to callbacks, etc. A get_current_context function is sort of the multi-threaded equivalent of using globals to keep track of your state. When you think about it that way, hopefully it's a little more obvious why you might want to consider alternate solutions.
| threading.local equivalent for twisted.web? | In asynchronous environments, threading.local is not guaranteed to be context-local anymore, because several contexts may coexist within a single thread. Most asynchronous frameworks (gevent, eventlet) provide a get_current_context() functionality to identify the current context. Some offer a way to monkey-patch threading.local so it is local to 'greenthreads' or other framework-specific contexts. I cannot find such a functionality in the twisted documentation. How do I do this?
| [
"I'm assuming you want this API in order to save and retrieve per-request state. If not, then you might want to clarify your question.\nTwisted Web doesn't offer any API along these lines. Since you're in control for the completely lifetime of the request, it's possible for you to store any per-request state yourself: on Resource instances, in locals, in arguments to callbacks, etc. A get_current_context function is sort of the multi-threaded equivalent of using globals to keep track of your state. When you think about it that way, hopefully it's a little more obvious why you might want to consider alternate solutions.\n"
] | [
3
] | [] | [] | [
"python",
"twisted",
"twisted.web"
] | stackoverflow_0002848686_python_twisted_twisted.web.txt |
Q:
Fastest method in merging of the two: dicts vs lists
I'm doing some indexing and memory is sufficient but CPU isn't. So I have one huge dictionary and then a smaller dictionary I'm merging into the bigger one:
big_dict = {"the" : {"1" : 1, "2" : 1, "3" : 1, "4" : 1, "5" : 1}}
smaller_dict = {"the" : {"6" : 1, "7" : 1}}
#after merging
resulting_dict = {"the" : {"1" : 1, "2" : 1, "3" : 1, "4" : 1, "5" : 1, "6" : 1, "7" : 1}}
My question is for the values in both dicts, should I use a dict (as displayed above) or list (as displayed below) when my priority is to use as much memory as possible to gain the most out of my CPU?
For clarification, using a list would look like:
big_dict = {"the" : [1, 2, 3, 4, 5]}
smaller_dict = {"the" : [6,7]}
#after merging
resulting_dict = {"the" : [1, 2, 3, 4, 5, 6, 7]}
Side note: The reason I'm using a dict nested into a dict rather than a set nested in a dict is because JSON won't let me do json.dumps because a set isn't key/value pairs, it's (as far as the JSON library is concerned) {"a", "series", "of", "keys"}
Also, after choosing between using dict to a list, how would I go about implementing the most efficient, in terms of CPU, method of merging them?
I appreciate the help.
A:
Hmmm. I would first go for a dict-of-dicts approach, as Python has one of the most fine-tuned dict implementation, so I highly doubt you can get any better with using a dict-of-lists.
As for merging the dicts, this should be enough:
for key, value in smaller_dict.iteritems():
try:
big_dict[key].update(value)
except KeyError:
big_dict[key] = dict(value)
I would probably also experiment with subclassing json.JSONEncoder to be able to serialize set types:
class SetEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, set):
return dict.fromkeys(obj)
return json.JSONEncoder.default(self, obj)
This latter method might add some overhead on the serialization side, however, and you will also need to convert these dicts to sets upon deserialization, either by subclassing json.JSONDecoder or doing it yourself in an extra step.
A:
It really depends on what you want to do with the values in your inner lists/dictionaries. If, when you add a new entry, you want the inner list to have only unique values, then the list implementation will be much slower for large lists. It scales roughly at O(n), rather than O(1) [average case] for dictionaries.
If you don't care about multiples in those inner lists, then it is a closer thing.
I would use dictionaries, as you have. Python's dictionaries are very efficient (speaking as someone who's tried to implement dictionary data structures in C for real time applications).
As for not using sets. It would be better (since memory isn't an issue, you say), to tweak the serialization, and have the speed critical part of your code be as simple as possible. After deserialization, just go through and convert the lists to sets:
big_dict = {"the" : [1, 2, 3, 4, 5]} # imagine we got this from JSON
for key, value in big_dict:
big_dict[key] = set(value)
Should do it. Unless you are serializing / deserializing the whole index all the time, this added pre-processing costs should be amortized over enough requests not to matter.
Alternatively you can register encoders and decoders with JSON so you can do this conversion automatically. I usually don't bother when the issue is something so small and contained, however.
So in your dictionary based approach you could do:
for key, value in smaller_dict.items():
if key in big_dict:
big_dict[key].update(value)
else:
big_dict[key] = value
If you want the big_dict to only copy the dictionary, use dict(value) instead of value on the last line. You could also use try: and except KeyError in the last loop, but if...else is a fraction faster (on my machine, YMMV).
A:
Any hashing-container will be better than a list for this kind of stuff.
I'd still use a set instead of a dict; if you're having trouble with json.dumps you can get around it by converting the set to a dict when you go to serialize: dict.fromkeys(the_set, 1)
And for pulling them out: set(the_dict.keys())
It's easier than mucking about with registering JSON providers.
And as for merging: merged_set = bigger_set.union(smaller_set)
| Fastest method in merging of the two: dicts vs lists | I'm doing some indexing and memory is sufficient but CPU isn't. So I have one huge dictionary and then a smaller dictionary I'm merging into the bigger one:
big_dict = {"the" : {"1" : 1, "2" : 1, "3" : 1, "4" : 1, "5" : 1}}
smaller_dict = {"the" : {"6" : 1, "7" : 1}}
#after merging
resulting_dict = {"the" : {"1" : 1, "2" : 1, "3" : 1, "4" : 1, "5" : 1, "6" : 1, "7" : 1}}
My question is for the values in both dicts, should I use a dict (as displayed above) or list (as displayed below) when my priority is to use as much memory as possible to gain the most out of my CPU?
For clarification, using a list would look like:
big_dict = {"the" : [1, 2, 3, 4, 5]}
smaller_dict = {"the" : [6,7]}
#after merging
resulting_dict = {"the" : [1, 2, 3, 4, 5, 6, 7]}
Side note: The reason I'm using a dict nested into a dict rather than a set nested in a dict is because JSON won't let me do json.dumps because a set isn't key/value pairs, it's (as far as the JSON library is concerned) {"a", "series", "of", "keys"}
Also, after choosing between using dict to a list, how would I go about implementing the most efficient, in terms of CPU, method of merging them?
I appreciate the help.
| [
"Hmmm. I would first go for a dict-of-dicts approach, as Python has one of the most fine-tuned dict implementation, so I highly doubt you can get any better with using a dict-of-lists.\nAs for merging the dicts, this should be enough:\nfor key, value in smaller_dict.iteritems():\n try:\n big_dict[key].update(value)\n except KeyError:\n big_dict[key] = dict(value)\n\nI would probably also experiment with subclassing json.JSONEncoder to be able to serialize set types:\nclass SetEncoder(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, set):\n return dict.fromkeys(obj)\n return json.JSONEncoder.default(self, obj)\n\nThis latter method might add some overhead on the serialization side, however, and you will also need to convert these dicts to sets upon deserialization, either by subclassing json.JSONDecoder or doing it yourself in an extra step.\n",
"It really depends on what you want to do with the values in your inner lists/dictionaries. If, when you add a new entry, you want the inner list to have only unique values, then the list implementation will be much slower for large lists. It scales roughly at O(n), rather than O(1) [average case] for dictionaries.\nIf you don't care about multiples in those inner lists, then it is a closer thing. \nI would use dictionaries, as you have. Python's dictionaries are very efficient (speaking as someone who's tried to implement dictionary data structures in C for real time applications).\nAs for not using sets. It would be better (since memory isn't an issue, you say), to tweak the serialization, and have the speed critical part of your code be as simple as possible. After deserialization, just go through and convert the lists to sets:\nbig_dict = {\"the\" : [1, 2, 3, 4, 5]} # imagine we got this from JSON\n\nfor key, value in big_dict: \n big_dict[key] = set(value)\n\nShould do it. Unless you are serializing / deserializing the whole index all the time, this added pre-processing costs should be amortized over enough requests not to matter.\nAlternatively you can register encoders and decoders with JSON so you can do this conversion automatically. I usually don't bother when the issue is something so small and contained, however.\nSo in your dictionary based approach you could do:\nfor key, value in smaller_dict.items():\n if key in big_dict: \n big_dict[key].update(value)\n else:\n big_dict[key] = value\n\nIf you want the big_dict to only copy the dictionary, use dict(value) instead of value on the last line. You could also use try: and except KeyError in the last loop, but if...else is a fraction faster (on my machine, YMMV).\n",
"Any hashing-container will be better than a list for this kind of stuff.\nI'd still use a set instead of a dict; if you're having trouble with json.dumps you can get around it by converting the set to a dict when you go to serialize: dict.fromkeys(the_set, 1)\nAnd for pulling them out: set(the_dict.keys())\nIt's easier than mucking about with registering JSON providers.\nAnd as for merging: merged_set = bigger_set.union(smaller_set)\n"
] | [
2,
2,
1
] | [] | [] | [
"performance",
"python"
] | stackoverflow_0002849101_performance_python.txt |
Q:
Create a Python User() class that both creates new users and modifies existing users
I'm trying to figure out the best way to create a class that can modify and create new users all in one. This is what I'm thinking:
class User(object):
def __init__(self,user_id):
if user_id == -1
self.new_user = True
else:
self.new_user = False
#fetch all records from db about user_id
self._populateUser()
def commit(self):
if self.new_user:
#Do INSERTs
else:
#Do UPDATEs
def delete(self):
if self.new_user == False:
return False
#Delete user code here
def _populate(self):
#Query self.user_id from database and
#set all instance variables, e.g.
#self.name = row['name']
def getFullName(self):
return self.name
#Create a new user
>>u = User()
>>u.name = 'Jason Martinez'
>>u.password = 'linebreak'
>>u.commit()
>>print u.getFullName()
>>Jason Martinez
#Update existing user
>>u = User(43)
>>u.name = 'New Name Here'
>>u.commit()
>>print u.getFullName()
>>New Name Here
Is this a logical and clean way to do this? Is there a better way?
Thanks.
A:
You can do this with metaclasses. Consider this :
class MetaCity:
def __call__(cls,name):
“”“
If it’s in the database, retrieve it and return it
If it’s not there, create it and return it
““”
theCity = database.get(name) # your custom code to get the object from the db goes here
if not theCity:
# create a new one
theCity = type.__call__(cls,name)
return theCity
class City():
__metaclass__ = MetaCity
name = Field(Unicode(64))
Now you can do things like :
paris = City(name=u"Paris") # this will create the Paris City in the database and return it.
paris_again = City(name=u"Paris") # this will retrieve Paris from the database and return it.
from : http://yassinechaouche.thecoderblogs.com/2009/11/21/using-beaker-as-a-second-level-query-cache-for-sqlalchemy-in-pylons/
A:
Off the top of my head, I would suggest the following:
1: Use a default argument None instead of -1 for user_id in the constructor:
def __init__(self, user_id=None):
if user_id is None:
...
2: Skip the getFullName method - that's just your Java talking. Instead use a normal attribute access - you can convert it into a property later if you need to.
A:
What you are trying to achieve is called Active Record pattern. I suggest learning existing systems providing this sort of things such as Elixir.
A:
Small change to your initializer:
def __init__(self, user_id=None):
if user_id is None:
| Create a Python User() class that both creates new users and modifies existing users | I'm trying to figure out the best way to create a class that can modify and create new users all in one. This is what I'm thinking:
class User(object):
def __init__(self,user_id):
if user_id == -1
self.new_user = True
else:
self.new_user = False
#fetch all records from db about user_id
self._populateUser()
def commit(self):
if self.new_user:
#Do INSERTs
else:
#Do UPDATEs
def delete(self):
if self.new_user == False:
return False
#Delete user code here
def _populate(self):
#Query self.user_id from database and
#set all instance variables, e.g.
#self.name = row['name']
def getFullName(self):
return self.name
#Create a new user
>>u = User()
>>u.name = 'Jason Martinez'
>>u.password = 'linebreak'
>>u.commit()
>>print u.getFullName()
>>Jason Martinez
#Update existing user
>>u = User(43)
>>u.name = 'New Name Here'
>>u.commit()
>>print u.getFullName()
>>New Name Here
Is this a logical and clean way to do this? Is there a better way?
Thanks.
| [
"You can do this with metaclasses. Consider this : \nclass MetaCity:\n def __call__(cls,name):\n “”“\n If it’s in the database, retrieve it and return it\n If it’s not there, create it and return it\n ““”\n theCity = database.get(name) # your custom code to get the object from the db goes here\n if not theCity:\n # create a new one\n theCity = type.__call__(cls,name)\n\n return theCity\n\nclass City():\n __metaclass__ = MetaCity\n name = Field(Unicode(64))\n\nNow you can do things like : \nparis = City(name=u\"Paris\") # this will create the Paris City in the database and return it.\nparis_again = City(name=u\"Paris\") # this will retrieve Paris from the database and return it.\n\nfrom : http://yassinechaouche.thecoderblogs.com/2009/11/21/using-beaker-as-a-second-level-query-cache-for-sqlalchemy-in-pylons/\n",
"Off the top of my head, I would suggest the following:\n1: Use a default argument None instead of -1 for user_id in the constructor:\ndef __init__(self, user_id=None):\n if user_id is None:\n ...\n\n2: Skip the getFullName method - that's just your Java talking. Instead use a normal attribute access - you can convert it into a property later if you need to.\n",
"What you are trying to achieve is called Active Record pattern. I suggest learning existing systems providing this sort of things such as Elixir.\n",
"Small change to your initializer:\ndef __init__(self, user_id=None):\n if user_id is None:\n\n"
] | [
4,
3,
2,
1
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0002521907_oop_python.txt |
Q:
How different protocols interact with eachother in Twisted
The scenario I want two different protocols interact with each other is as below:
A and B is two different protocols.
First A will interact with the server and retrieve some values.
Only after A finishes retrieving the values , B will start to interact with the server.
Now my problem is that is there an elegant way to initial B when A retrieves the values.
Currently I just initial B in A's data process function. But i don't think that this is an elegant way.
What I mean an elegant way is that the initialization of B is done by a flow controller or something like that, but not another protocol.
Is there an elegant way? such using defered or any other things.
I'm just new to twisted, not knowing very much about defered....
Thank you very much!
A:
It sounds like you've gotten past the first hurdle - figuring out how to have A and B interact at all. That's good, since for most people that's the biggest conceptual challenge. As for making it elegant, if you're after an approach that keeps your protocol code isolated from the application code driving it (ie, the "business logic"), there are several options. I'll give an example of one based on Deferreds.
Let's consider two POP3 clients. You want the first to retrieve a message list, then the second to retrieve the first message from the resulting list. This example
from twisted.internet import defer, protocol, reactor
from twisted.mail.pop3 import AdvancedPOP3Client
class MessageDownloader(object):
def __init__(self, host, port, user, password):
self.host = host
self.port = port
self.user = user
self.password = password
self.cc = ClientCreator(reactor, AdvancedPOP3Client)
def connect(self):
"""
Connect to the POP3 server and authenticate. Return a Deferred
which fires with the connected protocol instance.
"""
connDeferred = self.cc.connect(self.host, self.port)
def cbAuthenticate(proto):
loginDeferred = proto.login(user, password)
loginDeferred.addCallback(lambda ignored: proto)
return loginDeferred
connDeferred.addCallback(cbAuthenticate)
return connDeferred
def run(self):
connDeferred = self.connect()
connDeferred.addCallback(self.cbFirstConnection)
return connDeferred
def cbFirstConnection(self, firstProto):
listDeferred = firstProto.listUID()
def cbListed(uidList):
connDeferred = self.connect()
def cbConnected(secondProto):
return secondProto.retrieve(uidList[0])
connDeferred.addCallback(cbConnected)
listDeferred.addCallback(cbListed)
return listDeferred
if __name__ == '__main__':
import sys
MessageDownloader(*sys.argv[1:]).run()
reactor.run()
Here, all of the logic about retrieving a list of UIDs and setting up a new connection to retrieve a message is separate from the actual protocol implementation (which is entirely in Twisted). The Deferreds returned from almost all of the APIs used here allow events to be connected up however your application wants.
| How different protocols interact with eachother in Twisted | The scenario I want two different protocols interact with each other is as below:
A and B is two different protocols.
First A will interact with the server and retrieve some values.
Only after A finishes retrieving the values , B will start to interact with the server.
Now my problem is that is there an elegant way to initial B when A retrieves the values.
Currently I just initial B in A's data process function. But i don't think that this is an elegant way.
What I mean an elegant way is that the initialization of B is done by a flow controller or something like that, but not another protocol.
Is there an elegant way? such using defered or any other things.
I'm just new to twisted, not knowing very much about defered....
Thank you very much!
| [
"It sounds like you've gotten past the first hurdle - figuring out how to have A and B interact at all. That's good, since for most people that's the biggest conceptual challenge. As for making it elegant, if you're after an approach that keeps your protocol code isolated from the application code driving it (ie, the \"business logic\"), there are several options. I'll give an example of one based on Deferreds.\nLet's consider two POP3 clients. You want the first to retrieve a message list, then the second to retrieve the first message from the resulting list. This example \nfrom twisted.internet import defer, protocol, reactor\nfrom twisted.mail.pop3 import AdvancedPOP3Client\n\nclass MessageDownloader(object):\n def __init__(self, host, port, user, password):\n self.host = host\n self.port = port\n self.user = user\n self.password = password\n self.cc = ClientCreator(reactor, AdvancedPOP3Client)\n\n\n def connect(self):\n \"\"\"\n Connect to the POP3 server and authenticate. Return a Deferred\n which fires with the connected protocol instance.\n \"\"\"\n connDeferred = self.cc.connect(self.host, self.port)\n def cbAuthenticate(proto):\n loginDeferred = proto.login(user, password)\n loginDeferred.addCallback(lambda ignored: proto)\n return loginDeferred\n connDeferred.addCallback(cbAuthenticate)\n return connDeferred\n\n\n def run(self):\n connDeferred = self.connect()\n connDeferred.addCallback(self.cbFirstConnection)\n return connDeferred\n\n\n def cbFirstConnection(self, firstProto):\n listDeferred = firstProto.listUID()\n\n def cbListed(uidList):\n connDeferred = self.connect()\n def cbConnected(secondProto):\n return secondProto.retrieve(uidList[0])\n connDeferred.addCallback(cbConnected)\n listDeferred.addCallback(cbListed)\n return listDeferred\n\nif __name__ == '__main__':\n import sys\n MessageDownloader(*sys.argv[1:]).run()\n reactor.run()\n\nHere, all of the logic about retrieving a list of UIDs and setting up a new connection to retrieve a message is separate from the actual protocol implementation (which is entirely in Twisted). The Deferreds returned from almost all of the APIs used here allow events to be connected up however your application wants.\n"
] | [
1
] | [] | [] | [
"protocols",
"python",
"twisted"
] | stackoverflow_0002847979_protocols_python_twisted.txt |
Q:
Suggestions for a pluggable task framework in Django
I am developing a website which is aimed at being a GUI for several image processing algorithms (referred to as 'tasks').
At the moment, only one of these algorithms is finished, but there are more to come (which will have a similar, but not quite the same, workflow)
Basically, the algorithm works as follows (not that it matters a lot, but just for the sake of clarity):
1) Enter some parameters and an input image
2) run algorithm part one
--algorithm runs--
3) review an interim result
4) edit the parameters if needed, and go to 2.
5) run algorithm part two
--algorithm runs--
6) review the result
7) adjust some of the interim results if needed, and go to 5
8) all done
I expect some of the additional tasks to have a rather similar work flow, though it is perfectly possible that they won't.
So, the easy way to implement this would be to create a separate django application for each algorithm.
However, I'd like to be able to browse through a sorted list (by time of completion) of completed tasks, and for each of these task display a summary (name, description, start time, thumbnail).
Is there anyone that can provide me with some suggestions on how I can implement this? I'd like to keep it as simple as possible, so additional task can be 'plugged' in as easy as possible.
A:
I would make an app with a very abstract definition of a Task model. The Task model might contain properties for:
the input arguments,
the function to run,
the time that the task was submitted,
the time that the task has been actually running, and
the result (which would be something like a singleton Task.NotFinished until finished).
You could consider using twisted to run the tasks because:
twisted has a well designed and tested implementation of asynchronous tasks; and
you could run the tasks on other processors or machines.
| Suggestions for a pluggable task framework in Django | I am developing a website which is aimed at being a GUI for several image processing algorithms (referred to as 'tasks').
At the moment, only one of these algorithms is finished, but there are more to come (which will have a similar, but not quite the same, workflow)
Basically, the algorithm works as follows (not that it matters a lot, but just for the sake of clarity):
1) Enter some parameters and an input image
2) run algorithm part one
--algorithm runs--
3) review an interim result
4) edit the parameters if needed, and go to 2.
5) run algorithm part two
--algorithm runs--
6) review the result
7) adjust some of the interim results if needed, and go to 5
8) all done
I expect some of the additional tasks to have a rather similar work flow, though it is perfectly possible that they won't.
So, the easy way to implement this would be to create a separate django application for each algorithm.
However, I'd like to be able to browse through a sorted list (by time of completion) of completed tasks, and for each of these task display a summary (name, description, start time, thumbnail).
Is there anyone that can provide me with some suggestions on how I can implement this? I'd like to keep it as simple as possible, so additional task can be 'plugged' in as easy as possible.
| [
"I would make an app with a very abstract definition of a Task model. The Task model might contain properties for:\n\nthe input arguments, \nthe function to run, \nthe time that the task was submitted, \nthe time that the task has been actually running, and \nthe result (which would be something like a singleton Task.NotFinished until finished).\n\nYou could consider using twisted to run the tasks because:\n\ntwisted has a well designed and tested implementation of asynchronous tasks; and\nyou could run the tasks on other processors or machines.\n\n"
] | [
0
] | [] | [] | [
"django",
"plugins",
"python"
] | stackoverflow_0002849118_django_plugins_python.txt |
Q:
Why is there {Raw,Safe}ConfigParser in Python 3?
Am surprised there's 3 different forms: RawConfigParser, SafeConfigParser and ConfigParser (docs). I read the differences but why isn't everyone using SafeConfigParser, since it seems, well, safe? I can understand that in the case for Python 2 that the other two were kept for backward compatibility.
UPDATE: In Python 3.2, SafeConfigParser has been renamed to ConfigParser, and the old ConfigParser has been removed (source: NEWS for Python 3.2).
A:
In short, use configparser.SafeConfigParser.
To quote the docs, SafeConfigParser "implements a more-sane variant of the magical interpolation feature. This implementation is more predictable as well. New applications should prefer this version if they don’t need to be compatible with older versions of Python."
It seems that the old ConfigParser still exists in Python 3 for backwards compatibility: not everything was made backward-incompatible!
| Why is there {Raw,Safe}ConfigParser in Python 3? | Am surprised there's 3 different forms: RawConfigParser, SafeConfigParser and ConfigParser (docs). I read the differences but why isn't everyone using SafeConfigParser, since it seems, well, safe? I can understand that in the case for Python 2 that the other two were kept for backward compatibility.
UPDATE: In Python 3.2, SafeConfigParser has been renamed to ConfigParser, and the old ConfigParser has been removed (source: NEWS for Python 3.2).
| [
"In short, use configparser.SafeConfigParser.\nTo quote the docs, SafeConfigParser \"implements a more-sane variant of the magical interpolation feature. This implementation is more predictable as well. New applications should prefer this version if they don’t need to be compatible with older versions of Python.\"\nIt seems that the old ConfigParser still exists in Python 3 for backwards compatibility: not everything was made backward-incompatible!\n"
] | [
13
] | [] | [] | [
"backwards_compatibility",
"python",
"python_3.x"
] | stackoverflow_0002848711_backwards_compatibility_python_python_3.x.txt |
Q:
Text in gtk.ComboBox without active item
The following PyGTk code, gives a combo-box without an active item.
This serves a case where we do not want to have a default,
and force the user to select.
Still, is there a way to have the empty combo-bar show something like:
"Select an item..."
without adding a dummy item?
import gtk
import sys
say = sys.stdout.write
def cb_changed(w):
say("Active index=%d\n" % w.get_active())
topwin = gtk.Window()
topwin.set_title("No Default")
topwin.set_size_request(0x100, 0x20)
topwin.connect('delete-event', gtk.main_quit)
vbox = gtk.VBox()
ls = gtk.ListStore(str, str)
combo = gtk.ComboBox(ls)
cell = gtk.CellRendererText()
combo.pack_start(cell)
combo.add_attribute(cell, 'text', 0)
combo.connect('changed', cb_changed)
ls.clear()
map(lambda i: ls.append(["Item-%d" % i, "Id%d" % i]), range(3))
vbox.pack_start(combo, padding=2)
topwin.add(vbox)
topwin.show_all()
gtk.main()
say("%s Exiting\n" % sys.argv[0])
sys.exit(0)
A:
Huge hack ahead (I just added this to your program):
import gtk
import sys
say = sys.stdout.write
def cb_changed(w):
say("Active index=%d\n" % w.get_active())
topwin = gtk.Window()
topwin.set_title("No Default")
topwin.set_size_request(0x100, 0x20)
topwin.connect('delete-event', gtk.main_quit)
vbox = gtk.VBox()
ls = gtk.ListStore(str, str)
combo = gtk.ComboBox(ls)
cell = gtk.CellRendererText()
combo.pack_start(cell)
combo.add_attribute(cell, 'text', 0)
combo.connect('changed', cb_changed)
#- Begin of the hack ----------------------------------
def special_empty_text (cell_view, event):
if cell_view.window is None:
return False
row = cell_view.get_displayed_row ()
if row is not None:
return False
layout = cell_view.create_pango_layout ('bla bla bla')
context = cell_view.window.cairo_create ()
xpad = 0
ypad = 0
renderer = cell_view.get_cells () [0]
if renderer is not None:
xpad = renderer.props.xpad
ypad = renderer.props.ypad
context.move_to (cell_view.allocation.x + xpad, cell_view.allocation.y + ypad)
context.set_source_rgb (0.6, 0.6, 0.6)
context.show_layout (layout)
return True
combo.child.connect ('expose-event', special_empty_text)
#- End of the hack ----------------------------------
ls.clear()
map(lambda i: ls.append(["Item-%d" % i, "Id%d" % i]), range(3))
vbox.pack_start(combo, padding=2)
topwin.add(vbox)
topwin.show_all()
gtk.main()
say("%s Exiting\n" % sys.argv[0])
sys.exit(0)
Don't see a nicer way.
| Text in gtk.ComboBox without active item | The following PyGTk code, gives a combo-box without an active item.
This serves a case where we do not want to have a default,
and force the user to select.
Still, is there a way to have the empty combo-bar show something like:
"Select an item..."
without adding a dummy item?
import gtk
import sys
say = sys.stdout.write
def cb_changed(w):
say("Active index=%d\n" % w.get_active())
topwin = gtk.Window()
topwin.set_title("No Default")
topwin.set_size_request(0x100, 0x20)
topwin.connect('delete-event', gtk.main_quit)
vbox = gtk.VBox()
ls = gtk.ListStore(str, str)
combo = gtk.ComboBox(ls)
cell = gtk.CellRendererText()
combo.pack_start(cell)
combo.add_attribute(cell, 'text', 0)
combo.connect('changed', cb_changed)
ls.clear()
map(lambda i: ls.append(["Item-%d" % i, "Id%d" % i]), range(3))
vbox.pack_start(combo, padding=2)
topwin.add(vbox)
topwin.show_all()
gtk.main()
say("%s Exiting\n" % sys.argv[0])
sys.exit(0)
| [
"Huge hack ahead (I just added this to your program):\nimport gtk\nimport sys\nsay = sys.stdout.write\n\ndef cb_changed(w):\n say(\"Active index=%d\\n\" % w.get_active())\n\ntopwin = gtk.Window()\ntopwin.set_title(\"No Default\")\ntopwin.set_size_request(0x100, 0x20)\ntopwin.connect('delete-event', gtk.main_quit)\nvbox = gtk.VBox()\n\nls = gtk.ListStore(str, str)\ncombo = gtk.ComboBox(ls)\ncell = gtk.CellRendererText()\ncombo.pack_start(cell)\ncombo.add_attribute(cell, 'text', 0)\ncombo.connect('changed', cb_changed)\n\n#- Begin of the hack ----------------------------------\ndef special_empty_text (cell_view, event):\n if cell_view.window is None:\n return False\n\n row = cell_view.get_displayed_row ()\n if row is not None:\n return False\n\n layout = cell_view.create_pango_layout ('bla bla bla')\n context = cell_view.window.cairo_create ()\n\n xpad = 0\n ypad = 0\n\n renderer = cell_view.get_cells () [0]\n if renderer is not None:\n xpad = renderer.props.xpad\n ypad = renderer.props.ypad\n\n context.move_to (cell_view.allocation.x + xpad, cell_view.allocation.y + ypad)\n context.set_source_rgb (0.6, 0.6, 0.6)\n context.show_layout (layout)\n\n return True\n\ncombo.child.connect ('expose-event', special_empty_text)\n#- End of the hack ----------------------------------\n\nls.clear()\nmap(lambda i: ls.append([\"Item-%d\" % i, \"Id%d\" % i]), range(3))\n\nvbox.pack_start(combo, padding=2)\ntopwin.add(vbox)\ntopwin.show_all()\n\ngtk.main()\nsay(\"%s Exiting\\n\" % sys.argv[0])\nsys.exit(0)\n\nDon't see a nicer way.\n"
] | [
0
] | [] | [] | [
"combobox",
"pygtk",
"python"
] | stackoverflow_0002845605_combobox_pygtk_python.txt |
Q:
django: unit testing html tags from response and sessions
Is there a way to test the html from the response of:
response = self.client.get('/user/login/')
I want a detailed check like input ids, and other attributes. Also, how about sessions that has been set? is it possible to check their values in the test?
A:
Careful.
Also, how about sessions that has been set? is it possible to check their values in the test?
TDD is about externally visible behavior. To see if the user has a session, you would provide a link that only works when the user is logged in and has a session.
The usual drill is something like the following.
class When_NoLogin( TestCase ):
def test_should_not_get_some_resource( self ):
response= self.client.get( "/path/that/requires/login" )
self.assertEquals( 301, response.status_code )
That is, when not logged in, some (or all) URI's redirect to the login page.
class When_Login( TestCase ):
def setUp( self ):
self.client.login( username='this', password='that' )
def test_should_get_some_resource( self ):
response= self.client.get( "/path/that/requires/login" )
self.assertContains( response, '<input attr="this"', status_code=200 )
self.assertContains( response, '<tr class="that"', count=5 )
https://docs.djangoproject.com/en/dev/topics/testing/tools/#django.test.SimpleTestCase.assertContains
That is, when logged in, some (or all) URI's work as expected.
Further, the URI response contains the tags you require.
You don't test Django to see if it creates a session. Django already has unit tests for this. You test your application's externally visible behavior -- does it behave like there's a session? Are pages properly visible? Are they properly customized with session-specific information?
A:
Not sure, but take a look at https://docs.djangoproject.com/en/dev/topics/testing/tools/#testing-responses.
response.context is maybe a way to check your values.
A:
Simon Willison's soup-select is a nice way to test the content of an HTML response based on jQuery-like CSS selectors. So, for example, to check that your page has an input with ID my_input_id:
from BeautifulSoup import BeautifulSoup as Soup
from soupselect import select
response = self.client.get('/user/login/')
soup = Soup(response.content)
self.assertEquals(len(select(soup, 'input#my_input_id')), 1)
| django: unit testing html tags from response and sessions | Is there a way to test the html from the response of:
response = self.client.get('/user/login/')
I want a detailed check like input ids, and other attributes. Also, how about sessions that has been set? is it possible to check their values in the test?
| [
"Careful.\n\nAlso, how about sessions that has been set? is it possible to check their values in the test?\n\nTDD is about externally visible behavior. To see if the user has a session, you would provide a link that only works when the user is logged in and has a session. \nThe usual drill is something like the following.\nclass When_NoLogin( TestCase ):\n def test_should_not_get_some_resource( self ):\n response= self.client.get( \"/path/that/requires/login\" )\n self.assertEquals( 301, response.status_code )\n\nThat is, when not logged in, some (or all) URI's redirect to the login page.\nclass When_Login( TestCase ):\n def setUp( self ):\n self.client.login( username='this', password='that' )\n def test_should_get_some_resource( self ):\n response= self.client.get( \"/path/that/requires/login\" )\n self.assertContains( response, '<input attr=\"this\"', status_code=200 )\n self.assertContains( response, '<tr class=\"that\"', count=5 )\n\nhttps://docs.djangoproject.com/en/dev/topics/testing/tools/#django.test.SimpleTestCase.assertContains\nThat is, when logged in, some (or all) URI's work as expected.\nFurther, the URI response contains the tags you require.\nYou don't test Django to see if it creates a session. Django already has unit tests for this. You test your application's externally visible behavior -- does it behave like there's a session? Are pages properly visible? Are they properly customized with session-specific information?\n",
"Not sure, but take a look at https://docs.djangoproject.com/en/dev/topics/testing/tools/#testing-responses.\nresponse.context is maybe a way to check your values.\n",
"Simon Willison's soup-select is a nice way to test the content of an HTML response based on jQuery-like CSS selectors. So, for example, to check that your page has an input with ID my_input_id:\nfrom BeautifulSoup import BeautifulSoup as Soup\nfrom soupselect import select\nresponse = self.client.get('/user/login/')\nsoup = Soup(response.content)\nself.assertEquals(len(select(soup, 'input#my_input_id')), 1)\n\n"
] | [
10,
8,
6
] | [] | [] | [
"django",
"python",
"unit_testing"
] | stackoverflow_0002849457_django_python_unit_testing.txt |
Q:
google app engine: go to login page by javascript?
Do anyone know how do use javascript to redirect user login using Google Accounts?
I know there is "users.create_login_url(self.request.path)" but how do that integrated to "`window.location"
Or there is alternative??
A:
You should be able to pass the string that is created by users.create_login_url(self.request.path) to your template as a template variable, and then the template variable can be inserted into your Javascript with double curly braces (if you are using the bundled Django templates):
window.location = {{ authention_url }}
where authentication_url is the template variable that you created in your RequestHandler.
A:
My fault, I dont even know that users.create_login_url(self.request.path) will generate a string, simply print it out will do.
| google app engine: go to login page by javascript? | Do anyone know how do use javascript to redirect user login using Google Accounts?
I know there is "users.create_login_url(self.request.path)" but how do that integrated to "`window.location"
Or there is alternative??
| [
"You should be able to pass the string that is created by users.create_login_url(self.request.path) to your template as a template variable, and then the template variable can be inserted into your Javascript with double curly braces (if you are using the bundled Django templates):\nwindow.location = {{ authention_url }}\n\nwhere authentication_url is the template variable that you created in your RequestHandler.\n",
"My fault, I dont even know that users.create_login_url(self.request.path) will generate a string, simply print it out will do.\n"
] | [
2,
0
] | [] | [] | [
"google_app_engine",
"javascript",
"python"
] | stackoverflow_0002850074_google_app_engine_javascript_python.txt |
Q:
Producing a static HTML site from XML content
I have a long document in XML from which I need to produce static HTML pages (for distribution via CD). I know (to varying degrees) JavaScript, PHP and Python. The current options I've considered are listed here:
I'm not ruling out JavaScript, so one option would be to use ajax to dynamically load the XML content into HTML pages. Edit: I'd use jQuery for this option.
Learn some basic XSLT and produce HTML to the correct spec this way.
Produce the site with PHP (for example) and then generate a static site.
Write a script (in Python for example) to convert the XML into HTML. This is similar to the XSLT option but without having to learn XSLT.
Useful information:
The XML will likely change at some point, so I'd like to be able to easily regenerate the site.
I'll have to produce some kind of menu for jumping around the document (so I'll need to produce some kind of index of the content).
I'd like to know if anyone has any better ideas that I haven't thought of. If not, I'd like you to tell me which of my options seems the most sensible. I think I know what I'm going to do, but I'd like a second opinion. Thanks.
A:
I think XSLT is by far the easiest and best method -- even taking into account having to learn xslt.
There are several styles of xslt programming, but the easiest is "push processing" , where you write several templates that describe how your xml input is to be transformed into html output. Then you write a root template that outputs the basic html wrapper and calls the other templates. The root
template is the easy one:
<xsl:template match="/" > <!-- "/" matches the document root -->
<html> <!-- whatever is not in xsl: namespace is template output -->
<head><title>...</title></head>
<body>
<xsl:apply-templates /> <!-- this searches for and calls additional template matches -->
</body>
</html>
</xsl:template>
A:
I would go with the XSLT option, controlled via parameters to generate different pages from the same XML source if needed. It's really the tool made for XML transformations.
A:
I would go with the PHP option. The reason being is that when the XML changes your site content "should" automatically change without you having to touch your PHP code.
Creating a Python script to generate lots of static pages just seems like a bad idea to me and with javascript you will have your cross-browser headaches (unless you are using a framework maybe).
Use the server side languages for these kind of tasks, it is what they were made for.
A:
Go with what you are most comfortable with.
If it's straightforward you could use (for example) php to generate a page and then use a command line script (in python or php) to create cached files for you.
| Producing a static HTML site from XML content | I have a long document in XML from which I need to produce static HTML pages (for distribution via CD). I know (to varying degrees) JavaScript, PHP and Python. The current options I've considered are listed here:
I'm not ruling out JavaScript, so one option would be to use ajax to dynamically load the XML content into HTML pages. Edit: I'd use jQuery for this option.
Learn some basic XSLT and produce HTML to the correct spec this way.
Produce the site with PHP (for example) and then generate a static site.
Write a script (in Python for example) to convert the XML into HTML. This is similar to the XSLT option but without having to learn XSLT.
Useful information:
The XML will likely change at some point, so I'd like to be able to easily regenerate the site.
I'll have to produce some kind of menu for jumping around the document (so I'll need to produce some kind of index of the content).
I'd like to know if anyone has any better ideas that I haven't thought of. If not, I'd like you to tell me which of my options seems the most sensible. I think I know what I'm going to do, but I'd like a second opinion. Thanks.
| [
"I think XSLT is by far the easiest and best method -- even taking into account having to learn xslt. \nThere are several styles of xslt programming, but the easiest is \"push processing\" , where you write several templates that describe how your xml input is to be transformed into html output. Then you write a root template that outputs the basic html wrapper and calls the other templates. The root\ntemplate is the easy one:\n<xsl:template match=\"/\" > <!-- \"/\" matches the document root -->\n <html> <!-- whatever is not in xsl: namespace is template output -->\n <head><title>...</title></head>\n <body>\n <xsl:apply-templates /> <!-- this searches for and calls additional template matches --> \n </body>\n </html>\n</xsl:template> \n\n",
"I would go with the XSLT option, controlled via parameters to generate different pages from the same XML source if needed. It's really the tool made for XML transformations.\n",
"I would go with the PHP option. The reason being is that when the XML changes your site content \"should\" automatically change without you having to touch your PHP code.\nCreating a Python script to generate lots of static pages just seems like a bad idea to me and with javascript you will have your cross-browser headaches (unless you are using a framework maybe).\nUse the server side languages for these kind of tasks, it is what they were made for.\n",
"Go with what you are most comfortable with.\nIf it's straightforward you could use (for example) php to generate a page and then use a command line script (in python or php) to create cached files for you.\n"
] | [
4,
2,
1,
0
] | [] | [] | [
"ajax",
"html",
"python",
"xml",
"xslt"
] | stackoverflow_0002850534_ajax_html_python_xml_xslt.txt |
Q:
What's the standard config file name and extension in Python?
I'm creating a config file to hold configuration/properties settings for my project that frequently change, such as file paths. What's the standard name/extension for such a file? (e.g. in Java I've used config.xml, in VB.NET I've used App.config...)
A:
Ok, I've asked around where I work and researched a little, and this is what I've come up with as suggestions:
settings.ini
applicationName.config
applicationName.cfg
If anyone has any other suggestions, feel free to add...
A:
First, consider using ConfigParser (configparser in 3.0, so the documentation says). That doesn't solve the naming problem, but it is a readable alternative to xml for most configuration needs.
Whatever name you use, make all the parts meaningful. I would probably use something like appName.cfg, where appName identifies your application, or the part of the application the configuration is for.
A:
The docs seem to use .cfg
On Windows, many people (such as mercurial) use .ini
| What's the standard config file name and extension in Python? | I'm creating a config file to hold configuration/properties settings for my project that frequently change, such as file paths. What's the standard name/extension for such a file? (e.g. in Java I've used config.xml, in VB.NET I've used App.config...)
| [
"Ok, I've asked around where I work and researched a little, and this is what I've come up with as suggestions:\n\nsettings.ini\napplicationName.config\napplicationName.cfg\n\nIf anyone has any other suggestions, feel free to add...\n",
"First, consider using ConfigParser (configparser in 3.0, so the documentation says). That doesn't solve the naming problem, but it is a readable alternative to xml for most configuration needs.\nWhatever name you use, make all the parts meaningful. I would probably use something like appName.cfg, where appName identifies your application, or the part of the application the configuration is for.\n",
"The docs seem to use .cfg\nOn Windows, many people (such as mercurial) use .ini\n"
] | [
12,
7,
4
] | [] | [] | [
"config",
"file_extension",
"filenames",
"python"
] | stackoverflow_0002850084_config_file_extension_filenames_python.txt |
Q:
Multiple XML Namespaces in tag with LXML
I am trying to use Pythons LXML library to create a GPX file that can be read by Garmin's Mapsource Product. The header on their GPX files looks like this
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<gpx xmlns="http://www.topografix.com/GPX/1/1"
creator="MapSource 6.15.5" version="1.1"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd">
When I use the following code:
xmlns = "http://www.topografix.com/GPX/1/1"
xsi = "http://www.w3.org/2001/XMLSchema-instance"
schemaLocation = "http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd"
version = "1.1"
ns = "{xsi}"
getXML = etree.Element("{" + xmlns + "}gpx", version=version, attrib={"{xsi}schemaLocation": schemaLocation}, creator='My Product', nsmap={'xsi': xsi, None: xmlns})
print(etree.tostring(getXML, xml_declaration=True, standalone='Yes', encoding="UTF-8", pretty_print=True))
I get:
<?xml version=\'1.0\' encoding=\'UTF-8\' standalone=\'yes\'?>
<gpx xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.topografix.com/GPX/1/1" xmlns:ns0="xsi"
ns0:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd"
version="1.1" creator="My Product"/>
Which has the annoying ns0 tag. This might be perfectly valid XML but Mapsource does not appreciate it.
Any idea how to get this to not have the ns0 tag?
A:
The problem is with your attribute name.
attrib={"{xsi}schemaLocation" : schemaLocation},
puts schemaLocation in the xsi namespace.
I think you meant
attrib={"{" + xsi + "}schemaLocation" : schemaLocation}
to use the URL for xsi. This matches your uses of namespace variables in the element name. It puts the attribute in the http://www.w3.org/2001/XMLSchema-instance namespace
That gives the result of
<?xml version='1.0' encoding='UTF-8' standalone='yes'?>
<gpx xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.topografix.com/GPX/1/1"
xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd"
version="1.1"
creator="My Product"/>
| Multiple XML Namespaces in tag with LXML | I am trying to use Pythons LXML library to create a GPX file that can be read by Garmin's Mapsource Product. The header on their GPX files looks like this
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<gpx xmlns="http://www.topografix.com/GPX/1/1"
creator="MapSource 6.15.5" version="1.1"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd">
When I use the following code:
xmlns = "http://www.topografix.com/GPX/1/1"
xsi = "http://www.w3.org/2001/XMLSchema-instance"
schemaLocation = "http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd"
version = "1.1"
ns = "{xsi}"
getXML = etree.Element("{" + xmlns + "}gpx", version=version, attrib={"{xsi}schemaLocation": schemaLocation}, creator='My Product', nsmap={'xsi': xsi, None: xmlns})
print(etree.tostring(getXML, xml_declaration=True, standalone='Yes', encoding="UTF-8", pretty_print=True))
I get:
<?xml version=\'1.0\' encoding=\'UTF-8\' standalone=\'yes\'?>
<gpx xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.topografix.com/GPX/1/1" xmlns:ns0="xsi"
ns0:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd"
version="1.1" creator="My Product"/>
Which has the annoying ns0 tag. This might be perfectly valid XML but Mapsource does not appreciate it.
Any idea how to get this to not have the ns0 tag?
| [
"The problem is with your attribute name.\nattrib={\"{xsi}schemaLocation\" : schemaLocation},\n\nputs schemaLocation in the xsi namespace. \nI think you meant\nattrib={\"{\" + xsi + \"}schemaLocation\" : schemaLocation}\n\nto use the URL for xsi. This matches your uses of namespace variables in the element name. It puts the attribute in the http://www.w3.org/2001/XMLSchema-instance namespace \nThat gives the result of\n<?xml version='1.0' encoding='UTF-8' standalone='yes'?>\n<gpx xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n xmlns=\"http://www.topografix.com/GPX/1/1\" \n xsi:schemaLocation=\"http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd\" \n version=\"1.1\" \n creator=\"My Product\"/>\n\n"
] | [
16
] | [] | [] | [
"gpx",
"lxml",
"python",
"xml"
] | stackoverflow_0002850823_gpx_lxml_python_xml.txt |
Q:
Why isn't pyinstaller making me an .exe file?
I am attempting to follow this guide to make a simple Hello World script into an .exe file.
I have Windows Vista with an AMD 64-bit processor
I have installed Python 2.6.5 (Windows AMD64 version)
I have set the PATH (if that's the right word) so that the command line recognizes Python
I have installed UPX (there only seems to be a 32-bit version for Windows) and pasted a copy of upx.exe into the Python26 folder as instructed.
I have installed Pywin (Windows AMD 64 Python 2.6 version)
I have run Pyinstaller's Configure.py. It gives some error messages but seems to complete. I don't know if this is what's causing the problem, so the following is what it says when I run it:
C:\Python26\Pyinstaller\branches\py26win>Configure.py
I: read old config from C:\Python26\Pyinstaller\branches\py26win\config.dat
I: computing EXE_dependencies
I: Finding TCL/TK...
I: Analyzing C:\Python26\DLLs_tkinter.pyd
W: Cannot get binary dependencies for file:
W: C:\Python26\DLLs_tkinter.pyd
W: Traceback (most recent call last):
File "C:\Python26\Pyinstaller\branches\py26win\bindepend.py", line 608, in get
Imports
return _getImports_pe(pth)
File "C:\Python26\Pyinstaller\branches\py26win\bindepend.py", line 275, in _ge
tImports_pe
importva, importsz = datadirs[1]
IndexError: list index out of range
I: Analyzing C:\Python26\DLLs_ctypes.pyd
W: Cannot get binary dependencies for file:
W: C:\Python26\DLLs_ctypes.pyd
W: Traceback (most recent call last):
File "C:\Python26\Pyinstaller\branches\py26win\bindepend.py", line 608, in get
Imports
return _getImports_pe(pth)
File "C:\Python26\Pyinstaller\branches\py26win\bindepend.py", line 275, in _ge
tImports_pe
importva, importsz = datadirs[1]
IndexError: list index out of range
I: Analyzing C:\Python26\DLLs\select.pyd
W: Cannot get binary dependencies for file:
W: C:\Python26\DLLs\select.pyd
W: Traceback (most recent call last):
File "C:\Python26\Pyinstaller\branches\py26win\bindepend.py", line 608, in get
Imports
return _getImports_pe(pth)
File "C:\Python26\Pyinstaller\branches\py26win\bindepend.py", line 275, in _ge
tImports_pe
importva, importsz = datadirs[1]
IndexError: list index out of range
I: Analyzing C:\Python26\DLLs\unicodedata.pyd
W: Cannot get binary dependencies for file:
W: C:\Python26\DLLs\unicodedata.pyd
W: Traceback (most recent call last):
File "C:\Python26\Pyinstaller\branches\py26win\bindepend.py", line 608, in get
Imports
return _getImports_pe(pth)
File "C:\Python26\Pyinstaller\branches\py26win\bindepend.py", line 275, in _ge
tImports_pe
importva, importsz = datadirs[1]
IndexError: list index out of range
I: Analyzing C:\Python26\DLLs\bz2.pyd
W: Cannot get binary dependencies for file:
W: C:\Python26\DLLs\bz2.pyd
W: Traceback (most recent call last):
File "C:\Python26\Pyinstaller\branches\py26win\bindepend.py", line 608, in get
Imports
return _getImports_pe(pth)
File "C:\Python26\Pyinstaller\branches\py26win\bindepend.py", line 275, in _ge
tImports_pe
importva, importsz = datadirs[1]
IndexError: list index out of range
I: Analyzing C:\Python26\python.exe
I: Dependent assemblies of C:\Python26\python.exe:
I: amd64_Microsoft.VC90.CRT_1fc8b3b9a1e18e3b_9.0.21022.8_none
I: Searching for assembly amd64_Microsoft.VC90.CRT_1fc8b3b9a1e18e3b_9.0.21022.8_
none...
I: Found manifest C:\Windows\WinSxS\Manifests\amd64_microsoft.vc90.crt_1fc8b3b9a
1e18e3b_9.0.21022.8_none_750b37ff97f4f68b.manifest
I: Searching for file msvcr90.dll
I: Found file C:\Windows\WinSxS\amd64_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.21
022.8_none_750b37ff97f4f68b\msvcr90.dll
I: Searching for file msvcp90.dll
I: Found file C:\Windows\WinSxS\amd64_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.21
022.8_none_750b37ff97f4f68b\msvcp90.dll
I: Searching for file msvcm90.dll
I: Found file C:\Windows\WinSxS\amd64_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.21
022.8_none_750b37ff97f4f68b\msvcm90.dll
I: Adding Microsoft.VC90.CRT\Microsoft.VC90.CRT.manifest
I: Adding Microsoft.VC90.CRT\msvcr90.dll
I: Adding Microsoft.VC90.CRT\msvcp90.dll
I: Adding Microsoft.VC90.CRT\msvcm90.dll
W: Cannot get binary dependencies for file:
W: C:\Python26\python.exe
W: Traceback (most recent call last):
File "C:\Python26\Pyinstaller\branches\py26win\bindepend.py", line 608, in get
Imports
return _getImports_pe(pth)
File "C:\Python26\Pyinstaller\branches\py26win\bindepend.py", line 275, in _ge
tImports_pe
importva, importsz = datadirs[1]
IndexError: list index out of range
I: Analyzing C:\Windows\WinSxS\Manifests\amd64_microsoft.vc90.crt_1fc8b3b9a1e18e
3b_9.0.21022.8_none_750b37ff97f4f68b.manifest
I: Analyzing C:\Windows\WinSxS\amd64_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.210
22.8_none_750b37ff97f4f68b\msvcr90.dll
W: Cannot get binary dependencies for file:
W: C:\Windows\WinSxS\amd64_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.21022.8_none_
750b37ff97f4f68b\msvcr90.dll
W: Traceback (most recent call last):
File "C:\Python26\Pyinstaller\branches\py26win\bindepend.py", line 608, in get
Imports
return _getImports_pe(pth)
File "C:\Python26\Pyinstaller\branches\py26win\bindepend.py", line 275, in _ge
tImports_pe
importva, importsz = datadirs[1]
IndexError: list index out of range
I: Analyzing C:\Windows\WinSxS\amd64_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.210
22.8_none_750b37ff97f4f68b\msvcp90.dll
W: Cannot get binary dependencies for file:
W: C:\Windows\WinSxS\amd64_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.21022.8_none_
750b37ff97f4f68b\msvcp90.dll
W: Traceback (most recent call last):
File "C:\Python26\Pyinstaller\branches\py26win\bindepend.py", line 608, in get
Imports
return _getImports_pe(pth)
File "C:\Python26\Pyinstaller\branches\py26win\bindepend.py", line 275, in _ge
tImports_pe
importva, importsz = datadirs[1]
IndexError: list index out of range
I: Analyzing C:\Windows\WinSxS\amd64_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.210
22.8_none_750b37ff97f4f68b\msvcm90.dll
W: Cannot get binary dependencies for file:
W: C:\Windows\WinSxS\amd64_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.21022.8_none_
750b37ff97f4f68b\msvcm90.dll
W: Traceback (most recent call last):
File "C:\Python26\Pyinstaller\branches\py26win\bindepend.py", line 608, in get
Imports
return _getImports_pe(pth)
File "C:\Python26\Pyinstaller\branches\py26win\bindepend.py", line 275, in _ge
tImports_pe
importva, importsz = datadirs[1]
IndexError: list index out of range
I: could not find TCL/TK
I: testing for Zlib...
I: ... Zlib available
I: Testing for ability to set icons, version resources...
I: ... resource update available
I: Testing for Unicode support...
I: ... Unicode available
I: testing for UPX...
I: ...UPX available
I: computing PYZ dependencies...
I: done generating C:\Python26\Pyinstaller\branches\py26win\config.dat
My Python script (named Hello.py) is the same as the example:
#!/usr/bin/env python
for i in xrange(10000):
print "Hello, World!"
This is my BAT file, in the same directory:
set PIP=C:\Python26\Pyinstaller\branches\py26win\
python %PIP%Makespec.py --onefile --console --upx --tk Hello.py
python %PIP%Build.py Hello.spec
When I run Hello.bat in the command prompt several files are made, none of which are an .exe file, and the following is displayed:
C:\My Files>set PIP=C:\Python26\Pyinstaller\branches\py26win\
C:\My Files>python C:\Python26\Pyinstaller\branches\py26win\Makespec.py --onefil
e --console --upx --tk Hello.py
wrote C:\My Files\Hello.spec
now run Build.py to build the executable
C:\My Files>python C:\Python26\Pyinstaller\branches\py26win\Build.py Hello.spec
I: Dependent assemblies of C:\Python26\python.exe:
I: amd64_Microsoft.VC90.CRT_1fc8b3b9a1e18e3b_9.0.21022.8_none
Traceback (most recent call last):
File "C:\Python26\Pyinstaller\branches\py26win\Build.py", line 1359, in
main(args[0], configfilename=opts.configfile)
File "C:\Python26\Pyinstaller\branches\py26win\Build.py", line 1337, in main
build(specfile)
File "C:\Python26\Pyinstaller\branches\py26win\Build.py", line 1297, in build
execfile(spec)
File "Hello.spec", line 3, in
pathex=['C:\My Files'])
File "C:\Python26\Pyinstaller\branches\py26win\Build.py", line 292, in __init_
_
raise ValueError, "script '%s' not found" % script
ValueError: script 'C:\Python26\Pyinstaller\branches\py26win\support\useTK.py' n
ot found
I have limited knowledge with the command prompt, so please take baby steps with me if I need to do something there.
A:
64-bit Python is not supported by pyinstaller under Windows. There's normally no drawback when using 32-bit Python under a 64-bit environment, though, so the easiest option is to install and use that. It also has the added benefit that a executable generated by pyinstaller will work under both 32-bit and 64-bit Windows.
| Why isn't pyinstaller making me an .exe file? | I am attempting to follow this guide to make a simple Hello World script into an .exe file.
I have Windows Vista with an AMD 64-bit processor
I have installed Python 2.6.5 (Windows AMD64 version)
I have set the PATH (if that's the right word) so that the command line recognizes Python
I have installed UPX (there only seems to be a 32-bit version for Windows) and pasted a copy of upx.exe into the Python26 folder as instructed.
I have installed Pywin (Windows AMD 64 Python 2.6 version)
I have run Pyinstaller's Configure.py. It gives some error messages but seems to complete. I don't know if this is what's causing the problem, so the following is what it says when I run it:
C:\Python26\Pyinstaller\branches\py26win>Configure.py
I: read old config from C:\Python26\Pyinstaller\branches\py26win\config.dat
I: computing EXE_dependencies
I: Finding TCL/TK...
I: Analyzing C:\Python26\DLLs_tkinter.pyd
W: Cannot get binary dependencies for file:
W: C:\Python26\DLLs_tkinter.pyd
W: Traceback (most recent call last):
File "C:\Python26\Pyinstaller\branches\py26win\bindepend.py", line 608, in get
Imports
return _getImports_pe(pth)
File "C:\Python26\Pyinstaller\branches\py26win\bindepend.py", line 275, in _ge
tImports_pe
importva, importsz = datadirs[1]
IndexError: list index out of range
I: Analyzing C:\Python26\DLLs_ctypes.pyd
W: Cannot get binary dependencies for file:
W: C:\Python26\DLLs_ctypes.pyd
W: Traceback (most recent call last):
File "C:\Python26\Pyinstaller\branches\py26win\bindepend.py", line 608, in get
Imports
return _getImports_pe(pth)
File "C:\Python26\Pyinstaller\branches\py26win\bindepend.py", line 275, in _ge
tImports_pe
importva, importsz = datadirs[1]
IndexError: list index out of range
I: Analyzing C:\Python26\DLLs\select.pyd
W: Cannot get binary dependencies for file:
W: C:\Python26\DLLs\select.pyd
W: Traceback (most recent call last):
File "C:\Python26\Pyinstaller\branches\py26win\bindepend.py", line 608, in get
Imports
return _getImports_pe(pth)
File "C:\Python26\Pyinstaller\branches\py26win\bindepend.py", line 275, in _ge
tImports_pe
importva, importsz = datadirs[1]
IndexError: list index out of range
I: Analyzing C:\Python26\DLLs\unicodedata.pyd
W: Cannot get binary dependencies for file:
W: C:\Python26\DLLs\unicodedata.pyd
W: Traceback (most recent call last):
File "C:\Python26\Pyinstaller\branches\py26win\bindepend.py", line 608, in get
Imports
return _getImports_pe(pth)
File "C:\Python26\Pyinstaller\branches\py26win\bindepend.py", line 275, in _ge
tImports_pe
importva, importsz = datadirs[1]
IndexError: list index out of range
I: Analyzing C:\Python26\DLLs\bz2.pyd
W: Cannot get binary dependencies for file:
W: C:\Python26\DLLs\bz2.pyd
W: Traceback (most recent call last):
File "C:\Python26\Pyinstaller\branches\py26win\bindepend.py", line 608, in get
Imports
return _getImports_pe(pth)
File "C:\Python26\Pyinstaller\branches\py26win\bindepend.py", line 275, in _ge
tImports_pe
importva, importsz = datadirs[1]
IndexError: list index out of range
I: Analyzing C:\Python26\python.exe
I: Dependent assemblies of C:\Python26\python.exe:
I: amd64_Microsoft.VC90.CRT_1fc8b3b9a1e18e3b_9.0.21022.8_none
I: Searching for assembly amd64_Microsoft.VC90.CRT_1fc8b3b9a1e18e3b_9.0.21022.8_
none...
I: Found manifest C:\Windows\WinSxS\Manifests\amd64_microsoft.vc90.crt_1fc8b3b9a
1e18e3b_9.0.21022.8_none_750b37ff97f4f68b.manifest
I: Searching for file msvcr90.dll
I: Found file C:\Windows\WinSxS\amd64_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.21
022.8_none_750b37ff97f4f68b\msvcr90.dll
I: Searching for file msvcp90.dll
I: Found file C:\Windows\WinSxS\amd64_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.21
022.8_none_750b37ff97f4f68b\msvcp90.dll
I: Searching for file msvcm90.dll
I: Found file C:\Windows\WinSxS\amd64_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.21
022.8_none_750b37ff97f4f68b\msvcm90.dll
I: Adding Microsoft.VC90.CRT\Microsoft.VC90.CRT.manifest
I: Adding Microsoft.VC90.CRT\msvcr90.dll
I: Adding Microsoft.VC90.CRT\msvcp90.dll
I: Adding Microsoft.VC90.CRT\msvcm90.dll
W: Cannot get binary dependencies for file:
W: C:\Python26\python.exe
W: Traceback (most recent call last):
File "C:\Python26\Pyinstaller\branches\py26win\bindepend.py", line 608, in get
Imports
return _getImports_pe(pth)
File "C:\Python26\Pyinstaller\branches\py26win\bindepend.py", line 275, in _ge
tImports_pe
importva, importsz = datadirs[1]
IndexError: list index out of range
I: Analyzing C:\Windows\WinSxS\Manifests\amd64_microsoft.vc90.crt_1fc8b3b9a1e18e
3b_9.0.21022.8_none_750b37ff97f4f68b.manifest
I: Analyzing C:\Windows\WinSxS\amd64_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.210
22.8_none_750b37ff97f4f68b\msvcr90.dll
W: Cannot get binary dependencies for file:
W: C:\Windows\WinSxS\amd64_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.21022.8_none_
750b37ff97f4f68b\msvcr90.dll
W: Traceback (most recent call last):
File "C:\Python26\Pyinstaller\branches\py26win\bindepend.py", line 608, in get
Imports
return _getImports_pe(pth)
File "C:\Python26\Pyinstaller\branches\py26win\bindepend.py", line 275, in _ge
tImports_pe
importva, importsz = datadirs[1]
IndexError: list index out of range
I: Analyzing C:\Windows\WinSxS\amd64_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.210
22.8_none_750b37ff97f4f68b\msvcp90.dll
W: Cannot get binary dependencies for file:
W: C:\Windows\WinSxS\amd64_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.21022.8_none_
750b37ff97f4f68b\msvcp90.dll
W: Traceback (most recent call last):
File "C:\Python26\Pyinstaller\branches\py26win\bindepend.py", line 608, in get
Imports
return _getImports_pe(pth)
File "C:\Python26\Pyinstaller\branches\py26win\bindepend.py", line 275, in _ge
tImports_pe
importva, importsz = datadirs[1]
IndexError: list index out of range
I: Analyzing C:\Windows\WinSxS\amd64_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.210
22.8_none_750b37ff97f4f68b\msvcm90.dll
W: Cannot get binary dependencies for file:
W: C:\Windows\WinSxS\amd64_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.21022.8_none_
750b37ff97f4f68b\msvcm90.dll
W: Traceback (most recent call last):
File "C:\Python26\Pyinstaller\branches\py26win\bindepend.py", line 608, in get
Imports
return _getImports_pe(pth)
File "C:\Python26\Pyinstaller\branches\py26win\bindepend.py", line 275, in _ge
tImports_pe
importva, importsz = datadirs[1]
IndexError: list index out of range
I: could not find TCL/TK
I: testing for Zlib...
I: ... Zlib available
I: Testing for ability to set icons, version resources...
I: ... resource update available
I: Testing for Unicode support...
I: ... Unicode available
I: testing for UPX...
I: ...UPX available
I: computing PYZ dependencies...
I: done generating C:\Python26\Pyinstaller\branches\py26win\config.dat
My Python script (named Hello.py) is the same as the example:
#!/usr/bin/env python
for i in xrange(10000):
print "Hello, World!"
This is my BAT file, in the same directory:
set PIP=C:\Python26\Pyinstaller\branches\py26win\
python %PIP%Makespec.py --onefile --console --upx --tk Hello.py
python %PIP%Build.py Hello.spec
When I run Hello.bat in the command prompt several files are made, none of which are an .exe file, and the following is displayed:
C:\My Files>set PIP=C:\Python26\Pyinstaller\branches\py26win\
C:\My Files>python C:\Python26\Pyinstaller\branches\py26win\Makespec.py --onefil
e --console --upx --tk Hello.py
wrote C:\My Files\Hello.spec
now run Build.py to build the executable
C:\My Files>python C:\Python26\Pyinstaller\branches\py26win\Build.py Hello.spec
I: Dependent assemblies of C:\Python26\python.exe:
I: amd64_Microsoft.VC90.CRT_1fc8b3b9a1e18e3b_9.0.21022.8_none
Traceback (most recent call last):
File "C:\Python26\Pyinstaller\branches\py26win\Build.py", line 1359, in
main(args[0], configfilename=opts.configfile)
File "C:\Python26\Pyinstaller\branches\py26win\Build.py", line 1337, in main
build(specfile)
File "C:\Python26\Pyinstaller\branches\py26win\Build.py", line 1297, in build
execfile(spec)
File "Hello.spec", line 3, in
pathex=['C:\My Files'])
File "C:\Python26\Pyinstaller\branches\py26win\Build.py", line 292, in __init_
_
raise ValueError, "script '%s' not found" % script
ValueError: script 'C:\Python26\Pyinstaller\branches\py26win\support\useTK.py' n
ot found
I have limited knowledge with the command prompt, so please take baby steps with me if I need to do something there.
| [
"64-bit Python is not supported by pyinstaller under Windows. There's normally no drawback when using 32-bit Python under a 64-bit environment, though, so the easiest option is to install and use that. It also has the added benefit that a executable generated by pyinstaller will work under both 32-bit and 64-bit Windows.\n"
] | [
6
] | [] | [] | [
"pyinstaller",
"python"
] | stackoverflow_0002831602_pyinstaller_python.txt |
Q:
How can I lookup an attribute in any scope by name?
How can I lookup an attribute in any scope by name? My first trial is to use globals() and locals(). e.g.
>>> def foo(name):
... a=1
... print globals().get(name), locals().get(name)
...
>>> foo('a')
None 1
>>> b=1
>>> foo('b')
1 None
>>> foo('foo')
<function foo at 0x014744B0> None
So far so good. However it fails to lookup any built-in names.
>>> range
<built-in function range>
>>> foo('range')
None None
>>> int
<type 'int'>
>>> foo('int')
None None
Any idea on how to lookup built-in attributes?
A:
>>> getattr(__builtins__, 'range')
<built-in function range>
A:
Use __builtin__ (without the s at the end like Triptych and Duncan suggest):
>>> import __builtin__
>>> getattr(__builtin__, 'range')
<built-in function range>
__builtins__ is CPython-implementation specific thus makes your code less portable.
A:
Use the __builtins__ "superglobal". It contains exactly what you're looking for
| How can I lookup an attribute in any scope by name? | How can I lookup an attribute in any scope by name? My first trial is to use globals() and locals(). e.g.
>>> def foo(name):
... a=1
... print globals().get(name), locals().get(name)
...
>>> foo('a')
None 1
>>> b=1
>>> foo('b')
1 None
>>> foo('foo')
<function foo at 0x014744B0> None
So far so good. However it fails to lookup any built-in names.
>>> range
<built-in function range>
>>> foo('range')
None None
>>> int
<type 'int'>
>>> foo('int')
None None
Any idea on how to lookup built-in attributes?
| [
">>> getattr(__builtins__, 'range')\n<built-in function range>\n\n",
"Use __builtin__ (without the s at the end like Triptych and Duncan suggest):\n>>> import __builtin__\n>>> getattr(__builtin__, 'range')\n<built-in function range>\n\n__builtins__ is CPython-implementation specific thus makes your code less portable.\n",
"Use the __builtins__ \"superglobal\". It contains exactly what you're looking for\n"
] | [
4,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0002850966_python.txt |
Q:
Parent Thread exiting before Child Threads [python]
I'm using Python in a webapp (CGI for testing, FastCGI for production) that needs to send an occasional email (when a user registers or something else important happens). Since communicating with an SMTP server takes a long time, I'd like to spawn a thread for the mail function so that the rest of the app can finish up the request without waiting for the email to finish sending.
I tried using thread.start_new(func, (args)), but the Parent return's and exits before the sending is complete, thereby killing the sending process before it does anything useful. Is there anyway to keep the process alive long enough for the child process to finish?
A:
Take a look at the thread.join() method. Basically it will block your calling thread until the child thread has returned (thus preventing it from exiting before it should).
Update:
To avoid making your main thread unresponsive to new requests you can use a while loop.
while threading.active_count() > 0:
# ... look for new requests to handle ...
time.sleep(0.1)
# or try joining your threads with a timeout
#for thread in my_threads:
# thread.join(0.1)
Update 2:
It also looks like thread.start_new(func, args) is obsolete. It was updated to thread.start_new_thread(function, args[, kwargs]) You can also create threads with the higher level threading package (this is the package that allows you to get the active_count() in the previous code block):
import threading
my_thread = threading.Thread(target=func, args=(), kwargs={})
my_thread.daemon = True
my_thread.start()
A:
You might want to use threading.enumerate, if you have multiple workers and want to see which one(s) are still running.
Other alternatives include using threading.Event---the main thread sets the event to True and starts the worker thread off. The worker thread unsets the event when if finishes work, and the main check whether the event is set/unset to figure out if it can exit.
| Parent Thread exiting before Child Threads [python] | I'm using Python in a webapp (CGI for testing, FastCGI for production) that needs to send an occasional email (when a user registers or something else important happens). Since communicating with an SMTP server takes a long time, I'd like to spawn a thread for the mail function so that the rest of the app can finish up the request without waiting for the email to finish sending.
I tried using thread.start_new(func, (args)), but the Parent return's and exits before the sending is complete, thereby killing the sending process before it does anything useful. Is there anyway to keep the process alive long enough for the child process to finish?
| [
"Take a look at the thread.join() method. Basically it will block your calling thread until the child thread has returned (thus preventing it from exiting before it should).\nUpdate:\nTo avoid making your main thread unresponsive to new requests you can use a while loop.\nwhile threading.active_count() > 0:\n # ... look for new requests to handle ...\n time.sleep(0.1) \n\n # or try joining your threads with a timeout\n #for thread in my_threads:\n # thread.join(0.1) \n\nUpdate 2:\nIt also looks like thread.start_new(func, args) is obsolete. It was updated to thread.start_new_thread(function, args[, kwargs]) You can also create threads with the higher level threading package (this is the package that allows you to get the active_count() in the previous code block):\nimport threading\nmy_thread = threading.Thread(target=func, args=(), kwargs={})\nmy_thread.daemon = True\nmy_thread.start()\n\n",
"You might want to use threading.enumerate, if you have multiple workers and want to see which one(s) are still running. \nOther alternatives include using threading.Event---the main thread sets the event to True and starts the worker thread off. The worker thread unsets the event when if finishes work, and the main check whether the event is set/unset to figure out if it can exit. \n"
] | [
3,
0
] | [] | [] | [
"cgi",
"multithreading",
"python",
"smtp"
] | stackoverflow_0002850566_cgi_multithreading_python_smtp.txt |
Q:
Get list of Python module variables in Bash
For a Bash completion script I need to get all the variables from an installed Python module that match a pattern. I want to use only Python-aware functionality, to avoid having to parse comments and such.
A:
You can use python -c to execute a one-line Python script if you want. For example:
bash$ python -c "import os; print dir(os)"
If you want to filter by a pattern, you could do:
bash$ python -c "import os; print [x for x in dir(os) if x.startswith('r')]"
['read', 'readlink', 'remove', 'removedirs', 'rename', 'renames', 'rmdir']
| Get list of Python module variables in Bash | For a Bash completion script I need to get all the variables from an installed Python module that match a pattern. I want to use only Python-aware functionality, to avoid having to parse comments and such.
| [
"You can use python -c to execute a one-line Python script if you want. For example:\nbash$ python -c \"import os; print dir(os)\"\n\nIf you want to filter by a pattern, you could do:\nbash$ python -c \"import os; print [x for x in dir(os) if x.startswith('r')]\"\n['read', 'readlink', 'remove', 'removedirs', 'rename', 'renames', 'rmdir']\n\n"
] | [
3
] | [] | [] | [
"bash",
"python"
] | stackoverflow_0002851243_bash_python.txt |
Q:
In Python, is it better to use list comprehensions or for-each loops?
Which of the following is better to use and why?
Method 1:
for k, v in os.environ.items():
print "%s=%s" % (k, v)
Method 2:
print "\n".join(["%s=%s" % (k, v)
for k,v in os.environ.items()])
I tend to lead towards the first as more understandable, but that might just be because I'm new to Python and list comprehensions are still somewhat foreign to me. Is the second way considered more Pythonic? I'm assuming there's no performance difference, but I may be wrong. What would be the advantages and disadvantages of these 2 techniques?
(Code taken from Dive into Python)
A:
If the iteration is being done for its side effect ( as it is in your "print" example ), then a loop is clearer.
If the iteration is executed in order to build a composite value, then list comprehensions are usually more readable.
A:
The particular code examples you have chosen do not demonstrate any advantage of the list comprehension, because it is being (mis-)used for the trivial task of printing. In this simple case I would choose the simple for loop.
In many other cases, you will want to supply an actual list to another function or method, and the list comprehension is the easiest and most readable way to do that.
An example which would clearly show the superiority of the list comp could be made by replacing the print example with one involving creating another actual list, by appending to one on each iteration of the for loop:
L = []
for x in range(10):
L.append(x**2)
Gives the same L as:
L = [x**2 for x in range(10)]
A:
I find the first example better - less verbose, clearer and more readable.
In my opinion, go with what best gets your intention across, after all:
Programs should be written for people
to read, and only incidentally for
machines to execute.
-- from "Structure and Interpretation of Computer Programs" by Abelson and Sussman
By the way, since you're just starting to learn Python, start learning the new String Formatting syntax right away:
for k, v in os.environ.items():
print "{0}={1}".format(k, v)
A:
List comprehension is more than twice as fast as explicit loop. Base on Ben James' variation, but replace the x**2 with a more trivial x+2 function, the two alternatives are:
def foo(n):
L = []
for x in xrange(n):
L.append(x+2)
return L
def bar(n):
return [x+2 for x in xrange(n)]
Timing result:
In [674]: timeit foo(1000)
10000 loops, best of 3: 195 us per loop
In [675]: timeit bar(1000)
10000 loops, best of 3: 81.7 us per loop
List comprehension wins by a large margin.
I agree than readability should be a priority over performance optimization. However readability is in the eye of beholder. When I first learn Python, list comprehension is a weird thing I find hard to comprehend! :-O But once I got use to it, it becomes a really nice short hand notation. If you are to become proficient in Python you have to master list comprehension.
A:
The first one in my opinion, because:
It doesn't build a huge string.
It doesn't build a huge list (can easily be fixed with a generator, by removing the []).
In both cases, you access the items in the same way (using the dictionary iterator).
A:
list comprehensions are supposed to be run at C level, so if there is huge loop, list comprehensions are good choice.
A:
I agree with @Ben, @Tim, @Steven:
readability is the most important thing (do "import this" to remind yourself of what is)
a listcomp may or may not be much faster than an iterative-loop version... it depends on the total number of function calls that are made
if you do decide to go with listcomps with large datasets, it's better to use generator expressions instead
Example:
print "\n".join("%s=%s" % (k, v) for k,v in os.environ.iteritems())
in the code snippet above, I made two changes... I replaced the listcomp with a genexp, and I changed the method call to iteritems(). [this trend is moving forward as in Python 3, iteritems() replaces and is renamed to items().]
| In Python, is it better to use list comprehensions or for-each loops? | Which of the following is better to use and why?
Method 1:
for k, v in os.environ.items():
print "%s=%s" % (k, v)
Method 2:
print "\n".join(["%s=%s" % (k, v)
for k,v in os.environ.items()])
I tend to lead towards the first as more understandable, but that might just be because I'm new to Python and list comprehensions are still somewhat foreign to me. Is the second way considered more Pythonic? I'm assuming there's no performance difference, but I may be wrong. What would be the advantages and disadvantages of these 2 techniques?
(Code taken from Dive into Python)
| [
"If the iteration is being done for its side effect ( as it is in your \"print\" example ), then a loop is clearer. \nIf the iteration is executed in order to build a composite value, then list comprehensions are usually more readable. \n",
"The particular code examples you have chosen do not demonstrate any advantage of the list comprehension, because it is being (mis-)used for the trivial task of printing. In this simple case I would choose the simple for loop.\nIn many other cases, you will want to supply an actual list to another function or method, and the list comprehension is the easiest and most readable way to do that.\nAn example which would clearly show the superiority of the list comp could be made by replacing the print example with one involving creating another actual list, by appending to one on each iteration of the for loop:\nL = []\nfor x in range(10):\n L.append(x**2)\n\nGives the same L as:\nL = [x**2 for x in range(10)]\n\n",
"I find the first example better - less verbose, clearer and more readable.\nIn my opinion, go with what best gets your intention across, after all:\n\nPrograms should be written for people\n to read, and only incidentally for\n machines to execute.\n\n-- from \"Structure and Interpretation of Computer Programs\" by Abelson and Sussman\nBy the way, since you're just starting to learn Python, start learning the new String Formatting syntax right away:\nfor k, v in os.environ.items():\n print \"{0}={1}\".format(k, v)\n\n",
"List comprehension is more than twice as fast as explicit loop. Base on Ben James' variation, but replace the x**2 with a more trivial x+2 function, the two alternatives are:\ndef foo(n):\n L = []\n for x in xrange(n):\n L.append(x+2)\n return L\n\n\ndef bar(n):\n return [x+2 for x in xrange(n)]\n\nTiming result:\nIn [674]: timeit foo(1000)\n10000 loops, best of 3: 195 us per loop\n\nIn [675]: timeit bar(1000)\n10000 loops, best of 3: 81.7 us per loop\n\nList comprehension wins by a large margin.\nI agree than readability should be a priority over performance optimization. However readability is in the eye of beholder. When I first learn Python, list comprehension is a weird thing I find hard to comprehend! :-O But once I got use to it, it becomes a really nice short hand notation. If you are to become proficient in Python you have to master list comprehension.\n",
"The first one in my opinion, because:\n\nIt doesn't build a huge string.\nIt doesn't build a huge list (can easily be fixed with a generator, by removing the []).\n\nIn both cases, you access the items in the same way (using the dictionary iterator).\n",
"list comprehensions are supposed to be run at C level, so if there is huge loop, list comprehensions are good choice.\n",
"I agree with @Ben, @Tim, @Steven:\n\nreadability is the most important thing (do \"import this\" to remind yourself of what is)\na listcomp may or may not be much faster than an iterative-loop version... it depends on the total number of function calls that are made\nif you do decide to go with listcomps with large datasets, it's better to use generator expressions instead\n\nExample:\nprint \"\\n\".join(\"%s=%s\" % (k, v) for k,v in os.environ.iteritems())\n\nin the code snippet above, I made two changes... I replaced the listcomp with a genexp, and I changed the method call to iteritems(). [this trend is moving forward as in Python 3, iteritems() replaces and is renamed to items().]\n"
] | [
42,
26,
15,
15,
4,
3,
2
] | [] | [] | [
"coding_style",
"foreach",
"list_comprehension",
"python"
] | stackoverflow_0002849645_coding_style_foreach_list_comprehension_python.txt |
Q:
Setting up relations/mappings for a SQLAlchemy many-to-many database
I'm new to SQLAlchemy and relational databases, and I'm trying to set up a model for an annotated lexicon. I want to support an arbitrary number of key-value annotations for the words which can be added or removed at runtime. Since there will be a lot of repetition in the names of the keys, I don't want to use this solution directly, although the code is similar.
My design has word objects and property objects. The words and properties are stored in separate tables with a property_values table that links the two. Here's the code:
from sqlalchemy import Column, Integer, String, Table, create_engine
from sqlalchemy import MetaData, ForeignKey
from sqlalchemy.orm import relation, mapper, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine('sqlite:///test.db', echo=True)
meta = MetaData(bind=engine)
property_values = Table('property_values', meta,
Column('word_id', Integer, ForeignKey('words.id')),
Column('property_id', Integer, ForeignKey('properties.id')),
Column('value', String(20))
)
words = Table('words', meta,
Column('id', Integer, primary_key=True),
Column('name', String(20)),
Column('freq', Integer)
)
properties = Table('properties', meta,
Column('id', Integer, primary_key=True),
Column('name', String(20), nullable=False, unique=True)
)
meta.create_all()
class Word(object):
def __init__(self, name, freq=1):
self.name = name
self.freq = freq
class Property(object):
def __init__(self, name):
self.name = name
mapper(Property, properties)
Now I'd like to be able to do the following:
Session = sessionmaker(bind=engine)
s = Session()
word = Word('foo', 42)
word['bar'] = 'yes' # or word.bar = 'yes' ?
s.add(word)
s.commit()
Ideally this should add 1|foo|42 to the words table, add 1|bar to the properties table, and add 1|1|yes to the property_values table. However, I don't have the right mappings and relations in place to make this happen. I get the sense from reading the documentation at http://www.sqlalchemy.org/docs/05/mappers.html#association-pattern that I want to use an association proxy or something of that sort here, but the syntax is unclear to me. I experimented with this:
mapper(Word, words, properties={
'properties': relation(Property, secondary=property_values)
})
but this mapper only fills in the foreign key values, and I need to fill in the other value as well. Any assistance would be greatly appreciated.
A:
There is very similar question with slight interface difference. But it's easy to fix it by defining __getitem__, __setitem__ and __delitem__ methods.
A:
Simply use Dictionary-Based Collections mapping mapping - out of the box solution to your question. Extract from the link:
from sqlalchemy.orm.collections import column_mapped_collection, attribute_mapped_collection, mapped_collection
mapper(Item, items_table, properties={
# key by column
'notes': relation(Note, collection_class=column_mapped_collection(notes_table.c.keyword)),
# or named attribute
'notes2': relation(Note, collection_class=attribute_mapped_collection('keyword')),
# or any callable
'notes3': relation(Note, collection_class=mapped_collection(lambda entity: entity.a + entity.b))
})
# ...
item = Item()
item.notes['color'] = Note('color', 'blue')
print item.notes['color']
Or try the solution for Inserting data in Many to Many relationship in SQLAlchemy. Obviously you have to replace the list logic with the dict one.
Ask question author to post hist final code with associationproxy, which he mentioned he used in the end.
A:
Comment for Brent, above:
You can use session.flush() instead of commit() to get an id on your model instances. flush() will execute the necessary SQL, but will not commit, so you can rollback later if needed.
A:
I ended up combining Denis and van's posts together to form the solution:
from sqlalchemy import Column, Integer, String, Table, create_engine
from sqlalchemy import MetaData, ForeignKey
from sqlalchemy.orm import relation, mapper, sessionmaker
from sqlalchemy.orm.collections import attribute_mapped_collection
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.ext.declarative import declarative_base
meta = MetaData()
Base = declarative_base(metadata=meta, name='Base')
class PropertyValue(Base):
__tablename__ = 'property_values'
WordID = Column(Integer, ForeignKey('words.id'), primary_key=True)
PropID = Column(Integer, ForeignKey('properties.id'), primary_key=True)
Value = Column(String(20))
def _property_for_name(prop_name):
return s.query(Property).filter_by(name=prop_name).first()
def _create_propval(prop_name, prop_val):
p = _property_for_name(prop_name)
if not p:
p = Property(prop_name)
s.add(p)
s.commit()
return PropertyValue(PropID=p.id, Value=prop_val)
class Word(Base):
__tablename__ = 'words'
id = Column(Integer, primary_key=True)
string = Column(String(20), nullable=False)
freq = Column(Integer)
_props = relation(PropertyValue, collection_class=attribute_mapped_collection('PropID'), cascade='all, delete-orphan')
props = association_proxy('_props', 'Value', creator=_create_propval)
def __init__(self, string, freq=1):
self.string = string
self.freq = freq
def __getitem__(self, prop):
p = _property_for_name(prop)
if p:
return self.props[p.id]
else:
return None
def __setitem__(self, prop, val):
self.props[prop] = val
def __delitem__(self, prop):
p = _property_for_name(prop)
if p:
del self.props[prop]
class Property(Base):
__tablename__ = 'properties'
id = Column(Integer, primary_key=True)
name = Column(String(20), nullable=False, unique=True)
def __init__(self, name):
self.name = name
engine = create_engine('sqlite:///test.db', echo=False)
Session = sessionmaker(bind=engine)
s = Session()
meta.create_all(engine)
The test code is as follows:
word = Word('foo', 42)
word['bar'] = "yes"
word['baz'] = "certainly"
s.add(word)
word2 = Word('quux', 20)
word2['bar'] = "nope"
word2['groink'] = "nope"
s.add(word2)
word2['groink'] = "uh-uh"
del word2['bar']
s.commit()
word = s.query(Word).filter_by(string="foo").first()
print word.freq, word['baz']
# prints 42 certainly
The contents of the databases are:
$ sqlite3 test.db "select * from property_values"
1|2|certainly
1|1|yes
2|3|uh-uh
$ sqlite3 test.db "select * from words"
1|foo|42
2|quux|20
$ sqlite3 test.db "select * from properties"
1|bar
2|baz
3|groink
| Setting up relations/mappings for a SQLAlchemy many-to-many database | I'm new to SQLAlchemy and relational databases, and I'm trying to set up a model for an annotated lexicon. I want to support an arbitrary number of key-value annotations for the words which can be added or removed at runtime. Since there will be a lot of repetition in the names of the keys, I don't want to use this solution directly, although the code is similar.
My design has word objects and property objects. The words and properties are stored in separate tables with a property_values table that links the two. Here's the code:
from sqlalchemy import Column, Integer, String, Table, create_engine
from sqlalchemy import MetaData, ForeignKey
from sqlalchemy.orm import relation, mapper, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine('sqlite:///test.db', echo=True)
meta = MetaData(bind=engine)
property_values = Table('property_values', meta,
Column('word_id', Integer, ForeignKey('words.id')),
Column('property_id', Integer, ForeignKey('properties.id')),
Column('value', String(20))
)
words = Table('words', meta,
Column('id', Integer, primary_key=True),
Column('name', String(20)),
Column('freq', Integer)
)
properties = Table('properties', meta,
Column('id', Integer, primary_key=True),
Column('name', String(20), nullable=False, unique=True)
)
meta.create_all()
class Word(object):
def __init__(self, name, freq=1):
self.name = name
self.freq = freq
class Property(object):
def __init__(self, name):
self.name = name
mapper(Property, properties)
Now I'd like to be able to do the following:
Session = sessionmaker(bind=engine)
s = Session()
word = Word('foo', 42)
word['bar'] = 'yes' # or word.bar = 'yes' ?
s.add(word)
s.commit()
Ideally this should add 1|foo|42 to the words table, add 1|bar to the properties table, and add 1|1|yes to the property_values table. However, I don't have the right mappings and relations in place to make this happen. I get the sense from reading the documentation at http://www.sqlalchemy.org/docs/05/mappers.html#association-pattern that I want to use an association proxy or something of that sort here, but the syntax is unclear to me. I experimented with this:
mapper(Word, words, properties={
'properties': relation(Property, secondary=property_values)
})
but this mapper only fills in the foreign key values, and I need to fill in the other value as well. Any assistance would be greatly appreciated.
| [
"There is very similar question with slight interface difference. But it's easy to fix it by defining __getitem__, __setitem__ and __delitem__ methods.\n",
"Simply use Dictionary-Based Collections mapping mapping - out of the box solution to your question. Extract from the link:\nfrom sqlalchemy.orm.collections import column_mapped_collection, attribute_mapped_collection, mapped_collection\n\nmapper(Item, items_table, properties={\n # key by column\n 'notes': relation(Note, collection_class=column_mapped_collection(notes_table.c.keyword)),\n # or named attribute\n 'notes2': relation(Note, collection_class=attribute_mapped_collection('keyword')),\n # or any callable\n 'notes3': relation(Note, collection_class=mapped_collection(lambda entity: entity.a + entity.b))\n})\n\n# ...\nitem = Item()\nitem.notes['color'] = Note('color', 'blue')\nprint item.notes['color']\n\n\nOr try the solution for Inserting data in Many to Many relationship in SQLAlchemy. Obviously you have to replace the list logic with the dict one.\nAsk question author to post hist final code with associationproxy, which he mentioned he used in the end.\n",
"Comment for Brent, above:\nYou can use session.flush() instead of commit() to get an id on your model instances. flush() will execute the necessary SQL, but will not commit, so you can rollback later if needed.\n",
"I ended up combining Denis and van's posts together to form the solution:\nfrom sqlalchemy import Column, Integer, String, Table, create_engine\nfrom sqlalchemy import MetaData, ForeignKey\nfrom sqlalchemy.orm import relation, mapper, sessionmaker\nfrom sqlalchemy.orm.collections import attribute_mapped_collection\nfrom sqlalchemy.ext.associationproxy import association_proxy\nfrom sqlalchemy.ext.declarative import declarative_base\n\nmeta = MetaData()\nBase = declarative_base(metadata=meta, name='Base')\n\nclass PropertyValue(Base):\n __tablename__ = 'property_values'\n WordID = Column(Integer, ForeignKey('words.id'), primary_key=True)\n PropID = Column(Integer, ForeignKey('properties.id'), primary_key=True)\n Value = Column(String(20))\n\ndef _property_for_name(prop_name):\n return s.query(Property).filter_by(name=prop_name).first()\n\ndef _create_propval(prop_name, prop_val):\n p = _property_for_name(prop_name)\n if not p:\n p = Property(prop_name)\n s.add(p)\n s.commit()\n return PropertyValue(PropID=p.id, Value=prop_val)\n\nclass Word(Base):\n __tablename__ = 'words'\n id = Column(Integer, primary_key=True)\n string = Column(String(20), nullable=False)\n freq = Column(Integer)\n _props = relation(PropertyValue, collection_class=attribute_mapped_collection('PropID'), cascade='all, delete-orphan')\n props = association_proxy('_props', 'Value', creator=_create_propval)\n\n def __init__(self, string, freq=1):\n self.string = string\n self.freq = freq\n\n def __getitem__(self, prop):\n p = _property_for_name(prop)\n if p:\n return self.props[p.id]\n else:\n return None\n\n def __setitem__(self, prop, val):\n self.props[prop] = val\n\n def __delitem__(self, prop):\n p = _property_for_name(prop)\n if p:\n del self.props[prop]\n\nclass Property(Base):\n __tablename__ = 'properties'\n id = Column(Integer, primary_key=True)\n name = Column(String(20), nullable=False, unique=True)\n\n def __init__(self, name):\n self.name = name\n\nengine = create_engine('sqlite:///test.db', echo=False)\nSession = sessionmaker(bind=engine)\ns = Session()\nmeta.create_all(engine)\n\nThe test code is as follows:\nword = Word('foo', 42)\nword['bar'] = \"yes\"\nword['baz'] = \"certainly\"\ns.add(word)\n\nword2 = Word('quux', 20)\nword2['bar'] = \"nope\"\nword2['groink'] = \"nope\"\ns.add(word2)\nword2['groink'] = \"uh-uh\"\ndel word2['bar']\n\ns.commit()\n\nword = s.query(Word).filter_by(string=\"foo\").first()\nprint word.freq, word['baz']\n# prints 42 certainly\n\nThe contents of the databases are:\n$ sqlite3 test.db \"select * from property_values\"\n1|2|certainly\n1|1|yes\n2|3|uh-uh\n$ sqlite3 test.db \"select * from words\"\n1|foo|42\n2|quux|20\n$ sqlite3 test.db \"select * from properties\"\n1|bar\n2|baz\n3|groink\n\n"
] | [
1,
1,
1,
0
] | [] | [] | [
"orm",
"python",
"sqlalchemy"
] | stackoverflow_0002316537_orm_python_sqlalchemy.txt |
Q:
Can I turn off implicit Python unicode conversions to find my mixed-strings bugs?
When profiling our code I was surprised to find millions of calls to
C:\Python26\lib\encodings\utf_8.py:15(decode)
I started debugging and found that across our code base there are many small bugs, usually comparing a string to a unicode or adding a sting and a unicode. Python graciously decodes the strings and performs the following operations in unicode.
How kind. But expensive!
I am fluent in unicode, having read Joel Spolsky and Dive Into Python...
I try to keep our code internals in unicode only.
My question - can I turn off this pythonic nice-guy behavior? At least until I find all these bugs and fix them (usually by adding a u'u')?
Some of them are extremely hard to find (a variable that is sometimes a string...).
Python 2.6.5 (and I can't switch to 3.x).
A:
The following should work:
>>> import sys
>>> reload(sys)
<module 'sys' (built-in)>
>>> sys.setdefaultencoding('undefined')
>>> u"abc" + u"xyz"
u'abcxyz'
>>> u"abc" + "xyz"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/encodings/undefined.py", line 22, in decode
raise UnicodeError("undefined encoding")
UnicodeError: undefined encoding
reload(sys) in the snippet above is only necessary here since normally sys.setdefaultencoding is supposed to go in a sitecustomize.py file in your Python site-packages directory (it's advisable to do that).
| Can I turn off implicit Python unicode conversions to find my mixed-strings bugs? | When profiling our code I was surprised to find millions of calls to
C:\Python26\lib\encodings\utf_8.py:15(decode)
I started debugging and found that across our code base there are many small bugs, usually comparing a string to a unicode or adding a sting and a unicode. Python graciously decodes the strings and performs the following operations in unicode.
How kind. But expensive!
I am fluent in unicode, having read Joel Spolsky and Dive Into Python...
I try to keep our code internals in unicode only.
My question - can I turn off this pythonic nice-guy behavior? At least until I find all these bugs and fix them (usually by adding a u'u')?
Some of them are extremely hard to find (a variable that is sometimes a string...).
Python 2.6.5 (and I can't switch to 3.x).
| [
"The following should work:\n>>> import sys\n>>> reload(sys)\n<module 'sys' (built-in)>\n>>> sys.setdefaultencoding('undefined')\n>>> u\"abc\" + u\"xyz\"\nu'abcxyz'\n>>> u\"abc\" + \"xyz\"\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/encodings/undefined.py\", line 22, in decode\n raise UnicodeError(\"undefined encoding\")\nUnicodeError: undefined encoding\n\nreload(sys) in the snippet above is only necessary here since normally sys.setdefaultencoding is supposed to go in a sitecustomize.py file in your Python site-packages directory (it's advisable to do that). \n"
] | [
9
] | [] | [] | [
"debugging",
"decoding",
"python",
"unicode"
] | stackoverflow_0002851481_debugging_decoding_python_unicode.txt |
Q:
Google group word count for members?
I have a google group, and I'd like to figure out how many words each member has posted. Is there a utility to do this?
If not, how can I get started writing a Python script to do this? Should I just grab XML from the group's feed and look through that? (I don't know anything about Python's handling of XML.)
On the Google groups site, I see XML feeds for recent posts, but not for all posts.
A:
It looks like people have wanted a Groups API since about 3 years ago. It looks like you may have to resort to page-scraping.
| Google group word count for members? | I have a google group, and I'd like to figure out how many words each member has posted. Is there a utility to do this?
If not, how can I get started writing a Python script to do this? Should I just grab XML from the group's feed and look through that? (I don't know anything about Python's handling of XML.)
On the Google groups site, I see XML feeds for recent posts, but not for all posts.
| [
"It looks like people have wanted a Groups API since about 3 years ago. It looks like you may have to resort to page-scraping.\n"
] | [
0
] | [] | [] | [
"google_groups",
"google_groups_api",
"python",
"xml"
] | stackoverflow_0002852001_google_groups_google_groups_api_python_xml.txt |
Q:
Is there an efficient way to figure out the headers, cookies, and get/post data being passed to a site?
More specifically I'm looking for something, perhaps an add-on for firefox, once enabled it logs all of this information as it's passed to and from the server. I'm doing some web scripting and this would be really handy.
If anyone is wondering specifically what I'm doing currently I'm trying to make a script to repost my craigslist ad every 2 days since I handle a few things on there. Might even go so far as to make a simple gui to manage the submissions.
I do suspect this goes against the ToS, for that reason I don't plan to release the code. Besides cl is already bad enough with spam, I'm not trying to contribute further to it, figured I'd say what I'm doing for the sake of being honest though. I don't have any bad intentions with this, just some things I've been trying to sell and an ad for my pc repair business. I've been reposting some things for months now and so often I just forget to do it.
A:
The Network module of the Firefox Web Developer Toolbar lets you look at the HTTP headers in the request and the response, so it's a good starting point. It won't log everything for you, though, so you will have to copy everything to a text editor if you want to inspect it later.
Since you also tagged your post with Python, I presume you are planning to implement your script in Python. Take a look at the mechanize module which gives you a simple virtual browser object in Python that "remembers" cookies and stuff.
A:
I've used the Firefox extension LiveHTTPHeaders and it has worked well for me.
A:
Wireshark is great for logging and reading packets passed to and from your computer.
A:
I find the Firebug net panel really useful for this.
| Is there an efficient way to figure out the headers, cookies, and get/post data being passed to a site? | More specifically I'm looking for something, perhaps an add-on for firefox, once enabled it logs all of this information as it's passed to and from the server. I'm doing some web scripting and this would be really handy.
If anyone is wondering specifically what I'm doing currently I'm trying to make a script to repost my craigslist ad every 2 days since I handle a few things on there. Might even go so far as to make a simple gui to manage the submissions.
I do suspect this goes against the ToS, for that reason I don't plan to release the code. Besides cl is already bad enough with spam, I'm not trying to contribute further to it, figured I'd say what I'm doing for the sake of being honest though. I don't have any bad intentions with this, just some things I've been trying to sell and an ad for my pc repair business. I've been reposting some things for months now and so often I just forget to do it.
| [
"The Network module of the Firefox Web Developer Toolbar lets you look at the HTTP headers in the request and the response, so it's a good starting point. It won't log everything for you, though, so you will have to copy everything to a text editor if you want to inspect it later.\nSince you also tagged your post with Python, I presume you are planning to implement your script in Python. Take a look at the mechanize module which gives you a simple virtual browser object in Python that \"remembers\" cookies and stuff.\n",
"I've used the Firefox extension LiveHTTPHeaders and it has worked well for me.\n",
"Wireshark is great for logging and reading packets passed to and from your computer. \n",
"I find the Firebug net panel really useful for this.\n"
] | [
0,
0,
0,
0
] | [] | [] | [
"html",
"parsing",
"python",
"web",
"webforms"
] | stackoverflow_0002850840_html_parsing_python_web_webforms.txt |
Q:
python: how/where to put a simple library installed in a well-known-place on my computer
I need to put a python script somewhere on my computer so that in another file I can use it. How do I do this and where do I put it? And where in the python documentation do I learn how to do this? I'm a beginner + don't use python much.
library file: MyLib.py put in a well-known place
def myfunc():
....
other file SourceFile.py located elsewhere, doesn't need to know where MyLib.py is:
something = MyLib.myfunc()
A:
Option 1:
Put your file at:
<Wherever your Python is>/Lib/site-packages/myfile.py
Add this to your code:
import myfile
Pros: Easy
Cons: Clutters site-packages
Option 2:
Put your file at:
/Lib/site-packages/mypackage/myfile.py
Create an empty text file called:
<Wherever your Python is>/Lib/site-packages/mypackage/__init__.py
Add this to your code:
from mypackage import myfile
Pros: Reduces clutter in site-packages by keeping your stuff consolidated in a single directory
Cons: Slightly more work; still some clutter in site-packages. This isn't bad for stable stuff, but may be regarded as inappropriate for development work, and may be impossible if Python is installed on a shared drive
Option 3
Put your file in any directory you like
Add that directory to the PYTHONPATH environment variable
Proceed as with Option 1 or Option 2, except substitute the directory you just created for <Wherever your Python is>/Lib/site-packages/
Pros: Keeps development code out of the site-packages directory
Cons: slightly more setup
This is the approach I usually use for development work
A:
In general, the Modules section of the Python tutorial is a good introduction for beginners on this topic. It explains how to write your own modules and where to put them, but I'll summarize the answer to your question below:
Your Python installation has a site-packages directory; any python file you put in that directory will be available to any script you write. For example, if you put the file MyLib.py in the site-packages directory, then in your script you can say
import MyLib
something = MyLib.myfunc()
If you're not sure where Python is installed, the Stack Overflow question How do I find the location of my Python site-packages directory will be helpful to you.
Alternatively, you can modify sys.path, which is a list of directories where Python looks for libraries when you use the import statement. Your site-packages directory is already in this list, but you can add (or remove) entries yourself. For example, if you wanted to put your MyLib.py file in /usr/local/pythonModules, you could say
import sys
sys.path.append("/usr/local/pythonModules")
import MyLib
something = MyLib.myfunc()
Finally, you could use the PYTHONPATH environment variable to indicate the directory where your MyLib.py is located.
However, I recommend simply placing your MyLib.py file in the site-packages directory, as described above.
A:
No one has mentioned using .pth files in site-packages to abstract away the location.
A:
You will have to place your MyLib.py somewhere in your load path (this the paths in your sys.path variable) and then you'll be able to import it fine. Your code would look like
import MyLib
MyLib.myfunc()
Generally speaking, you should distribute your packages using distutils so that they can be easily installed in the proper locations. It would help you as well.
Also, you might not want to install packages in your global Python install. It's customary (and recommended) to use virtualenv which you can use to create small isolated Python environments that can hold local packages.
It's best your give the whole thing a shot and then ask further questions if you have them.
A:
The private version, from my .profile
export PYTHONPATH=${PYTHONPATH}:$HOME/lib/python
which has a subdirectory "msw" so import msw.primes is self documenting or add to a local directory that is already in sys.path
A:
The Python tutorial section 6 talks about modules, and 6.1.2 talks about the PYTHONPATH, which determines where Python will look for modules you try to import. The tutorial: http://docs.python.org/tutorial/modules.html
| python: how/where to put a simple library installed in a well-known-place on my computer | I need to put a python script somewhere on my computer so that in another file I can use it. How do I do this and where do I put it? And where in the python documentation do I learn how to do this? I'm a beginner + don't use python much.
library file: MyLib.py put in a well-known place
def myfunc():
....
other file SourceFile.py located elsewhere, doesn't need to know where MyLib.py is:
something = MyLib.myfunc()
| [
"Option 1:\nPut your file at:\n<Wherever your Python is>/Lib/site-packages/myfile.py\nAdd this to your code:\nimport myfile\n\nPros: Easy\nCons: Clutters site-packages\nOption 2:\nPut your file at:\n/Lib/site-packages/mypackage/myfile.py\nCreate an empty text file called:\n<Wherever your Python is>/Lib/site-packages/mypackage/__init__.py\nAdd this to your code:\nfrom mypackage import myfile\n\nPros: Reduces clutter in site-packages by keeping your stuff consolidated in a single directory\nCons: Slightly more work; still some clutter in site-packages. This isn't bad for stable stuff, but may be regarded as inappropriate for development work, and may be impossible if Python is installed on a shared drive\nOption 3\nPut your file in any directory you like\nAdd that directory to the PYTHONPATH environment variable\nProceed as with Option 1 or Option 2, except substitute the directory you just created for <Wherever your Python is>/Lib/site-packages/\nPros: Keeps development code out of the site-packages directory\nCons: slightly more setup\nThis is the approach I usually use for development work\n",
"In general, the Modules section of the Python tutorial is a good introduction for beginners on this topic. It explains how to write your own modules and where to put them, but I'll summarize the answer to your question below:\nYour Python installation has a site-packages directory; any python file you put in that directory will be available to any script you write. For example, if you put the file MyLib.py in the site-packages directory, then in your script you can say\nimport MyLib\nsomething = MyLib.myfunc()\n\nIf you're not sure where Python is installed, the Stack Overflow question How do I find the location of my Python site-packages directory will be helpful to you.\nAlternatively, you can modify sys.path, which is a list of directories where Python looks for libraries when you use the import statement. Your site-packages directory is already in this list, but you can add (or remove) entries yourself. For example, if you wanted to put your MyLib.py file in /usr/local/pythonModules, you could say\nimport sys\nsys.path.append(\"/usr/local/pythonModules\")\nimport MyLib\nsomething = MyLib.myfunc()\n\nFinally, you could use the PYTHONPATH environment variable to indicate the directory where your MyLib.py is located.\nHowever, I recommend simply placing your MyLib.py file in the site-packages directory, as described above.\n",
"No one has mentioned using .pth files in site-packages to abstract away the location.\n",
"You will have to place your MyLib.py somewhere in your load path (this the paths in your sys.path variable) and then you'll be able to import it fine. Your code would look like\nimport MyLib\nMyLib.myfunc()\n\nGenerally speaking, you should distribute your packages using distutils so that they can be easily installed in the proper locations. It would help you as well. \nAlso, you might not want to install packages in your global Python install. It's customary (and recommended) to use virtualenv which you can use to create small isolated Python environments that can hold local packages. \nIt's best your give the whole thing a shot and then ask further questions if you have them.\n",
"The private version, from my .profile\nexport PYTHONPATH=${PYTHONPATH}:$HOME/lib/python\n\nwhich has a subdirectory \"msw\" so import msw.primes is self documenting or add to a local directory that is already in sys.path\n",
"The Python tutorial section 6 talks about modules, and 6.1.2 talks about the PYTHONPATH, which determines where Python will look for modules you try to import. The tutorial: http://docs.python.org/tutorial/modules.html\n"
] | [
8,
4,
3,
2,
1,
1
] | [] | [] | [
"import",
"path",
"python"
] | stackoverflow_0002851182_import_path_python.txt |
Q:
Extracting words between delimiters [] in python
From the below string, I want to extract the words between delimters [ ] like 'Service Current','Service','9991','1.22':
str='mysrv events Generating Event Name [Service Current], Category [Service] Test [9991] Value [1.22]'
How can I extract the same in python?
Thanks in advance
Kris
A:
First, avoid using str as a variable name. str already has a meaning in Python and by defining it to be something else you will confuse people.
Having said that you can use the following regular expression:
>>> import re
>>> print re.findall(r'\[([^]]*)\]', s)
['Service Current', 'Service', '9991', '1.22']
This works as follows:
\[ match a literal [
( start a capturing group
[^]] match anything except a closing ]
* zero or more of the previous
) close the capturing group
\] match a literal ]
An alternative regular expression is:
r'\[(.*?)\]'
This works by using a non-greedy match instead of matching anything except ].
A:
you can use regex
import re
s = re.findall('\[(.*?)\]', str)
A:
re.findall(r'\[([^\]]*)\]', str)
| Extracting words between delimiters [] in python | From the below string, I want to extract the words between delimters [ ] like 'Service Current','Service','9991','1.22':
str='mysrv events Generating Event Name [Service Current], Category [Service] Test [9991] Value [1.22]'
How can I extract the same in python?
Thanks in advance
Kris
| [
"First, avoid using str as a variable name. str already has a meaning in Python and by defining it to be something else you will confuse people.\nHaving said that you can use the following regular expression:\n>>> import re\n>>> print re.findall(r'\\[([^]]*)\\]', s)\n['Service Current', 'Service', '9991', '1.22']\n\nThis works as follows:\n\n\\[ match a literal [\n( start a capturing group\n[^]] match anything except a closing ]\n* zero or more of the previous\n) close the capturing group\n\\] match a literal ]\n\nAn alternative regular expression is:\nr'\\[(.*?)\\]'\n\nThis works by using a non-greedy match instead of matching anything except ].\n",
"you can use regex\nimport re\ns = re.findall('\\[(.*?)\\]', str)\n\n",
"re.findall(r'\\[([^\\]]*)\\]', str)\n\n"
] | [
22,
8,
2
] | [] | [] | [
"python"
] | stackoverflow_0002852484_python.txt |
Q:
Django Deserialization
I am getting the following error:
Traceback (most recent call last):
File "../tests.py", line 92, in test_single_search
for return_obj in serializers.deserialize("json",response, ensure_ascii=False):
File "/Library/Python/2.6/site-packages/django/core/serializers/json.py",
line 38, in Deserializer
for obj in PythonDeserializer(simplejson.load(stream),
**options): File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/json/init.py",
line 264, in load
return loads(fp.read(), AttributeError: 'HttpResponse' object
has no attribute 'read'
In views.py the serialization works correctly:
resultsjson = serializers.serialize("json", results, ensure_ascii=False)
return HttpResponse(resultsjson, mimetype = 'application/json')
However, when I try to process the result in my calling method in test.py:
response = self.client.get("/path/?query=testValue")
for return_obj in serializers.deserialize("json", response, ensure_ascii=False):
print return_obj
I get the above error. Has anyone come across the same error. I am using Django 1.2 (latest version from svn) and it appears to be using the in-built simplejson serializser.
A:
You need to use response.content rather than just response in your call to deserialize. The response object is an instance of HttpResponse, but has an attribute of content which contains the actual JSON in this case.
| Django Deserialization | I am getting the following error:
Traceback (most recent call last):
File "../tests.py", line 92, in test_single_search
for return_obj in serializers.deserialize("json",response, ensure_ascii=False):
File "/Library/Python/2.6/site-packages/django/core/serializers/json.py",
line 38, in Deserializer
for obj in PythonDeserializer(simplejson.load(stream),
**options): File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/json/init.py",
line 264, in load
return loads(fp.read(), AttributeError: 'HttpResponse' object
has no attribute 'read'
In views.py the serialization works correctly:
resultsjson = serializers.serialize("json", results, ensure_ascii=False)
return HttpResponse(resultsjson, mimetype = 'application/json')
However, when I try to process the result in my calling method in test.py:
response = self.client.get("/path/?query=testValue")
for return_obj in serializers.deserialize("json", response, ensure_ascii=False):
print return_obj
I get the above error. Has anyone come across the same error. I am using Django 1.2 (latest version from svn) and it appears to be using the in-built simplejson serializser.
| [
"You need to use response.content rather than just response in your call to deserialize. The response object is an instance of HttpResponse, but has an attribute of content which contains the actual JSON in this case.\n"
] | [
9
] | [] | [] | [
"django",
"python",
"serialization"
] | stackoverflow_0002852583_django_python_serialization.txt |
Q:
How to fix this dll loading python error?
I use one c++ dll in my python code.
When I run my python app on my computer, it works fine but when I copy all to another computer this happen:
Traceback (most recent call last):
File "C:\users\Public\SoundLog\Code\Código Python\SoundLog\SoundLog.py", line 9, in <module>
from Auxiliar import *
File "C:\users\Public\SoundLog\Code\Código Python\SoundLog\Auxiliar\DataCollection.py", line 4, in <module>
import SoundLogDLL
File "C:\users\Public\SoundLog\Code\Código Python\SoundLog\Auxiliar\SoundLogDLL.py", line 4, in <module>
dll = cdll.LoadLibrary(os.environ['PUBLIC'] + "\\SoundLog\\DLLs\\ForPython\\SoundLogC++WrapperDLL.dll")
File "C:\Python26\lib\ctypes\__init__.py", line 431, in LoadLibrary
return self._dlltype(name)
File "C:\Python26\lib\ctypes\__init__.py", line 353, in __init__
self._handle = _dlopen(self._name, mode)
WindowsError: [Error 14001] The application has failed to start because its side-by-side configuration is incorrect. Please see the application event log or use the command-line sxstrace.exe tool for more detail
How can I fix this problem so that my python app work in every computer?
Note:
I only need them to work on windows 7 like mine. And I tested on another win7 computer (both 32bits).
A:
You're using a DLL which depends on a Microsoft Visual C++ runtime which isn't installed on the target computer. You have a few options:
Install or copy the Visual C++ runtime libraries to the target computer. Installation is done by adding merge modules to your installer (if you have one) or by running the redistributable installer (vcredist.exe). The various methods are documented here for VS2005 (other versions will be similar).
If you built the DLL, you can change the project settings to statically link the runtime libraries. See this answer to see how this is done.
| How to fix this dll loading python error? | I use one c++ dll in my python code.
When I run my python app on my computer, it works fine but when I copy all to another computer this happen:
Traceback (most recent call last):
File "C:\users\Public\SoundLog\Code\Código Python\SoundLog\SoundLog.py", line 9, in <module>
from Auxiliar import *
File "C:\users\Public\SoundLog\Code\Código Python\SoundLog\Auxiliar\DataCollection.py", line 4, in <module>
import SoundLogDLL
File "C:\users\Public\SoundLog\Code\Código Python\SoundLog\Auxiliar\SoundLogDLL.py", line 4, in <module>
dll = cdll.LoadLibrary(os.environ['PUBLIC'] + "\\SoundLog\\DLLs\\ForPython\\SoundLogC++WrapperDLL.dll")
File "C:\Python26\lib\ctypes\__init__.py", line 431, in LoadLibrary
return self._dlltype(name)
File "C:\Python26\lib\ctypes\__init__.py", line 353, in __init__
self._handle = _dlopen(self._name, mode)
WindowsError: [Error 14001] The application has failed to start because its side-by-side configuration is incorrect. Please see the application event log or use the command-line sxstrace.exe tool for more detail
How can I fix this problem so that my python app work in every computer?
Note:
I only need them to work on windows 7 like mine. And I tested on another win7 computer (both 32bits).
| [
"You're using a DLL which depends on a Microsoft Visual C++ runtime which isn't installed on the target computer. You have a few options:\n\nInstall or copy the Visual C++ runtime libraries to the target computer. Installation is done by adding merge modules to your installer (if you have one) or by running the redistributable installer (vcredist.exe). The various methods are documented here for VS2005 (other versions will be similar).\nIf you built the DLL, you can change the project settings to statically link the runtime libraries. See this answer to see how this is done.\n\n"
] | [
3
] | [] | [] | [
"python"
] | stackoverflow_0002852652_python.txt |
Q:
python: where to put application data that can be edited by computer users
I'm working on a really simple python package for our internal use, and want to package it as a .egg file, and when it's installed/used I want it to access a text file that is placed in an appropriate place on the computer.
So where is the best place to put application data in python? (that is meant to be edited by users) How do I get my python package to automatically install a default file there?
note: I know about the Windows application data directory, but would like to avoid it, as it's nonportable and kind of cumbersome both for users to access and for my application to access.
A:
os.path.expanduser('~')
A:
Each OS will have it's own directory where application data is expected to exist. There does not appear to be a method that provides this path in a platform-independent manner. You can write your own function to do this for you by checking os.name and then returning the appropriate value depending on the result.
| python: where to put application data that can be edited by computer users | I'm working on a really simple python package for our internal use, and want to package it as a .egg file, and when it's installed/used I want it to access a text file that is placed in an appropriate place on the computer.
So where is the best place to put application data in python? (that is meant to be edited by users) How do I get my python package to automatically install a default file there?
note: I know about the Windows application data directory, but would like to avoid it, as it's nonportable and kind of cumbersome both for users to access and for my application to access.
| [
"os.path.expanduser('~')\n",
"Each OS will have it's own directory where application data is expected to exist. There does not appear to be a method that provides this path in a platform-independent manner. You can write your own function to do this for you by checking os.name and then returning the appropriate value depending on the result.\n"
] | [
3,
0
] | [] | [] | [
"application_data",
"installation",
"python"
] | stackoverflow_0002852606_application_data_installation_python.txt |
Q:
Python required variable style
What is the best style for a Python method that requires the keyword argument 'required_arg':
def test_method(required_arg, *args, **kwargs):
def test_method(*args, **kwargs):
required_arg = kwargs.pop('required_arg')
if kwargs:
raise ValueError('Unexpected keyword arguments: %s' % kwargs)
Or something else? I want to use this for all my methods in the future so I'm kind of looking for the best practices way to deal with required keyword arguments in Python methods.
A:
The first method by far. Why duplicate something the language already provides for you?
Optional arguments in most cases should be known (only use *args and **kwargs when there is no possible way of knowing the arguments). Denote optional arguments by giving them their default value (def bar(foo = 0) or def bar(foo = None)). Watch out for the classic gotcha of def bar(foo = []) which doesn't do what you expect.
A:
The first method offers you the opportunity to give your required argument a meaningful name; using *args doesn't. Using *args is great when you need it, but why give up the opportunity for clearer expression of your intent?
A:
If you don't want arbitrary keyword arguments, leave out the ** parameter. For the love of all that is holy, if you have something that is required, just make it a normal argument.
Instead of this:
def test_method(*args, **kwargs):
required_arg = kwargs.pop('required_arg')
if kwargs:
raise ValueError('Unexpected keyword arguments: %s' % kwargs)
Do this:
def test_method(required_arg, *args):
pass
| Python required variable style | What is the best style for a Python method that requires the keyword argument 'required_arg':
def test_method(required_arg, *args, **kwargs):
def test_method(*args, **kwargs):
required_arg = kwargs.pop('required_arg')
if kwargs:
raise ValueError('Unexpected keyword arguments: %s' % kwargs)
Or something else? I want to use this for all my methods in the future so I'm kind of looking for the best practices way to deal with required keyword arguments in Python methods.
| [
"The first method by far. Why duplicate something the language already provides for you?\nOptional arguments in most cases should be known (only use *args and **kwargs when there is no possible way of knowing the arguments). Denote optional arguments by giving them their default value (def bar(foo = 0) or def bar(foo = None)). Watch out for the classic gotcha of def bar(foo = []) which doesn't do what you expect.\n",
"The first method offers you the opportunity to give your required argument a meaningful name; using *args doesn't. Using *args is great when you need it, but why give up the opportunity for clearer expression of your intent?\n",
"If you don't want arbitrary keyword arguments, leave out the ** parameter. For the love of all that is holy, if you have something that is required, just make it a normal argument.\nInstead of this:\ndef test_method(*args, **kwargs):\n required_arg = kwargs.pop('required_arg')\n if kwargs:\n raise ValueError('Unexpected keyword arguments: %s' % kwargs)\n\nDo this:\ndef test_method(required_arg, *args):\n pass\n\n"
] | [
7,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0002852623_python.txt |
Q:
Django Grouping Query
I have the following (simplified) models:
class Donation(models.Model):
entry_date = models.DateTimeField()
class Category(models.Model):
name = models.CharField()
class Item(models.Model):
donation = models.ForeignKey(Donation)
category = models.ForeignKey(Category)
I'm trying to display the total number of items, per category, grouped by the donation year.
I've tried this:
Donation.objects.extra(select={'year': "django_date_trunc('year',
%s.entry_date)" % Donation._meta.db_table}).values('year',
'item__category__name').annotate(items=Sum('item__quantity'))
But I get a Field Error on item__category__name.
I've also tried:
Item.objects.extra(select={"year": "django_date_trunc('year',
entry_date)"}, tables=["donations_donation"]).values("year",
"category__name").annotate(items=Sum("quantity")).order_by()
Which generally gets me what I want, but the item quantity count is multiplied by the number of donation records.
Any ideas? Basically I want to display this:
2010
- Category 1: 10 items
- Category 2: 17 items
2009
- Category 1: 5 items
- Category 3: 8 items
A:
This other post looks like what you're looking for:
Django equivalent for count and group by
Depending on your Django version, you may or may not be able to use it though.
A:
I realize you've probably already written your raw SQL, but the following came to mind when I saw the way you want to display your data:
If it's alright to do it at the template level you might be able to make strategic use of the regroup tag and length filter.
Regroup takes a "list of alike objects" so a queryset might work just fine, but the docs show a list of dictionaries, so I've used values here:
item_listing = Item.objects.values('category__name', 'donation__entry_date')
# use your favourite method to extract the year information into a key in item_listing
item_listing = ...
Now in the template, something like:
<ul>
{% for year_group in item_listing %}
<li>{{ year_group.grouper }}
<ul>
{% regroup year_group.list by category__name as category_listing %}
{% for category_group in category_listing %}
<li>
Category: {{ category_group.grouper }}
Count: {{ category_group.list|length }}
</li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
I'm not sure if the regroup tag nests well like that (haven't tried it). Also, I have no idea how well regroup performs if you've got a lot of data, but then again, there's always caching...
If you decide to use this, make sure that you take note of the ordering gotcha mentioned in the regroup docs.
| Django Grouping Query | I have the following (simplified) models:
class Donation(models.Model):
entry_date = models.DateTimeField()
class Category(models.Model):
name = models.CharField()
class Item(models.Model):
donation = models.ForeignKey(Donation)
category = models.ForeignKey(Category)
I'm trying to display the total number of items, per category, grouped by the donation year.
I've tried this:
Donation.objects.extra(select={'year': "django_date_trunc('year',
%s.entry_date)" % Donation._meta.db_table}).values('year',
'item__category__name').annotate(items=Sum('item__quantity'))
But I get a Field Error on item__category__name.
I've also tried:
Item.objects.extra(select={"year": "django_date_trunc('year',
entry_date)"}, tables=["donations_donation"]).values("year",
"category__name").annotate(items=Sum("quantity")).order_by()
Which generally gets me what I want, but the item quantity count is multiplied by the number of donation records.
Any ideas? Basically I want to display this:
2010
- Category 1: 10 items
- Category 2: 17 items
2009
- Category 1: 5 items
- Category 3: 8 items
| [
"This other post looks like what you're looking for:\nDjango equivalent for count and group by\nDepending on your Django version, you may or may not be able to use it though.\n",
"I realize you've probably already written your raw SQL, but the following came to mind when I saw the way you want to display your data:\nIf it's alright to do it at the template level you might be able to make strategic use of the regroup tag and length filter.\nRegroup takes a \"list of alike objects\" so a queryset might work just fine, but the docs show a list of dictionaries, so I've used values here:\nitem_listing = Item.objects.values('category__name', 'donation__entry_date')\n# use your favourite method to extract the year information into a key in item_listing\nitem_listing = ...\n\nNow in the template, something like:\n<ul>\n{% for year_group in item_listing %}\n <li>{{ year_group.grouper }}\n <ul>\n {% regroup year_group.list by category__name as category_listing %}\n {% for category_group in category_listing %}\n <li>\n Category: {{ category_group.grouper }}\n Count: {{ category_group.list|length }}\n </li>\n {% endfor %}\n </ul>\n </li>\n{% endfor %}\n</ul>\n\nI'm not sure if the regroup tag nests well like that (haven't tried it). Also, I have no idea how well regroup performs if you've got a lot of data, but then again, there's always caching...\nIf you decide to use this, make sure that you take note of the ordering gotcha mentioned in the regroup docs.\n"
] | [
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002831238_django_python.txt |
Q:
How do I search & replace all occurrences of a string in a ms word doc with python?
I am pretty stumped at the moment. Based on Can I use Win32 COM to replace text inside a word document? I was able to code a simple template system that generates word docs out of a template word doc (in Python).
My problem is that text in "Text Fields" is not find that way. Even in Word itself there is no option to search everything - you actually have to choose between "Main Document" and "Text Fields". Being new to the Windows world I tried to browse the VBA docs for it but found no help (probably due to "text field" being a very common term).
word.Documents.Open(f)
wdFindContinue = 1
wdReplaceAll = 2
find_str = '\{\{(*)\}\}'
find = word.Selection.Find
find.Execute(find_str, False, False, True, False, False, \
True, wdFindContinue, False, False, False)
while find.Found:
t = word.Selection.Text.__str__()
r = process_placeholder(t, answer_data, question_data)
if type(r) == dict:
errors.append(r)
else:
find.Execute(t, False, True, False, False, False, \
True, False, False, r, wdReplaceAll)
This is the relevant portion of my code. I was able to get around all problems by myself by now (hint: if you want to replace strings with more than 256 chars, you have to do it via clipboard, etc ...)
A:
Maybe you can use the OpenOffice API using the UNO component technology. With the Python-UNO bridge you can connect to an OpenOffice instance running in headless mode. Look at the tutorial to get started.
This is maybe an overkill for your scenario but it's a very powerful and flexible solution.
| How do I search & replace all occurrences of a string in a ms word doc with python? | I am pretty stumped at the moment. Based on Can I use Win32 COM to replace text inside a word document? I was able to code a simple template system that generates word docs out of a template word doc (in Python).
My problem is that text in "Text Fields" is not find that way. Even in Word itself there is no option to search everything - you actually have to choose between "Main Document" and "Text Fields". Being new to the Windows world I tried to browse the VBA docs for it but found no help (probably due to "text field" being a very common term).
word.Documents.Open(f)
wdFindContinue = 1
wdReplaceAll = 2
find_str = '\{\{(*)\}\}'
find = word.Selection.Find
find.Execute(find_str, False, False, True, False, False, \
True, wdFindContinue, False, False, False)
while find.Found:
t = word.Selection.Text.__str__()
r = process_placeholder(t, answer_data, question_data)
if type(r) == dict:
errors.append(r)
else:
find.Execute(t, False, True, False, False, False, \
True, False, False, r, wdReplaceAll)
This is the relevant portion of my code. I was able to get around all problems by myself by now (hint: if you want to replace strings with more than 256 chars, you have to do it via clipboard, etc ...)
| [
"Maybe you can use the OpenOffice API using the UNO component technology. With the Python-UNO bridge you can connect to an OpenOffice instance running in headless mode. Look at the tutorial to get started.\nThis is maybe an overkill for your scenario but it's a very powerful and flexible solution.\n"
] | [
2
] | [] | [] | [
"ms_word",
"python",
"vba",
"win32com"
] | stackoverflow_0002852857_ms_word_python_vba_win32com.txt |
Q:
How does one wrap numpy array types?
I'd like to make a class extending the numpy array base type,
class LemmaMatrix(numpy.ndarray):
@classmethod
def init_from_corpus(cls, ...): cls(numpy.empty(...))
But apparently, it will not allow multi-dimensional array types. Is there a way around this? Thanks in advance!
ndarray(empty([3, 3]))
TypeError: only length-1 arrays can be converted to Python scalars
A:
import numpy as np
class LemmaMatrix(np.ndarray):
def __new__(subtype,data,dtype=None):
subarr=np.empty(data,dtype=dtype)
return subarr
lm=LemmaMatrix([3,3])
print(lm)
# [[ 3.15913337e-260 4.94951870e+173 4.88364603e-309]
# [ 1.63321355e-301 4.80218258e-309 2.05227026e-287]
# [ 2.10277051e-309 2.07088188e+289 7.29366696e-304]]
You may also want read this guide for more information on how to subclass ndarray.
| How does one wrap numpy array types? | I'd like to make a class extending the numpy array base type,
class LemmaMatrix(numpy.ndarray):
@classmethod
def init_from_corpus(cls, ...): cls(numpy.empty(...))
But apparently, it will not allow multi-dimensional array types. Is there a way around this? Thanks in advance!
ndarray(empty([3, 3]))
TypeError: only length-1 arrays can be converted to Python scalars
| [
"import numpy as np\nclass LemmaMatrix(np.ndarray):\n def __new__(subtype,data,dtype=None):\n subarr=np.empty(data,dtype=dtype)\n return subarr\n\nlm=LemmaMatrix([3,3])\nprint(lm)\n# [[ 3.15913337e-260 4.94951870e+173 4.88364603e-309]\n# [ 1.63321355e-301 4.80218258e-309 2.05227026e-287]\n# [ 2.10277051e-309 2.07088188e+289 7.29366696e-304]]\n\nYou may also want read this guide for more information on how to subclass ndarray.\n"
] | [
5
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0002853051_arrays_numpy_python.txt |
Q:
All possible permutations of a set of lists in Python
In Python I have a list of n lists, each with a variable number of elements. How can I create a single list containing all the possible permutations:
For example
[ [ a, b, c], [d], [e, f] ]
I want
[ [a, d, e] , [a, d, f], [b, d, e], [b, d, f], [c, d, e], [c, d, f] ]
Note I don't know n in advance. I thought itertools.product would be the right approach but it requires me to know the number of arguments in advance
A:
You don't need to know n in advance to use itertools.product
>>> import itertools
>>> s=[ [ 'a', 'b', 'c'], ['d'], ['e', 'f'] ]
>>> list(itertools.product(*s))
[('a', 'd', 'e'), ('a', 'd', 'f'), ('b', 'd', 'e'), ('b', 'd', 'f'), ('c', 'd', 'e'), ('c', 'd', 'f')]
A:
You can do it with a multi-level list comprehension:
>>> L1=['a','b','c']
>>> L2=['d']
>>> L3=['e','f']
>>> [[i,j,k] for i in L1 for j in L2 for k in L3]
[['a', 'd', 'e'], ['a', 'd', 'f'], ['b', 'd', 'e'], ['b', 'd', 'f'], ['c', 'd', 'e'], ['c', 'd', 'f']]
A:
itertools.product works for me.
>>> l=[ [ 1, 2, 3], [4], [5, 6] ]
>>> list(itertools.product(*l))
[(1, 4, 5), (1, 4, 6), (2, 4, 5), (2, 4, 6), (3, 4, 5), (3, 4, 6)]
>>> l=[ [ 1, 2, 3], [4], [5, 6],[7,8] ]
>>> list(itertools.product(*l))
[(1, 4, 5, 7), (1, 4, 5, 8), (1, 4, 6, 7), (1, 4, 6, 8), (2, 4, 5, 7), (2, 4, 5, 8), (2, 4, 6, 7), (2, 4, 6, 8), (3, 4, 5, 7), (3, 4, 5, 8), (3, 4, 6,
7), (3, 4, 6, 8)]
>>>
| All possible permutations of a set of lists in Python | In Python I have a list of n lists, each with a variable number of elements. How can I create a single list containing all the possible permutations:
For example
[ [ a, b, c], [d], [e, f] ]
I want
[ [a, d, e] , [a, d, f], [b, d, e], [b, d, f], [c, d, e], [c, d, f] ]
Note I don't know n in advance. I thought itertools.product would be the right approach but it requires me to know the number of arguments in advance
| [
"You don't need to know n in advance to use itertools.product\n>>> import itertools\n>>> s=[ [ 'a', 'b', 'c'], ['d'], ['e', 'f'] ]\n>>> list(itertools.product(*s))\n[('a', 'd', 'e'), ('a', 'd', 'f'), ('b', 'd', 'e'), ('b', 'd', 'f'), ('c', 'd', 'e'), ('c', 'd', 'f')]\n\n",
"You can do it with a multi-level list comprehension:\n>>> L1=['a','b','c']\n>>> L2=['d']\n>>> L3=['e','f']\n>>> [[i,j,k] for i in L1 for j in L2 for k in L3]\n[['a', 'd', 'e'], ['a', 'd', 'f'], ['b', 'd', 'e'], ['b', 'd', 'f'], ['c', 'd', 'e'], ['c', 'd', 'f']]\n\n",
"itertools.product works for me.\n>>> l=[ [ 1, 2, 3], [4], [5, 6] ]\n>>> list(itertools.product(*l))\n[(1, 4, 5), (1, 4, 6), (2, 4, 5), (2, 4, 6), (3, 4, 5), (3, 4, 6)]\n>>> l=[ [ 1, 2, 3], [4], [5, 6],[7,8] ]\n>>> list(itertools.product(*l))\n[(1, 4, 5, 7), (1, 4, 5, 8), (1, 4, 6, 7), (1, 4, 6, 8), (2, 4, 5, 7), (2, 4, 5, 8), (2, 4, 6, 7), (2, 4, 6, 8), (3, 4, 5, 7), (3, 4, 5, 8), (3, 4, 6,\n 7), (3, 4, 6, 8)]\n>>>\n\n"
] | [
117,
7,
6
] | [] | [] | [
"list",
"permutation",
"python"
] | stackoverflow_0002853212_list_permutation_python.txt |
Q:
Loading a DB table into nested dictionaries in Python
I have a table in MySql DB which I want to load it to a dictionary in python.
the table columns is as follows:
id,url,tag,tagCount
tagCount is the number of times that a tag has been repeated for a certain url. So in that case I need a nested dictionary, in other words a dictionary of dictionary, to load this table. Because each url have several tags for which there are different tagCounts.the code that I used is this:( the whole table is about 22,000 records )
cursor.execute( ''' SELECT url,tag,tagCount
FROM wtp ''')
urlTagCount = cursor.fetchall()
d = defaultdict(defaultdict)
for url,tag,tagCount in urlTagCount:
d[url][tag]=tagCount
print d
first of all I want to know if this is correct.. and if it is why it takes so much time? Is there any faster solutions? I am loading this table into memory to have fast access to get rid of the hassle of slow database operations, but with this slow speed it has become a bottleneck itself, it is even much slower than DB access. and anyone help? thanks
A:
maybe you could try with normal dicts and tuple keys like
d = dict()
for url,tag,tagCount in urlTagCount:
d[(url, tag)] = tagCount
in any case did you try:
d = defaultdict(dict)
instead of
d = defaultdict(defaultdict)
A:
You need to ensure that the dictionary (and each of the nested dictionaries) exist before you assign a key, value to them. It is helpful to use setdefault for this purpose. You end up with something like this:
d = {}
for url, tag, tagCount in urlTagCount:
d.setdefault(url, {})[tag] = tagCount
A:
I could manage to verify the code, and it is working perfectly. For those amateurs like me, i suggest never try to "print" a very large nested dictionary. that "print d" in the last line of the code was the problem for it being slow. If remove it or try to access the dictionary with actual keys, then it is very fast.
| Loading a DB table into nested dictionaries in Python | I have a table in MySql DB which I want to load it to a dictionary in python.
the table columns is as follows:
id,url,tag,tagCount
tagCount is the number of times that a tag has been repeated for a certain url. So in that case I need a nested dictionary, in other words a dictionary of dictionary, to load this table. Because each url have several tags for which there are different tagCounts.the code that I used is this:( the whole table is about 22,000 records )
cursor.execute( ''' SELECT url,tag,tagCount
FROM wtp ''')
urlTagCount = cursor.fetchall()
d = defaultdict(defaultdict)
for url,tag,tagCount in urlTagCount:
d[url][tag]=tagCount
print d
first of all I want to know if this is correct.. and if it is why it takes so much time? Is there any faster solutions? I am loading this table into memory to have fast access to get rid of the hassle of slow database operations, but with this slow speed it has become a bottleneck itself, it is even much slower than DB access. and anyone help? thanks
| [
"maybe you could try with normal dicts and tuple keys like \nd = dict()\n\nfor url,tag,tagCount in urlTagCount:\n d[(url, tag)] = tagCount\n\nin any case did you try:\nd = defaultdict(dict)\n\ninstead of\nd = defaultdict(defaultdict)\n\n",
"You need to ensure that the dictionary (and each of the nested dictionaries) exist before you assign a key, value to them. It is helpful to use setdefault for this purpose. You end up with something like this:\nd = {}\nfor url, tag, tagCount in urlTagCount:\n d.setdefault(url, {})[tag] = tagCount\n\n",
"I could manage to verify the code, and it is working perfectly. For those amateurs like me, i suggest never try to \"print\" a very large nested dictionary. that \"print d\" in the last line of the code was the problem for it being slow. If remove it or try to access the dictionary with actual keys, then it is very fast.\n"
] | [
1,
1,
0
] | [] | [] | [
"dictionary",
"mysql",
"nested",
"python"
] | stackoverflow_0002853269_dictionary_mysql_nested_python.txt |
Q:
On-Demand Python Thread Start/Join Freezing Up from wxPython GUI
I'm attempting to build a very simple wxPython GUI that monitors and displays external data. There is a button that turns the monitoring on/off. When monitoring is turned on, the GUI updates a couple of wx StaticLabels with real-time data. When monitoring is turned off, the GUI idles.
The way I tried to build it was with a fairly simple Python Thread layout. When the 'Start Monitoring' button is clicked, the program spawns a thread that updates the labels with real-time information. When the 'Stop Monitoring' button is clicked, thread.join() is called, and it should stop.
The start function works and the real-time data updating works great, but when I click 'Stop', the whole program freezes. I'm running this on Windows 7 64-bit, so I get the usual "This Program has Stopped Responding" Windows dialog.
Here is the relevant code:
class MonGUI(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
...
... other code for the GUI here ...
...
# Create the thread that will update the VFO information
self.monThread = Thread(None, target=self.monThreadWork)
self.monThread.daemon = True
self.runThread = False
def monThreadWork(self):
while self.runThread:
...
... Update the StaticLabels with info
... (This part working)
...
# Turn monitoring on/off when the button is pressed.
def OnClick(self, event):
if self.isMonitoring:
self.button.SetLabel("Start Monitoring")
self.isMonitoring = False
self.runThread = False
self.monThread.join()
else:
self.button.SetLabel("Stop Monitoring")
self.isMonitoring = True
# Start the monitor thread!
self.runThread = True
self.monThread.start()
I'm sure there is a better way to do this, but I'm fairly new to GUI programming and Python threads, and this was the first thing I came up with.
So, why does clicking the button to stop the thread make the whole thing freeze up?
A:
In wxPython, GUI operations need to take place in the main thread. At places in your code you are calling the GUI from a different thread.
The easiest solution is to use wx.CallAfter(). A line of code would look like
wx.CallAfter(self.button.SetLabel, “Start Monitoring”)
which will then call self.button.SetLabel(“Start Monitoring”) from the main thread after the function completes.
There are other ways around this as well, such as using a Python threading Queue or wx.PostEvent, but start with CallAfter because it's easiest.
Other issues are also relevant, like you can't restart the same thread, but using CallAfter will stop the crashing.
A:
It's likely hanging on join([timeout]), which blocks the calling thread until the thread whose join() method is called terminates – either normally or through an unhandled exception – or until the optional timeout occurs.
Do you have some inner loop in your thread, or a blocking call that waits for some source of data that may never come? When I wrote a basic serial program that grabbed COM port data, it would sometimes hang because a read function in my thread would block until it got something.
I would sprinkle in a few debugging print statements to see whats happening.
Edit:
I'd also use a threading.Event() instead of a Boolean flag, e.g.:
# in the init code...
self.runThread = threading.Event()
# when starting thread...
self.runThread.set()
self.monThread.start()
# in the thread...
while self.runThread.isSet():
pass # do stuff
# killing the thread...
self.runThread.clear()
self.monThread.join()
This shouldn't make it work differently, but it's a slightly safer way to do it.
A:
tom10 has the right idea with avoiding UI updates from the monitor thread.
Also, it is probably not a good idea to have the blocking call self.monThread.join() in your UI thread. If you want the UI to give some feedback that the monitor thread has actually ended, have monThreadWorker issue a wx.CallAfter() or wx.PostEvent() just before it closes.
Avoid anything that blocks in your UI thread, and you will avoid deadlocking the UI
| On-Demand Python Thread Start/Join Freezing Up from wxPython GUI | I'm attempting to build a very simple wxPython GUI that monitors and displays external data. There is a button that turns the monitoring on/off. When monitoring is turned on, the GUI updates a couple of wx StaticLabels with real-time data. When monitoring is turned off, the GUI idles.
The way I tried to build it was with a fairly simple Python Thread layout. When the 'Start Monitoring' button is clicked, the program spawns a thread that updates the labels with real-time information. When the 'Stop Monitoring' button is clicked, thread.join() is called, and it should stop.
The start function works and the real-time data updating works great, but when I click 'Stop', the whole program freezes. I'm running this on Windows 7 64-bit, so I get the usual "This Program has Stopped Responding" Windows dialog.
Here is the relevant code:
class MonGUI(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
...
... other code for the GUI here ...
...
# Create the thread that will update the VFO information
self.monThread = Thread(None, target=self.monThreadWork)
self.monThread.daemon = True
self.runThread = False
def monThreadWork(self):
while self.runThread:
...
... Update the StaticLabels with info
... (This part working)
...
# Turn monitoring on/off when the button is pressed.
def OnClick(self, event):
if self.isMonitoring:
self.button.SetLabel("Start Monitoring")
self.isMonitoring = False
self.runThread = False
self.monThread.join()
else:
self.button.SetLabel("Stop Monitoring")
self.isMonitoring = True
# Start the monitor thread!
self.runThread = True
self.monThread.start()
I'm sure there is a better way to do this, but I'm fairly new to GUI programming and Python threads, and this was the first thing I came up with.
So, why does clicking the button to stop the thread make the whole thing freeze up?
| [
"In wxPython, GUI operations need to take place in the main thread. At places in your code you are calling the GUI from a different thread.\nThe easiest solution is to use wx.CallAfter(). A line of code would look like\nwx.CallAfter(self.button.SetLabel, “Start Monitoring”)\n\nwhich will then call self.button.SetLabel(“Start Monitoring”) from the main thread after the function completes.\nThere are other ways around this as well, such as using a Python threading Queue or wx.PostEvent, but start with CallAfter because it's easiest.\nOther issues are also relevant, like you can't restart the same thread, but using CallAfter will stop the crashing.\n",
"It's likely hanging on join([timeout]), which blocks the calling thread until the thread whose join() method is called terminates – either normally or through an unhandled exception – or until the optional timeout occurs.\nDo you have some inner loop in your thread, or a blocking call that waits for some source of data that may never come? When I wrote a basic serial program that grabbed COM port data, it would sometimes hang because a read function in my thread would block until it got something.\nI would sprinkle in a few debugging print statements to see whats happening.\nEdit:\nI'd also use a threading.Event() instead of a Boolean flag, e.g.:\n# in the init code...\nself.runThread = threading.Event()\n\n# when starting thread...\nself.runThread.set()\nself.monThread.start()\n\n# in the thread...\nwhile self.runThread.isSet():\n pass # do stuff\n\n# killing the thread...\nself.runThread.clear()\nself.monThread.join()\n\nThis shouldn't make it work differently, but it's a slightly safer way to do it. \n",
"tom10 has the right idea with avoiding UI updates from the monitor thread.\nAlso, it is probably not a good idea to have the blocking call self.monThread.join() in your UI thread. If you want the UI to give some feedback that the monitor thread has actually ended, have monThreadWorker issue a wx.CallAfter() or wx.PostEvent() just before it closes.\nAvoid anything that blocks in your UI thread, and you will avoid deadlocking the UI\n"
] | [
2,
1,
1
] | [] | [] | [
"multithreading",
"python",
"windows_7_x64",
"wxpython"
] | stackoverflow_0002852124_multithreading_python_windows_7_x64_wxpython.txt |
Q:
Searching through large data set
how would i search through a list with ~5 mil 128bit (or 256, depending on how you look at it) strings quickly and find the duplicates (in python)? i can turn the strings into numbers, but i don't think that's going to help much. since i haven't learned much information theory, is there anything about this in information theory?
and since these are hashes already, there's no point in hashing them again
A:
If it fits into memeory, use set(). I think it will be faster than sort. O(n log n) for 5 million items is going to cost you.
If it does not fit into memory, say you've lot more than 5 million record, divide and conquer. Break the records at the mid point like 1 x 2^127. Apply any of the above methods. I guess information theory helps by stating that a good hash function will distribute the keys evenly. So the divide by mid point method should work great.
You can also apply divide and conquer even if it fit into memory. Sorting 2 x 2.5 mil records is faster than sorting 5 mil records.
A:
Load them into memory (5M x 64B = 320MB), sort them, and scan through them finding the duplicates.
A:
In Python2.7+ you can use collections.Counter for older Python use collections.deaultdict(int). Either way is O(n).
first make a list with some hashes in it
>>> import hashlib
>>> s=[hashlib.sha1(str(x)).digest() for x in (1,2,3,4,5,1,2)]
>>> s
['5j\x19+y\x13\xb0LTWM\x18\xc2\x8dF\xe69T(\xab', '\xdaK\x927\xba\xcc\xcd\xf1\x9c\x07`\xca\xb7\xae\xc4\xa85\x90\x10\xb0', 'w\xdeh\xda\xec\xd8#\xba\xbb\xb5\x8e\xdb\x1c\x8e\x14\xd7\x10n\x83\xbb', '\x1bdS\x89$s\xa4g\xd0sr\xd4^\xb0Z\xbc 1dz', '\xac4x\xd6\x9a<\x81\xfab\xe6\x0f\\6\x96\x16ZN^j\xc4', '5j\x19+y\x13\xb0LTWM\x18\xc2\x8dF\xe69T(\xab', '\xdaK\x927\xba\xcc\xcd\xf1\x9c\x07`\xca\xb7\xae\xc4\xa85\x90\x10\xb0']
If you are using Python2.7 or later
>>> from collections import Counter
>>> c=Counter(s)
>>> duplicates = [k for k in c if c[k]>1]
>>> print duplicates
['\xdaK\x927\xba\xcc\xcd\xf1\x9c\x07`\xca\xb7\xae\xc4\xa85\x90\x10\xb0', '5j\x19+y\x13\xb0LTWM\x18\xc2\x8dF\xe69T(\xab']
if you are using Python2.6 or earlier
>>> from collections import defaultdict
>>> d=defaultdict(int)
>>> for i in s:
... d[i]+=1
...
>>> duplicates = [k for k in d if d[k]>1]
>>> print duplicates
['\xdaK\x927\xba\xcc\xcd\xf1\x9c\x07`\xca\xb7\xae\xc4\xa85\x90\x10\xb0', '5j\x19+y\x13\xb0LTWM\x18\xc2\x8dF\xe69T(\xab']
A:
Is this array sorted?
I think the fastest solution can be a heap sort or quick sort, and after go through the array, and find the duplicates.
A:
You say you have a list of about 5 million strings, and the list may contain duplicates. You don't say (1) what you want to do with the duplicates (log them, delete all but one occurrence, ...) (2) what you want to do with the non-duplicates (3) whether this list is a stand-alone structure or whether the strings are keys to some other data that you haven't mentioned (4) why you haven't deleted duplicates at input time instead building a list containing duplicates.
As a Data Structures and Algorithms 101 exercise, the answer you have accepted is a nonsense. If you have enough memory, detecting duplicates using a set should be faster than sorting a list and scanning it. Note that deleting M items from a list of size N is O(MN). The code for each of the various alternatives is short and rather obvious; why don't you try writing them, timing them, and reporting back?
If this is a real-world problem that you have, you need to provide much more information if you want a sensible answer.
| Searching through large data set | how would i search through a list with ~5 mil 128bit (or 256, depending on how you look at it) strings quickly and find the duplicates (in python)? i can turn the strings into numbers, but i don't think that's going to help much. since i haven't learned much information theory, is there anything about this in information theory?
and since these are hashes already, there's no point in hashing them again
| [
"If it fits into memeory, use set(). I think it will be faster than sort. O(n log n) for 5 million items is going to cost you.\nIf it does not fit into memory, say you've lot more than 5 million record, divide and conquer. Break the records at the mid point like 1 x 2^127. Apply any of the above methods. I guess information theory helps by stating that a good hash function will distribute the keys evenly. So the divide by mid point method should work great.\nYou can also apply divide and conquer even if it fit into memory. Sorting 2 x 2.5 mil records is faster than sorting 5 mil records.\n",
"Load them into memory (5M x 64B = 320MB), sort them, and scan through them finding the duplicates.\n",
"In Python2.7+ you can use collections.Counter for older Python use collections.deaultdict(int). Either way is O(n).\nfirst make a list with some hashes in it\n>>> import hashlib\n>>> s=[hashlib.sha1(str(x)).digest() for x in (1,2,3,4,5,1,2)]\n>>> s\n['5j\\x19+y\\x13\\xb0LTWM\\x18\\xc2\\x8dF\\xe69T(\\xab', '\\xdaK\\x927\\xba\\xcc\\xcd\\xf1\\x9c\\x07`\\xca\\xb7\\xae\\xc4\\xa85\\x90\\x10\\xb0', 'w\\xdeh\\xda\\xec\\xd8#\\xba\\xbb\\xb5\\x8e\\xdb\\x1c\\x8e\\x14\\xd7\\x10n\\x83\\xbb', '\\x1bdS\\x89$s\\xa4g\\xd0sr\\xd4^\\xb0Z\\xbc 1dz', '\\xac4x\\xd6\\x9a<\\x81\\xfab\\xe6\\x0f\\\\6\\x96\\x16ZN^j\\xc4', '5j\\x19+y\\x13\\xb0LTWM\\x18\\xc2\\x8dF\\xe69T(\\xab', '\\xdaK\\x927\\xba\\xcc\\xcd\\xf1\\x9c\\x07`\\xca\\xb7\\xae\\xc4\\xa85\\x90\\x10\\xb0']\n\nIf you are using Python2.7 or later\n>>> from collections import Counter\n>>> c=Counter(s)\n>>> duplicates = [k for k in c if c[k]>1]\n>>> print duplicates\n['\\xdaK\\x927\\xba\\xcc\\xcd\\xf1\\x9c\\x07`\\xca\\xb7\\xae\\xc4\\xa85\\x90\\x10\\xb0', '5j\\x19+y\\x13\\xb0LTWM\\x18\\xc2\\x8dF\\xe69T(\\xab']\n\nif you are using Python2.6 or earlier\n>>> from collections import defaultdict\n>>> d=defaultdict(int)\n>>> for i in s:\n... d[i]+=1\n... \n>>> duplicates = [k for k in d if d[k]>1]\n>>> print duplicates\n['\\xdaK\\x927\\xba\\xcc\\xcd\\xf1\\x9c\\x07`\\xca\\xb7\\xae\\xc4\\xa85\\x90\\x10\\xb0', '5j\\x19+y\\x13\\xb0LTWM\\x18\\xc2\\x8dF\\xe69T(\\xab']\n\n",
"Is this array sorted?\nI think the fastest solution can be a heap sort or quick sort, and after go through the array, and find the duplicates.\n",
"You say you have a list of about 5 million strings, and the list may contain duplicates. You don't say (1) what you want to do with the duplicates (log them, delete all but one occurrence, ...) (2) what you want to do with the non-duplicates (3) whether this list is a stand-alone structure or whether the strings are keys to some other data that you haven't mentioned (4) why you haven't deleted duplicates at input time instead building a list containing duplicates.\nAs a Data Structures and Algorithms 101 exercise, the answer you have accepted is a nonsense. If you have enough memory, detecting duplicates using a set should be faster than sorting a list and scanning it. Note that deleting M items from a list of size N is O(MN). The code for each of the various alternatives is short and rather obvious; why don't you try writing them, timing them, and reporting back?\nIf this is a real-world problem that you have, you need to provide much more information if you want a sensible answer.\n"
] | [
4,
2,
2,
1,
0
] | [] | [] | [
"arrays",
"duplicates",
"python",
"search",
"string"
] | stackoverflow_0002852912_arrays_duplicates_python_search_string.txt |
Q:
What will be the setup process for website development?
I want to create a simple site for my personal usage. And this only in python based technologies. So I want to get a expert oponian on this topic.
What should i used as platform? I did a search for available options and found Django, grok, web2py and many more of these. Which one a novice use should use? If I choose to use only the basic python scripts then what option i have to work on?
http://wiki.python.org/moin/WebBrowserProgramming. This link on python site confused me more, instead of solving my curiosity about the topic. Please give some pointer to accurate and easy to understand reading materials.
I have got a idea of developing java based web applications using either spring-webmvc and struts. Can I relate Java process to python process for web development?
A:
If the size of the community matters to you above everything else go consider that PHP has at least 10x more users than any Python framework.
If you have an existing database and you do not want to move data over to a new one, you probably should use SQLAlchemy and therefore you need a glued framework (Pylons in the best in that case). Since glued framework are built using third party components they tend to have less integration than full-stack frameworks.
If you are starting an app from scratch a full-stack framework, like Django and web2py, is the best options. Django gives you a better looking database administrative interface. web2py instead gives you something easier to start with, a web based IDE and the option to run code unmodified on the Google cloud.
web2py is the only framework that promises backward compatibility and never broke it. I do not know if that is an issue to you.
The official online web2py documentation includes the entire web2py book (350 pages).
Avoid smaller frameworks that are still under development because APIs will change and because they miss a lot of the features that bigger frameworks have.
This was built with web2py.
A:
I recommend You the django framework. Why? Because of big community, thought architecture and really many applications for it (something like plugins in jquery).
A:
If you're new to web programming in general, then I'd recommend trying Google App Engine. It's based on django, free, and is really easy to get started.
| What will be the setup process for website development? | I want to create a simple site for my personal usage. And this only in python based technologies. So I want to get a expert oponian on this topic.
What should i used as platform? I did a search for available options and found Django, grok, web2py and many more of these. Which one a novice use should use? If I choose to use only the basic python scripts then what option i have to work on?
http://wiki.python.org/moin/WebBrowserProgramming. This link on python site confused me more, instead of solving my curiosity about the topic. Please give some pointer to accurate and easy to understand reading materials.
I have got a idea of developing java based web applications using either spring-webmvc and struts. Can I relate Java process to python process for web development?
| [
"If the size of the community matters to you above everything else go consider that PHP has at least 10x more users than any Python framework.\nIf you have an existing database and you do not want to move data over to a new one, you probably should use SQLAlchemy and therefore you need a glued framework (Pylons in the best in that case). Since glued framework are built using third party components they tend to have less integration than full-stack frameworks.\nIf you are starting an app from scratch a full-stack framework, like Django and web2py, is the best options. Django gives you a better looking database administrative interface. web2py instead gives you something easier to start with, a web based IDE and the option to run code unmodified on the Google cloud. \nweb2py is the only framework that promises backward compatibility and never broke it. I do not know if that is an issue to you.\nThe official online web2py documentation includes the entire web2py book (350 pages).\nAvoid smaller frameworks that are still under development because APIs will change and because they miss a lot of the features that bigger frameworks have.\nThis was built with web2py.\n",
"I recommend You the django framework. Why? Because of big community, thought architecture and really many applications for it (something like plugins in jquery).\n",
"If you're new to web programming in general, then I'd recommend trying Google App Engine. It's based on django, free, and is really easy to get started.\n"
] | [
3,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0002842748_python.txt |
Q:
Using virtualenv to install different versions of same package
Since I have Django 1.1x on my Debian setup - how can I use virtualenv or similar and not have it mess up my system's default django version which in turn would break all my sites?
Detailed instructions or a great tutorial link would very much be appreciated - please don't offer vague advice since I'm still a noob.
Currently I store all my django projects in ~/django-sites and I am using Apache2 + mod_wsgi to deploy.
A:
If you have easy_install, or better yet pip installed, should be as easy as:
easy_install/pip install virtualenv
mkdir django1.2
virtualenv django1.2
This will put the python binary in a bin folder inside the django1.2 folder. Just use that python binary, and you've got a nice little self-contained environment. You can then install easy_install/pip into that environment, and then install django 1.2 as well, and hack away.
A:
Since you are using mod_wsgi, make sure you read:
http://code.google.com/p/modwsgi/wiki/VirtualEnvironments
| Using virtualenv to install different versions of same package | Since I have Django 1.1x on my Debian setup - how can I use virtualenv or similar and not have it mess up my system's default django version which in turn would break all my sites?
Detailed instructions or a great tutorial link would very much be appreciated - please don't offer vague advice since I'm still a noob.
Currently I store all my django projects in ~/django-sites and I am using Apache2 + mod_wsgi to deploy.
| [
"If you have easy_install, or better yet pip installed, should be as easy as:\n\neasy_install/pip install virtualenv\nmkdir django1.2\nvirtualenv django1.2\n\nThis will put the python binary in a bin folder inside the django1.2 folder. Just use that python binary, and you've got a nice little self-contained environment. You can then install easy_install/pip into that environment, and then install django 1.2 as well, and hack away.\n",
"Since you are using mod_wsgi, make sure you read:\nhttp://code.google.com/p/modwsgi/wiki/VirtualEnvironments\n"
] | [
2,
2
] | [] | [] | [
"django",
"python",
"virtualenv"
] | stackoverflow_0002851632_django_python_virtualenv.txt |
Q:
Problem with dictionary key in Python
For some project I have to make a dictionary in which the keys are urls,among which I have this url:
http://www.microsoft.com/isapi/redir.dll?prd=windows&sbp=mediaplayer&ar=Media&sba=Guide&pver=6.2
the url is too long to fit in here I guess in one single line.
I can build a dictionary without any errors this url is also a key. but for some reason when I want to extract the values associated to this key(url). I cannot, I get and error "error key:...."
Does someone know what is wrong with this url? Are dictionary keys sensitive to some stuff?
thanks
below is the code:
def initialize_sumWTP_table(cursor):
cursor.execute( ''' SELECT url,tagsCount
FROM sumWTP''')
rows = cursor.fetchall ()
for url,tagsCount in rows:
sumWTP[url] = tagsCount
A:
It is almost inconceivable that the dictionary is "losing" your key. I would guess that there is some small change in the string (case, or how the query string is ordered) that results in the same effective URL, but with a slightly different string.
If this is the case, find a way to "normalize" the URL.
A:
The problem was a bug in my code. I added some exception handling to solve the problem.The data was right, but I have forgotten to do exception handling in these cases.
example:
def getWPT(url,tag):
try:
row = MemoryInitializer.wtp[url][tag]
except KeyError:
row = 0
#print row
return row
A:
The reason for getting a key error when accessing a dict is that the key does not exist. Verify that the key you think exists, and that you're using the correct string.
A:
It's hard to tell based on the code fragment offered. It looks like you are initializing the dictionary. You need to create the sumWTP dictionary first, something like:
sumWTP = {}.
Then statements like
sumWTP[url] = tagcount
should work.
| Problem with dictionary key in Python | For some project I have to make a dictionary in which the keys are urls,among which I have this url:
http://www.microsoft.com/isapi/redir.dll?prd=windows&sbp=mediaplayer&ar=Media&sba=Guide&pver=6.2
the url is too long to fit in here I guess in one single line.
I can build a dictionary without any errors this url is also a key. but for some reason when I want to extract the values associated to this key(url). I cannot, I get and error "error key:...."
Does someone know what is wrong with this url? Are dictionary keys sensitive to some stuff?
thanks
below is the code:
def initialize_sumWTP_table(cursor):
cursor.execute( ''' SELECT url,tagsCount
FROM sumWTP''')
rows = cursor.fetchall ()
for url,tagsCount in rows:
sumWTP[url] = tagsCount
| [
"It is almost inconceivable that the dictionary is \"losing\" your key. I would guess that there is some small change in the string (case, or how the query string is ordered) that results in the same effective URL, but with a slightly different string.\nIf this is the case, find a way to \"normalize\" the URL. \n",
"The problem was a bug in my code. I added some exception handling to solve the problem.The data was right, but I have forgotten to do exception handling in these cases.\nexample:\ndef getWPT(url,tag):\ntry:\n row = MemoryInitializer.wtp[url][tag]\nexcept KeyError:\n row = 0\n#print row\nreturn row\n\n",
"The reason for getting a key error when accessing a dict is that the key does not exist. Verify that the key you think exists, and that you're using the correct string.\n",
"It's hard to tell based on the code fragment offered. It looks like you are initializing the dictionary. You need to create the sumWTP dictionary first, something like:\nsumWTP = {}.\nThen statements like\nsumWTP[url] = tagcount\nshould work.\n"
] | [
1,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0002845764_python.txt |
Q:
What scripts should not be ported from bash to python?
I decided to rewrite all our Bash scripts in Python (there are not so many of them) as my first Python project. The reason for it is that although being quite fluent in Bash I feel it's somewhat archaic language and since our system is in the first stages of its developments I think switching to Python now will be the right thing to do.
Are there scripts that should always be written in Bash? For example, we have an init.d daemon script - is it OK to use Python for it?
We run CentOS.
Thanks.
A:
It is OK in the sense that you can do it. But the scripts in /etc/init.d usually need to load config data and some functions (for example to print the nice green OK on the console) which will be hard to emulate in Python.
So try to convert those which make sense (i.e. those which contain complex logic). If you need job control (starting/stopping processes), then bash is better suited than Python.
A:
Generally, scripts in /etc/init.d are written in the "native shell" of the OS (e.g. bash, sh, posix-sh, etc). This is especially true of scripts that will be run at the lower init levels (e.g. not every directory will be mounted in single user mode, including wherever python or the site-libraries might be installed).
Most OS's provide some "helper functions" that make writing scripts in some native shell easier. These scripts define certain return codes and messages that are required/desired when writing service scripts. On RedHat based systems, see:
/etc/init.d/functions
Beyond that, the service scripts in /etc/init.d can be written in any language (including compiled languages). The general calling syntax will need to be supported. Typically there are three arguments that should be supported: start, stop, and status. Some additional arguments might be appropriate, depending on the purpose of the scripts.
% /etc/init.d/foo (start|stop|status)
A:
Every task has languages that are better suited for it and less so. Replacing the backtick ` quote of sh is pretty ponderous in Python as would be myriad quoting details, just to name a couple. There are likely better projects to cut your teeth on.
And all that they said above about Python being relatively heavyweight and not necessarily available when needed.
A:
Certain scripts that I write simply involving looping over a glob in some directories, and then executing some a piped series of commands on them. This kind of thing is much more tedious in python.
| What scripts should not be ported from bash to python? | I decided to rewrite all our Bash scripts in Python (there are not so many of them) as my first Python project. The reason for it is that although being quite fluent in Bash I feel it's somewhat archaic language and since our system is in the first stages of its developments I think switching to Python now will be the right thing to do.
Are there scripts that should always be written in Bash? For example, we have an init.d daemon script - is it OK to use Python for it?
We run CentOS.
Thanks.
| [
"It is OK in the sense that you can do it. But the scripts in /etc/init.d usually need to load config data and some functions (for example to print the nice green OK on the console) which will be hard to emulate in Python.\nSo try to convert those which make sense (i.e. those which contain complex logic). If you need job control (starting/stopping processes), then bash is better suited than Python.\n",
"Generally, scripts in /etc/init.d are written in the \"native shell\" of the OS (e.g. bash, sh, posix-sh, etc). This is especially true of scripts that will be run at the lower init levels (e.g. not every directory will be mounted in single user mode, including wherever python or the site-libraries might be installed). \nMost OS's provide some \"helper functions\" that make writing scripts in some native shell easier. These scripts define certain return codes and messages that are required/desired when writing service scripts. On RedHat based systems, see: \n/etc/init.d/functions \n\nBeyond that, the service scripts in /etc/init.d can be written in any language (including compiled languages). The general calling syntax will need to be supported. Typically there are three arguments that should be supported: start, stop, and status. Some additional arguments might be appropriate, depending on the purpose of the scripts. \n% /etc/init.d/foo (start|stop|status) \n\n",
"Every task has languages that are better suited for it and less so. Replacing the backtick ` quote of sh is pretty ponderous in Python as would be myriad quoting details, just to name a couple. There are likely better projects to cut your teeth on.\nAnd all that they said above about Python being relatively heavyweight and not necessarily available when needed.\n",
"Certain scripts that I write simply involving looping over a glob in some directories, and then executing some a piped series of commands on them. This kind of thing is much more tedious in python.\n"
] | [
3,
2,
1,
0
] | [] | [] | [
"bash",
"linux",
"python",
"scripting"
] | stackoverflow_0002852397_bash_linux_python_scripting.txt |
Q:
Do you know of any python mapreduce ready clustering libraries?
Do you know of any python mapreduce ready clustering libraries?
I have found some good libraries in Java (http://lucene.apache.org/mahout/), I'd prefer to use python though.
https://github.com/klbostee/dumbo/wiki (Python mapreduce API )
Edit ---
I'm looking for mapreduce ready : Canopy, K-means, Means-shift,etc..
A:
You can use Python in combination with Hadoop, if you like:
http://www.michael-noll.com/wiki/Writing_An_Hadoop_MapReduce_Program_In_Python
| Do you know of any python mapreduce ready clustering libraries? | Do you know of any python mapreduce ready clustering libraries?
I have found some good libraries in Java (http://lucene.apache.org/mahout/), I'd prefer to use python though.
https://github.com/klbostee/dumbo/wiki (Python mapreduce API )
Edit ---
I'm looking for mapreduce ready : Canopy, K-means, Means-shift,etc..
| [
"You can use Python in combination with Hadoop, if you like:\nhttp://www.michael-noll.com/wiki/Writing_An_Hadoop_MapReduce_Program_In_Python\n"
] | [
3
] | [] | [] | [
"libraries",
"mapreduce",
"python"
] | stackoverflow_0002853752_libraries_mapreduce_python.txt |
Q:
Automatically support new changes with Python
I was working on a program,that I need to support new additions. Hmmm. Let me give you some background on the program.
It is an educational software program that has quizzes for the user to take, just to gain odd knowledge. Now, It currently supports 6 subjects, all organized with directores on the HDD ( i.e. the Science directory is called science. ) and the way you launch the subject to see what quizzes you have to take is by pushing a button on the home screen.
This sort of thing prevents easy subject additions. I want to be able to add a subject later on without having to recode the home screen and re organize all the buttons. I would use a Listbox and os.listdir(...), but I was kind of wanting something prettier than a Listbox. I am using Tkinter on Windows. The Python version I am using is 2.6
Is there a "fancy" listbox sort of thing that can be styled to work with the background?
A:
You can add buttons dynamically just fine, nothing is forcing you into the listbox. That said, I don't know why you care so much about "prettiness" since you're using Tkinter, which is very ugly by default.
| Automatically support new changes with Python | I was working on a program,that I need to support new additions. Hmmm. Let me give you some background on the program.
It is an educational software program that has quizzes for the user to take, just to gain odd knowledge. Now, It currently supports 6 subjects, all organized with directores on the HDD ( i.e. the Science directory is called science. ) and the way you launch the subject to see what quizzes you have to take is by pushing a button on the home screen.
This sort of thing prevents easy subject additions. I want to be able to add a subject later on without having to recode the home screen and re organize all the buttons. I would use a Listbox and os.listdir(...), but I was kind of wanting something prettier than a Listbox. I am using Tkinter on Windows. The Python version I am using is 2.6
Is there a "fancy" listbox sort of thing that can be styled to work with the background?
| [
"You can add buttons dynamically just fine, nothing is forcing you into the listbox. That said, I don't know why you care so much about \"prettiness\" since you're using Tkinter, which is very ugly by default.\n"
] | [
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0002853708_python_tkinter.txt |
Q:
How to maintain long-lived python projects w.r.t. dependencies and python versions?
short version: how can I get rid of the multiple-versions-of-python nightmare ?
long version: over the years, I've used several versions of python, and what is worse, several extensions to python (e.g. pygame, pylab, wxPython...). Each time it was on a different setup, with different OSes, sometimes different architectures (like my old PowerPC mac).
Nowadays I'm using a mac (OSX 10.6 on x86-64) and it's a dependency nightmare each time I want to revive script older than a few months. Python itself already comes in three different flavours in /usr/bin (2.5, 2.6, 3.1), but I had to install 2.4 from macports for pygame, something else (cannot remember what) forced me to install all three others from macports as well, so at the end of the day I'm the happy owner of seven (!) instances of python on my system.
But that's not the problem, the problem is, none of them has the right (i.e. same set of) libraries installed, some of them are 32bits, some 64bits, and now I'm pretty much lost.
For example right now I'm trying to run a three-year-old script (not written by me) which used to use matplotlib/numpy to draw a real-time plot within a rectangle of a wxwidgets window. But I'm failing miserably: py26-wxpython from macports won't install, stock python has wxwidgets included but also has some conflict between 32 bits and 64 bits, and it doesn't have numpy... what a mess !
Obviously, I'm doing things the wrong way. How do you usally cope with all that chaos ?
A:
I solve this using virtualenv. I sympathise with wanting to avoid further layers of nightmare abstraction, but virtualenv is actually amazingly clean and simple to use. You literally do this (command line, Linux):
virtualenv my_env
This creates a new python binary and library location, and symlinks to your existing system libraries by default. Then, to switch paths to use the new environment, you do this:
source my_env/bin/activate
That's it. Now if you install modules (e.g. with easy_install), they get installed to the lib directory of the my_env directory. They don't interfere with existing libraries, you don't get weird conflicts, stuff doesn't stop working in your old environment. They're completely isolated.
To exit the environment, just do
deactivate
If you decide you made a mistake with an installation, or you don't want that environment anymore, just delete the directory:
rm -rf my_env
And you're done. It's really that simple.
virtualenv is great. ;)
A:
Take a look at virtualenv.
A:
Some tips:
on Mac OS X, use only the python installation in /Library/Frameworks/Python.framework.
whenever you use numpy/scipy/matplotlib, install the enthought python distribution
use virtualenv and virtualenvwrapper to keep those "system" installations pristine; ideally use one virtual environment per project, so each project's dependencies are fulfilled. And, yes, that means potentially a lot of code will be replicated in the various virtual envs.
That seems like a bigger mess indeed, but at least things work that way. Basically, if one of the projects works in a virtualenv, it will keep working no matter what upgrades you perform, since you never change the "system" installs.
A:
What I usually do is trying to (progressively) keep up with the Python versions as they come along (and once all of the external dependencies have correct versions available).
Most of the time the Python code itself can be transferred as-is with only minor needed modifications.
My biggest Python project @ work (15.000+ LOC) is now on Python 2.6 a few months (upgrading everything from Python 2.5 did take most of a day due to installing / checking 10+ dependencies...)
In general I think this is the best strategy with most of the interdependent components in the free software stack (think the dependencies in the linux software repositories): keep your versions (semi)-current (or at least: progressing at the same pace).
A:
install the python versions you need, better if from sources
when you write a script, include the full python version into it (such as #!/usr/local/bin/python2.6)
I can't see what could go wrong.
If something does, it's probably macports fault anyway, not yours (one of the reasons I don't use macports anymore).
I know I'm probably missing something and this will get downvoted, but please leave at least a little comment in that case, thanks :)
A:
I use the MacPorts version for everything, but as you note a lot of the default versions are bizarrely old. For example vim omnicomplete in Snow Leopard has python25 as a dependency. A lot of python related ports have old dependencies but you can usually flag the newer version at build time, for example port install vim +python26 instead of port install vim +python. Do a dry run before installing anything to see if you are pulling, for example, the whole of python24 when it isn't necessary. Check portfiles often because the naming convention as Darwin ports was getting off the ground left something to be desired. In practice I just leave everything in the default /opt... folders of MacPorts, including a copy of the entire framework with duplicates of PyObjC, etc., and just stick with one version at a time, retaining the option to return to the system default if things break unexpectedly. Which is all perhaps a bit too much work to avoid using virtualenv, which I've been meaning to get around to using.
A:
I've had good luck using Buildout. You set up a list of which eggs and which versions you want. Buildout then downloads and installs private versions of each for you. It makes a private "python" binary with all the eggs already installed. A local "nosetests" makes things easy to debug. You can extend the build with your own functions.
On the down side, Buildout can be quite mysterious. Do "buildout -vvvv" for a while to see exactly what it's doing and why.
http://www.buildout.org/docs/tutorial.html
A:
At least under Linux, multiple pythons can co-exist fairly happily. I use Python 2.6 on a CentOS system that needs Python 2.4 to be the default for various system things. I simply compiled and installed python 2.6 into a separate directory tree (and added the appropriate bin directory to my path) which was fairly painless. It's then invoked by typing "python2.6".
Once you have separate pythons up and running, installing libraries for a specific version is straightforward. If you invoke the setup.py script with the python you want, it will be installed in directories appropriate to that python, and scripts will be installed in the same directory as the python executable itself and will automagically use the correct python when invoked.
I also try to avoid using too many libraries. When I only need one or two functions from a library (eg scipy), I'll often see if I can just copy them to my own project.
| How to maintain long-lived python projects w.r.t. dependencies and python versions? | short version: how can I get rid of the multiple-versions-of-python nightmare ?
long version: over the years, I've used several versions of python, and what is worse, several extensions to python (e.g. pygame, pylab, wxPython...). Each time it was on a different setup, with different OSes, sometimes different architectures (like my old PowerPC mac).
Nowadays I'm using a mac (OSX 10.6 on x86-64) and it's a dependency nightmare each time I want to revive script older than a few months. Python itself already comes in three different flavours in /usr/bin (2.5, 2.6, 3.1), but I had to install 2.4 from macports for pygame, something else (cannot remember what) forced me to install all three others from macports as well, so at the end of the day I'm the happy owner of seven (!) instances of python on my system.
But that's not the problem, the problem is, none of them has the right (i.e. same set of) libraries installed, some of them are 32bits, some 64bits, and now I'm pretty much lost.
For example right now I'm trying to run a three-year-old script (not written by me) which used to use matplotlib/numpy to draw a real-time plot within a rectangle of a wxwidgets window. But I'm failing miserably: py26-wxpython from macports won't install, stock python has wxwidgets included but also has some conflict between 32 bits and 64 bits, and it doesn't have numpy... what a mess !
Obviously, I'm doing things the wrong way. How do you usally cope with all that chaos ?
| [
"I solve this using virtualenv. I sympathise with wanting to avoid further layers of nightmare abstraction, but virtualenv is actually amazingly clean and simple to use. You literally do this (command line, Linux):\nvirtualenv my_env\n\nThis creates a new python binary and library location, and symlinks to your existing system libraries by default. Then, to switch paths to use the new environment, you do this:\nsource my_env/bin/activate\n\nThat's it. Now if you install modules (e.g. with easy_install), they get installed to the lib directory of the my_env directory. They don't interfere with existing libraries, you don't get weird conflicts, stuff doesn't stop working in your old environment. They're completely isolated.\nTo exit the environment, just do\ndeactivate\n\nIf you decide you made a mistake with an installation, or you don't want that environment anymore, just delete the directory:\nrm -rf my_env\n\nAnd you're done. It's really that simple.\nvirtualenv is great. ;)\n",
"Take a look at virtualenv.\n",
"Some tips:\n\non Mac OS X, use only the python installation in /Library/Frameworks/Python.framework.\nwhenever you use numpy/scipy/matplotlib, install the enthought python distribution\nuse virtualenv and virtualenvwrapper to keep those \"system\" installations pristine; ideally use one virtual environment per project, so each project's dependencies are fulfilled. And, yes, that means potentially a lot of code will be replicated in the various virtual envs.\n\nThat seems like a bigger mess indeed, but at least things work that way. Basically, if one of the projects works in a virtualenv, it will keep working no matter what upgrades you perform, since you never change the \"system\" installs.\n",
"What I usually do is trying to (progressively) keep up with the Python versions as they come along (and once all of the external dependencies have correct versions available).\nMost of the time the Python code itself can be transferred as-is with only minor needed modifications.\nMy biggest Python project @ work (15.000+ LOC) is now on Python 2.6 a few months (upgrading everything from Python 2.5 did take most of a day due to installing / checking 10+ dependencies...)\nIn general I think this is the best strategy with most of the interdependent components in the free software stack (think the dependencies in the linux software repositories): keep your versions (semi)-current (or at least: progressing at the same pace).\n",
"\ninstall the python versions you need, better if from sources\nwhen you write a script, include the full python version into it (such as #!/usr/local/bin/python2.6)\n\nI can't see what could go wrong.\nIf something does, it's probably macports fault anyway, not yours (one of the reasons I don't use macports anymore).\nI know I'm probably missing something and this will get downvoted, but please leave at least a little comment in that case, thanks :)\n",
"I use the MacPorts version for everything, but as you note a lot of the default versions are bizarrely old. For example vim omnicomplete in Snow Leopard has python25 as a dependency. A lot of python related ports have old dependencies but you can usually flag the newer version at build time, for example port install vim +python26 instead of port install vim +python. Do a dry run before installing anything to see if you are pulling, for example, the whole of python24 when it isn't necessary. Check portfiles often because the naming convention as Darwin ports was getting off the ground left something to be desired. In practice I just leave everything in the default /opt... folders of MacPorts, including a copy of the entire framework with duplicates of PyObjC, etc., and just stick with one version at a time, retaining the option to return to the system default if things break unexpectedly. Which is all perhaps a bit too much work to avoid using virtualenv, which I've been meaning to get around to using.\n",
"I've had good luck using Buildout. You set up a list of which eggs and which versions you want. Buildout then downloads and installs private versions of each for you. It makes a private \"python\" binary with all the eggs already installed. A local \"nosetests\" makes things easy to debug. You can extend the build with your own functions.\nOn the down side, Buildout can be quite mysterious. Do \"buildout -vvvv\" for a while to see exactly what it's doing and why.\nhttp://www.buildout.org/docs/tutorial.html\n",
"At least under Linux, multiple pythons can co-exist fairly happily. I use Python 2.6 on a CentOS system that needs Python 2.4 to be the default for various system things. I simply compiled and installed python 2.6 into a separate directory tree (and added the appropriate bin directory to my path) which was fairly painless. It's then invoked by typing \"python2.6\".\nOnce you have separate pythons up and running, installing libraries for a specific version is straightforward. If you invoke the setup.py script with the python you want, it will be installed in directories appropriate to that python, and scripts will be installed in the same directory as the python executable itself and will automagically use the correct python when invoked.\nI also try to avoid using too many libraries. When I only need one or two functions from a library (eg scipy), I'll often see if I can just copy them to my own project.\n"
] | [
10,
4,
4,
1,
1,
0,
0,
0
] | [] | [] | [
"dependencies",
"installation",
"multiple_versions",
"python"
] | stackoverflow_0002759623_dependencies_installation_multiple_versions_python.txt |
Q:
How do you PEP 8-name a class whose name is an acronym?
I try to adhere to the style guide for Python code (also known as PEP 8). Accordingly, the preferred way to name a class is using CamelCase:
Almost without exception, class names
use the CapWords convention. Classes for internal use have a leading underscore in addition.
How can I be consistent with PEP 8 if my class name is formed by two acronyms (which in proper English should be capitalized). For instance, if my class name was 'NASA JPL', what would you name it?:
class NASAJPL(): # 1
class NASA_JPL(): # 2
class NasaJpl(): # 3
I am using #1, but it looks weird; #3 looks weird too, and #2 seems to violate PEP 8.
A:
PEP-8 does cover this (at least partially):
Note: When using abbreviations in CapWords, capitalize all the letters of the abbreviation. Thus HTTPServerError is better than HttpServerError.
Which I would read to mean that NASAJPL() is the recommended name according to PEP-8.
Personally I'd find NasaJpl() the easiest to scan since the upper case letters easily mark word boundaries and give the name a distinctive shape.
A:
As others have noted, NASAJPL is probably the PEP-8 approved form.
Just to be contrary, however, I would probably use NasaJPL. Because if you are reading it, you pronounce "NASA" as a single word, whereas "JPL" you spell out.
You can make an argument that this is consistent with PEP-8, since "NASA" is an acronym, but "JPL" is an abbreviation (or initialism, if you want to get pedantic).
A:
#1 in this particular case looks fine to me (if it's really an acronym). Out of curiosity, what does it stand for (and what exactly is the class instance, maybe a module would be the more appropriate divisor)?
class NASAJPL:
When you're combining two acronyms chances are you want to divide functionality over modules (you never know when you're adding that next feature to your program):
from NASA import JPL
from NASA import ARC
A:
I also work in an acronym-heavy environment. I tend to prefer form #3 because even though it lower-cases parts of an acronym, it clearly delineates parts of the name. It also avoids confusion when part of the name is an acronym and part is a word.
A:
You're Doing it Right.
If ChristophD's split it into a module hierarchy suggestion isn't a viable option, then I'd suggest your #2 form (class NASA_JPL ():) is the most legible, PEP-8 be damned.
No, really...
That said... I don't think PEP-8 need be damned in order for you to use that option and still adhere to its core principles. As you point out in your original question, itself, the first sentence of the "CamelCase class names" guideline begins:
Almost without exception, [...]
PEP-8's "fundamental principles" statement, as Dan alludes to with the "A Foolish Consistency [...]" line, declares legibility and comprehensibility the primary goals of PEP-8's recommendations. PEP-8 is a collection of established, successful patterns in service to those goals.
Emerson on the application of PEP-8 to reality...
Fundamentally, any system has aspects which are necessarily inconsistent with the character of the whole. When a system makes good and consistent use of a style guide's recommendations, any inconsistencies will be conscious responses to necessity. (I regard maintaining the legibility of corner cases as a necessity.)
When handled this way, those inconsistencies, counter-intuitively, reinforce the cohesion of the whole, rather than disrupting it.
PEP-8 states this more succinctly (and, thus, more usefully):
But most importantly: know when to be inconsistent -- sometimes the style
guide just doesn't apply. When in doubt, use your best judgment. Look
at other examples and decide what looks best. And don't hesitate to ask!
Two good reasons to break a particular rule:
When applying the rule would make the code less readable, even for someone who is used to reading code that follows the rules.
To be consistent with surrounding code that also breaks it (maybe for historic reasons)—although this is also an opportunity to clean up someone else's mess (in true XP style).
A:
I tend to use #3. It looks weird at first but you (sort of) get used to it. I went this way after suffering for too long under strings of acronyms jammed together, e.g. NPCAIXMLParser was one. I decided that NpcAiXmlParser was much easier to read and have been doing that ever since, even though seeing these things lowercased still looks weird sometimes.
In terms of "the standards," I tend to think of these entities as "words" and as such capitalize them as I would capitalize any other word. E.g. if I had a local variable representing some NPC (non-player character), I would name it 'npc' and not 'nPC'.
In regards to PEP-8, I disagree with this statement; I find the last spelling of the word to be preferable.
Note: When using abbreviations in
CapWords, capitalize all the letters
of the abbreviation. Thus
HTTPServerError is better than
HttpServerError.
A:
Number 1 is too hard to read for me - there's no way to tell that's it's two acronyms.
Number 2 violates PEP8, but looks fine. Remember "A foolish consistency is the hobgoblin of little minds"
I like number 3 the best, but I do a lot of C# programming - that's how you'd be supposed to do it in C#.
A:
It depends on the acronym. Another option would be class NASAJpl():, which makes it seem that "NASA" is the primary part, and "JPL" is the subordinate part.
| How do you PEP 8-name a class whose name is an acronym? | I try to adhere to the style guide for Python code (also known as PEP 8). Accordingly, the preferred way to name a class is using CamelCase:
Almost without exception, class names
use the CapWords convention. Classes for internal use have a leading underscore in addition.
How can I be consistent with PEP 8 if my class name is formed by two acronyms (which in proper English should be capitalized). For instance, if my class name was 'NASA JPL', what would you name it?:
class NASAJPL(): # 1
class NASA_JPL(): # 2
class NasaJpl(): # 3
I am using #1, but it looks weird; #3 looks weird too, and #2 seems to violate PEP 8.
| [
"PEP-8 does cover this (at least partially):\n\nNote: When using abbreviations in CapWords, capitalize all the letters of the abbreviation. Thus HTTPServerError is better than HttpServerError.\n\nWhich I would read to mean that NASAJPL() is the recommended name according to PEP-8. \nPersonally I'd find NasaJpl() the easiest to scan since the upper case letters easily mark word boundaries and give the name a distinctive shape.\n",
"As others have noted, NASAJPL is probably the PEP-8 approved form.\nJust to be contrary, however, I would probably use NasaJPL. Because if you are reading it, you pronounce \"NASA\" as a single word, whereas \"JPL\" you spell out.\nYou can make an argument that this is consistent with PEP-8, since \"NASA\" is an acronym, but \"JPL\" is an abbreviation (or initialism, if you want to get pedantic).\n",
"#1 in this particular case looks fine to me (if it's really an acronym). Out of curiosity, what does it stand for (and what exactly is the class instance, maybe a module would be the more appropriate divisor)?\nclass NASAJPL:\n\nWhen you're combining two acronyms chances are you want to divide functionality over modules (you never know when you're adding that next feature to your program):\nfrom NASA import JPL\nfrom NASA import ARC\n\n",
"I also work in an acronym-heavy environment. I tend to prefer form #3 because even though it lower-cases parts of an acronym, it clearly delineates parts of the name. It also avoids confusion when part of the name is an acronym and part is a word. \n",
"You're Doing it Right.\nIf ChristophD's split it into a module hierarchy suggestion isn't a viable option, then I'd suggest your #2 form (class NASA_JPL ():) is the most legible, PEP-8 be damned.\nNo, really...\nThat said... I don't think PEP-8 need be damned in order for you to use that option and still adhere to its core principles. As you point out in your original question, itself, the first sentence of the \"CamelCase class names\" guideline begins:\n\nAlmost without exception, [...]\n\nPEP-8's \"fundamental principles\" statement, as Dan alludes to with the \"A Foolish Consistency [...]\" line, declares legibility and comprehensibility the primary goals of PEP-8's recommendations. PEP-8 is a collection of established, successful patterns in service to those goals.\nEmerson on the application of PEP-8 to reality...\nFundamentally, any system has aspects which are necessarily inconsistent with the character of the whole. When a system makes good and consistent use of a style guide's recommendations, any inconsistencies will be conscious responses to necessity. (I regard maintaining the legibility of corner cases as a necessity.)\nWhen handled this way, those inconsistencies, counter-intuitively, reinforce the cohesion of the whole, rather than disrupting it.\nPEP-8 states this more succinctly (and, thus, more usefully):\n\nBut most importantly: know when to be inconsistent -- sometimes the style\nguide just doesn't apply. When in doubt, use your best judgment. Look\nat other examples and decide what looks best. And don't hesitate to ask!\nTwo good reasons to break a particular rule:\n\nWhen applying the rule would make the code less readable, even for someone who is used to reading code that follows the rules.\n\nTo be consistent with surrounding code that also breaks it (maybe for historic reasons)—although this is also an opportunity to clean up someone else's mess (in true XP style).\n\n\n\n",
"I tend to use #3. It looks weird at first but you (sort of) get used to it. I went this way after suffering for too long under strings of acronyms jammed together, e.g. NPCAIXMLParser was one. I decided that NpcAiXmlParser was much easier to read and have been doing that ever since, even though seeing these things lowercased still looks weird sometimes.\nIn terms of \"the standards,\" I tend to think of these entities as \"words\" and as such capitalize them as I would capitalize any other word. E.g. if I had a local variable representing some NPC (non-player character), I would name it 'npc' and not 'nPC'.\nIn regards to PEP-8, I disagree with this statement; I find the last spelling of the word to be preferable.\n\nNote: When using abbreviations in\n CapWords, capitalize all the letters\n of the abbreviation. Thus\n HTTPServerError is better than\n HttpServerError.\n\n",
"Number 1 is too hard to read for me - there's no way to tell that's it's two acronyms.\nNumber 2 violates PEP8, but looks fine. Remember \"A foolish consistency is the hobgoblin of little minds\"\nI like number 3 the best, but I do a lot of C# programming - that's how you'd be supposed to do it in C#.\n",
"It depends on the acronym. Another option would be class NASAJpl():, which makes it seem that \"NASA\" is the primary part, and \"JPL\" is the subordinate part.\n"
] | [
101,
38,
11,
9,
7,
6,
3,
1
] | [] | [] | [
"coding_style",
"naming_conventions",
"python"
] | stackoverflow_0002853531_coding_style_naming_conventions_python.txt |
Q:
Reversing Django URLs With Extra Options
Suppose I have a URLconf like below, and 'foo' and 'bar' are valid values for page_slug.
urlpatterns = patterns('',
(r'^page/(?P<page_slug>.*)/', 'myapp.views.someview'),
)
Then, I could reconstruct the URLs using the below, right?
>>> from django.core.urlresolvers import reverse
>>> reverse('myapp.views.someview', kwargs={'page_slug': 'foo'})
'/page/foo/'
>>> reverse('myapp.views.someview', kwargs={'page_slug': 'bar'})
'/page/bar/'
But what if I change my URLconf to this?
urlpatterns = patterns('',
(r'^foo-direct/', 'myapp.views.someview', {'page_slug': 'foo'}),
(r'^my-bar-page/', 'myapp.views.someview', {'page_slug': 'bar'}),
)
I expected this result:
>>> from django.core.urlresolvers import reverse
>>> reverse('myapp.views.someview', kwargs={'page_slug': 'foo'})
'/foo-direct/'
>>> reverse('myapp.views.someview', kwargs={'page_slug': 'bar'})
'/my-bar-page/'
However, this throws a NoReverseMatch exception. I suspect I'm trying to do something impossible. Any suggestions on a saner way to accomplish what I want?
Named URLs aren't an option, since I don't want other apps that link to these to need to know about the specifics of the URL structure (encapsulation and all that).
A:
You should try naming your urlconfs. Example:
urlpatterns = patterns('',
url(r'^foo-direct/', 'myapp.views.someview', {'page_slug': 'foo'}, name='foo-direct'),
url(r'^my-bar-page/', 'myapp.views.someview', {'page_slug': 'bar'}, name='bar-page'),
)
Then just edit your reverses and you should get it working.
>>> from django.core.urlresolvers import reverse
>>> reverse('foo-direct', kwargs={'page_slug': 'foo'})
'/foo-direct/'
>>> reverse('bar-page', kwargs={'page_slug': 'bar'})
'/my-bar-page/'
More info at: Django Docs
A:
Here's what we do.
urls.py has patterns like this
url(r'^(?P< datarealm >.*?)/json/someClass/(?P<object_id>.*?)/$', 'json_someClass_resource', ),
views.py as reverse calls like this
object = SomeModel.objects.get(...)
url= reverse('json_someClass_resource', kwargs={'object_id':object.id,'datarealm':object.datarealm.name})
A:
Named urls ought to be an option. Your case is highlighted in the Django reference:
http://docs.djangoproject.com/en/dev/topics/http/urls/?from=olddocs#id2
I'm not sure the designers left another work-around; they expected named urls to cover it.
May I digress about encapsulation? Thanks. There are two main reasons:
Abstraction--no one wants to see the details
Security--no one should see the details
As for 1, you can get a decent amount of mileage out of it in python, and Django is an excellent example. As for 2, it's an interpreted language. Either you're running it where it's written, or you're shipping off compiled .pyc files. If that's really what you're doing, then compile the url conf.
Finally, it seems less encapsulated to let other apps know about the functions than the url structure. But if you really disagree, I think you'll have to implement a more flexible reverse method yourself.
| Reversing Django URLs With Extra Options | Suppose I have a URLconf like below, and 'foo' and 'bar' are valid values for page_slug.
urlpatterns = patterns('',
(r'^page/(?P<page_slug>.*)/', 'myapp.views.someview'),
)
Then, I could reconstruct the URLs using the below, right?
>>> from django.core.urlresolvers import reverse
>>> reverse('myapp.views.someview', kwargs={'page_slug': 'foo'})
'/page/foo/'
>>> reverse('myapp.views.someview', kwargs={'page_slug': 'bar'})
'/page/bar/'
But what if I change my URLconf to this?
urlpatterns = patterns('',
(r'^foo-direct/', 'myapp.views.someview', {'page_slug': 'foo'}),
(r'^my-bar-page/', 'myapp.views.someview', {'page_slug': 'bar'}),
)
I expected this result:
>>> from django.core.urlresolvers import reverse
>>> reverse('myapp.views.someview', kwargs={'page_slug': 'foo'})
'/foo-direct/'
>>> reverse('myapp.views.someview', kwargs={'page_slug': 'bar'})
'/my-bar-page/'
However, this throws a NoReverseMatch exception. I suspect I'm trying to do something impossible. Any suggestions on a saner way to accomplish what I want?
Named URLs aren't an option, since I don't want other apps that link to these to need to know about the specifics of the URL structure (encapsulation and all that).
| [
"You should try naming your urlconfs. Example:\nurlpatterns = patterns('',\n url(r'^foo-direct/', 'myapp.views.someview', {'page_slug': 'foo'}, name='foo-direct'),\n url(r'^my-bar-page/', 'myapp.views.someview', {'page_slug': 'bar'}, name='bar-page'),\n)\n\nThen just edit your reverses and you should get it working.\n>>> from django.core.urlresolvers import reverse\n>>> reverse('foo-direct', kwargs={'page_slug': 'foo'})\n'/foo-direct/'\n>>> reverse('bar-page', kwargs={'page_slug': 'bar'})\n'/my-bar-page/'\n\nMore info at: Django Docs\n",
"Here's what we do.\nurls.py has patterns like this\nurl(r'^(?P< datarealm >.*?)/json/someClass/(?P<object_id>.*?)/$', 'json_someClass_resource', ),\n\nviews.py as reverse calls like this\n object = SomeModel.objects.get(...)\n url= reverse('json_someClass_resource', kwargs={'object_id':object.id,'datarealm':object.datarealm.name})\n\n",
"Named urls ought to be an option. Your case is highlighted in the Django reference:\nhttp://docs.djangoproject.com/en/dev/topics/http/urls/?from=olddocs#id2\nI'm not sure the designers left another work-around; they expected named urls to cover it.\nMay I digress about encapsulation? Thanks. There are two main reasons:\n\nAbstraction--no one wants to see the details\nSecurity--no one should see the details\n\nAs for 1, you can get a decent amount of mileage out of it in python, and Django is an excellent example. As for 2, it's an interpreted language. Either you're running it where it's written, or you're shipping off compiled .pyc files. If that's really what you're doing, then compile the url conf.\nFinally, it seems less encapsulated to let other apps know about the functions than the url structure. But if you really disagree, I think you'll have to implement a more flexible reverse method yourself.\n"
] | [
21,
7,
4
] | [] | [] | [
"django",
"python"
] | stackoverflow_0000659832_django_python.txt |
Q:
Lisp vs Python -- Static Compilation
Why can Lisp with all its dynamic features be statically compiled but Python cannot (without losing all its dynamic features)?
A:
There is nothing that prevents static compilation of Python. It's a bit less efficient because Python reveals more mutable local scope, also, to retain some of the dynamic properties (e.g. eval) you need to include the compiler with the compiled program but nothing prevents that too.
That said, research shows that most Python programs, while dynamic under static analysis, are rather static and monomorphic at runtime. This means that runtime JIT compilation approaches work much better on Python programs. See unladen-swallow, PyPy, Psyco for approaches that do compile Python into machine code. But also IronPython and Jython that use a virtual machines originally intended for a static languages to compile Python into machinecode.
A:
For what its worth, Python scripts are compiled into .pyc files when the are executed, see "Compiled" Python files.
You can also use a tool such as py2exe to compile a Python program into an executable.
A:
Actually, there isn't anything that stops you from statically compile a Python program, it's just that no-one wrote such a compiler so far (I personally find Python's runtime to be very easy compared to CL's).
You could say that the difference lies in details like "how much time was spent on actually writing compilers and does the language have a formal specification of how to write one".
Let's address those points:
Lisp compilers have been evolving for over 40 years now, with work starting back in 70's if not earlier (I'm not sure of my dates, too lazy too google exact ones). That creates a massive chunk of lore about how to write a compiler. OTOH, Python was nominally designed as "teaching language", and as such compilers weren't that important.
Lack of specification - Python doesn't have a single source specifying exact semantics of the language. Sure, you can point to PEP documents, but it still doesn't change the fact that the only real spec is the source of the main implementation, CPython. Which, nota bene, is a simple compiler of sorts (into bytecode).
As for whether it is possible - Python uses quite simple structure to deal with symbols etc., namely its dictionaries. You can treat them as symbol table of a program. You can tag the data types to recognize primitive ones and get the rest based on stored naming and internal structure. rest of the language is also quite simple. The only bit missing is actual work to implement it, and make it run correctly.
A:
Python can be 'compiled', where compilation is seen as a translation from one Turing Complete language (source code) to another (object code). However in Lisp, the object is assembly, something which is theoretically possible with Python (proven) but not feasible.
The true reason however is less flattening. Lisp is in many ways a revolutionary language that pioneered in its dialects a lot of the features in programming languages we are used to today. In Lisps however they just 'follow' logically from the basics of the language. Language which are inspired by the raw expressive powers of lisps such as JavaScript, Ruby, Perl and Python are necessarily interpreted because getting those features in a language with an 'Algol-like syntax' is just hard.
Lisp gains these features from being 'homo-iconic' there is no essential difference between a lisp program, and a lisp data-structure. Lisp programs are data-structures, they are structural descriptions of a program in such an S-expression if you like, therefore a compiled lisp program effectively 'interprets itself' without the need of a lexer and all that stuff, a lisp program could just be seen as a manual input of parse tree. Which necessitates a syntax which many people find counter-intuitive to work with, therefore there were a lot of attempts to transport the raw expressive power of the paradigm to a more readable syntax, which means that it's infeasible, but not impossible, to compile it towards assembly.
Also, compiling Python to assembly would possibly be slower and larger than 'half-interpreting' it on a virtual machine, a lot of features in python depend upon a syntactic analysis.
The above though is written by a huge lisp fanboy, keep that conflict of interest in mind.
| Lisp vs Python -- Static Compilation | Why can Lisp with all its dynamic features be statically compiled but Python cannot (without losing all its dynamic features)?
| [
"There is nothing that prevents static compilation of Python. It's a bit less efficient because Python reveals more mutable local scope, also, to retain some of the dynamic properties (e.g. eval) you need to include the compiler with the compiled program but nothing prevents that too.\nThat said, research shows that most Python programs, while dynamic under static analysis, are rather static and monomorphic at runtime. This means that runtime JIT compilation approaches work much better on Python programs. See unladen-swallow, PyPy, Psyco for approaches that do compile Python into machine code. But also IronPython and Jython that use a virtual machines originally intended for a static languages to compile Python into machinecode.\n",
"For what its worth, Python scripts are compiled into .pyc files when the are executed, see \"Compiled\" Python files.\nYou can also use a tool such as py2exe to compile a Python program into an executable.\n",
"Actually, there isn't anything that stops you from statically compile a Python program, it's just that no-one wrote such a compiler so far (I personally find Python's runtime to be very easy compared to CL's). \nYou could say that the difference lies in details like \"how much time was spent on actually writing compilers and does the language have a formal specification of how to write one\".\nLet's address those points:\n\nLisp compilers have been evolving for over 40 years now, with work starting back in 70's if not earlier (I'm not sure of my dates, too lazy too google exact ones). That creates a massive chunk of lore about how to write a compiler. OTOH, Python was nominally designed as \"teaching language\", and as such compilers weren't that important.\nLack of specification - Python doesn't have a single source specifying exact semantics of the language. Sure, you can point to PEP documents, but it still doesn't change the fact that the only real spec is the source of the main implementation, CPython. Which, nota bene, is a simple compiler of sorts (into bytecode).\n\nAs for whether it is possible - Python uses quite simple structure to deal with symbols etc., namely its dictionaries. You can treat them as symbol table of a program. You can tag the data types to recognize primitive ones and get the rest based on stored naming and internal structure. rest of the language is also quite simple. The only bit missing is actual work to implement it, and make it run correctly.\n",
"Python can be 'compiled', where compilation is seen as a translation from one Turing Complete language (source code) to another (object code). However in Lisp, the object is assembly, something which is theoretically possible with Python (proven) but not feasible.\nThe true reason however is less flattening. Lisp is in many ways a revolutionary language that pioneered in its dialects a lot of the features in programming languages we are used to today. In Lisps however they just 'follow' logically from the basics of the language. Language which are inspired by the raw expressive powers of lisps such as JavaScript, Ruby, Perl and Python are necessarily interpreted because getting those features in a language with an 'Algol-like syntax' is just hard. \nLisp gains these features from being 'homo-iconic' there is no essential difference between a lisp program, and a lisp data-structure. Lisp programs are data-structures, they are structural descriptions of a program in such an S-expression if you like, therefore a compiled lisp program effectively 'interprets itself' without the need of a lexer and all that stuff, a lisp program could just be seen as a manual input of parse tree. Which necessitates a syntax which many people find counter-intuitive to work with, therefore there were a lot of attempts to transport the raw expressive power of the paradigm to a more readable syntax, which means that it's infeasible, but not impossible, to compile it towards assembly.\nAlso, compiling Python to assembly would possibly be slower and larger than 'half-interpreting' it on a virtual machine, a lot of features in python depend upon a syntactic analysis.\nThe above though is written by a huge lisp fanboy, keep that conflict of interest in mind.\n"
] | [
13,
4,
4,
4
] | [] | [] | [
"compilation",
"dynamic_languages",
"lisp",
"python"
] | stackoverflow_0002812954_compilation_dynamic_languages_lisp_python.txt |
Q:
How should I build a simple database package for my python application?
I'm building a database library for my application using sqlite3 as the base. I want to structure it like so:
db/
__init__.py
users.py
blah.py
etc.py
So I would do this in Python:
import db
db.users.create('username', 'password')
I'm suffering analysis paralysis (oh no!) about how to handle the database connection. I don't really want to use classes in these modules, it doesn't really seem appropriate to be able to create a bunch of "users" objects that can all manipulate the same database in the same ways -- so inheriting a connection is a no-go.
Should I have one global connection to the database that all the modules use, and then put this in each module:
#users.py
from db_stuff import connection
Or should I create a new connection for each module and keep that alive?
Or should I create a new connection for every transaction?
How are these database connections supposed to be used? The same goes for cursor objects: Do I create a new cursor for each transaction? Create just one for each database connection?
A:
No, don't spread a connection over several modules - this is bad design. Have a single class handle the DB connection and provide services to other classes/modules in your application.
This isn't different from non-DB-related good design principles. A connection is a global resource. Sharing that resource over many modules is akin to having a global variable accessible from many places - which is by default a bad thing (unless you have a very compelling reason, but you don't). Encapsulate the global resource in a class to handle it.
A:
I know this doesn't really answer the actual question you asked, but the real answer is that you probably should not implement your own database package. You should probably use an existing one (e.g. SQLALchemy) and then use whatever pattern is standard for that library.
If you really want to do your own then the best approach is going to depend on a lot of factors, e.g. Is the project sure to only ever need a connection to one database?
If it's a fairly simple application I think importing a global connection object is probably the way to go. You can always swap it out for a connection pool behind the scenes, etc.
| How should I build a simple database package for my python application? | I'm building a database library for my application using sqlite3 as the base. I want to structure it like so:
db/
__init__.py
users.py
blah.py
etc.py
So I would do this in Python:
import db
db.users.create('username', 'password')
I'm suffering analysis paralysis (oh no!) about how to handle the database connection. I don't really want to use classes in these modules, it doesn't really seem appropriate to be able to create a bunch of "users" objects that can all manipulate the same database in the same ways -- so inheriting a connection is a no-go.
Should I have one global connection to the database that all the modules use, and then put this in each module:
#users.py
from db_stuff import connection
Or should I create a new connection for each module and keep that alive?
Or should I create a new connection for every transaction?
How are these database connections supposed to be used? The same goes for cursor objects: Do I create a new cursor for each transaction? Create just one for each database connection?
| [
"No, don't spread a connection over several modules - this is bad design. Have a single class handle the DB connection and provide services to other classes/modules in your application.\nThis isn't different from non-DB-related good design principles. A connection is a global resource. Sharing that resource over many modules is akin to having a global variable accessible from many places - which is by default a bad thing (unless you have a very compelling reason, but you don't). Encapsulate the global resource in a class to handle it.\n",
"I know this doesn't really answer the actual question you asked, but the real answer is that you probably should not implement your own database package. You should probably use an existing one (e.g. SQLALchemy) and then use whatever pattern is standard for that library.\nIf you really want to do your own then the best approach is going to depend on a lot of factors, e.g. Is the project sure to only ever need a connection to one database?\nIf it's a fairly simple application I think importing a global connection object is probably the way to go. You can always swap it out for a connection pool behind the scenes, etc.\n"
] | [
5,
3
] | [] | [] | [
"database",
"library_design",
"python",
"sqlite"
] | stackoverflow_0002854305_database_library_design_python_sqlite.txt |
Q:
Any other way to import data files(like .csv) in python sqlite3 module ? [not insert one by one]
In sqlite3's client CLI, there is " .import file TABLE_name " to do it.
But, I do not want to install sqlite3 to my server at present.
In python sqlite3 module, we can creat and edit a DB.
But, I have not found a way to import data-file to a TABLE,
except inserting rows one by one.
Any other way?
A:
You could insert at one shot using executemany command instead of inserting one by one
Lets say I have users.csv with following contents
"Hugo","Boss"
"Calvin","Klein"
and basically open with csv module and pass it to .executemany function
import csv,sqlite3
persons= csv.reader(open("users.csv"))
con = sqlite3.connect(":memory:")
con.execute("create table person(firstname, lastname)")
con.executemany("insert into person(firstname, lastname) values (?, ?)", persons)
for row in con.execute("select firstname, lastname from person"):
print row
#(u'Hugo', u'Boss')
#(u'Calvin', u'Klein')
| Any other way to import data files(like .csv) in python sqlite3 module ? [not insert one by one] | In sqlite3's client CLI, there is " .import file TABLE_name " to do it.
But, I do not want to install sqlite3 to my server at present.
In python sqlite3 module, we can creat and edit a DB.
But, I have not found a way to import data-file to a TABLE,
except inserting rows one by one.
Any other way?
| [
"You could insert at one shot using executemany command instead of inserting one by one\nLets say I have users.csv with following contents\n\"Hugo\",\"Boss\"\n\"Calvin\",\"Klein\"\n\nand basically open with csv module and pass it to .executemany function\nimport csv,sqlite3\n\npersons= csv.reader(open(\"users.csv\"))\ncon = sqlite3.connect(\":memory:\")\n\ncon.execute(\"create table person(firstname, lastname)\")\ncon.executemany(\"insert into person(firstname, lastname) values (?, ?)\", persons)\n\nfor row in con.execute(\"select firstname, lastname from person\"):\n print row\n\n#(u'Hugo', u'Boss')\n#(u'Calvin', u'Klein')\n\n"
] | [
7
] | [] | [] | [
"executemany",
"import",
"python",
"sqlite"
] | stackoverflow_0002854560_executemany_import_python_sqlite.txt |
Q:
making errorbars not clipped in matplotlib with Python
I am using matplotlib in Python to plot a line with errorbars as follows:
plt.errorbar(xvalues, up_densities, yerr=ctl_sds, fmt='-^', lw=1.2, markersize=markersize,
markeredgecolor=up_color, color=up_color, label="My label", clip_on=False)
plt.xticks(xvalues)
I set the ticks on the x-axis using "xticks". However, the error bars of the last point in xvalues (i.e. xvalues[-1]) are clipped on the right -- meaning only half an error bar appears. This is true even with the clip_on=False option. How can I fix this, so that the error bars appear in full, even though their right side is technically outside xvalues[-1]?
thanks.
A:
In matplotlib, most of the detailed control needs to be done through the Artists. I think this should do what you want:
import matplotlib.pyplot as plt
from random import uniform as r
x = range(10)
e = plt.errorbar(x, [r(2,10) for i in x], [r(.1,1) for i in x], capsize=8, color='r')
for b in e[1]:
b.set_clip_on(False)
plt.show()
The problem you were having is that the clip_on keyword was being used to control the markers and not the error bars. To control the errorbars, plt.errorbar returns a tuple, where the second item is a list of errorbars. So here I go through the list and turn the clipping off for each errorbar.
A:
Is this what you mean? Do you want to redefine the horizontal limits of your plot?
plt.errorbar(range(5), [3,2,4,5,1], yerr=[0.1,0.2,0.3,0.4,0.5])
ax = plt.gca()
ax.set_xlim([-0.5,4.5])
(source: stevetjoa.com)
| making errorbars not clipped in matplotlib with Python | I am using matplotlib in Python to plot a line with errorbars as follows:
plt.errorbar(xvalues, up_densities, yerr=ctl_sds, fmt='-^', lw=1.2, markersize=markersize,
markeredgecolor=up_color, color=up_color, label="My label", clip_on=False)
plt.xticks(xvalues)
I set the ticks on the x-axis using "xticks". However, the error bars of the last point in xvalues (i.e. xvalues[-1]) are clipped on the right -- meaning only half an error bar appears. This is true even with the clip_on=False option. How can I fix this, so that the error bars appear in full, even though their right side is technically outside xvalues[-1]?
thanks.
| [
"In matplotlib, most of the detailed control needs to be done through the Artists. I think this should do what you want:\nimport matplotlib.pyplot as plt\nfrom random import uniform as r\n\nx = range(10)\ne = plt.errorbar(x, [r(2,10) for i in x], [r(.1,1) for i in x], capsize=8, color='r')\n\nfor b in e[1]:\n b.set_clip_on(False)\n\nplt.show()\n\n\nThe problem you were having is that the clip_on keyword was being used to control the markers and not the error bars. To control the errorbars, plt.errorbar returns a tuple, where the second item is a list of errorbars. So here I go through the list and turn the clipping off for each errorbar.\n",
"Is this what you mean? Do you want to redefine the horizontal limits of your plot?\nplt.errorbar(range(5), [3,2,4,5,1], yerr=[0.1,0.2,0.3,0.4,0.5])\nax = plt.gca()\nax.set_xlim([-0.5,4.5])\n\n\n(source: stevetjoa.com) \n"
] | [
13,
0
] | [] | [] | [
"matplotlib",
"plot",
"python",
"scipy"
] | stackoverflow_0002842123_matplotlib_plot_python_scipy.txt |
Q:
Directly call distutils' or setuptools' setup() function with command name/options, without parsing the command line?
I'd like to call Python's distutils' or setuptools' setup() function in a slightly unconventional way, but I'm not sure whether distutils is meant for this kind of usage.
As an example, let's say I currently have a 'setup.py' file, which looks like this (lifted verbatim from the distutils docs--the setuptools usage is almost identical):
from distutils.core import setup
setup(name='Distutils',
version='1.0',
description='Python Distribution Utilities',
author='Greg Ward',
author_email='gward@python.net',
url='http://www.python.org/sigs/distutils-sig/',
packages=['distutils', 'distutils.command'],
)
Normally, to build just the .spec file for an RPM of this module, I could run python setup.py bdist_rpm --spec-only, which parses the command line and calls the 'bdist_rpm' code to handle the RPM-specific stuff. The .spec file ends up in './dist'.
How can I change my setup() invocation so that it runs the 'bdist_rpm' command with the '--spec-only' option, WITHOUT parsing command-line parameters? Can I pass the command name and options as parameters to setup()? Or can I manually construct a command line, and pass that as a parameter, instead?
NOTE: I already know that I could call the script in a separate process, with an actual command line, using os.system() or the subprocess module or something similar. I'm trying to avoid using any kind of external command invocations. I'm looking specifically for a solution that runs setup() in the current interpreter.
For background, I'm converting some release-management shell scripts into a single Python program. One of the tasks is running 'setup.py' to generate a .spec file for further pre-release testing. Running 'setup.py' as an external command, with its own command line options, seems like an awkward method, and it complicates the rest of the program. I feel like there may be a more Pythonic way.
A:
Never tried this, but I did happen to look in distutils/core.py, where I notice this near the start of setup():
if 'script_name' not in attrs:
attrs['script_name'] = os.path.basename(sys.argv[0])
if 'script_args' not in attrs:
attrs['script_args'] = sys.argv[1:]
So, it looks as if you can "fake-out" setup() by adding:
setup(
...
script_name = 'setup.py',
script_args = ['bdist_rpm', '--spec-only']
)
A:
Just "fake" the commandline parameters -- e.g, start you script with
import sys
sys.argv[1:] = ['bdist_rpm', '--spec-only']
from distutils.core import setup
setup(name='Distutils',
etc, etc. After all, that's how distutils gets the command line parameters: it looks in sys.argv! So, just set sys.argv to be exactly as you want it, and whatever command line the misguided user typed will be completely ignored.
Actually, you might want to check if the user did enter any argument you're about to ignore -- len(sys.argv) > 1 before you modify sys.argv -- and give a warning, or avoid the alteration of sys.argv, or "merge" what the user typed, etc... but that's quite different from what you actually asked, so I'm going to leave it at that;-).
| Directly call distutils' or setuptools' setup() function with command name/options, without parsing the command line? | I'd like to call Python's distutils' or setuptools' setup() function in a slightly unconventional way, but I'm not sure whether distutils is meant for this kind of usage.
As an example, let's say I currently have a 'setup.py' file, which looks like this (lifted verbatim from the distutils docs--the setuptools usage is almost identical):
from distutils.core import setup
setup(name='Distutils',
version='1.0',
description='Python Distribution Utilities',
author='Greg Ward',
author_email='gward@python.net',
url='http://www.python.org/sigs/distutils-sig/',
packages=['distutils', 'distutils.command'],
)
Normally, to build just the .spec file for an RPM of this module, I could run python setup.py bdist_rpm --spec-only, which parses the command line and calls the 'bdist_rpm' code to handle the RPM-specific stuff. The .spec file ends up in './dist'.
How can I change my setup() invocation so that it runs the 'bdist_rpm' command with the '--spec-only' option, WITHOUT parsing command-line parameters? Can I pass the command name and options as parameters to setup()? Or can I manually construct a command line, and pass that as a parameter, instead?
NOTE: I already know that I could call the script in a separate process, with an actual command line, using os.system() or the subprocess module or something similar. I'm trying to avoid using any kind of external command invocations. I'm looking specifically for a solution that runs setup() in the current interpreter.
For background, I'm converting some release-management shell scripts into a single Python program. One of the tasks is running 'setup.py' to generate a .spec file for further pre-release testing. Running 'setup.py' as an external command, with its own command line options, seems like an awkward method, and it complicates the rest of the program. I feel like there may be a more Pythonic way.
| [
"Never tried this, but I did happen to look in distutils/core.py, where I notice this near the start of setup():\nif 'script_name' not in attrs:\n attrs['script_name'] = os.path.basename(sys.argv[0])\nif 'script_args' not in attrs:\n attrs['script_args'] = sys.argv[1:]\n\nSo, it looks as if you can \"fake-out\" setup() by adding:\nsetup(\n ...\n script_name = 'setup.py',\n script_args = ['bdist_rpm', '--spec-only']\n)\n\n",
"Just \"fake\" the commandline parameters -- e.g, start you script with\nimport sys\n\nsys.argv[1:] = ['bdist_rpm', '--spec-only']\n\nfrom distutils.core import setup\n\nsetup(name='Distutils',\n\netc, etc. After all, that's how distutils gets the command line parameters: it looks in sys.argv! So, just set sys.argv to be exactly as you want it, and whatever command line the misguided user typed will be completely ignored.\nActually, you might want to check if the user did enter any argument you're about to ignore -- len(sys.argv) > 1 before you modify sys.argv -- and give a warning, or avoid the alteration of sys.argv, or \"merge\" what the user typed, etc... but that's quite different from what you actually asked, so I'm going to leave it at that;-).\n"
] | [
15,
2
] | [] | [] | [
"distutils",
"python",
"setuptools"
] | stackoverflow_0002850971_distutils_python_setuptools.txt |
Q:
Eventlet and locking
Since Eventlet uses green threading and asynchronous I/O, do I still need to set locks before accessing objects? My understanding is that greenlets are all part of one thread and locking isn't necessary. Can anyone confirm or deny this?
A:
Your understanding is correct: "green" threads are not actually threads, they don't get pre-empted at unpredictable points (esp. not "in the middle" of an operation), so you have full control of when execution moves away from one (and can thus get dispatched to another) and can save yourself the trouble/overhead of lock acquire/release operations.
| Eventlet and locking | Since Eventlet uses green threading and asynchronous I/O, do I still need to set locks before accessing objects? My understanding is that greenlets are all part of one thread and locking isn't necessary. Can anyone confirm or deny this?
| [
"Your understanding is correct: \"green\" threads are not actually threads, they don't get pre-empted at unpredictable points (esp. not \"in the middle\" of an operation), so you have full control of when execution moves away from one (and can thus get dispatched to another) and can save yourself the trouble/overhead of lock acquire/release operations.\n"
] | [
7
] | [] | [] | [
"python"
] | stackoverflow_0002851499_python.txt |
Q:
Advantages of using *args in python instead of passing a list as a parameter
I'm going through python and I was wondering what are the advantages of using the *args as a parameter over just passing a list as a parameter, besides aesthetics?
A:
Generally it's used to either pass a list of arguments to a function that would normally take a fixed number of arguments, or in function definitions to allow a variable number of arguments to be passed in the style of normal arguments. For instance, the print() function uses varargs so that you can do things like print(a,b,c).
One example from a recent SO question: you can use it to pass a list of range() result lists to itertools.product() without having to know the length of the list-of-lists.
Sure, you could write every library function to look like this:
def libfunc1(arglist):
arg1 = arglist[1]
arg2 = arglist[2]
...
...but that defeats the point of having named positional argument variables, it's basically exactly what *args does for you, and it results in redundant braces/parens, since you'd have to call a function like this:
libfunc1([arg1val,arg2val,...])
...which looks very similar to...
libfunc1(arg1val,arg2val,...)
...except with unnecessary characters, as opposed to using *args.
A:
That is for flexibility.
It allows you to pass on the arguments, without knowing how much you need. A typical example:
def f(some, args, here): # <- this function might accept a varying nb of args
...
def run_f(args, *f_args):
do_something(args)
# run f with whatever arguments were given:
f(*f_args)
Make sure to check out the ** keyword version.
| Advantages of using *args in python instead of passing a list as a parameter | I'm going through python and I was wondering what are the advantages of using the *args as a parameter over just passing a list as a parameter, besides aesthetics?
| [
"Generally it's used to either pass a list of arguments to a function that would normally take a fixed number of arguments, or in function definitions to allow a variable number of arguments to be passed in the style of normal arguments. For instance, the print() function uses varargs so that you can do things like print(a,b,c).\nOne example from a recent SO question: you can use it to pass a list of range() result lists to itertools.product() without having to know the length of the list-of-lists.\nSure, you could write every library function to look like this:\ndef libfunc1(arglist):\n arg1 = arglist[1]\n arg2 = arglist[2]\n ...\n\n...but that defeats the point of having named positional argument variables, it's basically exactly what *args does for you, and it results in redundant braces/parens, since you'd have to call a function like this:\nlibfunc1([arg1val,arg2val,...])\n\n...which looks very similar to...\nlibfunc1(arg1val,arg2val,...)\n\n...except with unnecessary characters, as opposed to using *args.\n",
"That is for flexibility.\nIt allows you to pass on the arguments, without knowing how much you need. A typical example:\ndef f(some, args, here): # <- this function might accept a varying nb of args\n ...\n\ndef run_f(args, *f_args):\n do_something(args)\n # run f with whatever arguments were given:\n f(*f_args)\n\nMake sure to check out the ** keyword version.\n"
] | [
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0002855500_python.txt |
Q:
Gzip and subprocess' stdout in python
I'm using python 2.6.4 and discovered that I can't use gzip with subprocess the way I might hope. This illustrates the problem:
May 17 18:05:36> python
Python 2.6.4 (r264:75706, Mar 10 2010, 14:41:19)
[GCC 4.1.2 20071124 (Red Hat 4.1.2-42)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import gzip
>>> import subprocess
>>> fh = gzip.open("tmp","wb")
>>> subprocess.Popen("echo HI", shell=True, stdout=fh).wait()
0
>>> fh.close()
>>>
[2]+ Stopped python
May 17 18:17:49> file tmp
tmp: data
May 17 18:17:53> less tmp
"tmp" may be a binary file. See it anyway?
May 17 18:17:58> zcat tmp
zcat: tmp: not in gzip format
Here's what it looks like inside less
HI
^_<8B>^H^Hh<C0><F1>K^B<FF>tmp^@^C^@^@^@^@^@^@^@^@^@
which looks like it put in the stdout as text and then put in an empty gzip file. Indeed, if I remove the "Hi\n", then I get this:
May 17 18:22:34> file tmp
tmp: gzip compressed data, was "tmp", last modified: Mon May 17 18:17:12 2010, max compression
What is going on here?
UPDATE:
This earlier question is asking the same thing: Can I use an opened gzip file with Popen in Python?
A:
You can't use file-likes with subprocess, only real files. The fileno() method of GzipFile returns the FD of the underlying file, so that's what the echo redirects to. The GzipFile then closes, writing an empty gzip file.
A:
just pipe that sucker
from subprocess import Popen,PIPE
GZ = Popen("gzip > outfile.gz",stdin=PIPE,shell=True)
P = Popen("echo HI",stdout=GZ.stdin,shell=True)
# these next three must be in order
P.wait()
GZ.stdin.close()
GZ.wait()
A:
I'm not totally sure why this isn't working (perhaps the output redirection is not calling python's write, which is what gzip works with?) but this works:
>>> fh.write(subprocess.Popen("echo Hi", shell=True, stdout=subprocess.PIPE).stdout.read())
| Gzip and subprocess' stdout in python | I'm using python 2.6.4 and discovered that I can't use gzip with subprocess the way I might hope. This illustrates the problem:
May 17 18:05:36> python
Python 2.6.4 (r264:75706, Mar 10 2010, 14:41:19)
[GCC 4.1.2 20071124 (Red Hat 4.1.2-42)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import gzip
>>> import subprocess
>>> fh = gzip.open("tmp","wb")
>>> subprocess.Popen("echo HI", shell=True, stdout=fh).wait()
0
>>> fh.close()
>>>
[2]+ Stopped python
May 17 18:17:49> file tmp
tmp: data
May 17 18:17:53> less tmp
"tmp" may be a binary file. See it anyway?
May 17 18:17:58> zcat tmp
zcat: tmp: not in gzip format
Here's what it looks like inside less
HI
^_<8B>^H^Hh<C0><F1>K^B<FF>tmp^@^C^@^@^@^@^@^@^@^@^@
which looks like it put in the stdout as text and then put in an empty gzip file. Indeed, if I remove the "Hi\n", then I get this:
May 17 18:22:34> file tmp
tmp: gzip compressed data, was "tmp", last modified: Mon May 17 18:17:12 2010, max compression
What is going on here?
UPDATE:
This earlier question is asking the same thing: Can I use an opened gzip file with Popen in Python?
| [
"You can't use file-likes with subprocess, only real files. The fileno() method of GzipFile returns the FD of the underlying file, so that's what the echo redirects to. The GzipFile then closes, writing an empty gzip file.\n",
"just pipe that sucker\nfrom subprocess import Popen,PIPE\nGZ = Popen(\"gzip > outfile.gz\",stdin=PIPE,shell=True)\nP = Popen(\"echo HI\",stdout=GZ.stdin,shell=True)\n# these next three must be in order\nP.wait()\nGZ.stdin.close()\nGZ.wait()\n\n",
"I'm not totally sure why this isn't working (perhaps the output redirection is not calling python's write, which is what gzip works with?) but this works:\n>>> fh.write(subprocess.Popen(\"echo Hi\", shell=True, stdout=subprocess.PIPE).stdout.read())\n\n"
] | [
10,
8,
1
] | [
"You don't need to use subprocess to write to the gzip.GzipFile. Instead, write to it like any other file-like object. The result is automagically gzipped!\nimport gzip\nwith gzip.open(\"tmp.gz\", \"wb\") as fh:\n fh.write('echo HI')\n\n"
] | [
-1
] | [
"gzip",
"python",
"subprocess"
] | stackoverflow_0002853339_gzip_python_subprocess.txt |
Q:
gevent install on x86_64 fails: "undefined symbol: evhttp_accept_socket"
I'm trying to install gevent on a fresh EC2 CentOS 5.3 64-bit system.
Since the libevent version available in yum was too old for another package (beanstalkd) I compiled/installed libevent-1.4.13-stable manually using the following command:
./configure --prefix=/usr && make && make install
This is the output from installing gevent:
[gevent-0.12.2]# python setup.py build --libevent /usr/lib
Using libevent 1.4.13-stable: libevent.so
running build
running build_py
running build_ext
Linking /usr/src/gevent-0.12.2/build/lib.linux-x86_64-2.6/gevent/core.so to
/usr/src/gevent-0.12.2/gevent/core.so
[gevent-0.12.2]# cd /path/to/my/project
[project]# python myscript.py
Traceback (most recent call last):
File "myscript.py", line 9, in <module>
from gevent.wsgi import WSGIServer as GeventServer
File "/usr/lib/python2.6/site-packages/gevent/__init__.py", line 32, in <module>
from gevent.core import reinit
ImportError: /usr/lib/python2.6/site-packages/gevent/core.so: undefined symbol: evhttp_accept_socket
I've followed exactly the same steps on a local VirtualBox instance (32-bit) and I'm not seeing any errors.
How would I fix this?
A:
Easiest fix was to clone the git repository, switch to the wip-all branch, and run python setup.py build_libevent build install which grabs & builds libevent statically against gevent:
# git clone http://github.com/schmir/gevent.git
# cd gevent
# git branch -a
* upstream
origin/HEAD
origin/close-socket-cancel-event
origin/pywsgi-without-basehttpserver
origin/upstream
origin/wip-all
origin/wip-setup-config
# git checkout origin/wip-all
# python setup.py build_libevent build install
More information here.
| gevent install on x86_64 fails: "undefined symbol: evhttp_accept_socket" | I'm trying to install gevent on a fresh EC2 CentOS 5.3 64-bit system.
Since the libevent version available in yum was too old for another package (beanstalkd) I compiled/installed libevent-1.4.13-stable manually using the following command:
./configure --prefix=/usr && make && make install
This is the output from installing gevent:
[gevent-0.12.2]# python setup.py build --libevent /usr/lib
Using libevent 1.4.13-stable: libevent.so
running build
running build_py
running build_ext
Linking /usr/src/gevent-0.12.2/build/lib.linux-x86_64-2.6/gevent/core.so to
/usr/src/gevent-0.12.2/gevent/core.so
[gevent-0.12.2]# cd /path/to/my/project
[project]# python myscript.py
Traceback (most recent call last):
File "myscript.py", line 9, in <module>
from gevent.wsgi import WSGIServer as GeventServer
File "/usr/lib/python2.6/site-packages/gevent/__init__.py", line 32, in <module>
from gevent.core import reinit
ImportError: /usr/lib/python2.6/site-packages/gevent/core.so: undefined symbol: evhttp_accept_socket
I've followed exactly the same steps on a local VirtualBox instance (32-bit) and I'm not seeing any errors.
How would I fix this?
| [
"Easiest fix was to clone the git repository, switch to the wip-all branch, and run python setup.py build_libevent build install which grabs & builds libevent statically against gevent:\n# git clone http://github.com/schmir/gevent.git\n# cd gevent\n# git branch -a\n* upstream\n origin/HEAD\n origin/close-socket-cancel-event\n origin/pywsgi-without-basehttpserver\n origin/upstream\n origin/wip-all\n origin/wip-setup-config\n# git checkout origin/wip-all\n# python setup.py build_libevent build install\n\nMore information here.\n"
] | [
3
] | [] | [] | [
"gevent",
"libevent",
"python"
] | stackoverflow_0002849964_gevent_libevent_python.txt |
Q:
adding the feedparser module to python
I recently downloaded and installed feedparser with python,
I tried to run it but Netbeans shouts on import:
ImportError: No module named feedparser
restarted the Netbeans, still no go.
A:
Netbeans by default uses Jython,
if you go to Tools>Python Platforms and see that Jython is the default.
Switch it to Python and so the installed libraries would work.
If you already have a project, you should right click on it, choose Python and on the platform choose Python instead of Jython.
A:
You might need to set the PYTHONPATH environment variable to include the install path of feedparser. Just a guess, but this has fixed this issue in the past for me.
| adding the feedparser module to python | I recently downloaded and installed feedparser with python,
I tried to run it but Netbeans shouts on import:
ImportError: No module named feedparser
restarted the Netbeans, still no go.
| [
"Netbeans by default uses Jython, \nif you go to Tools>Python Platforms and see that Jython is the default. \nSwitch it to Python and so the installed libraries would work. \nIf you already have a project, you should right click on it, choose Python and on the platform choose Python instead of Jython.\n",
"You might need to set the PYTHONPATH environment variable to include the install path of feedparser. Just a guess, but this has fixed this issue in the past for me.\n"
] | [
1,
0
] | [] | [] | [
"feedparser",
"netbeans",
"python"
] | stackoverflow_0002852301_feedparser_netbeans_python.txt |
Q:
Using Django with mod_wsgi
When you use Django with mod_wsgi, what exactly happens when a user makes a request to the server from a browser? Does apache load up your Django app when it starts and have it running in a separate process? Does it create a new Python process for every HTTP request?
A:
In embedded mode, the Django app is part of the httpd worker. In daemon mode, the Django app is a separate process and the httpd worker communicates with it over a socket. In either case, the WSGI interface is the same.
| Using Django with mod_wsgi | When you use Django with mod_wsgi, what exactly happens when a user makes a request to the server from a browser? Does apache load up your Django app when it starts and have it running in a separate process? Does it create a new Python process for every HTTP request?
| [
"In embedded mode, the Django app is part of the httpd worker. In daemon mode, the Django app is a separate process and the httpd worker communicates with it over a socket. In either case, the WSGI interface is the same.\n"
] | [
1
] | [] | [] | [
"django",
"mod_wsgi",
"python"
] | stackoverflow_0002856403_django_mod_wsgi_python.txt |
Q:
what is the '' of remote_api in google-app-engine
http://code.google.com/intl/en/appengine/docs/python/tools/uploadingdata.html
the api is :
Downloading Data from App Engine
To start a data download, run appcfg.py download_data with the appropriate arguments:
appcfg.py download_data --config_file=album_loader.py --filename=album_data_archive.csv --kind=Album <app-directory>
i want to download data from my gae app zjm1126.appspot.com
so i write this in the commond:
appcfg.py download_data --config_file=GreetingLoad.py --filename=GreetingLoad.csv
but, i don't know how to write the 'app-directory'
so , how to write the 'app-directory'..
thanks
updated
i use this:
appcfg.py download_data --config_file=helloworld/GreetingLoad.py --filename=a.csv --kind=Greeting helloworld
and the error is :
D:\zjm_code>appcfg.py download_data --config_file=helloworld/GreetingLoad.py --f
ilename=a.csv --kind=Greeting helloworld
Application: zjm1126; version: 1-h1.
Downloading data records.
[INFO ] Logging to bulkloader-log-20100518.195933
[INFO ] Throttling transfers:
[INFO ] Bandwidth: 250000 bytes/second
[INFO ] HTTP connections: 8/second
[INFO ] Entities inserted/fetched/modified: 20/second
[INFO ] Batch Size: 10
[INFO ] Opening database: bulkloader-progress-20100518.195933.sql3
Traceback (most recent call last):
File "d:\Program Files\Google\google_appengine\appcfg.py", line 68, in <module
>
run_file(__file__, globals())
File "d:\Program Files\Google\google_appengine\appcfg.py", line 64, in run_fil
e
execfile(script_path, globals_)
File "d:\Program Files\Google\google_appengine\google\appengine\tools\appcfg.p
y", line 2709, in <module>
main(sys.argv)
File "d:\Program Files\Google\google_appengine\google\appengine\tools\appcfg.p
y", line 2700, in main
result = AppCfgApp(argv).Run()
File "d:\Program Files\Google\google_appengine\google\appengine\tools\appcfg.p
y", line 1763, in Run
self.action(self)
File "d:\Program Files\Google\google_appengine\google\appengine\tools\appcfg.p
y", line 2580, in __call__
return method()
File "d:\Program Files\Google\google_appengine\google\appengine\tools\appcfg.p
y", line 2446, in PerformDownload
run_fn(args)
File "d:\Program Files\Google\google_appengine\google\appengine\tools\appcfg.p
y", line 2368, in RunBulkloader
sys.exit(bulkloader.Run(arg_dict))
File "D:\Program Files\Google\google_appengine\google\appengine\tools\bulkload
er.py", line 4012, in Run
return _PerformBulkload(arg_dict)
File "D:\Program Files\Google\google_appengine\google\appengine\tools\bulkload
er.py", line 3887, in _PerformBulkload
exporter = Exporter.RegisteredExporter(kind)
File "D:\Program Files\Google\google_appengine\google\appengine\tools\bulkload
er.py", line 2901, in RegisteredExporter
return Exporter.__exporters[kind]
KeyError: 'Greeting'
and my GreetingLoad.py is :
import datetime
from google.appengine.ext import db
from google.appengine.tools import bulkloader
class Greeting(db.Model):
author = db.UserProperty()
content = db.StringProperty(multiline=True)
date = db.DateTimeProperty(auto_now_add=True)
class GreetingLoader(bulkloader.Loader):
def __init__(self):
bulkloader.Loader.__init__(self, 'Greeting',
[('author', lambda x: x.decode('utf-8')),
('content', lambda x: x.decode('utf-8')),
('date',
lambda x: datetime.datetime.strptime(x, '%m/%d/%Y').date())
])
loaders = [GreetingLoader]
mu url is :
- url: /remote_api
script: $PYTHON_LIB/google/appengine/ext/remote_api/handler.py
login: admin
updated2
it is ok now ,thanks
appcfg.py download_data --config_file=helloworld/GreetingLoad.py --filename=a.csv --kind=Greeting helloworld
and
class AlbumExporter(bulkloader.Exporter):
def __init__(self):
bulkloader.Exporter.__init__(self, 'Greeting',
[('author', str, None),
('content', str, None),
('date', str, None),
])
exporters = [AlbumExporter]
A:
Please take a look at this article, it explains how to set up downloading data: http://code.google.com/appengine/docs/python/tools/uploadingdata.html
The app-directory is the path you set up in the app.yaml file to map to the remote_api:
- url: /app-directory
script: $PYTHON_LIB/google/appengine/ext/remote_api/handler.py
login: admin
To answer the updated question:
change your loaders = ... line to exporters = [GreetingExporter]
| what is the '' of remote_api in google-app-engine | http://code.google.com/intl/en/appengine/docs/python/tools/uploadingdata.html
the api is :
Downloading Data from App Engine
To start a data download, run appcfg.py download_data with the appropriate arguments:
appcfg.py download_data --config_file=album_loader.py --filename=album_data_archive.csv --kind=Album <app-directory>
i want to download data from my gae app zjm1126.appspot.com
so i write this in the commond:
appcfg.py download_data --config_file=GreetingLoad.py --filename=GreetingLoad.csv
but, i don't know how to write the 'app-directory'
so , how to write the 'app-directory'..
thanks
updated
i use this:
appcfg.py download_data --config_file=helloworld/GreetingLoad.py --filename=a.csv --kind=Greeting helloworld
and the error is :
D:\zjm_code>appcfg.py download_data --config_file=helloworld/GreetingLoad.py --f
ilename=a.csv --kind=Greeting helloworld
Application: zjm1126; version: 1-h1.
Downloading data records.
[INFO ] Logging to bulkloader-log-20100518.195933
[INFO ] Throttling transfers:
[INFO ] Bandwidth: 250000 bytes/second
[INFO ] HTTP connections: 8/second
[INFO ] Entities inserted/fetched/modified: 20/second
[INFO ] Batch Size: 10
[INFO ] Opening database: bulkloader-progress-20100518.195933.sql3
Traceback (most recent call last):
File "d:\Program Files\Google\google_appengine\appcfg.py", line 68, in <module
>
run_file(__file__, globals())
File "d:\Program Files\Google\google_appengine\appcfg.py", line 64, in run_fil
e
execfile(script_path, globals_)
File "d:\Program Files\Google\google_appengine\google\appengine\tools\appcfg.p
y", line 2709, in <module>
main(sys.argv)
File "d:\Program Files\Google\google_appengine\google\appengine\tools\appcfg.p
y", line 2700, in main
result = AppCfgApp(argv).Run()
File "d:\Program Files\Google\google_appengine\google\appengine\tools\appcfg.p
y", line 1763, in Run
self.action(self)
File "d:\Program Files\Google\google_appengine\google\appengine\tools\appcfg.p
y", line 2580, in __call__
return method()
File "d:\Program Files\Google\google_appengine\google\appengine\tools\appcfg.p
y", line 2446, in PerformDownload
run_fn(args)
File "d:\Program Files\Google\google_appengine\google\appengine\tools\appcfg.p
y", line 2368, in RunBulkloader
sys.exit(bulkloader.Run(arg_dict))
File "D:\Program Files\Google\google_appengine\google\appengine\tools\bulkload
er.py", line 4012, in Run
return _PerformBulkload(arg_dict)
File "D:\Program Files\Google\google_appengine\google\appengine\tools\bulkload
er.py", line 3887, in _PerformBulkload
exporter = Exporter.RegisteredExporter(kind)
File "D:\Program Files\Google\google_appengine\google\appengine\tools\bulkload
er.py", line 2901, in RegisteredExporter
return Exporter.__exporters[kind]
KeyError: 'Greeting'
and my GreetingLoad.py is :
import datetime
from google.appengine.ext import db
from google.appengine.tools import bulkloader
class Greeting(db.Model):
author = db.UserProperty()
content = db.StringProperty(multiline=True)
date = db.DateTimeProperty(auto_now_add=True)
class GreetingLoader(bulkloader.Loader):
def __init__(self):
bulkloader.Loader.__init__(self, 'Greeting',
[('author', lambda x: x.decode('utf-8')),
('content', lambda x: x.decode('utf-8')),
('date',
lambda x: datetime.datetime.strptime(x, '%m/%d/%Y').date())
])
loaders = [GreetingLoader]
mu url is :
- url: /remote_api
script: $PYTHON_LIB/google/appengine/ext/remote_api/handler.py
login: admin
updated2
it is ok now ,thanks
appcfg.py download_data --config_file=helloworld/GreetingLoad.py --filename=a.csv --kind=Greeting helloworld
and
class AlbumExporter(bulkloader.Exporter):
def __init__(self):
bulkloader.Exporter.__init__(self, 'Greeting',
[('author', str, None),
('content', str, None),
('date', str, None),
])
exporters = [AlbumExporter]
| [
"Please take a look at this article, it explains how to set up downloading data: http://code.google.com/appengine/docs/python/tools/uploadingdata.html\nThe app-directory is the path you set up in the app.yaml file to map to the remote_api:\n- url: /app-directory\n script: $PYTHON_LIB/google/appengine/ext/remote_api/handler.py\n login: admin\n\nTo answer the updated question:\nchange your loaders = ... line to exporters = [GreetingExporter]\n"
] | [
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0002856178_google_app_engine_python.txt |
Q:
Python (Django). Store telnet connection
I am programming web interface which communicates with cisco switches via telnet. I want to make such system which will be storing one telnet connection per switch and every script (web interface, cron jobs, etc.) will have access to it. This is needed to make a single query queue for each device and prevent huge cisco processor load caused by several concurent telnet connections.
How do I can do this?
updated
Option with connection handling daemon is good and will work in the best way. Sharing telnet connection object between scripts may be difficult to implement and debug. But this option is interesting because interface is using only by couple of operators and cron jobs.
A:
The usual way would be to have a process running in the background that keeps hold of the persistent telnet connections and commands queued to go down them.
Then have the front-end scripts connect to it (eg. via a unix socket) to queue commands and get the results asynchronously.
But this might be overkill. How many people are you expecting to be using a switch interface concurrently? A lightweight alternative for just the web part of it would be to keep the telnet connection object in the web scripts, and configure the web server/gateway to only launch one instance of your webapp at once.
| Python (Django). Store telnet connection | I am programming web interface which communicates with cisco switches via telnet. I want to make such system which will be storing one telnet connection per switch and every script (web interface, cron jobs, etc.) will have access to it. This is needed to make a single query queue for each device and prevent huge cisco processor load caused by several concurent telnet connections.
How do I can do this?
updated
Option with connection handling daemon is good and will work in the best way. Sharing telnet connection object between scripts may be difficult to implement and debug. But this option is interesting because interface is using only by couple of operators and cron jobs.
| [
"The usual way would be to have a process running in the background that keeps hold of the persistent telnet connections and commands queued to go down them.\nThen have the front-end scripts connect to it (eg. via a unix socket) to queue commands and get the results asynchronously.\nBut this might be overkill. How many people are you expecting to be using a switch interface concurrently? A lightweight alternative for just the web part of it would be to keep the telnet connection object in the web scripts, and configure the web server/gateway to only launch one instance of your webapp at once.\n"
] | [
1
] | [] | [] | [
"django",
"python",
"telnet",
"telnetlib"
] | stackoverflow_0002856356_django_python_telnet_telnetlib.txt |
Q:
How can I create a key using RSA/ECB/PKCS1Padding in python?
I am struggling to find any method of using RSA in ECB mode with PKCS1 padding in python. I've looked into pyCrypto, but they don't have PKCS1 padding in the master branch (but do in a patch). Nevertheless I found RSA with PKCS1 in the M2Crypto package, but I'm not sure if I can choose ECB mode...
A:
Chaining mode such as ECB makes no sense for RSA, unless you are doing it wrong.
ECB is for block ciphers: the input data is split into equal-size blocks, and each block is encrypted separately. This induces some weaknesses so ECB mode is best avoided for block ciphers.
RSA is not a block cipher. In particular, RSA necessarily enlarges the encrypted message: with a 1024-bit RSA key (a fairly typical size), one can encrypt a message up to 117 bytes, but the result is a 128-byte value.
One could imagine taking a larger message, split it into individual blocks of length 117 bytes (or less) and RSA-encrypt each of them individually, but nobody ever does that, mostly because of the size increase, and the CPU cost. Also, security issues related to that splitting and recombining are not studied at all, so it is quite possible that the result would be quite weak. Usually, when a cryptographic library requires a padding mode as part of an algorithm name, such as in "RSA/ECB/PKCS1Padding", this is only due to the syntaxic constraints on the name, and the chaining part (ECB) is actually ignored (this is what Java does, for instance).
In practice, when encrypting some data which may be larger than the maximum RSA input size, hybrid encryption is used: what is RSA-encrypted is a random symmetric key (e.g. a bunch of 16 uniformly random bytes), and that key is used to symmetrically encrypt (e.g. with AES) the actual data. This is more space-effective (because symmetric encryption does not enlarge blocks) and CPU-efficient (symmetric encryption is vastly faster than asymmetric encryption, and in particular RSA decryption).
| How can I create a key using RSA/ECB/PKCS1Padding in python? | I am struggling to find any method of using RSA in ECB mode with PKCS1 padding in python. I've looked into pyCrypto, but they don't have PKCS1 padding in the master branch (but do in a patch). Nevertheless I found RSA with PKCS1 in the M2Crypto package, but I'm not sure if I can choose ECB mode...
| [
"Chaining mode such as ECB makes no sense for RSA, unless you are doing it wrong.\nECB is for block ciphers: the input data is split into equal-size blocks, and each block is encrypted separately. This induces some weaknesses so ECB mode is best avoided for block ciphers.\nRSA is not a block cipher. In particular, RSA necessarily enlarges the encrypted message: with a 1024-bit RSA key (a fairly typical size), one can encrypt a message up to 117 bytes, but the result is a 128-byte value.\nOne could imagine taking a larger message, split it into individual blocks of length 117 bytes (or less) and RSA-encrypt each of them individually, but nobody ever does that, mostly because of the size increase, and the CPU cost. Also, security issues related to that splitting and recombining are not studied at all, so it is quite possible that the result would be quite weak. Usually, when a cryptographic library requires a padding mode as part of an algorithm name, such as in \"RSA/ECB/PKCS1Padding\", this is only due to the syntaxic constraints on the name, and the chaining part (ECB) is actually ignored (this is what Java does, for instance).\nIn practice, when encrypting some data which may be larger than the maximum RSA input size, hybrid encryption is used: what is RSA-encrypted is a random symmetric key (e.g. a bunch of 16 uniformly random bytes), and that key is used to symmetrically encrypt (e.g. with AES) the actual data. This is more space-effective (because symmetric encryption does not enlarge blocks) and CPU-efficient (symmetric encryption is vastly faster than asymmetric encryption, and in particular RSA decryption).\n"
] | [
13
] | [] | [] | [
"encryption",
"python",
"rsa"
] | stackoverflow_0002855326_encryption_python_rsa.txt |
Q:
OOWrite is to LaTeX as OODraw is to?
I'm looking for a tool to nicely generate single-page PDFs. My needs are:
Able to put a PDF/EPS/... as a background
Absolute positioning
Able to define tables, lists
Able to rotate blocks
Reasonably easy syntax (will be used to automatically generate many similar looking documents)
Easily usable from Python
Free or very cheap
In essence I'm looking for the tool X that is to OODraw/CorelDraw/... as LaTeX is to OOWrite/MS Word.
I've looked at webkit2pdf and a headless OODraw, but both seem a bit of an overkill. XML-FO has some limitations such as not being able to predict how many pages your document spans. Reportlab is pricey.
Any ideas?
Thanks!
A:
Definitely PGF/TikZ. Selling point:
Created by this code:
% Rooty helix
% Author: Felix Lindemann
\documentclass{minimal}
\usepackage{tikz}
\usetikzlibrary{calc}
\begin{document}
\pagestyle{empty}
\pgfdeclarelayer{background}
\pgfdeclarelayer{foreground}
\pgfsetlayers{background,main,foreground}
\xdefinecolor{darkgreen}{RGB}{175, 193, 36}
\newcounter{cntShader}
\newcounter{cntRoot}
\setcounter{cntShader}{20}
\def\couleur{darkgreen}
\begin{tikzpicture}
\foreach \y in {86,38,15}{
\setcounter{cntShader}{1}
\coordinate (a) at (0,0);
\coordinate (b) at (0:1);
\foreach \x in {1,...,\y}{%
\coordinate (c) at ($ (b)!1cm!270:(a) $);
\begin{pgfonlayer}{background}
\draw[fill=\couleur!\thecntShader] (a)--(b)--(c)--cycle;
\end{pgfonlayer}
\setcounter{cntRoot}{\x}
\addtocounter{cntRoot}{1}
\node[fill=white,draw,circle,inner sep=1pt] at (c)
{$\sqrt{\thecntRoot}$};
\coordinate (b) at (c);
\pgfmathsetcounter{cntShader}{\thecntShader+4}
\setcounter{cntShader}{\thecntShader}
}
}
\node[fill=white,draw,circle,inner sep=1pt] at (0:1) {$\sqrt{1}$};
\end{tikzpicture}
\end{document}
Blatantly stolen from the examples.
A:
An alternative to TikZ is using Metapost with Context: this is a slightly more expressive language than PGF, the basis language for TikZ, within a Tex-based processing language, Context, that is better suited for page layout in PDF than either Latex or Plain Tex.
Three points in favour of Context/Metapost:
The key expressive advantage Metapost has over PGF is that it is a constraint-solving language that can determine the intersection of curves. This allows one to specify recursive algorithms for tree layout, say, that pack the trees as closely as possible without overlap, something that can't be done in PGF. See section 9 of The Metapost user manual;
Context's layers allow PDF images to be inserted behind text or other PDF images fairly easily. See the entry on Layers at the Context wiki;
Context allows page layout to be specified with respect to grids, something that is really unpleasant to do with Latex. See section 3.4 of Context: the manual.
And three in favour of Latex/TikZ:
They're better documented and more widely used.
TikZ has a lovely library of sample graphics.
TikZ works with all the major Tex implementations, whilst Context is tied to Luatex.
The best place to start finding out about using Context with Metapost are the two (long!) introductory guides by Hans Hagen: Context: an excursion and Metafun (Metafun is an implementation of Metapost with some extensions).
A:
ReportLab might be a good solution:
The ReportLab Toolkit is the time-proven, ultra-robust open-source engine for programatically creating PDF documents and forms the foundation of RML; it also contains a library for creating platform-independent vector graphics. It's a fast, flexible, cross platform solution written in Python.
http://www.reportlab.com/software/opensource/
| OOWrite is to LaTeX as OODraw is to? | I'm looking for a tool to nicely generate single-page PDFs. My needs are:
Able to put a PDF/EPS/... as a background
Absolute positioning
Able to define tables, lists
Able to rotate blocks
Reasonably easy syntax (will be used to automatically generate many similar looking documents)
Easily usable from Python
Free or very cheap
In essence I'm looking for the tool X that is to OODraw/CorelDraw/... as LaTeX is to OOWrite/MS Word.
I've looked at webkit2pdf and a headless OODraw, but both seem a bit of an overkill. XML-FO has some limitations such as not being able to predict how many pages your document spans. Reportlab is pricey.
Any ideas?
Thanks!
| [
"Definitely PGF/TikZ. Selling point:\n\nCreated by this code:\n% Rooty helix\n% Author: Felix Lindemann\n\\documentclass{minimal}\n\n\\usepackage{tikz}\n\\usetikzlibrary{calc}\n\\begin{document}\n\n\\pagestyle{empty}\n\\pgfdeclarelayer{background}\n\\pgfdeclarelayer{foreground}\n\\pgfsetlayers{background,main,foreground}\n\n\\xdefinecolor{darkgreen}{RGB}{175, 193, 36}\n\\newcounter{cntShader}\n\\newcounter{cntRoot}\n\\setcounter{cntShader}{20}\n\\def\\couleur{darkgreen}\n\n\\begin{tikzpicture}\n \\foreach \\y in {86,38,15}{\n \\setcounter{cntShader}{1}\n \\coordinate (a) at (0,0);\n \\coordinate (b) at (0:1);\n \\foreach \\x in {1,...,\\y}{%\n \\coordinate (c) at ($ (b)!1cm!270:(a) $);\n \\begin{pgfonlayer}{background}\n \\draw[fill=\\couleur!\\thecntShader] (a)--(b)--(c)--cycle;\n \\end{pgfonlayer}\n \\setcounter{cntRoot}{\\x}\n \\addtocounter{cntRoot}{1}\n \\node[fill=white,draw,circle,inner sep=1pt] at (c)\n {$\\sqrt{\\thecntRoot}$};\n \\coordinate (b) at (c);\n \\pgfmathsetcounter{cntShader}{\\thecntShader+4}\n \\setcounter{cntShader}{\\thecntShader}\n }\n }\n \\node[fill=white,draw,circle,inner sep=1pt] at (0:1) {$\\sqrt{1}$};\n\\end{tikzpicture}\n\n\\end{document} \n\nBlatantly stolen from the examples.\n",
"An alternative to TikZ is using Metapost with Context: this is a slightly more expressive language than PGF, the basis language for TikZ, within a Tex-based processing language, Context, that is better suited for page layout in PDF than either Latex or Plain Tex.\nThree points in favour of Context/Metapost:\n\nThe key expressive advantage Metapost has over PGF is that it is a constraint-solving language that can determine the intersection of curves. This allows one to specify recursive algorithms for tree layout, say, that pack the trees as closely as possible without overlap, something that can't be done in PGF. See section 9 of The Metapost user manual;\nContext's layers allow PDF images to be inserted behind text or other PDF images fairly easily. See the entry on Layers at the Context wiki;\nContext allows page layout to be specified with respect to grids, something that is really unpleasant to do with Latex. See section 3.4 of Context: the manual.\n\nAnd three in favour of Latex/TikZ:\n\nThey're better documented and more widely used.\nTikZ has a lovely library of sample graphics.\nTikZ works with all the major Tex implementations, whilst Context is tied to Luatex.\n\nThe best place to start finding out about using Context with Metapost are the two (long!) introductory guides by Hans Hagen: Context: an excursion and Metafun (Metafun is an implementation of Metapost with some extensions).\n",
"ReportLab might be a good solution:\n\nThe ReportLab Toolkit is the time-proven, ultra-robust open-source engine for programatically creating PDF documents and forms the foundation of RML; it also contains a library for creating platform-independent vector graphics. It's a fast, flexible, cross platform solution written in Python.\n\nhttp://www.reportlab.com/software/opensource/\n"
] | [
12,
3,
0
] | [] | [] | [
"latex",
"pdf",
"python"
] | stackoverflow_0002850000_latex_pdf_python.txt |
Q:
numpy arange with multiple intervals
i have an numpy array which represents multiple x-intervals of a function:
In [137]: x_foo
Out[137]:
array([211, 212, 213, 214, 215, 216, 217, 218, 940, 941, 942, 943, 944,
945, 946, 947, 948, 949, 950])
as you can see, in x_foo are two intervals: one from 211 to 218, and one from 940 to 950. these are intervals, which i want to interpolate with scipy. for this, i need to adjust the spacing, e.g "211.0 211.1 211.2 ..." which you would normaly do with:
arange( x_foo[0], x_foo[-1], 0.1 )
in the case of multiple intervals, this is not possible. so heres my question: is there a numpy-thonic way to do this in array-style? or do i need to write a function which loops over the whole array and split if the difference is >1?
thanks!
A:
import numpy as np
x = np.array([211, 212, 213, 214, 215, 216, 217, 218, 940, 941, 942, 943, 944,
945, 946, 947, 948, 949, 950])
ind = np.where((x[1:] - x[:-1]) > 1)[0]
will give you the index for the element in x that is equal to 218. Then the two ranges you want are:
np.arange(x[0],x[ind],0.1)
and
np.arange(x[ind+1],x[-1],0.1)
A:
np.r_[ 211:218+1, 940:950+1 ]
array([211, 212, 213, 214, 215, 216, 217, 218, 940, 941, 942, 943, 944, 945, 946, 947, 948, 949, 950])
r_[] makes a row out of scalars, ranges, arrays, lists, tuples ...;
I guess r_ is short for row.
For doc, see np.r_? in Ipython.
(Python handles 211:218 inside square brackets but not round, hence r_[] not () ).
| numpy arange with multiple intervals | i have an numpy array which represents multiple x-intervals of a function:
In [137]: x_foo
Out[137]:
array([211, 212, 213, 214, 215, 216, 217, 218, 940, 941, 942, 943, 944,
945, 946, 947, 948, 949, 950])
as you can see, in x_foo are two intervals: one from 211 to 218, and one from 940 to 950. these are intervals, which i want to interpolate with scipy. for this, i need to adjust the spacing, e.g "211.0 211.1 211.2 ..." which you would normaly do with:
arange( x_foo[0], x_foo[-1], 0.1 )
in the case of multiple intervals, this is not possible. so heres my question: is there a numpy-thonic way to do this in array-style? or do i need to write a function which loops over the whole array and split if the difference is >1?
thanks!
| [
"import numpy as np\nx = np.array([211, 212, 213, 214, 215, 216, 217, 218, 940, 941, 942, 943, 944,\n 945, 946, 947, 948, 949, 950])\nind = np.where((x[1:] - x[:-1]) > 1)[0]\n\nwill give you the index for the element in x that is equal to 218. Then the two ranges you want are:\nnp.arange(x[0],x[ind],0.1)\n\nand\nnp.arange(x[ind+1],x[-1],0.1)\n\n",
"np.r_[ 211:218+1, 940:950+1 ]\narray([211, 212, 213, 214, 215, 216, 217, 218, 940, 941, 942, 943, 944, 945, 946, 947, 948, 949, 950])\n\nr_[] makes a row out of scalars, ranges, arrays, lists, tuples ...;\nI guess r_ is short for row.\nFor doc, see np.r_? in Ipython.\n(Python handles 211:218 inside square brackets but not round, hence r_[] not () ).\n"
] | [
3,
1
] | [] | [] | [
"interpolation",
"numpy",
"python",
"scipy"
] | stackoverflow_0002737487_interpolation_numpy_python_scipy.txt |
Q:
deployment public keys
How do you guys deploy your code on your servers? I am using Fabric and Python and I would like a more automated way of pulling code from the repository through the use of public keys, but without any ops or manual intervention to set up the public keys.
Are you storing them in the code as text or in a database and generate the pk file on the fly? Any other opinions on this one ?
A:
This is what ssh-copy-id is for. It deploys your public key onto a machine for you. Key management isn't something I'd suggest putting into code/VCS. Each user needs to setup their keys so that the local ssh client knows to use them. We use Fabric as well, but it only uses the key that the ssh config is already telling it to.
| deployment public keys | How do you guys deploy your code on your servers? I am using Fabric and Python and I would like a more automated way of pulling code from the repository through the use of public keys, but without any ops or manual intervention to set up the public keys.
Are you storing them in the code as text or in a database and generate the pk file on the fly? Any other opinions on this one ?
| [
"This is what ssh-copy-id is for. It deploys your public key onto a machine for you. Key management isn't something I'd suggest putting into code/VCS. Each user needs to setup their keys so that the local ssh client knows to use them. We use Fabric as well, but it only uses the key that the ssh config is already telling it to. \n"
] | [
1
] | [] | [] | [
"fabric",
"python"
] | stackoverflow_0002855650_fabric_python.txt |
Q:
Python __setattr__ and __getattr__ for global scope?
Suppose I need to create my own small DSL that would use Python to describe a certain data structure. E.g. I'd like to be able to write something like
f(x) = some_stuff(a,b,c)
and have Python, instead of complaining about undeclared identifiers or attempting to invoke the function some_stuff, convert it to a literal expression for my further convenience.
It is possible to get a reasonable approximation to this by creating a class with properly redefined __getattr__ and __setattr__ methods and use it as follows:
e = Expression()
e.f[e.x] = e.some_stuff(e.a, e.b, e.c)
It would be cool though, if it were possible to get rid of the annoying "e." prefixes and maybe even avoid the use of []. So I was wondering, is it possible to somehow temporarily "redefine" global name lookups and assignments? On a related note, maybe there are good packages for easily achieving such "quoting" functionality for Python expressions?
A:
I'm not sure it's a good idea, but I thought I'd give it a try. To summarize:
class PermissiveDict(dict):
default = None
def __getitem__(self, item):
try:
return dict.__getitem__(self, item)
except KeyError:
return self.default
def exec_with_default(code, default=None):
ns = PermissiveDict()
ns.default = default
exec code in ns
return ns
A:
You might want to take a look at the ast or parser modules included with Python to parse, access and transform the abstract syntax tree (or parse tree, respectively) of the input code. As far as I know, the Sage mathematical system, written in Python, has a similar sort of precompiler.
| Python __setattr__ and __getattr__ for global scope? | Suppose I need to create my own small DSL that would use Python to describe a certain data structure. E.g. I'd like to be able to write something like
f(x) = some_stuff(a,b,c)
and have Python, instead of complaining about undeclared identifiers or attempting to invoke the function some_stuff, convert it to a literal expression for my further convenience.
It is possible to get a reasonable approximation to this by creating a class with properly redefined __getattr__ and __setattr__ methods and use it as follows:
e = Expression()
e.f[e.x] = e.some_stuff(e.a, e.b, e.c)
It would be cool though, if it were possible to get rid of the annoying "e." prefixes and maybe even avoid the use of []. So I was wondering, is it possible to somehow temporarily "redefine" global name lookups and assignments? On a related note, maybe there are good packages for easily achieving such "quoting" functionality for Python expressions?
| [
"I'm not sure it's a good idea, but I thought I'd give it a try. To summarize:\nclass PermissiveDict(dict):\n default = None\n\n def __getitem__(self, item):\n try:\n return dict.__getitem__(self, item)\n except KeyError:\n return self.default\n\ndef exec_with_default(code, default=None):\n ns = PermissiveDict()\n ns.default = default\n exec code in ns\n return ns\n\n",
"You might want to take a look at the ast or parser modules included with Python to parse, access and transform the abstract syntax tree (or parse tree, respectively) of the input code. As far as I know, the Sage mathematical system, written in Python, has a similar sort of precompiler.\n"
] | [
3,
2
] | [
"In response to Wai's comment, here's one fun solution that I've found. First of all, to explain once more what it does, suppose that you have the following code:\ndefinitions = Structure()\ndefinitions.add_definition('f[x]', 'x*2')\ndefinitions.add_definition('f[z]', 'some_function(z)')\ndefinitions.add_definition('g.i', 'some_object[i].method(param=value)')\n\nwhere adding definitions implies parsing the left hand sides and the right hand sides and doing other ugly stuff. Now one (not necessarily good, but certainly fun) approach here would allow to write the above code as follows:\n@my_dsl\ndef definitions():\n f[x] = x*2\n f[z] = some_function(z)\n g.i = some_object[i].method(param=value)\n\nand have Python do most of the parsing under the hood.\nThe idea is based on the simple exec <code> in <environment> statement, mentioned by Ian, with one hackish addition. Namely, the bytecode of the function must be slightly tweaked and all local variable access operations (LOAD_FAST) switched to variable access from the environment (LOAD_NAME).\nIt is easier shown than explained: http://fouryears.eu/wp-content/uploads/pydsl/\nThere are various tricks you may want to do to make it practical. For example, in the code presented at the link above you can't use builtin functions and language constructions like for loops and if statements within a @my_dsl function. You can make those work, however, by adding more behaviour to the Env class.\nUpdate. Here is a slightly more verbose explanation of the same thing.\n"
] | [
-1
] | [
"lookup",
"python",
"quoting",
"redefine",
"variable_assignment"
] | stackoverflow_0002656697_lookup_python_quoting_redefine_variable_assignment.txt |
Q:
How to hide Cygwin Python console window in Windows?
How to hide Cygwin Python console window in Windows?
Neither pythonw, nor renaming to *.pyw does not seem to apply here, since Cygwin is a different build from regular Windows CPython build.
A:
A small .vbs launcher script should do the trick:
COMMAND = "c:\cygwin\bin\python <path_to_your.py>"
Set wshell = CreateObject("WScript.Shell")
Set proc = wshell.Environment("Process")
proc("PATH") = "c:\cygwin\bin;" & proc("PATH")
wshell.Run COMMAND, 0
| How to hide Cygwin Python console window in Windows? | How to hide Cygwin Python console window in Windows?
Neither pythonw, nor renaming to *.pyw does not seem to apply here, since Cygwin is a different build from regular Windows CPython build.
| [
"A small .vbs launcher script should do the trick:\nCOMMAND = \"c:\\cygwin\\bin\\python <path_to_your.py>\"\n\nSet wshell = CreateObject(\"WScript.Shell\")\nSet proc = wshell.Environment(\"Process\")\n\nproc(\"PATH\") = \"c:\\cygwin\\bin;\" & proc(\"PATH\")\n\nwshell.Run COMMAND, 0\n\n"
] | [
3
] | [] | [] | [
"cygwin",
"python",
"windows"
] | stackoverflow_0002854832_cygwin_python_windows.txt |
Q:
python binding of variable to particular expression
I am developing a simple application which hava a file Constants.py containing all configuration, it is like this
x = y
during execution of program , the value of y changes , I want value of x o get updated too , automatically, this can be reffered as binding, how can I achieve this
A:
In Python variable names point at values. x=y tells Python that the variable name x should point at the value that y is currently pointing at.
When you change y, then the variable name y points at a new value, while the variable name x still points at the old value.
You can not achieve what you want with plain variable names.
I like KennyTM's suggestion to define x as a function since it makes explicit that the value of x requires running some code (the lookup of the value of y).
However, if you want to maintain a uniform syntax (making all the constants accessible in the same way), then you could use a class with properties (attributes which call getter and setter functions):
Constants.py:
class BunchOConstants(object):
def __init__(self, **kwds):
self.__dict__.update(kwds)
@property
def x(self):
return self.y
@x.setter
def x(self,val):
self.y=val
const=BunchOConstants(y=10,z='foo')
Your script.py:
import Constants
const=Constants.const
print(const.y)
# 10
print(const.x)
# 10
Here you change the "constant" y:
const.y='bar'
And the "constant" x is changed too:
print(const.x)
# bar
You can change x also,
const.x='foo'
and y too gets changed:
print(const.y)
# foo
A:
If you change the value (object) itself, then all references to it will be updated:
>>> a = []
>>> b = a # b refers to the same object a is refering right now
>>> a.append('foo')
>>> print b
['foo']
However, if you make the name point to some other object, then other names will still reference whatever they were referencing before:
>>> a = 15
>>> print b
['foo']
That's how python works. Names are just references to objects. You can make a name reference the same object another name is referencing, but you can't make a name reference another name. Name attribution using the = operator (a = 15) changes what a refers to, so it can't affect other names.
A:
if your configuration values are inside a class, you could do something like this:
>>> class A(object):
... a = 4
... @property
... def b(self):
... return self.a
...
then, every time you access b, it will return the value of a.
A:
There is a simple solution you can do. Just define a property and ask for the fget value you defined.
For example:
a = 7
@property
def b():
return a
if you ask for b, you will get something like this <property object at 0x1150418> but if you do b.fget(), you will obtain the value 7
Now try this:
a = 9
b.fget() # this will give you 9. The current value of a
You don't need to have a class with this way, otherwise, I think you will need it.
| python binding of variable to particular expression | I am developing a simple application which hava a file Constants.py containing all configuration, it is like this
x = y
during execution of program , the value of y changes , I want value of x o get updated too , automatically, this can be reffered as binding, how can I achieve this
| [
"In Python variable names point at values. x=y tells Python that the variable name x should point at the value that y is currently pointing at.\nWhen you change y, then the variable name y points at a new value, while the variable name x still points at the old value.\nYou can not achieve what you want with plain variable names.\nI like KennyTM's suggestion to define x as a function since it makes explicit that the value of x requires running some code (the lookup of the value of y).\nHowever, if you want to maintain a uniform syntax (making all the constants accessible in the same way), then you could use a class with properties (attributes which call getter and setter functions):\nConstants.py:\nclass BunchOConstants(object):\n def __init__(self, **kwds):\n self.__dict__.update(kwds)\n @property\n def x(self):\n return self.y\n @x.setter\n def x(self,val):\n self.y=val\nconst=BunchOConstants(y=10,z='foo')\n\nYour script.py:\nimport Constants\n\nconst=Constants.const\nprint(const.y)\n# 10\nprint(const.x)\n# 10\n\nHere you change the \"constant\" y:\nconst.y='bar'\n\nAnd the \"constant\" x is changed too:\nprint(const.x)\n# bar\n\nYou can change x also,\nconst.x='foo'\n\nand y too gets changed:\nprint(const.y)\n# foo\n\n",
"If you change the value (object) itself, then all references to it will be updated:\n>>> a = []\n>>> b = a # b refers to the same object a is refering right now\n>>> a.append('foo')\n>>> print b\n['foo']\n\nHowever, if you make the name point to some other object, then other names will still reference whatever they were referencing before:\n>>> a = 15\n>>> print b\n['foo']\n\nThat's how python works. Names are just references to objects. You can make a name reference the same object another name is referencing, but you can't make a name reference another name. Name attribution using the = operator (a = 15) changes what a refers to, so it can't affect other names.\n",
"if your configuration values are inside a class, you could do something like this:\n>>> class A(object):\n... a = 4\n... @property\n... def b(self):\n... return self.a\n... \n\nthen, every time you access b, it will return the value of a.\n",
"There is a simple solution you can do. Just define a property and ask for the fget value you defined.\nFor example:\na = 7\n\n@property \ndef b():\n return a\n\nif you ask for b, you will get something like this <property object at 0x1150418> but if you do b.fget(), you will obtain the value 7\nNow try this:\na = 9\nb.fget() # this will give you 9. The current value of a\n\nYou don't need to have a class with this way, otherwise, I think you will need it.\n"
] | [
2,
0,
0,
0
] | [] | [] | [
"binding",
"python"
] | stackoverflow_0002856675_binding_python.txt |
Q:
python: calling constructor from dictionary?
I'm not quite sure of the terminology here so please bear with me....
Let's say I have a constructor call like this:
machineSpecificEnvironment = Environment(
TI_C28_ROOT = 'C:/appl/ti/ccs/4.1.1/ccsv4/tools/compiler/c2000',
JSDB = 'c:/bin/jsdb/jsdb.exe',
PYTHON_PATH = 'c:/appl/python/2.6.4',
)
except I would like to replace that by an operation on a dictionary provided to me:
keys = {'TI_C28_ROOT': 'C:/appl/ti/ccs/4.1.1/ccsv4/tools/compiler/c2000',
'JSDB': 'c:/bin/jsdb/jsdb.exe',
'PYTHON_PATH': 'c:/appl/python/2.6.4'}
machineSpecificEnvironment = Environment(
... what do I put here? it needs to be a function of "keys" ...
)
How can I do this?
A:
machineSpecificEnvironment = Environment(**keys)
A:
You can apply a dict as an argument list by the ** notation
machineSpecificEnvironment = Environment(**keys)
| python: calling constructor from dictionary? | I'm not quite sure of the terminology here so please bear with me....
Let's say I have a constructor call like this:
machineSpecificEnvironment = Environment(
TI_C28_ROOT = 'C:/appl/ti/ccs/4.1.1/ccsv4/tools/compiler/c2000',
JSDB = 'c:/bin/jsdb/jsdb.exe',
PYTHON_PATH = 'c:/appl/python/2.6.4',
)
except I would like to replace that by an operation on a dictionary provided to me:
keys = {'TI_C28_ROOT': 'C:/appl/ti/ccs/4.1.1/ccsv4/tools/compiler/c2000',
'JSDB': 'c:/bin/jsdb/jsdb.exe',
'PYTHON_PATH': 'c:/appl/python/2.6.4'}
machineSpecificEnvironment = Environment(
... what do I put here? it needs to be a function of "keys" ...
)
How can I do this?
| [
"machineSpecificEnvironment = Environment(**keys)\n\n",
"You can apply a dict as an argument list by the ** notation\nmachineSpecificEnvironment = Environment(**keys)\n\n"
] | [
5,
3
] | [] | [] | [
"argument_unpacking",
"dictionary",
"python"
] | stackoverflow_0002858070_argument_unpacking_dictionary_python.txt |
Q:
how to load a module within python debugger
This looks like something simple but I could not find the answer so far -
I have just learnt python and need to start learning pdb. In my module I have the usual if __name__ == __main_ trick to execute some code when the module is run as a program.
So far I have been running it via python -m mymod arg1 arg2 syntax
Now I want to do exactly the same thing from inside pdb. Normally in C, I would just do gdb mybinary followed by run arg1 arg2
But I cannot figure out how to achieve the same thing in pdb.
I am sure there has to be a simple way to achieve this but it is taking me too long to search for it..
Thanks for your help!
A:
Try:
python -m pdb mymod.py arg1 arg2
That should start up pdb debugging mymod.py (if mymod.py is not in the current directory then you'll have to specify the path).
Alternatively set a breakpoint in your code where you want to start debugging. The usual way to get a breakpoint into pdb is:
if somecondition:
import pdb; pdb.set_trace()
You can make the condition whatever is convenient to ensure the breakpoint doesn't trigger too soon.
| how to load a module within python debugger | This looks like something simple but I could not find the answer so far -
I have just learnt python and need to start learning pdb. In my module I have the usual if __name__ == __main_ trick to execute some code when the module is run as a program.
So far I have been running it via python -m mymod arg1 arg2 syntax
Now I want to do exactly the same thing from inside pdb. Normally in C, I would just do gdb mybinary followed by run arg1 arg2
But I cannot figure out how to achieve the same thing in pdb.
I am sure there has to be a simple way to achieve this but it is taking me too long to search for it..
Thanks for your help!
| [
"Try:\npython -m pdb mymod.py arg1 arg2\n\nThat should start up pdb debugging mymod.py (if mymod.py is not in the current directory then you'll have to specify the path).\nAlternatively set a breakpoint in your code where you want to start debugging. The usual way to get a breakpoint into pdb is:\nif somecondition:\n import pdb; pdb.set_trace()\n\nYou can make the condition whatever is convenient to ensure the breakpoint doesn't trigger too soon.\n"
] | [
1
] | [] | [] | [
"debugging",
"python"
] | stackoverflow_0002858088_debugging_python.txt |
Q:
Webapp best practice template_dict
After just been coding for about 6-9 months. I probably changed my coding style a number of times after reading some code or read best practices. But one thing I haven't yet come a cross is a good why to populate the template_dict.
As of now I pass the template_dict across a number of methods (that changes/modifies it) and returns is. The result is that every methods takes template_dict as first argument and the returns it and this in my eyes doesn't seems to be the best solution.
An idea is to have a method that handles all the changes. But I'm curios if there's a best practice for this? Or is it "do what you feel like"-type of thing?
The 2 things I think is pretty ugly is to send as an argument and return it in all methods. And the just the var name is written xxx number of times in the code :)
..fredrik
EDIT:
To demonstrate what I mean with template_dict (I thought that was a general term, I got it from the google implementation of django's template methods).
I have an dict I pass to the template via the render.template method:
template.render(path, template_dict) #from google.appengine.ext.webapp import template
This template_dict I need to manipulate in order to send data/dicts/lists to the view (html-file). If I'm not mistaken.
So with this in mind, my code usually ends up looking some this like this:
## Main.py file to handle the request and imports classes.
from models import data
from util import foo
class MainHandler(webapp.RequestHandler):
template_dict = { 'lang' : 'en' }
## reads all current keys and returns dict w/ new keys, if needed
template_dict = data.getData(template_dict)
if 'unsorted_list' in template_dict:
template_dict = util.foo(template_dict)
## and so on....
path = os.path.join(os.path.dirname(__file__), 'templates', file)
self.response.out.write(template.render(path, template_dict))
In most of my applications the many returns and sets doesn't appear in the main.py but rather in other classes and methods.
But you should do the general idea.
A:
If the functions in question are all methods of some object foo, then each of them can refer to the context they're building up (I imagine that's what you mean by "template dict"?) as self.ctx or the like (attribute name's somewhat arbitrary, the key point is that you can keep the context as an attribute of foo, typically initialized to empty in foo's __init__, and incrementally build it up via foo's methods; in the end, foo.ctx is ready for you).
This doesn't work in a more general case where the functions are all over the place rather than being methods of a single object. In that case ctx does need to be passed to each function (though the function can typically alter it in-place and doesn't need to return it).
| Webapp best practice template_dict | After just been coding for about 6-9 months. I probably changed my coding style a number of times after reading some code or read best practices. But one thing I haven't yet come a cross is a good why to populate the template_dict.
As of now I pass the template_dict across a number of methods (that changes/modifies it) and returns is. The result is that every methods takes template_dict as first argument and the returns it and this in my eyes doesn't seems to be the best solution.
An idea is to have a method that handles all the changes. But I'm curios if there's a best practice for this? Or is it "do what you feel like"-type of thing?
The 2 things I think is pretty ugly is to send as an argument and return it in all methods. And the just the var name is written xxx number of times in the code :)
..fredrik
EDIT:
To demonstrate what I mean with template_dict (I thought that was a general term, I got it from the google implementation of django's template methods).
I have an dict I pass to the template via the render.template method:
template.render(path, template_dict) #from google.appengine.ext.webapp import template
This template_dict I need to manipulate in order to send data/dicts/lists to the view (html-file). If I'm not mistaken.
So with this in mind, my code usually ends up looking some this like this:
## Main.py file to handle the request and imports classes.
from models import data
from util import foo
class MainHandler(webapp.RequestHandler):
template_dict = { 'lang' : 'en' }
## reads all current keys and returns dict w/ new keys, if needed
template_dict = data.getData(template_dict)
if 'unsorted_list' in template_dict:
template_dict = util.foo(template_dict)
## and so on....
path = os.path.join(os.path.dirname(__file__), 'templates', file)
self.response.out.write(template.render(path, template_dict))
In most of my applications the many returns and sets doesn't appear in the main.py but rather in other classes and methods.
But you should do the general idea.
| [
"If the functions in question are all methods of some object foo, then each of them can refer to the context they're building up (I imagine that's what you mean by \"template dict\"?) as self.ctx or the like (attribute name's somewhat arbitrary, the key point is that you can keep the context as an attribute of foo, typically initialized to empty in foo's __init__, and incrementally build it up via foo's methods; in the end, foo.ctx is ready for you).\nThis doesn't work in a more general case where the functions are all over the place rather than being methods of a single object. In that case ctx does need to be passed to each function (though the function can typically alter it in-place and doesn't need to return it).\n"
] | [
1
] | [] | [] | [
"google_app_engine",
"python",
"web_applications"
] | stackoverflow_0002857745_google_app_engine_python_web_applications.txt |
Q:
Is there an Oracle wrapper for Python that supports xmltype columns?
It seems cx_Oracle doesn't.
Any other suggestion for handling xml with Oracle and Python is appreciated.
Thanks.
A:
I managed to do this with cx_Oracle.
I used the sys.xmltype.createxml() function in the statement that inserts the rows in a table with XMLTYPE fields; then I used prepare() and setinputsizes() to specify that the bind variables I used for XMLTYPE fields were of cx_Oracle.CLOB type.
A:
I managed to get this to work by wrapping the XMLElement call in a call to XMLType.GetClobVal():
For example:
select xmltype.getclobval(xmlelement("rowcount", count(1)))
from...
No idea of the limitations yet but it got me out of trouble. Found the relelvant info on Oracle site:
Mastering Oracle+Python, Part 1: Querying Best Practices
A:
(edited to remove mention of a non-Oracle Python DB-API module and add some more relevant and hopefully useful info).
Don't know of any alternative to cx_oracle (as the DCOracle2 author says, "DCOracle2 is currently unmaintained, and no support is available." so it's not really an alternative).
However, a recent article on Oracle's own site asserts that (at least with recent releases such as Oracle 10g XE -- and presumably recent cx_oracle releases) Python can work with Oracle's XML support -- I don't know if the examples in that article can help you address your issues, but I sure hope so!
| Is there an Oracle wrapper for Python that supports xmltype columns? | It seems cx_Oracle doesn't.
Any other suggestion for handling xml with Oracle and Python is appreciated.
Thanks.
| [
"I managed to do this with cx_Oracle.\nI used the sys.xmltype.createxml() function in the statement that inserts the rows in a table with XMLTYPE fields; then I used prepare() and setinputsizes() to specify that the bind variables I used for XMLTYPE fields were of cx_Oracle.CLOB type.\n",
"I managed to get this to work by wrapping the XMLElement call in a call to XMLType.GetClobVal():\nFor example:\nselect xmltype.getclobval(xmlelement(\"rowcount\", count(1)))\nfrom...\n\nNo idea of the limitations yet but it got me out of trouble. Found the relelvant info on Oracle site:\nMastering Oracle+Python, Part 1: Querying Best Practices\n",
"(edited to remove mention of a non-Oracle Python DB-API module and add some more relevant and hopefully useful info).\nDon't know of any alternative to cx_oracle (as the DCOracle2 author says, \"DCOracle2 is currently unmaintained, and no support is available.\" so it's not really an alternative).\nHowever, a recent article on Oracle's own site asserts that (at least with recent releases such as Oracle 10g XE -- and presumably recent cx_oracle releases) Python can work with Oracle's XML support -- I don't know if the examples in that article can help you address your issues, but I sure hope so!\n"
] | [
1,
1,
0
] | [] | [] | [
"oracle",
"python",
"xml",
"xmltype"
] | stackoverflow_0000936381_oracle_python_xml_xmltype.txt |
Q:
Why does the "is" keyword have a different behavior when there is a dot in the string?
Consider this code:
>>> x = "google"
>>> x is "google"
True
>>> x = "google.com"
>>> x is "google.com"
False
>>>
Why is it like that?
To make sure the above is correct, I have just tested on Python 2.5.4, 2.6.5, 2.7b2, Python 3.1 on windows and Python 2.7b1 on Linux.
It looks like there is consistency across all of them, so it's by design. Am I missing something?
I just find it out that from some of my personal domain filtering script failing with that.
A:
is verifies object identity, and any implementation of Python, when it meets literal of immutable types, is perfectly free to either make a new object of that immutable type, or seek through existing objects of that type to see if some of them could be reused (by adding a new reference to the same underlying object). This is a pragmatic choice of optimization and not subject to semantic constraints, so your code should never rely on which path a give implementation may take (or it could break with a bugfix/optimization release of Python!).
Consider for example:
>>> import dis
>>> def f():
... x = 'google.com'
... return x is 'google.com'
...
>>> dis.dis(f)
2 0 LOAD_CONST 1 ('google.com')
3 STORE_FAST 0 (x)
3 6 LOAD_FAST 0 (x)
9 LOAD_CONST 1 ('google.com')
12 COMPARE_OP 8 (is)
15 RETURN_VALUE
so in this particular implementation, within a function, your observation does not apply and only one object is made for the literal (any literal), and, indeed:
>>> f()
True
Pragmatically that's because within a function making a pass through the local table of constants (to save some memory by not making multiple constant immutable objects where one suffices) is pretty cheap and fast, and may offer good performance returns since the function may be called repeatedly afterwards.
But, the very same implementation, at the interactive prompt (Edit: I originally thought this would also happen at a module's top level, but a comment by @Thomas set me right, see later):
>>> x = 'google.com'
>>> y = 'google.com'
>>> id(x), id(y)
(4213000, 4290864)
does NOT bother trying to save memory that way -- the ids are different, i.e., distinct objects. There are potentially higher costs and lower returns and so the heuristics of this implementation's optimizer tell it to not bother searching and just go ahead.
Edit: at module top level, per @Thomas' observation, given e.g.:
$ cat aaa.py
x = 'google.com'
y = 'google.com'
print id(x), id(y)
again we see the table-of-constants-based memory-optimization in this implementation:
>>> import aaa
4291104 4291104
(end of Edit per @Thomas' observation).
Lastly, again on the same implementation:
>>> x = 'google'
>>> y = 'google'
>>> id(x), id(y)
(2484672, 2484672)
the heuristics are different here because the literal string "looks like it might be an identifier" -- so it might be used in operation requiring interning... so the optimizer interns it anyway (and once interned, looking for it becomes very fast of course). And indeed, surprise surprise...:
>>> z = intern(x)
>>> id(z)
2484672
...x has been interned the very first time (as you see, the return value of intern is the same object as x and y, as it has the same id()). Of course, you shouldn't rely on this either -- the optimizer doesn't have to intern anything automatically, it's just an optimization heuristic; if you need interned string, intern them explicitly, just to be safe. When you do intern strings explicitly...:
>>> x = intern('google.com')
>>> y = intern('google.com')
>>> id(x), id(y)
(4213000, 4213000)
...then you do ensure exactly the same object (i.e., same id()) results each and every time -- so you can apply micro-optimizations such as checking with is rather than == (I've hardly ever found the miniscule performance gain to be worth the bother;-).
Edit: just to clarify, here are the kind of performance differences I'm talking about, on a slow Macbook Air...:
$ python -mtimeit -s"a='google';b='google'" 'a==b'
10000000 loops, best of 3: 0.132 usec per loop
$ python -mtimeit -s"a='google';b='google'" 'a is b'
10000000 loops, best of 3: 0.107 usec per loop
$ python -mtimeit -s"a='goo.gle';b='goo.gle'" 'a==b'
10000000 loops, best of 3: 0.132 usec per loop
$ python -mtimeit -s"a='google';b='google'" 'a is b'
10000000 loops, best of 3: 0.106 usec per loop
$ python -mtimeit -s"a=intern('goo.gle');b=intern('goo.gle')" 'a is b'
10000000 loops, best of 3: 0.0966 usec per loop
$ python -mtimeit -s"a=intern('goo.gle');b=intern('goo.gle')" 'a == b'
10000000 loops, best of 3: 0.126 usec per loop
...a few tens of nanoseconds either way, at most. So, worth even thinking about only in the most extreme "optimize the [expletive deleted] out of this [expletive deleted] performance bottleneck" situations!-)
A:
"is" is an identity test. Python has some caching behavior for small integers and (apparently) strings. "is" is best used for singleton testing (ex. None).
>>> x = "google"
>>> x is "google"
True
>>> id(x)
32553984L
>>> id("google")
32553984L
>>> x = "google.com"
>>> x is "google.com"
False
>>> id(x)
32649320L
>>> id("google.com")
37787888L
| Why does the "is" keyword have a different behavior when there is a dot in the string? | Consider this code:
>>> x = "google"
>>> x is "google"
True
>>> x = "google.com"
>>> x is "google.com"
False
>>>
Why is it like that?
To make sure the above is correct, I have just tested on Python 2.5.4, 2.6.5, 2.7b2, Python 3.1 on windows and Python 2.7b1 on Linux.
It looks like there is consistency across all of them, so it's by design. Am I missing something?
I just find it out that from some of my personal domain filtering script failing with that.
| [
"is verifies object identity, and any implementation of Python, when it meets literal of immutable types, is perfectly free to either make a new object of that immutable type, or seek through existing objects of that type to see if some of them could be reused (by adding a new reference to the same underlying object). This is a pragmatic choice of optimization and not subject to semantic constraints, so your code should never rely on which path a give implementation may take (or it could break with a bugfix/optimization release of Python!).\nConsider for example:\n>>> import dis\n>>> def f():\n... x = 'google.com'\n... return x is 'google.com'\n... \n>>> dis.dis(f)\n 2 0 LOAD_CONST 1 ('google.com')\n 3 STORE_FAST 0 (x)\n\n 3 6 LOAD_FAST 0 (x)\n 9 LOAD_CONST 1 ('google.com')\n 12 COMPARE_OP 8 (is)\n 15 RETURN_VALUE \n\nso in this particular implementation, within a function, your observation does not apply and only one object is made for the literal (any literal), and, indeed:\n>>> f()\nTrue\n\nPragmatically that's because within a function making a pass through the local table of constants (to save some memory by not making multiple constant immutable objects where one suffices) is pretty cheap and fast, and may offer good performance returns since the function may be called repeatedly afterwards.\nBut, the very same implementation, at the interactive prompt (Edit: I originally thought this would also happen at a module's top level, but a comment by @Thomas set me right, see later):\n>>> x = 'google.com'\n>>> y = 'google.com'\n>>> id(x), id(y)\n(4213000, 4290864)\n\ndoes NOT bother trying to save memory that way -- the ids are different, i.e., distinct objects. There are potentially higher costs and lower returns and so the heuristics of this implementation's optimizer tell it to not bother searching and just go ahead.\nEdit: at module top level, per @Thomas' observation, given e.g.:\n$ cat aaa.py\nx = 'google.com'\ny = 'google.com'\nprint id(x), id(y)\n\nagain we see the table-of-constants-based memory-optimization in this implementation:\n>>> import aaa\n4291104 4291104\n\n(end of Edit per @Thomas' observation).\nLastly, again on the same implementation:\n>>> x = 'google'\n>>> y = 'google'\n>>> id(x), id(y)\n(2484672, 2484672)\n\nthe heuristics are different here because the literal string \"looks like it might be an identifier\" -- so it might be used in operation requiring interning... so the optimizer interns it anyway (and once interned, looking for it becomes very fast of course). And indeed, surprise surprise...:\n>>> z = intern(x)\n>>> id(z)\n2484672\n\n...x has been interned the very first time (as you see, the return value of intern is the same object as x and y, as it has the same id()). Of course, you shouldn't rely on this either -- the optimizer doesn't have to intern anything automatically, it's just an optimization heuristic; if you need interned string, intern them explicitly, just to be safe. When you do intern strings explicitly...:\n>>> x = intern('google.com')\n>>> y = intern('google.com')\n>>> id(x), id(y)\n(4213000, 4213000)\n\n...then you do ensure exactly the same object (i.e., same id()) results each and every time -- so you can apply micro-optimizations such as checking with is rather than == (I've hardly ever found the miniscule performance gain to be worth the bother;-).\nEdit: just to clarify, here are the kind of performance differences I'm talking about, on a slow Macbook Air...:\n$ python -mtimeit -s\"a='google';b='google'\" 'a==b'\n10000000 loops, best of 3: 0.132 usec per loop\n$ python -mtimeit -s\"a='google';b='google'\" 'a is b'\n10000000 loops, best of 3: 0.107 usec per loop\n$ python -mtimeit -s\"a='goo.gle';b='goo.gle'\" 'a==b'\n10000000 loops, best of 3: 0.132 usec per loop\n$ python -mtimeit -s\"a='google';b='google'\" 'a is b'\n10000000 loops, best of 3: 0.106 usec per loop\n$ python -mtimeit -s\"a=intern('goo.gle');b=intern('goo.gle')\" 'a is b'\n10000000 loops, best of 3: 0.0966 usec per loop\n$ python -mtimeit -s\"a=intern('goo.gle');b=intern('goo.gle')\" 'a == b'\n10000000 loops, best of 3: 0.126 usec per loop\n\n...a few tens of nanoseconds either way, at most. So, worth even thinking about only in the most extreme \"optimize the [expletive deleted] out of this [expletive deleted] performance bottleneck\" situations!-)\n",
"\"is\" is an identity test. Python has some caching behavior for small integers and (apparently) strings. \"is\" is best used for singleton testing (ex. None).\n>>> x = \"google\"\n>>> x is \"google\"\nTrue\n>>> id(x)\n32553984L\n>>> id(\"google\")\n32553984L\n>>> x = \"google.com\"\n>>> x is \"google.com\"\nFalse\n>>> id(x)\n32649320L\n>>> id(\"google.com\")\n37787888L\n\n"
] | [
91,
15
] | [] | [] | [
"equality",
"identity",
"python"
] | stackoverflow_0002858603_equality_identity_python.txt |
Q:
python: equivalent to Javascript "||" to override non-truthful value
In Javascript I can do this:
function A(x) { return x || 3; }
This returns 3 if x is a "non-truthful" value like 0, null, false, and it returns x otherwise. This is useful for empty arguments, e.g. I can do A() and it will evaluate as 3.
Does Python have an equivalent? I guess I could make one out of the ternary operator a if b else c but was wondering what people use for this.
A:
You can use or to do the same thing but you have to be careful because some unexpected things can be considered False in that arrangement. Just make sure you want this behavior if you choose to do it that way:
>>> "" or 1
1
>>> " " or 1
' '
>>> 0 or 1
1
>>> 10 or 1
10
>>> ['a', 'b', 'c'] or 1
['a', 'b', 'c']
>>> [] or 1
1
>>> None or 1
1
A:
The answer is or:
def A(x):
return x or 3
| python: equivalent to Javascript "||" to override non-truthful value | In Javascript I can do this:
function A(x) { return x || 3; }
This returns 3 if x is a "non-truthful" value like 0, null, false, and it returns x otherwise. This is useful for empty arguments, e.g. I can do A() and it will evaluate as 3.
Does Python have an equivalent? I guess I could make one out of the ternary operator a if b else c but was wondering what people use for this.
| [
"You can use or to do the same thing but you have to be careful because some unexpected things can be considered False in that arrangement. Just make sure you want this behavior if you choose to do it that way:\n>>> \"\" or 1\n1\n>>> \" \" or 1\n' '\n>>> 0 or 1\n1\n>>> 10 or 1\n10\n>>> ['a', 'b', 'c'] or 1\n['a', 'b', 'c']\n>>> [] or 1\n1\n>>> None or 1\n1\n\n",
"The answer is or:\ndef A(x):\n return x or 3\n\n"
] | [
10,
5
] | [] | [] | [
"python"
] | stackoverflow_0002858723_python.txt |
Q:
use python / django to let users login to my site using their google credentials
I want to let users use their google account to login to my website. Exactly the way SO lets me. Can anyone please point in the right direction? I'm assuming the oAuth library is to be used but what I'd really like is a snippet of code I can directly copy paste and get this to work.
A:
It's not OAuth particularly that you need (OAuth is for authorising access for one website to specific private content held on another), but OpenID - which is meant for authentication rather than authorisation. (Some sites, like Twitter, do provide authentication services via OAuth, but that's not what it's primarily for.) I have used python-openid which is fairly straightforward to use, or you can look at django-openid - though it admits to being incomplete, you could get some idea of how to implement OpenID support.
The problem's a little too involved to admit a copy-and-paste solution, but it's not especially hard to do this.
Update: piquadrat's link (in he comment) is definitely worth following.
A:
You may want to check out django-piston which is a mini-framework with oAuth built in. Here's a tutorial on how to set it up.
A:
You might consider using Django-Socialauth, as it supports
Twitter
Gmail
Facebook
Yahoo (essentially openid)
OpenId
| use python / django to let users login to my site using their google credentials | I want to let users use their google account to login to my website. Exactly the way SO lets me. Can anyone please point in the right direction? I'm assuming the oAuth library is to be used but what I'd really like is a snippet of code I can directly copy paste and get this to work.
| [
"It's not OAuth particularly that you need (OAuth is for authorising access for one website to specific private content held on another), but OpenID - which is meant for authentication rather than authorisation. (Some sites, like Twitter, do provide authentication services via OAuth, but that's not what it's primarily for.) I have used python-openid which is fairly straightforward to use, or you can look at django-openid - though it admits to being incomplete, you could get some idea of how to implement OpenID support.\nThe problem's a little too involved to admit a copy-and-paste solution, but it's not especially hard to do this.\nUpdate: piquadrat's link (in he comment) is definitely worth following.\n",
"You may want to check out django-piston which is a mini-framework with oAuth built in. Here's a tutorial on how to set it up.\n",
"You might consider using Django-Socialauth, as it supports \n\nTwitter\nGmail\nFacebook\nYahoo (essentially openid)\nOpenId\n\n"
] | [
3,
1,
1
] | [] | [] | [
"django",
"oauth",
"python"
] | stackoverflow_0002847629_django_oauth_python.txt |
Q:
Python: converting string to flags
If I have a string that is the output of matching the regexp [MSP]*, what's the cleanest way to convert it to a dict containing keys M, S, and P where the value of each key is true if the key appears in the string?
e.g.
'MSP' => {'M': True, 'S': True, 'P': True}
'PMMM' => {'M': True, 'S': False, 'P': True}
'' => {'M': False, 'S': False, 'P': False}
'MOO' won't occur...
if it was the input to matching the regexp, 'M' would be the output
The best I can come up with is:
result = {'M': False, 'S': False, 'P': False}
if (matchstring):
for c in matchstring:
result[c] = True
but this seems slightly clunky, I wondered if there was a better way.
A:
Why not use a frozenset (or set if mutability is needed)?
s = frozenset('PMMM')
# now s == frozenset({'P', 'M'})
then you can use
'P' in s
to check whether the flag P exists.
A:
In newer versions of Python you can use a dict comprehension:
s = 'MMSMSS'
d = { c: c in s for c in 'MSP' }
In older versions you can use this as KennyTM points out:
d = dict((c, c in s) for c in 'MSP')
This will give good performance for long strings because if all three characters occur at the beginning of the string the search can stop early. It won't require searching the entire string.
| Python: converting string to flags | If I have a string that is the output of matching the regexp [MSP]*, what's the cleanest way to convert it to a dict containing keys M, S, and P where the value of each key is true if the key appears in the string?
e.g.
'MSP' => {'M': True, 'S': True, 'P': True}
'PMMM' => {'M': True, 'S': False, 'P': True}
'' => {'M': False, 'S': False, 'P': False}
'MOO' won't occur...
if it was the input to matching the regexp, 'M' would be the output
The best I can come up with is:
result = {'M': False, 'S': False, 'P': False}
if (matchstring):
for c in matchstring:
result[c] = True
but this seems slightly clunky, I wondered if there was a better way.
| [
"Why not use a frozenset (or set if mutability is needed)?\ns = frozenset('PMMM')\n# now s == frozenset({'P', 'M'})\n\nthen you can use \n'P' in s\n\nto check whether the flag P exists.\n",
"In newer versions of Python you can use a dict comprehension:\ns = 'MMSMSS'\nd = { c: c in s for c in 'MSP' }\n\nIn older versions you can use this as KennyTM points out:\nd = dict((c, c in s) for c in 'MSP')\n\nThis will give good performance for long strings because if all three characters occur at the beginning of the string the search can stop early. It won't require searching the entire string.\n"
] | [
6,
3
] | [] | [] | [
"dictionary",
"python",
"string"
] | stackoverflow_0002858880_dictionary_python_string.txt |
Q:
Problems with Threading in Python 2.5, KeyError: 51, Help debugging?
I have a python script which runs a particular script large number of times (for monte carlo purpose) and the way I have scripted it is that, I queue up the script the desired number of times it should be run then I spawn threads and each thread runs the script once and again when its done.
Once the script in a particular thread is finished, the output is written to a file by accessing a lock (so my guess was that only one thread accesses the lock at a given time). Once the lock is released by one thread, the next thread accesses it and adds its output to the previously written file and rewrites it.
I am not facing a problem when the number of iterations is small like 10 or 20 but when its large like 50 or 150, python returns a KeyError: 51 telling me element doesn't exist and the error it points out to is within the lock which puzzles me since only one thread should access the lock at once and I do not expect an error.
This is the class I use:
class errorclass(threading.Thread):
def __init__(self, queue):
self.__queue=queue
threading.Thread.__init__(self)
def run(self):
while 1:
item = self.__queue.get()
if item is None: break
result = myfunction()
lock = threading.RLock()
lock.acquire()
ADD entries from current thread to entries in file and
REWRITE FILE
lock.release()
queue = Queue.Queue()
for i in range(threads):
errorclass(queue).start()
for i in range(desired iterations):
queue.put(i)
for i in range(threads):
queue.put(None)
Python returns with KeyError: 51 for large number of desired iterations during the adding/write file operation after lock access, I am wondering if this is the correct way to use the lock since every thread has a lock operation rather than every thread accessing a shared lock? What would be the way to rectify this?
A:
What you have right now is a new lock for every iteration in each thread's run method. In effect, there is no locking going on at all. If you want to protect writes to a file, you need to make sure that all threads that access the same file use the same lock object. The simplest way to do that is to create it at the global level:
lock = threading.RLock()
class errorclass(...):
...
def run(self)
... # get items and process
with lock:
ADD entries from current thread to entries in file and REWRITE FILE
You'll need to use from __future__ import with_statement to use the with statement in Python 2.5, but it makes sure you never forget to unlock the lock, not even when an error occurs. (If you need Python 2.4-and-earlier compatibility, you'll have to use a try/finally instead.)
A:
Create the lock and pass it into errorclass.__init__ so they do share an instance. Otherwise each thread is locking itself out of re-entering their own critical section which is exactly a no-op.
| Problems with Threading in Python 2.5, KeyError: 51, Help debugging? | I have a python script which runs a particular script large number of times (for monte carlo purpose) and the way I have scripted it is that, I queue up the script the desired number of times it should be run then I spawn threads and each thread runs the script once and again when its done.
Once the script in a particular thread is finished, the output is written to a file by accessing a lock (so my guess was that only one thread accesses the lock at a given time). Once the lock is released by one thread, the next thread accesses it and adds its output to the previously written file and rewrites it.
I am not facing a problem when the number of iterations is small like 10 or 20 but when its large like 50 or 150, python returns a KeyError: 51 telling me element doesn't exist and the error it points out to is within the lock which puzzles me since only one thread should access the lock at once and I do not expect an error.
This is the class I use:
class errorclass(threading.Thread):
def __init__(self, queue):
self.__queue=queue
threading.Thread.__init__(self)
def run(self):
while 1:
item = self.__queue.get()
if item is None: break
result = myfunction()
lock = threading.RLock()
lock.acquire()
ADD entries from current thread to entries in file and
REWRITE FILE
lock.release()
queue = Queue.Queue()
for i in range(threads):
errorclass(queue).start()
for i in range(desired iterations):
queue.put(i)
for i in range(threads):
queue.put(None)
Python returns with KeyError: 51 for large number of desired iterations during the adding/write file operation after lock access, I am wondering if this is the correct way to use the lock since every thread has a lock operation rather than every thread accessing a shared lock? What would be the way to rectify this?
| [
"What you have right now is a new lock for every iteration in each thread's run method. In effect, there is no locking going on at all. If you want to protect writes to a file, you need to make sure that all threads that access the same file use the same lock object. The simplest way to do that is to create it at the global level:\nlock = threading.RLock()\nclass errorclass(...):\n ...\n def run(self)\n ... # get items and process\n with lock:\n ADD entries from current thread to entries in file and REWRITE FILE\n\nYou'll need to use from __future__ import with_statement to use the with statement in Python 2.5, but it makes sure you never forget to unlock the lock, not even when an error occurs. (If you need Python 2.4-and-earlier compatibility, you'll have to use a try/finally instead.)\n",
"Create the lock and pass it into errorclass.__init__ so they do share an instance. Otherwise each thread is locking itself out of re-entering their own critical section which is exactly a no-op.\n"
] | [
1,
0
] | [] | [] | [
"multithreading",
"python",
"windows"
] | stackoverflow_0002858960_multithreading_python_windows.txt |
Q:
Connection to DB2 in Python
I'm trying to create a database connection in a python script to my DB2 database. When the connection is done I've to run some different SQL statements.
I googled the problem and has read the ibm_db API (http://code.google.com/p/ibm-db/wiki/APIs) but just can't seem to get it right.
Here is what I got so far:
import sys
import getopt
import timeit
import multiprocessing
import random
import os
import re
import ibm_db
import time
from string import maketrans
query_str = None
conn = ibm_db.pconnect("dsn=write","usrname","secret")
query_stmt = ibm_db.prepare(conn, query_str)
ibm_db.execute(query_stmt, "SELECT COUNT(*) FROM accounts")
result = ibm_db.fetch_assoc()
print result
status = ibm_db.close(conn)
but I get an error. I really tried everything (or, not everything but pretty damn close) and I can't get it to work.
I just need to make a automatic test python script that can test different queries with different indexes and so on and for that I need to create and remove indexes a long the way.
Hope someone has a solutions or maybe knows about some example codes out there I can download and study.
Thanks
Mestika
A:
it should be:
query_str = "SELECT COUNT(*) FROM accounts"
conn = ibm_db.pconnect("dsn=write","usrname","secret")
query_stmt = ibm_db.prepare(conn, query_str)
ibm_db.execute(query_stmt)
A:
I'm sorry, of cause you need to error message. When trying to run my script it gives me this error:
Traceback (most recent call last):
File "test.py", line 16, in <module>
ibm_db.execute(query_stmt, "SELECT COUNT(*) FROM accounts")
Exception: Param is not a tuple
I'm pretty sure that it is my parameter "SELECT COUNT(*) FROM accounts" that is the problem, but I have no idea how to fix it or what to put in its place.
| Connection to DB2 in Python | I'm trying to create a database connection in a python script to my DB2 database. When the connection is done I've to run some different SQL statements.
I googled the problem and has read the ibm_db API (http://code.google.com/p/ibm-db/wiki/APIs) but just can't seem to get it right.
Here is what I got so far:
import sys
import getopt
import timeit
import multiprocessing
import random
import os
import re
import ibm_db
import time
from string import maketrans
query_str = None
conn = ibm_db.pconnect("dsn=write","usrname","secret")
query_stmt = ibm_db.prepare(conn, query_str)
ibm_db.execute(query_stmt, "SELECT COUNT(*) FROM accounts")
result = ibm_db.fetch_assoc()
print result
status = ibm_db.close(conn)
but I get an error. I really tried everything (or, not everything but pretty damn close) and I can't get it to work.
I just need to make a automatic test python script that can test different queries with different indexes and so on and for that I need to create and remove indexes a long the way.
Hope someone has a solutions or maybe knows about some example codes out there I can download and study.
Thanks
Mestika
| [
"it should be:\nquery_str = \"SELECT COUNT(*) FROM accounts\"\n\nconn = ibm_db.pconnect(\"dsn=write\",\"usrname\",\"secret\")\nquery_stmt = ibm_db.prepare(conn, query_str)\nibm_db.execute(query_stmt)\n\n",
"I'm sorry, of cause you need to error message. When trying to run my script it gives me this error:\nTraceback (most recent call last):\n File \"test.py\", line 16, in <module>\n ibm_db.execute(query_stmt, \"SELECT COUNT(*) FROM accounts\")\nException: Param is not a tuple\n\nI'm pretty sure that it is my parameter \"SELECT COUNT(*) FROM accounts\" that is the problem, but I have no idea how to fix it or what to put in its place.\n"
] | [
4,
0
] | [] | [] | [
"database",
"db2",
"python"
] | stackoverflow_0002859081_database_db2_python.txt |
Q:
Best way to test instance methods without running __init__
I've got a simple class that gets most of its arguments via init, which also runs a variety of private methods that do most of the work. Output is available either through access to object variables or public methods.
Here's the problem - I'd like my unittest framework to directly call the private methods called by init with different data - without going through init.
What's the best way to do this?
So far, I've been refactoring these classes so that init does less and data is passed in separately. This makes testing easy, but I think the usability of the class suffers a little.
EDIT: Example solution based on Ignacio's answer:
import types
class C(object):
def __init__(self, number):
new_number = self._foo(number)
self._bar(new_number)
def _foo(self, number):
return number * 2
def _bar(self, number):
print number * 10
#--- normal execution - should print 160: -------
MyC = C(8)
#--- testing execution - should print 80 --------
MyC = object.__new__(C)
MyC._bar(8)
A:
For new-style classes, call object.__new__(), passing the class as a parameter. For old-style classes, call types.InstanceType() passing the class as a parameter.
import types
class C(object):
def __init__(self):
print 'init'
class OldC:
def __init__(self):
print 'initOld'
c = object.__new__(C)
print c
oc = types.InstanceType(OldC)
print oc
A:
Why does the usability of the class have to suffer? If all the __init__ is doing is precomputing things so you can expose values as simple variables, change those variables into properties and do the computation (potentially cached/memoized) in the getter. That way your __init__ method is back to doing initialization only and testability is improved.
The downside to this approach is that it might be less performant, but probably not to a significant degree.
| Best way to test instance methods without running __init__ | I've got a simple class that gets most of its arguments via init, which also runs a variety of private methods that do most of the work. Output is available either through access to object variables or public methods.
Here's the problem - I'd like my unittest framework to directly call the private methods called by init with different data - without going through init.
What's the best way to do this?
So far, I've been refactoring these classes so that init does less and data is passed in separately. This makes testing easy, but I think the usability of the class suffers a little.
EDIT: Example solution based on Ignacio's answer:
import types
class C(object):
def __init__(self, number):
new_number = self._foo(number)
self._bar(new_number)
def _foo(self, number):
return number * 2
def _bar(self, number):
print number * 10
#--- normal execution - should print 160: -------
MyC = C(8)
#--- testing execution - should print 80 --------
MyC = object.__new__(C)
MyC._bar(8)
| [
"For new-style classes, call object.__new__(), passing the class as a parameter. For old-style classes, call types.InstanceType() passing the class as a parameter.\nimport types\n\nclass C(object):\n def __init__(self):\n print 'init'\n\nclass OldC:\n def __init__(self):\n print 'initOld'\n\nc = object.__new__(C)\nprint c\n\noc = types.InstanceType(OldC)\nprint oc\n\n",
"Why does the usability of the class have to suffer? If all the __init__ is doing is precomputing things so you can expose values as simple variables, change those variables into properties and do the computation (potentially cached/memoized) in the getter. That way your __init__ method is back to doing initialization only and testability is improved.\nThe downside to this approach is that it might be less performant, but probably not to a significant degree.\n"
] | [
5,
4
] | [] | [] | [
"python",
"unit_testing"
] | stackoverflow_0002859429_python_unit_testing.txt |
Q:
Reverse mapping from a table to a model in SQLAlchemy
To provide an activity log in my SQLAlchemy-based app, I have a model like this:
class ActivityLog(Base):
__tablename__ = 'activitylog'
id = Column(Integer, primary_key=True)
activity_by_id = Column(Integer, ForeignKey('users.id'), nullable=False)
activity_by = relation(User, primaryjoin=activity_by_id == User.id)
activity_at = Column(DateTime, default=datetime.utcnow, nullable=False)
activity_type = Column(SmallInteger, nullable=False)
target_table = Column(Unicode(20), nullable=False)
target_id = Column(Integer, nullable=False)
target_title = Column(Unicode(255), nullable=False)
The log contains entries for multiple tables, so I can't use ForeignKey relations. Log entries are made like this:
doc = Document(name=u'mydoc', title=u'My Test Document',
created_by=user, edited_by=user)
session.add(doc)
session.flush() # See note below
log = ActivityLog(activity_by=user, activity_type=ACTIVITY_ADD,
target_table=Document.__table__.name, target_id=doc.id,
target_title=doc.title)
session.add(log)
This leaves me with three problems:
I have to flush the session before my doc object gets an id. If I had used a ForeignKey column and a relation mapper, I could have simply called ActivityLog(target=doc) and let SQLAlchemy do the work. Is there any way to work around needing to flush by hand?
The target_table parameter is too verbose. I suppose I could solve this with a target property setter in ActivityLog that automatically retrieves the table name and id from a given instance.
Biggest of all, I'm not sure how to retrieve a model instance from the database. Given an ActivityLog instance log, calling self.session.query(log.target_table).get(log.target_id) does not work, as query() expects a model as parameter.
One workaround appears to be to use polymorphism and derive all my models from a base model which ActivityLog recognises. Something like this:
class Entity(Base):
__tablename__ = 'entities'
id = Column(Integer, primary_key=True)
title = Column(Unicode(255), nullable=False)
edited_at = Column(DateTime, onupdate=datetime.utcnow, nullable=False)
entity_type = Column(Unicode(20), nullable=False)
__mapper_args__ = {'polymorphic_on': entity_type}
class Document(Entity):
__tablename__ = 'documents'
__mapper_args__ = {'polymorphic_identity': 'document'}
body = Column(UnicodeText, nullable=False)
class ActivityLog(Base):
__tablename__ = 'activitylog'
id = Column(Integer, primary_key=True)
...
target_id = Column(Integer, ForeignKey('entities.id'), nullable=False)
target = relation(Entity)
If I do this, ActivityLog(...).target will give me a Document instance when it refers to a Document, but I'm not sure it's worth the overhead of having two tables for everything. Should I go ahead and do it this way?
A:
One way to solve this is polymorphic associations. It should solve all 3 of your issues and also make database foreign key constraints work. See the polymorphic association example in SQLAlchemy source. Mike Bayer has an old blogpost that discusses this in greater detail.
A:
Definitely go through the blogpost and examples Ants linked to. I did not find the explanation confusion, but rather assuming some more experience on the topic.
Few things I can suggest are:
ForeignKeys: in general I agree they are a good thing go have, but I am not sure it is conceptually important in your case: you seem to be using this ActivityLog as an orthogonal cross-cutting concern (AOP); but version with foreign keys would effectively make your business objects aware of the ActivityLog. Another problem with having FK for audit purposes using schema setup you have is that if you allow object deletion, FK requirement will delete all the ActivityLog entries for this object.
Automatic logging: you are doing all this logging manually whenever you create/modify(/delete) the object. With SA you could implement a SessionExtension with before_commit which would do the job for you automatically.
In this way you completely can avoid writing parts like below:
log = ActivityLog(activity_by=user, activity_type=ACTIVITY_ADD,
target_table=Document.__table__.name, target_id=doc.id,
target_title=doc.title)
session.add(log)
EDIT-1: complete sample code added
The code is based on the first non-FK version from http://techspot.zzzeek.org/?p=13.
The choice not to use FK is based on the fact that for audit purposes when the
main object is deleted, it should not cascade to delete all the audit log entries.
Also this keeps auditable objects unaware of the fact they are being audited.
Implementation uses a SA one-to-many relationship. It is possible that some
objects are modified many times, which will result in many audit log entries.
By default SA will load the relationship objects when adding a new entry to the
list. Assuming that during "normal" usage we would like only to add new audit
log entry, we use lazy='noload' flag so that the relation from the main object
will never be loaded. It is loaded when navigated from the other side though,
and also can be loaded from the main object using custom query, which is shown
in the example as well using activitylog_readonly readonly property.
Code (runnable with some tests):
from datetime import datetime
from sqlalchemy import create_engine, Column, Integer, SmallInteger, String, DateTime, ForeignKey, Table, UnicodeText, Unicode, and_
from sqlalchemy.orm import relationship, dynamic_loader, scoped_session, sessionmaker, class_mapper, backref
from sqlalchemy.orm.session import Session
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm.interfaces import SessionExtension
import logging
logging.basicConfig(level=logging.INFO)
_logger = logging.getLogger()
ACTIVITY_ADD = 1
ACTIVITY_MOD = 2
ACTIVITY_DEL = 3
class ActivityLogSessionExtension(SessionExtension):
_logger = logging.getLogger('ActivityLogSessionExtension')
def before_commit(self, session):
self._logger.debug("before_commit: %s", session)
for d in session.new:
self._logger.info("before_commit >> add: %s", d)
if hasattr(d, 'create_activitylog'):
log = d.create_activitylog(ACTIVITY_ADD)
for d in session.dirty:
self._logger.info("before_commit >> mod: %s", d)
if hasattr(d, 'create_activitylog'):
log = d.create_activitylog(ACTIVITY_MOD)
for d in session.deleted:
self._logger.info("before_commit >> del: %s", d)
if hasattr(d, 'create_activitylog'):
log = d.create_activitylog(ACTIVITY_DEL)
# Configure test data SA
engine = create_engine('sqlite:///:memory:', echo=False)
session = scoped_session(sessionmaker(bind=engine, autoflush=False, extension=ActivityLogSessionExtension()))
Base = declarative_base()
Base.query = session.query_property()
class _BaseMixin(object):
""" Just a helper mixin class to set properties on object creation.
Also provides a convenient default __repr__() function, but be aware that
also relationships are printed, which might result in loading relations.
"""
def __init__(self, **kwargs):
for k,v in kwargs.items():
setattr(self, k, v)
def __repr__(self):
return "<%s(%s)>" % (self.__class__.__name__,
', '.join('%s=%r' % (k, self.__dict__[k])
for k in sorted(self.__dict__) if '_sa_' != k[:4] and '_backref_' != k[:9])
)
class User(Base, _BaseMixin):
__tablename__ = u'users'
id = Column(Integer, primary_key=True)
name = Column(String)
class Document(Base, _BaseMixin):
__tablename__ = u'documents'
id = Column(Integer, primary_key=True)
title = Column(Unicode(255), nullable=False)
body = Column(UnicodeText, nullable=False)
class Folder(Base, _BaseMixin):
__tablename__ = u'folders'
id = Column(Integer, primary_key=True)
title = Column(Unicode(255), nullable=False)
comment = Column(UnicodeText, nullable=False)
class ActivityLog(Base, _BaseMixin):
__tablename__ = u'activitylog'
id = Column(Integer, primary_key=True)
activity_by_id = Column(Integer, ForeignKey('users.id'), nullable=False)
activity_by = relationship(User) # @note: no need to specify the primaryjoin
activity_at = Column(DateTime, default=datetime.utcnow, nullable=False)
activity_type = Column(SmallInteger, nullable=False)
target_table = Column(Unicode(20), nullable=False)
target_id = Column(Integer, nullable=False)
target_title = Column(Unicode(255), nullable=False)
# backref relation for auditable
target = property(lambda self: getattr(self, '_backref_%s' % self.target_table))
def _get_user():
""" This method returns the User object for the current user.
@todo: proper implementation required
@hack: currently returns the 'user2'
"""
return session.query(User).filter_by(name='user2').one()
# auditable support function
# based on first non-FK version from http://techspot.zzzeek.org/?p=13
def auditable(cls, name):
def create_activitylog(self, activity_type):
log = ActivityLog(activity_by=_get_user(),
activity_type=activity_type,
target_table=table.name,
target_title=self.title,
)
getattr(self, name).append(log)
return log
mapper = class_mapper(cls)
table = mapper.local_table
cls.create_activitylog = create_activitylog
def _get_activitylog(self):
return Session.object_session(self).query(ActivityLog).with_parent(self).all()
setattr(cls, '%s_readonly' %(name,), property(_get_activitylog))
# no constraints, therefore define constraints in an ad-hoc fashion.
primaryjoin = and_(
list(table.primary_key)[0] == ActivityLog.__table__.c.target_id,
ActivityLog.__table__.c.target_table == table.name
)
foreign_keys = [ActivityLog.__table__.c.target_id]
mapper.add_property(name,
# @note: because we use the relationship, by default all previous
# ActivityLog items will be loaded for an object when new one is
# added. To avoid this, use either dynamic_loader (http://www.sqlalchemy.org/docs/reference/orm/mapping.html#sqlalchemy.orm.dynamic_loader)
# or lazy='noload'. This is the trade-off decision to be made.
# Additional benefit of using lazy='noload' is that one can also
# record DEL operations in the same way as ADD, MOD
relationship(
ActivityLog,
lazy='noload', # important for relationship
primaryjoin=primaryjoin,
foreign_keys=foreign_keys,
backref=backref('_backref_%s' % table.name,
primaryjoin=list(table.primary_key)[0] == ActivityLog.__table__.c.target_id,
foreign_keys=foreign_keys)
)
)
# this will define which classes support the ActivityLog interface
auditable(Document, 'activitylogs')
auditable(Folder, 'activitylogs')
# create db schema
Base.metadata.create_all(engine)
## >>>>> TESTS >>>>>>
# create some basic data first
u1 = User(name='user1')
u2 = User(name='user2')
session.add(u1)
session.add(u2)
session.commit()
session.expunge_all()
# --check--
assert not(_get_user() is None)
##############################
## ADD
##############################
_logger.info('-' * 80)
d1 = Document(title=u'Document-1', body=u'Doc1 some body skipped the body')
# when not using SessionExtension for any reason, this can be called manually
#d1.create_activitylog(ACTIVITY_ADD)
session.add(d1)
session.commit()
f1 = Folder(title=u'Folder-1', comment=u'This folder is empty')
# when not using SessionExtension for any reason, this can be called manually
#f1.create_activitylog(ACTIVITY_ADD)
session.add(f1)
session.commit()
# --check--
session.expunge_all()
logs = session.query(ActivityLog).all()
_logger.debug(logs)
assert len(logs) == 2
assert logs[0].activity_type == ACTIVITY_ADD
assert logs[0].target.title == u'Document-1'
assert logs[0].target.title == logs[0].target_title
assert logs[1].activity_type == ACTIVITY_ADD
assert logs[1].target.title == u'Folder-1'
assert logs[1].target.title == logs[1].target_title
##############################
## MOD(ify)
##############################
_logger.info('-' * 80)
session.expunge_all()
d1 = session.query(Document).filter_by(id=1).one()
assert d1.title == u'Document-1'
assert d1.body == u'Doc1 some body skipped the body'
assert d1.activitylogs == []
d1.title = u'Modified: Document-1'
d1.body = u'Modified: body'
# when not using SessionExtension (or it does not work, this can be called manually)
#d1.create_activitylog(ACTIVITY_MOD)
session.commit()
_logger.debug(d1.activitylogs_readonly)
# --check--
session.expunge_all()
logs = session.query(ActivityLog).all()
assert len(logs)==3
assert logs[2].activity_type == ACTIVITY_MOD
assert logs[2].target.title == u'Modified: Document-1'
assert logs[2].target.title == logs[2].target_title
##############################
## DEL(ete)
##############################
_logger.info('-' * 80)
session.expunge_all()
d1 = session.query(Document).filter_by(id=1).one()
# when not using SessionExtension for any reason, this can be called manually,
#d1.create_activitylog(ACTIVITY_DEL)
session.delete(d1)
session.commit()
session.expunge_all()
# --check--
session.expunge_all()
logs = session.query(ActivityLog).all()
assert len(logs)==4
assert logs[0].target is None
assert logs[2].target is None
assert logs[3].activity_type == ACTIVITY_DEL
assert logs[3].target is None
##############################
## print all activity logs
##############################
_logger.info('=' * 80)
logs = session.query(ActivityLog).all()
for log in logs:
_ = log.target
_logger.info("%s -> %s", log, log.target)
##############################
## navigate from main object
##############################
_logger.info('=' * 80)
session.expunge_all()
f1 = session.query(Folder).filter_by(id=1).one()
_logger.info(f1.activitylogs_readonly)
| Reverse mapping from a table to a model in SQLAlchemy | To provide an activity log in my SQLAlchemy-based app, I have a model like this:
class ActivityLog(Base):
__tablename__ = 'activitylog'
id = Column(Integer, primary_key=True)
activity_by_id = Column(Integer, ForeignKey('users.id'), nullable=False)
activity_by = relation(User, primaryjoin=activity_by_id == User.id)
activity_at = Column(DateTime, default=datetime.utcnow, nullable=False)
activity_type = Column(SmallInteger, nullable=False)
target_table = Column(Unicode(20), nullable=False)
target_id = Column(Integer, nullable=False)
target_title = Column(Unicode(255), nullable=False)
The log contains entries for multiple tables, so I can't use ForeignKey relations. Log entries are made like this:
doc = Document(name=u'mydoc', title=u'My Test Document',
created_by=user, edited_by=user)
session.add(doc)
session.flush() # See note below
log = ActivityLog(activity_by=user, activity_type=ACTIVITY_ADD,
target_table=Document.__table__.name, target_id=doc.id,
target_title=doc.title)
session.add(log)
This leaves me with three problems:
I have to flush the session before my doc object gets an id. If I had used a ForeignKey column and a relation mapper, I could have simply called ActivityLog(target=doc) and let SQLAlchemy do the work. Is there any way to work around needing to flush by hand?
The target_table parameter is too verbose. I suppose I could solve this with a target property setter in ActivityLog that automatically retrieves the table name and id from a given instance.
Biggest of all, I'm not sure how to retrieve a model instance from the database. Given an ActivityLog instance log, calling self.session.query(log.target_table).get(log.target_id) does not work, as query() expects a model as parameter.
One workaround appears to be to use polymorphism and derive all my models from a base model which ActivityLog recognises. Something like this:
class Entity(Base):
__tablename__ = 'entities'
id = Column(Integer, primary_key=True)
title = Column(Unicode(255), nullable=False)
edited_at = Column(DateTime, onupdate=datetime.utcnow, nullable=False)
entity_type = Column(Unicode(20), nullable=False)
__mapper_args__ = {'polymorphic_on': entity_type}
class Document(Entity):
__tablename__ = 'documents'
__mapper_args__ = {'polymorphic_identity': 'document'}
body = Column(UnicodeText, nullable=False)
class ActivityLog(Base):
__tablename__ = 'activitylog'
id = Column(Integer, primary_key=True)
...
target_id = Column(Integer, ForeignKey('entities.id'), nullable=False)
target = relation(Entity)
If I do this, ActivityLog(...).target will give me a Document instance when it refers to a Document, but I'm not sure it's worth the overhead of having two tables for everything. Should I go ahead and do it this way?
| [
"One way to solve this is polymorphic associations. It should solve all 3 of your issues and also make database foreign key constraints work. See the polymorphic association example in SQLAlchemy source. Mike Bayer has an old blogpost that discusses this in greater detail.\n",
"Definitely go through the blogpost and examples Ants linked to. I did not find the explanation confusion, but rather assuming some more experience on the topic.\nFew things I can suggest are:\n\nForeignKeys: in general I agree they are a good thing go have, but I am not sure it is conceptually important in your case: you seem to be using this ActivityLog as an orthogonal cross-cutting concern (AOP); but version with foreign keys would effectively make your business objects aware of the ActivityLog. Another problem with having FK for audit purposes using schema setup you have is that if you allow object deletion, FK requirement will delete all the ActivityLog entries for this object.\nAutomatic logging: you are doing all this logging manually whenever you create/modify(/delete) the object. With SA you could implement a SessionExtension with before_commit which would do the job for you automatically.\n\nIn this way you completely can avoid writing parts like below:\nlog = ActivityLog(activity_by=user, activity_type=ACTIVITY_ADD,\n target_table=Document.__table__.name, target_id=doc.id,\n target_title=doc.title)\nsession.add(log)\n\n\nEDIT-1: complete sample code added\n\nThe code is based on the first non-FK version from http://techspot.zzzeek.org/?p=13.\nThe choice not to use FK is based on the fact that for audit purposes when the \nmain object is deleted, it should not cascade to delete all the audit log entries.\nAlso this keeps auditable objects unaware of the fact they are being audited.\nImplementation uses a SA one-to-many relationship. It is possible that some\nobjects are modified many times, which will result in many audit log entries.\nBy default SA will load the relationship objects when adding a new entry to the\nlist. Assuming that during \"normal\" usage we would like only to add new audit\nlog entry, we use lazy='noload' flag so that the relation from the main object\nwill never be loaded. It is loaded when navigated from the other side though,\nand also can be loaded from the main object using custom query, which is shown\nin the example as well using activitylog_readonly readonly property.\n\nCode (runnable with some tests):\nfrom datetime import datetime\n\nfrom sqlalchemy import create_engine, Column, Integer, SmallInteger, String, DateTime, ForeignKey, Table, UnicodeText, Unicode, and_\nfrom sqlalchemy.orm import relationship, dynamic_loader, scoped_session, sessionmaker, class_mapper, backref\nfrom sqlalchemy.orm.session import Session\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm.interfaces import SessionExtension\n\nimport logging\nlogging.basicConfig(level=logging.INFO)\n_logger = logging.getLogger()\n\nACTIVITY_ADD = 1\nACTIVITY_MOD = 2\nACTIVITY_DEL = 3\n\nclass ActivityLogSessionExtension(SessionExtension):\n _logger = logging.getLogger('ActivityLogSessionExtension')\n\n def before_commit(self, session):\n self._logger.debug(\"before_commit: %s\", session)\n for d in session.new:\n self._logger.info(\"before_commit >> add: %s\", d)\n if hasattr(d, 'create_activitylog'):\n log = d.create_activitylog(ACTIVITY_ADD)\n for d in session.dirty:\n self._logger.info(\"before_commit >> mod: %s\", d)\n if hasattr(d, 'create_activitylog'):\n log = d.create_activitylog(ACTIVITY_MOD)\n for d in session.deleted:\n self._logger.info(\"before_commit >> del: %s\", d)\n if hasattr(d, 'create_activitylog'):\n log = d.create_activitylog(ACTIVITY_DEL)\n\n\n# Configure test data SA\nengine = create_engine('sqlite:///:memory:', echo=False)\nsession = scoped_session(sessionmaker(bind=engine, autoflush=False, extension=ActivityLogSessionExtension()))\nBase = declarative_base()\nBase.query = session.query_property()\n\nclass _BaseMixin(object):\n \"\"\" Just a helper mixin class to set properties on object creation. \n Also provides a convenient default __repr__() function, but be aware that \n also relationships are printed, which might result in loading relations.\n \"\"\"\n def __init__(self, **kwargs):\n for k,v in kwargs.items():\n setattr(self, k, v)\n\n def __repr__(self):\n return \"<%s(%s)>\" % (self.__class__.__name__, \n ', '.join('%s=%r' % (k, self.__dict__[k]) \n for k in sorted(self.__dict__) if '_sa_' != k[:4] and '_backref_' != k[:9])\n )\n\nclass User(Base, _BaseMixin):\n __tablename__ = u'users'\n id = Column(Integer, primary_key=True)\n name = Column(String)\n\nclass Document(Base, _BaseMixin):\n __tablename__ = u'documents'\n id = Column(Integer, primary_key=True)\n title = Column(Unicode(255), nullable=False)\n body = Column(UnicodeText, nullable=False)\n\nclass Folder(Base, _BaseMixin):\n __tablename__ = u'folders'\n id = Column(Integer, primary_key=True)\n title = Column(Unicode(255), nullable=False)\n comment = Column(UnicodeText, nullable=False)\n\nclass ActivityLog(Base, _BaseMixin):\n __tablename__ = u'activitylog'\n id = Column(Integer, primary_key=True)\n\n activity_by_id = Column(Integer, ForeignKey('users.id'), nullable=False)\n activity_by = relationship(User) # @note: no need to specify the primaryjoin\n activity_at = Column(DateTime, default=datetime.utcnow, nullable=False)\n activity_type = Column(SmallInteger, nullable=False)\n\n target_table = Column(Unicode(20), nullable=False)\n target_id = Column(Integer, nullable=False)\n target_title = Column(Unicode(255), nullable=False)\n # backref relation for auditable\n target = property(lambda self: getattr(self, '_backref_%s' % self.target_table))\n\ndef _get_user():\n \"\"\" This method returns the User object for the current user.\n @todo: proper implementation required\n @hack: currently returns the 'user2'\n \"\"\"\n return session.query(User).filter_by(name='user2').one()\n\n# auditable support function\n# based on first non-FK version from http://techspot.zzzeek.org/?p=13\ndef auditable(cls, name):\n def create_activitylog(self, activity_type):\n log = ActivityLog(activity_by=_get_user(),\n activity_type=activity_type,\n target_table=table.name, \n target_title=self.title,\n )\n getattr(self, name).append(log)\n return log\n\n mapper = class_mapper(cls)\n table = mapper.local_table\n cls.create_activitylog = create_activitylog\n\n def _get_activitylog(self):\n return Session.object_session(self).query(ActivityLog).with_parent(self).all()\n setattr(cls, '%s_readonly' %(name,), property(_get_activitylog))\n\n # no constraints, therefore define constraints in an ad-hoc fashion.\n primaryjoin = and_(\n list(table.primary_key)[0] == ActivityLog.__table__.c.target_id,\n ActivityLog.__table__.c.target_table == table.name\n )\n foreign_keys = [ActivityLog.__table__.c.target_id]\n mapper.add_property(name, \n # @note: because we use the relationship, by default all previous\n # ActivityLog items will be loaded for an object when new one is\n # added. To avoid this, use either dynamic_loader (http://www.sqlalchemy.org/docs/reference/orm/mapping.html#sqlalchemy.orm.dynamic_loader)\n # or lazy='noload'. This is the trade-off decision to be made.\n # Additional benefit of using lazy='noload' is that one can also\n # record DEL operations in the same way as ADD, MOD\n relationship(\n ActivityLog,\n lazy='noload', # important for relationship\n primaryjoin=primaryjoin, \n foreign_keys=foreign_keys,\n backref=backref('_backref_%s' % table.name, \n primaryjoin=list(table.primary_key)[0] == ActivityLog.__table__.c.target_id, \n foreign_keys=foreign_keys)\n )\n )\n\n# this will define which classes support the ActivityLog interface\nauditable(Document, 'activitylogs')\nauditable(Folder, 'activitylogs')\n\n# create db schema\nBase.metadata.create_all(engine)\n\n\n## >>>>> TESTS >>>>>>\n\n# create some basic data first\nu1 = User(name='user1')\nu2 = User(name='user2')\nsession.add(u1)\nsession.add(u2)\nsession.commit()\nsession.expunge_all()\n# --check--\nassert not(_get_user() is None)\n\n\n##############################\n## ADD\n##############################\n_logger.info('-' * 80)\nd1 = Document(title=u'Document-1', body=u'Doc1 some body skipped the body')\n# when not using SessionExtension for any reason, this can be called manually\n#d1.create_activitylog(ACTIVITY_ADD)\nsession.add(d1)\nsession.commit()\n\nf1 = Folder(title=u'Folder-1', comment=u'This folder is empty')\n# when not using SessionExtension for any reason, this can be called manually\n#f1.create_activitylog(ACTIVITY_ADD)\nsession.add(f1)\nsession.commit()\n\n# --check--\nsession.expunge_all()\nlogs = session.query(ActivityLog).all()\n_logger.debug(logs)\nassert len(logs) == 2\nassert logs[0].activity_type == ACTIVITY_ADD\nassert logs[0].target.title == u'Document-1'\nassert logs[0].target.title == logs[0].target_title\nassert logs[1].activity_type == ACTIVITY_ADD\nassert logs[1].target.title == u'Folder-1'\nassert logs[1].target.title == logs[1].target_title\n\n##############################\n## MOD(ify)\n##############################\n_logger.info('-' * 80)\nsession.expunge_all()\nd1 = session.query(Document).filter_by(id=1).one()\nassert d1.title == u'Document-1'\nassert d1.body == u'Doc1 some body skipped the body'\nassert d1.activitylogs == []\nd1.title = u'Modified: Document-1'\nd1.body = u'Modified: body'\n# when not using SessionExtension (or it does not work, this can be called manually)\n#d1.create_activitylog(ACTIVITY_MOD)\nsession.commit()\n_logger.debug(d1.activitylogs_readonly)\n\n# --check--\nsession.expunge_all()\nlogs = session.query(ActivityLog).all()\nassert len(logs)==3\nassert logs[2].activity_type == ACTIVITY_MOD\nassert logs[2].target.title == u'Modified: Document-1'\nassert logs[2].target.title == logs[2].target_title\n\n\n##############################\n## DEL(ete)\n##############################\n_logger.info('-' * 80)\nsession.expunge_all()\nd1 = session.query(Document).filter_by(id=1).one()\n# when not using SessionExtension for any reason, this can be called manually,\n#d1.create_activitylog(ACTIVITY_DEL)\nsession.delete(d1)\nsession.commit()\nsession.expunge_all()\n\n# --check--\nsession.expunge_all()\nlogs = session.query(ActivityLog).all()\nassert len(logs)==4\nassert logs[0].target is None\nassert logs[2].target is None\nassert logs[3].activity_type == ACTIVITY_DEL\nassert logs[3].target is None\n\n##############################\n## print all activity logs\n##############################\n_logger.info('=' * 80)\nlogs = session.query(ActivityLog).all()\nfor log in logs:\n _ = log.target\n _logger.info(\"%s -> %s\", log, log.target)\n\n##############################\n## navigate from main object\n##############################\n_logger.info('=' * 80)\nsession.expunge_all()\nf1 = session.query(Folder).filter_by(id=1).one()\n_logger.info(f1.activitylogs_readonly)\n\n"
] | [
1,
1
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0002850988_python_sqlalchemy.txt |
Q:
Creating an interface and swappable implementations in python
Would it be possible to create a class interface in python and various implementations of the interface.
Example: I want to create a class for pop3 access (and all methods etc.). If I go with a commercial component, I want to wrap it to adhere to a contract.
In the future, if I want to use another component or code my own, I want to be able to swap things out and not have things very tightly coupled.
Possible? I'm new to python.
A:
For people coming from a strongly typed language background, Python does not need a class interface. You can simulate it using a base class.
class BaseAccess:
def open(arg):
raise NotImplementedError()
class Pop3Access(BaseAccess):
def open(arg):
...
class AlternateAccess(BaseAccess):
def open(arg):
...
But you can easily write the same code without using BaseAccess. Strongly typed language needs the interface for type checking during compile time. For Python, this is not necessary because everything is looked up dynamically in run time. Google 'duck typing' for its philosophy.
There is a Abstract Base Classes module added in Python 2.6. But I haven't have used it.
A:
Of course. There is no need to create a base class or an interface in this case either, as everything is dynamic.
A:
One option is to use zope interfaces. However, as was stated by Wai Yip Tung, you do not need to use interfaces to achieve the same results.
The zope.interface package is really more a tool for discovering how to interact with objects (generally within large code bases with multiple developers).
A:
Yes, this is possible. There are typically no impediments to doing so: just keep a stable API and change how you implement it.
| Creating an interface and swappable implementations in python | Would it be possible to create a class interface in python and various implementations of the interface.
Example: I want to create a class for pop3 access (and all methods etc.). If I go with a commercial component, I want to wrap it to adhere to a contract.
In the future, if I want to use another component or code my own, I want to be able to swap things out and not have things very tightly coupled.
Possible? I'm new to python.
| [
"For people coming from a strongly typed language background, Python does not need a class interface. You can simulate it using a base class.\nclass BaseAccess:\n def open(arg):\n raise NotImplementedError()\n\nclass Pop3Access(BaseAccess):\n def open(arg):\n ...\n\nclass AlternateAccess(BaseAccess):\n def open(arg):\n ...\n\nBut you can easily write the same code without using BaseAccess. Strongly typed language needs the interface for type checking during compile time. For Python, this is not necessary because everything is looked up dynamically in run time. Google 'duck typing' for its philosophy.\nThere is a Abstract Base Classes module added in Python 2.6. But I haven't have used it.\n",
"Of course. There is no need to create a base class or an interface in this case either, as everything is dynamic.\n",
"One option is to use zope interfaces. However, as was stated by Wai Yip Tung, you do not need to use interfaces to achieve the same results. \nThe zope.interface package is really more a tool for discovering how to interact with objects (generally within large code bases with multiple developers).\n",
"Yes, this is possible. There are typically no impediments to doing so: just keep a stable API and change how you implement it. \n"
] | [
6,
2,
1,
0
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0002860106_oop_python.txt |
Q:
How to access __init__.py variables from deeper parts of a package
I apologize for yet another __init__.py question.
I have the following package structure:
+contrib
+--__init__.py
|
+database
+--__init__.py
|
+--connection.py
In the top-level __init__.py I define: USER='me'. If I import contrib from the command line, then I can access contrib.USER.
Now, I want to access contrib.user from withih connection.py but I cannot do it.
The top-level __init__.py is called when I issue from contrib.database import connection, so Python is really creating the parameter USER.
So the question is: how to you access the parameters and variables declared in the top-level __init__.py from within the children.
Thank you.
EDIT:
I realize that you can add import contrib to connection.py, but it seems repetitive, as it is obvious (incorrectly so?) that if you need connection.py you already imported contrib.
A:
Adding import contrib to connection.py is the way to go. Yes, the contrib module is already imported (you can find out from sys.modules). The problem is there is no reference to the module from your code in connection.py. Doing another import will give you the reference. You do not need to worry about additional loading time because the module is already loaded.
A:
You need to import contrib in connection. Either use a relative import (..contrib) or an absolute import.
| How to access __init__.py variables from deeper parts of a package | I apologize for yet another __init__.py question.
I have the following package structure:
+contrib
+--__init__.py
|
+database
+--__init__.py
|
+--connection.py
In the top-level __init__.py I define: USER='me'. If I import contrib from the command line, then I can access contrib.USER.
Now, I want to access contrib.user from withih connection.py but I cannot do it.
The top-level __init__.py is called when I issue from contrib.database import connection, so Python is really creating the parameter USER.
So the question is: how to you access the parameters and variables declared in the top-level __init__.py from within the children.
Thank you.
EDIT:
I realize that you can add import contrib to connection.py, but it seems repetitive, as it is obvious (incorrectly so?) that if you need connection.py you already imported contrib.
| [
"Adding import contrib to connection.py is the way to go. Yes, the contrib module is already imported (you can find out from sys.modules). The problem is there is no reference to the module from your code in connection.py. Doing another import will give you the reference. You do not need to worry about additional loading time because the module is already loaded.\n",
"You need to import contrib in connection. Either use a relative import (..contrib) or an absolute import.\n"
] | [
13,
0
] | [] | [] | [
"python"
] | stackoverflow_0002860482_python.txt |
Q:
Google Wave Robot / Python Variable question
I'm experimenting/having a little fun with wave robot python apiv2.
I made a little 8ball app for the robot which works fine, and now I'm trying to make a trivia app.
I've never programmed in Python but I'm pretty sure my syntax is correct. Here is the relevant code:
elif (bliptxt == "\n!strivia"):
reply = blip.reply()
if (triviaStatus != "playing"):
reply.append("Trivia Started!")
triviaStatus = "playing"
else:
reply.append("Trivia is already running!")
elif (bliptxt == "\n!etrivia"):
reply = blip.reply()
if (triviaStatus == "playing"):
reply.append("Trivia Ended!")
triviaStatus = "stopped"
else:
reply.append("Trivia is not running! To start trivia, type !strivia")
else: (snipped out)
Okay so basically I want it to work so that when someone blips "strivia" the bot recognizes that someone wants to play so it first checks a variable called triviaStatus to see if we are already playing and goes from there. Pretty simple stuff.
In order for this to work (and, actually, this code is really meant to test this question out) the variables would need to effectively be like the php $_SESSION variables - that is, it remembers the value of the variable every time someone blips and does not reset each time.
Nevertheless, whether or not that is the case (if it isn't then I assume I can do the same thing by saving variable settings in a txt file or something) I am baffled because the code above does not work at all. That is to say, the robot is not replying on !strivia or on !etrivia. If the variables didn't save then if anything the robot should just reply with "Trivia Started" or with "Trivia is not running!" each time. But it just does not reply at all.
If I remove the check for triviaStatus, the robot DOES reply. But then there's no logic and I can't test my question out.
I also tried making a !trivstatus where it would reply back with
"Trivia status is " + triviaStatus
but that ALSO choked up. Why is it that every time I want to USE triviaStatus, the bot just dies? Note that I am able to SET triviaStatus fine (I just can't ever check what the output is by replying with it....)
So, to sum this up...how come the above code does not work but the following code DOES work:
elif (bliptxt == "\n!strivia"):
reply = blip.reply()
reply.append("Trivia Started!")
trivia_status = "playing"
elif (bliptxt == "\n!etrivia"):
reply = blip.reply()
reply.append("Trivia Ended!")
trivia_status = "stopped"
Thanks!
A:
It seems that you should rename triviaStatus to trivia_status and make sure that trivia_status has some value e.g., bind it to None before the first use. Otherwise your code might raise UnboundLocalError or NameError exceptions due to triviaStatus/trivia_status doesn't refer to any object.
| Google Wave Robot / Python Variable question | I'm experimenting/having a little fun with wave robot python apiv2.
I made a little 8ball app for the robot which works fine, and now I'm trying to make a trivia app.
I've never programmed in Python but I'm pretty sure my syntax is correct. Here is the relevant code:
elif (bliptxt == "\n!strivia"):
reply = blip.reply()
if (triviaStatus != "playing"):
reply.append("Trivia Started!")
triviaStatus = "playing"
else:
reply.append("Trivia is already running!")
elif (bliptxt == "\n!etrivia"):
reply = blip.reply()
if (triviaStatus == "playing"):
reply.append("Trivia Ended!")
triviaStatus = "stopped"
else:
reply.append("Trivia is not running! To start trivia, type !strivia")
else: (snipped out)
Okay so basically I want it to work so that when someone blips "strivia" the bot recognizes that someone wants to play so it first checks a variable called triviaStatus to see if we are already playing and goes from there. Pretty simple stuff.
In order for this to work (and, actually, this code is really meant to test this question out) the variables would need to effectively be like the php $_SESSION variables - that is, it remembers the value of the variable every time someone blips and does not reset each time.
Nevertheless, whether or not that is the case (if it isn't then I assume I can do the same thing by saving variable settings in a txt file or something) I am baffled because the code above does not work at all. That is to say, the robot is not replying on !strivia or on !etrivia. If the variables didn't save then if anything the robot should just reply with "Trivia Started" or with "Trivia is not running!" each time. But it just does not reply at all.
If I remove the check for triviaStatus, the robot DOES reply. But then there's no logic and I can't test my question out.
I also tried making a !trivstatus where it would reply back with
"Trivia status is " + triviaStatus
but that ALSO choked up. Why is it that every time I want to USE triviaStatus, the bot just dies? Note that I am able to SET triviaStatus fine (I just can't ever check what the output is by replying with it....)
So, to sum this up...how come the above code does not work but the following code DOES work:
elif (bliptxt == "\n!strivia"):
reply = blip.reply()
reply.append("Trivia Started!")
trivia_status = "playing"
elif (bliptxt == "\n!etrivia"):
reply = blip.reply()
reply.append("Trivia Ended!")
trivia_status = "stopped"
Thanks!
| [
"It seems that you should rename triviaStatus to trivia_status and make sure that trivia_status has some value e.g., bind it to None before the first use. Otherwise your code might raise UnboundLocalError or NameError exceptions due to triviaStatus/trivia_status doesn't refer to any object.\n"
] | [
1
] | [] | [] | [
"google_wave",
"python",
"scope"
] | stackoverflow_0002860677_google_wave_python_scope.txt |
Q:
Fabfiles With Command Line Arguments
Is there a clean way to have your fabfile take command line arguments? I'm writing an installation script for a tool that I want to be able to specify an optional target directory via the command line.
I wrote some code to test what would happen if I passed in some command line arguments:
# fabfile.py
import sys
def install():
_get_options()
def _get_options():
print repr(sys.argv[1:])
A couple of runs:
$ fab install
['install']
Done.
$ fab install --electric-boogaloo
Usage: fab [options] <command>[:arg1,arg2=val2,host=foo,hosts='h1;h2',...] ...
fab: error: no such option: --electric-boogaloo
A:
I ended up using the per-task arguments. It seems like a better idea than doing unattached command line arguments.
| Fabfiles With Command Line Arguments | Is there a clean way to have your fabfile take command line arguments? I'm writing an installation script for a tool that I want to be able to specify an optional target directory via the command line.
I wrote some code to test what would happen if I passed in some command line arguments:
# fabfile.py
import sys
def install():
_get_options()
def _get_options():
print repr(sys.argv[1:])
A couple of runs:
$ fab install
['install']
Done.
$ fab install --electric-boogaloo
Usage: fab [options] <command>[:arg1,arg2=val2,host=foo,hosts='h1;h2',...] ...
fab: error: no such option: --electric-boogaloo
| [
"I ended up using the per-task arguments. It seems like a better idea than doing unattached command line arguments.\n"
] | [
4
] | [] | [] | [
"fabric",
"python"
] | stackoverflow_0002859424_fabric_python.txt |
Q:
Mercurial fails while commiting/updating/etc. using Mercuriual+TrueCrypt+MAC
While trying to work with Mercurial on project located on TrueCrypt partition I always get en error as follows:
** unknown exception encountered, details follow
** report bug details to http://mercurial.selenic.com/bts/
** or mercurial@selenic.com
** Mercurial Distributed SCM (version 1.5.2+20100502)
** Extensions loaded:
Traceback (most recent call last):
File "/usr/local/bin/hg", line 27, in <module>
mercurial.dispatch.run()
File "/Library/Python/2.6/site-packages/mercurial/dispatch.py", line 16, in run
sys.exit(dispatch(sys.argv[1:]))
File "/Library/Python/2.6/site-packages/mercurial/dispatch.py", line 30, in dispatch
return _runcatch(u, args)
File "/Library/Python/2.6/site-packages/mercurial/dispatch.py", line 50, in _runcatch
return _dispatch(ui, args)
File "/Library/Python/2.6/site-packages/mercurial/dispatch.py", line 470, in _dispatch
return runcommand(lui, repo, cmd, fullargs, ui, options, d)
File "/Library/Python/2.6/site-packages/mercurial/dispatch.py", line 340, in runcommand
ret = _runcommand(ui, options, cmd, d)
File "/Library/Python/2.6/site-packages/mercurial/dispatch.py", line 521, in _runcommand
return checkargs()
File "/Library/Python/2.6/site-packages/mercurial/dispatch.py", line 475, in checkargs
return cmdfunc()
File "/Library/Python/2.6/site-packages/mercurial/dispatch.py", line 469, in <lambda>
d = lambda: util.checksignature(func)(ui, *args, **cmdoptions)
File "/Library/Python/2.6/site-packages/mercurial/util.py", line 401, in check
return func(*args, **kwargs)
File "/Library/Python/2.6/site-packages/mercurial/commands.py", line 3332, in update
return hg.update(repo, rev)
File "/Library/Python/2.6/site-packages/mercurial/hg.py", line 362, in update
stats = _merge.update(repo, node, False, False, None)
File "/Library/Python/2.6/site-packages/mercurial/merge.py", line 495, in update
_checkunknown(wc, p2)
File "/Library/Python/2.6/site-packages/mercurial/merge.py", line 77, in _checkunknown
for f in wctx.unknown():
File "/Library/Python/2.6/site-packages/mercurial/context.py", line 660, in unknown
return self._status[4]
File "/Library/Python/2.6/site-packages/mercurial/util.py", line 156, in __get__
result = self.func(obj)
File "/Library/Python/2.6/site-packages/mercurial/context.py", line 622, in _status
return self._repo.status(unknown=True)
File "/Library/Python/2.6/site-packages/mercurial/localrepo.py", line 1023, in status
if (f not in ctx1 or ctx2.flags(f) != ctx1.flags(f)
File "/Library/Python/2.6/site-packages/mercurial/context.py", line 694, in flags
flag = findflag(self._parents[0])
File "/Library/Python/2.6/site-packages/mercurial/context.py", line 690, in findflag
return ff(path)
File "/Library/Python/2.6/site-packages/mercurial/dirstate.py", line 145, in f
if 'x' in fallback(x):
TypeError: argument of type 'NoneType' is not iterable
It is worth mention that Mercurial works perfectly if project is not located on TrueCrypt partition.
Configuration:
MacOS X 10.6.3
Mercurial Distributed SCM (version 1.5.2+20100502)
Python 2.6.5
Have anyone of you generous people able to help me? :)
A:
This bug was added in 1.5.2 (sorry about that), we released 1.5.3 shortly afterwards, please use it.
| Mercurial fails while commiting/updating/etc. using Mercuriual+TrueCrypt+MAC | While trying to work with Mercurial on project located on TrueCrypt partition I always get en error as follows:
** unknown exception encountered, details follow
** report bug details to http://mercurial.selenic.com/bts/
** or mercurial@selenic.com
** Mercurial Distributed SCM (version 1.5.2+20100502)
** Extensions loaded:
Traceback (most recent call last):
File "/usr/local/bin/hg", line 27, in <module>
mercurial.dispatch.run()
File "/Library/Python/2.6/site-packages/mercurial/dispatch.py", line 16, in run
sys.exit(dispatch(sys.argv[1:]))
File "/Library/Python/2.6/site-packages/mercurial/dispatch.py", line 30, in dispatch
return _runcatch(u, args)
File "/Library/Python/2.6/site-packages/mercurial/dispatch.py", line 50, in _runcatch
return _dispatch(ui, args)
File "/Library/Python/2.6/site-packages/mercurial/dispatch.py", line 470, in _dispatch
return runcommand(lui, repo, cmd, fullargs, ui, options, d)
File "/Library/Python/2.6/site-packages/mercurial/dispatch.py", line 340, in runcommand
ret = _runcommand(ui, options, cmd, d)
File "/Library/Python/2.6/site-packages/mercurial/dispatch.py", line 521, in _runcommand
return checkargs()
File "/Library/Python/2.6/site-packages/mercurial/dispatch.py", line 475, in checkargs
return cmdfunc()
File "/Library/Python/2.6/site-packages/mercurial/dispatch.py", line 469, in <lambda>
d = lambda: util.checksignature(func)(ui, *args, **cmdoptions)
File "/Library/Python/2.6/site-packages/mercurial/util.py", line 401, in check
return func(*args, **kwargs)
File "/Library/Python/2.6/site-packages/mercurial/commands.py", line 3332, in update
return hg.update(repo, rev)
File "/Library/Python/2.6/site-packages/mercurial/hg.py", line 362, in update
stats = _merge.update(repo, node, False, False, None)
File "/Library/Python/2.6/site-packages/mercurial/merge.py", line 495, in update
_checkunknown(wc, p2)
File "/Library/Python/2.6/site-packages/mercurial/merge.py", line 77, in _checkunknown
for f in wctx.unknown():
File "/Library/Python/2.6/site-packages/mercurial/context.py", line 660, in unknown
return self._status[4]
File "/Library/Python/2.6/site-packages/mercurial/util.py", line 156, in __get__
result = self.func(obj)
File "/Library/Python/2.6/site-packages/mercurial/context.py", line 622, in _status
return self._repo.status(unknown=True)
File "/Library/Python/2.6/site-packages/mercurial/localrepo.py", line 1023, in status
if (f not in ctx1 or ctx2.flags(f) != ctx1.flags(f)
File "/Library/Python/2.6/site-packages/mercurial/context.py", line 694, in flags
flag = findflag(self._parents[0])
File "/Library/Python/2.6/site-packages/mercurial/context.py", line 690, in findflag
return ff(path)
File "/Library/Python/2.6/site-packages/mercurial/dirstate.py", line 145, in f
if 'x' in fallback(x):
TypeError: argument of type 'NoneType' is not iterable
It is worth mention that Mercurial works perfectly if project is not located on TrueCrypt partition.
Configuration:
MacOS X 10.6.3
Mercurial Distributed SCM (version 1.5.2+20100502)
Python 2.6.5
Have anyone of you generous people able to help me? :)
| [
"This bug was added in 1.5.2 (sorry about that), we released 1.5.3 shortly afterwards, please use it.\n"
] | [
2
] | [] | [] | [
"mercurial",
"python",
"truecrypt"
] | stackoverflow_0002859913_mercurial_python_truecrypt.txt |
Q:
Emacs: Inferior-mode python-shell appears "lagged"
I'm a Python(3.1.2)/emacs(23.2) newbie teaching myself tkinter using the pythonware tutorial found here. Relevant code is pasted below the question.
Question: when I click the Hello button (which should call the say_hi function) why does the inferior python shell (i.e. the one I kicked off with C-c C-c) wait to execute the say_hi print function until I either a) click the Quit button or b) close the root widget down? When I try the same in IDLE, each click of the Hello button produces an immediate print in the IDLE python shell, even before I click Quit or close the root widget.
Is there some quirk in the way emacs runs the Python shell (vs. IDLE) that causes this "lagged" behavior? I've noticed similar emacs lags vs. IDLE as I've worked through Project Euler problems, but this is the clearest example I've seen yet.
FYI: I use python.el and have a relatively clean init.el...
(setq python-python-command "d:/bin/python31/python")
is the only line in my init.el.
Thanks,
Mike
=== Begin Code===
from tkinter import *
class App:
def __init__(self,master):
frame = Frame(master)
frame.pack()
self.button = Button(frame, text="QUIT", fg="red", command=frame.quit)
self.button.pack(side=LEFT)
self.hi_there = Button(frame, text="Hello", command=self.say_hi)
self.hi_there.pack(side=LEFT)
def say_hi(self):
print("hi there, everyone!")
root = Tk()
app = App(root)
root.mainloop()
A:
I'd guess that not being attached to a tty, the Python interpreter (via C stdio) switches to block buffered from line buffered and doesn't flush stdout until it closes. Running os.isatty(1) in an "Inferior Python:run Shell Compile" buffer returns false, thus adding weight to this guess.
def say_hi(self):
print("hi there, everyone!")
sys.stdout.flush()
May make a difference.
| Emacs: Inferior-mode python-shell appears "lagged" | I'm a Python(3.1.2)/emacs(23.2) newbie teaching myself tkinter using the pythonware tutorial found here. Relevant code is pasted below the question.
Question: when I click the Hello button (which should call the say_hi function) why does the inferior python shell (i.e. the one I kicked off with C-c C-c) wait to execute the say_hi print function until I either a) click the Quit button or b) close the root widget down? When I try the same in IDLE, each click of the Hello button produces an immediate print in the IDLE python shell, even before I click Quit or close the root widget.
Is there some quirk in the way emacs runs the Python shell (vs. IDLE) that causes this "lagged" behavior? I've noticed similar emacs lags vs. IDLE as I've worked through Project Euler problems, but this is the clearest example I've seen yet.
FYI: I use python.el and have a relatively clean init.el...
(setq python-python-command "d:/bin/python31/python")
is the only line in my init.el.
Thanks,
Mike
=== Begin Code===
from tkinter import *
class App:
def __init__(self,master):
frame = Frame(master)
frame.pack()
self.button = Button(frame, text="QUIT", fg="red", command=frame.quit)
self.button.pack(side=LEFT)
self.hi_there = Button(frame, text="Hello", command=self.say_hi)
self.hi_there.pack(side=LEFT)
def say_hi(self):
print("hi there, everyone!")
root = Tk()
app = App(root)
root.mainloop()
| [
"I'd guess that not being attached to a tty, the Python interpreter (via C stdio) switches to block buffered from line buffered and doesn't flush stdout until it closes. Running os.isatty(1) in an \"Inferior Python:run Shell Compile\" buffer returns false, thus adding weight to this guess.\ndef say_hi(self):\n print(\"hi there, everyone!\")\n sys.stdout.flush()\n\nMay make a difference. \n"
] | [
4
] | [] | [] | [
"emacs",
"python"
] | stackoverflow_0002861178_emacs_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.