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:
Creating equivalent classes in Python?
I played around with overloading or masking classes in Python. Do the following code examples create equivalent classes?
class CustASample(object):
def __init__(self):
self.__class__.__name__ = "Sample"
def doSomething(self):
dummy = 1
and
class Sample(object):
def doSomething(self):
dummy = 1
EDIT: From the comments and and the good answer by gs, it occured to me, that I really wanted to ask: What "attributes" make these classes differ?
Because
>>> dir(a) == dir(b)
True
and
>>> print Sample
<class '__main__.Sample'>
>>> print CustASample
<class '__main__.Sample'>
but
>>> Sample == CustASample
False
A:
No, they are still different.
a = CustASample()
b = Sample()
a.__class__ is b.__class__
-> False
Here's how you could do it:
class A(object):
def __init__(self):
self.__class__ = B
class B(object):
def bark(self):
print "Wuff!"
a = A()
b = B()
a.__class__ is b.__class__
-> True
a.bark()
-> Wuff!
b.bark()
-> Wuff!
Usually you would do it in the __new__ method instead of in __init__:
class C(object):
def __new__(cls):
return A()
To answer your updated question:
>>> a = object()
>>> b = object()
>>> a == b
False
Why would a not be equal to b, since both are just plain objects without attributes?
Well, that answer is simple. The == operator invokes __eq__, if it's available. But unless you define it yourself it's not. Instead of it a is b gets used.
is compares the ids of the objects. (In CPython the memory address.) You can get the id of an object like this:
>>> id(a)
156808
A:
Classes also, not only instances, are objects. For example, you can get id(Sample). Try it and see that these two numbers differ, as differ the classes' memory locations. They are not the same object. It's like asking whether [] is [].
EDIT: Too late and the explanation by gs is better.
|
Creating equivalent classes in Python?
|
I played around with overloading or masking classes in Python. Do the following code examples create equivalent classes?
class CustASample(object):
def __init__(self):
self.__class__.__name__ = "Sample"
def doSomething(self):
dummy = 1
and
class Sample(object):
def doSomething(self):
dummy = 1
EDIT: From the comments and and the good answer by gs, it occured to me, that I really wanted to ask: What "attributes" make these classes differ?
Because
>>> dir(a) == dir(b)
True
and
>>> print Sample
<class '__main__.Sample'>
>>> print CustASample
<class '__main__.Sample'>
but
>>> Sample == CustASample
False
|
[
"No, they are still different.\na = CustASample()\nb = Sample()\na.__class__ is b.__class__\n-> False\n\nHere's how you could do it:\nclass A(object):\n def __init__(self):\n self.__class__ = B\n\nclass B(object):\n def bark(self):\n print \"Wuff!\"\n\na = A()\nb = B()\na.__class__ is b.__class__\n-> True\n\na.bark()\n-> Wuff!\n\nb.bark()\n-> Wuff!\n\nUsually you would do it in the __new__ method instead of in __init__:\nclass C(object):\n def __new__(cls):\n return A()\n\n\nTo answer your updated question:\n>>> a = object()\n>>> b = object()\n>>> a == b\nFalse\n\nWhy would a not be equal to b, since both are just plain objects without attributes?\nWell, that answer is simple. The == operator invokes __eq__, if it's available. But unless you define it yourself it's not. Instead of it a is b gets used.\nis compares the ids of the objects. (In CPython the memory address.) You can get the id of an object like this:\n>>> id(a)\n156808\n\n",
"Classes also, not only instances, are objects. For example, you can get id(Sample). Try it and see that these two numbers differ, as differ the classes' memory locations. They are not the same object. It's like asking whether [] is [].\nEDIT: Too late and the explanation by gs is better.\n"
] |
[
10,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001999551_python.txt
|
Q:
is there a way to append the etag at the end of the static resources in django
In rails, if I import a css file or javascript file, the url will be like this
<script type="text/javascript" src="some.js?<ETag here>"></script>
if I upgrade the some.js the etag will be changed, so my browser can cache the static resource smartly and update the cache when necessary.
Is there a way to do it in django?
A:
Maybe django-static can help you on this ..
django_static is a Django app that enables as various template tags for better serving your static content. It basically rewrites references to static files and where applicable it does whitespace optmization of the content.
By making references to static content unique (timestamp included in the name) you can be very aggressive with your cache-control settings without ever having to worry about upgrading your code and worrying about visitors using an older version.
This solution is, as <jldupont> pointed out, one, which does not relate to HTTP ETags.
A:
Besides django-static mentioned by The MYYN, these projects will do what you need and also contain other highly useful features like compression and concatenation:
django-compress
django_compressor
|
is there a way to append the etag at the end of the static resources in django
|
In rails, if I import a css file or javascript file, the url will be like this
<script type="text/javascript" src="some.js?<ETag here>"></script>
if I upgrade the some.js the etag will be changed, so my browser can cache the static resource smartly and update the cache when necessary.
Is there a way to do it in django?
|
[
"Maybe django-static can help you on this ..\n\ndjango_static is a Django app that enables as various template tags for better serving your static content. It basically rewrites references to static files and where applicable it does whitespace optmization of the content.\nBy making references to static content unique (timestamp included in the name) you can be very aggressive with your cache-control settings without ever having to worry about upgrading your code and worrying about visitors using an older version.\n\nThis solution is, as <jldupont> pointed out, one, which does not relate to HTTP ETags.\n",
"Besides django-static mentioned by The MYYN, these projects will do what you need and also contain other highly useful features like compression and concatenation:\ndjango-compress\ndjango_compressor\n"
] |
[
1,
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002000306_django_python.txt
|
Q:
Using Python csv module on updating file
I am using python's csv module to extract data from a csv that is constantly being updated by an external tool. I have run into a problem where when I reach the end of the file I get a StopIteration error, however, I would like the script to continue to loop waiting for more lines to be added by the external tool.
What I came up with so far to do this is:
f = open('file.csv')
csvReader = csv.reader(f, delimiter=',')
while 1:
try:
doStuff(csvReader.next())
except StopIteration:
depth = f.tell()
f.close()
f = open('file.csv')
f.seek(depth)
csvReader = csv.reader(f, delimiter=',')
This has the intended functionality but it also seems terrible. Looping after catching the StopIteration is not possible since once StopIteration is thrown, it will throw a StopIteration on every subsequent call to next(). Anyone have any suggestions on how to implement this is in such a way that I don't have to do this silly tell and seeking? Or have a different python module that can easily support this functionality.
A:
Your problem is not with the CSV reader, but with the file object itself. You may still have to do the crazy gyrations you're doing in your snippet above, but it would be better to create a file object wrapper or subclass that does it for you, and use that with your CSV reader. That keeps the complexity isolated from your csv processing code.
For instance (warning: untested code):
class ReopeningFile(object):
def __init__(self, filename):
self.filename = filename
self.f = open(self.filename)
def next(self):
try:
self.f.next()
except StopIteration:
depth = self.f.tell()
self.f.close()
self.f = open(self.filename)
self.f.seek(depth)
# May need to sleep here to allow more data to come in
# Also may need a way to signal a real StopIteration
self.next()
def __iter__(self):
return self
Then your main code becomes simpler, as it is freed from having to manage the file reopening (note that you also don't have to restart your csv_reader whenever the file restarts:
import csv
csv_reader = csv.reader(ReopeningFile('data.csv'))
for each in csv_reader:
process_csv_line(each)
A:
Producer-consumer stuff can get a bit tricky. How about using seek and reading bytes instead? What about using a named pipe?
Heck, why not communicate over a local socket?
A:
You rarely need to catch StopIteration explicitly. Do this:
for row in csvReader:
doStuff(row)
As for detecting when new lines are written to the file, you can either popen a tail -f process or write out the Python code for what tail -f does. (It isn't complicated; it basically just stats the file every second to see if it's changed. Here's the C source code of tail.)
EDIT: Disappointingly, popening tail -f doesn't work as I expected in Python 2.x. It seems iterating over the lines of a file is implemented using fread and a largeish buffer, even if the file is supposed to be unbuffered (like when subprocess.py creates the file, passing bufsize=0). But popening tail would be a mildly ugly hack anyway.
|
Using Python csv module on updating file
|
I am using python's csv module to extract data from a csv that is constantly being updated by an external tool. I have run into a problem where when I reach the end of the file I get a StopIteration error, however, I would like the script to continue to loop waiting for more lines to be added by the external tool.
What I came up with so far to do this is:
f = open('file.csv')
csvReader = csv.reader(f, delimiter=',')
while 1:
try:
doStuff(csvReader.next())
except StopIteration:
depth = f.tell()
f.close()
f = open('file.csv')
f.seek(depth)
csvReader = csv.reader(f, delimiter=',')
This has the intended functionality but it also seems terrible. Looping after catching the StopIteration is not possible since once StopIteration is thrown, it will throw a StopIteration on every subsequent call to next(). Anyone have any suggestions on how to implement this is in such a way that I don't have to do this silly tell and seeking? Or have a different python module that can easily support this functionality.
|
[
"Your problem is not with the CSV reader, but with the file object itself. You may still have to do the crazy gyrations you're doing in your snippet above, but it would be better to create a file object wrapper or subclass that does it for you, and use that with your CSV reader. That keeps the complexity isolated from your csv processing code.\nFor instance (warning: untested code):\nclass ReopeningFile(object):\n def __init__(self, filename):\n self.filename = filename\n self.f = open(self.filename)\n\n def next(self):\n try:\n self.f.next()\n except StopIteration:\n depth = self.f.tell()\n self.f.close()\n self.f = open(self.filename)\n self.f.seek(depth)\n # May need to sleep here to allow more data to come in\n # Also may need a way to signal a real StopIteration\n self.next()\n\n def __iter__(self):\n return self\n\nThen your main code becomes simpler, as it is freed from having to manage the file reopening (note that you also don't have to restart your csv_reader whenever the file restarts:\nimport csv\ncsv_reader = csv.reader(ReopeningFile('data.csv'))\nfor each in csv_reader:\n process_csv_line(each)\n\n",
"Producer-consumer stuff can get a bit tricky. How about using seek and reading bytes instead? What about using a named pipe?\nHeck, why not communicate over a local socket?\n",
"You rarely need to catch StopIteration explicitly. Do this:\nfor row in csvReader:\n doStuff(row)\n\nAs for detecting when new lines are written to the file, you can either popen a tail -f process or write out the Python code for what tail -f does. (It isn't complicated; it basically just stats the file every second to see if it's changed. Here's the C source code of tail.)\nEDIT: Disappointingly, popening tail -f doesn't work as I expected in Python 2.x. It seems iterating over the lines of a file is implemented using fread and a largeish buffer, even if the file is supposed to be unbuffered (like when subprocess.py creates the file, passing bufsize=0). But popening tail would be a mildly ugly hack anyway.\n"
] |
[
4,
2,
0
] |
[] |
[] |
[
"csv",
"file",
"python"
] |
stackoverflow_0002001201_csv_file_python.txt
|
Q:
Cannot understand how to get data from checklistbox in wxpython
I am trying to get either the strings checked or the integers from a check list. I cannot seem to get it anywhere. In the code below, you'll see a bunch of un-commented code, those are just different ways I've tried. I thought I would leave them in case any one's suggestions have to do with it. I am very new to GUI-programming and wx. Thanks for your help.
import wx
class Panel1(wx.Panel):
def __init__(self, parent, log):
wx.Panel.__init__(self, parent, -1)
allLoc = ['One', 'Two', 'Three', 'Four']
wx.StaticText(self, -1, "Choose:", (45, 15))
citList = wx.CheckListBox(self, -1, (60, 50), wx.DefaultSize, allLoc)
#self.Bind(wx.EVT_CHECKLISTBOX, self.GetChecks, citList)
#h = citList.GetChecked()
#cities = ()
#v = cities.append(h)
#print h
pos = citList.GetPosition().x + citList.GetSize().width + 25
nextBtn = wx.Button(self, -1, "Next", (pos, 50))
self.Bind(wx.EVT_BUTTON, wx.EvyRadBox2, nextBtn)
#def GetChecks(self, event):
#r = citList.GetId()
#print r
#def printChecks(self, event):
#l = event.CetCheckStrings()
#print l
def EvyRadBox2(self, event):
filepath2 = "c:\\logger2.txt"
file1 = open(filepath2, 'w')
file1.write('%d \n' % event.GetChecked())
file1.close()
app = wx.PySimpleApp()
frame = wx.Frame(None, -1, "Charlie")
Panel1(frame,-1)
frame.Show(1)
app.MainLoop()
**************************EDIT********************************
So I changed my code to look like this
import wx
checkedItems = []
class citPanel(wx.Panel):
def __init__(self, parent, id):
wx.Panel.__init__(self, parent, id)
allLoc = ['One', 'Two', 'Three', 'Four']
wx.StaticText(self, -1, "Choose:", (45, 15))
citList = wx.CheckListBox(self, -1, (60, 50), wx.DefaultSize, allLoc)
checkedItems = [i for i in range(citList.GetCount()) if citList.IsChecked(i)]
class nextButton(wx.Button):
def __init__(self, parent, id, label, pos):
wx.Button.__init__(self, parent, id, label, pos)
class checkList(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, size=(400, 400))
panel = citPanel(self, -1)
nextButton(panel, -1, 'Ok', (275, 50))
self.Bind(wx.EVT_BUTTON, self.Clicked)
self.Centre()
self.Show(True)
def Clicked(self, event):
print checkedItems
event.Skip()
app = wx.App()
checkList(None, -1, 'Charlie')
app.MainLoop()
When I did this at first, when I clicked the button, It threw a global name not defined into wxstdout. I add the checkedlist at the top, and it at first showed none, now it shows an empty list., Any help, as always, thanks in advance
A:
checkedItems = [i for i in range(citList.GetCount()) if citList.IsChecked(i)]
citList.GetChecked() should have also completed the task for you. May the problem be that you are trying to get selected items in __init__?
Upd.: You do not want to get checked items during __init__ - they cannot be checked by the user at that moment. You'd better check them in any event handler, e.g. wx.EVT_BUTTON.
Try writing self more often, e.g.:
self.citList = wx.CheckListBox(self, -1, (60, 50), wx.DefaultSize, allLoc)
# some code
self.panel = citPanel(self, -1)
and change Clicked to:
def Clicked(self, event):
checkedItems = [i for i in range(self.panel.citList.GetCount()) if self.panel.citList.IsChecked(i)]
print checkedItems
event.Skip()
Hope this helps.
|
Cannot understand how to get data from checklistbox in wxpython
|
I am trying to get either the strings checked or the integers from a check list. I cannot seem to get it anywhere. In the code below, you'll see a bunch of un-commented code, those are just different ways I've tried. I thought I would leave them in case any one's suggestions have to do with it. I am very new to GUI-programming and wx. Thanks for your help.
import wx
class Panel1(wx.Panel):
def __init__(self, parent, log):
wx.Panel.__init__(self, parent, -1)
allLoc = ['One', 'Two', 'Three', 'Four']
wx.StaticText(self, -1, "Choose:", (45, 15))
citList = wx.CheckListBox(self, -1, (60, 50), wx.DefaultSize, allLoc)
#self.Bind(wx.EVT_CHECKLISTBOX, self.GetChecks, citList)
#h = citList.GetChecked()
#cities = ()
#v = cities.append(h)
#print h
pos = citList.GetPosition().x + citList.GetSize().width + 25
nextBtn = wx.Button(self, -1, "Next", (pos, 50))
self.Bind(wx.EVT_BUTTON, wx.EvyRadBox2, nextBtn)
#def GetChecks(self, event):
#r = citList.GetId()
#print r
#def printChecks(self, event):
#l = event.CetCheckStrings()
#print l
def EvyRadBox2(self, event):
filepath2 = "c:\\logger2.txt"
file1 = open(filepath2, 'w')
file1.write('%d \n' % event.GetChecked())
file1.close()
app = wx.PySimpleApp()
frame = wx.Frame(None, -1, "Charlie")
Panel1(frame,-1)
frame.Show(1)
app.MainLoop()
**************************EDIT********************************
So I changed my code to look like this
import wx
checkedItems = []
class citPanel(wx.Panel):
def __init__(self, parent, id):
wx.Panel.__init__(self, parent, id)
allLoc = ['One', 'Two', 'Three', 'Four']
wx.StaticText(self, -1, "Choose:", (45, 15))
citList = wx.CheckListBox(self, -1, (60, 50), wx.DefaultSize, allLoc)
checkedItems = [i for i in range(citList.GetCount()) if citList.IsChecked(i)]
class nextButton(wx.Button):
def __init__(self, parent, id, label, pos):
wx.Button.__init__(self, parent, id, label, pos)
class checkList(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, size=(400, 400))
panel = citPanel(self, -1)
nextButton(panel, -1, 'Ok', (275, 50))
self.Bind(wx.EVT_BUTTON, self.Clicked)
self.Centre()
self.Show(True)
def Clicked(self, event):
print checkedItems
event.Skip()
app = wx.App()
checkList(None, -1, 'Charlie')
app.MainLoop()
When I did this at first, when I clicked the button, It threw a global name not defined into wxstdout. I add the checkedlist at the top, and it at first showed none, now it shows an empty list., Any help, as always, thanks in advance
|
[
"checkedItems = [i for i in range(citList.GetCount()) if citList.IsChecked(i)]\n\ncitList.GetChecked() should have also completed the task for you. May the problem be that you are trying to get selected items in __init__?\nUpd.: You do not want to get checked items during __init__ - they cannot be checked by the user at that moment. You'd better check them in any event handler, e.g. wx.EVT_BUTTON.\nTry writing self more often, e.g.:\nself.citList = wx.CheckListBox(self, -1, (60, 50), wx.DefaultSize, allLoc)\n# some code\nself.panel = citPanel(self, -1)\n\nand change Clicked to:\ndef Clicked(self, event):\n checkedItems = [i for i in range(self.panel.citList.GetCount()) if self.panel.citList.IsChecked(i)]\n print checkedItems\n event.Skip()\n\nHope this helps.\n"
] |
[
3
] |
[] |
[] |
[
"python",
"user_interface",
"wxpython"
] |
stackoverflow_0002001703_python_user_interface_wxpython.txt
|
Q:
python, and unicode stderr
I used an anonymous pipe to capture all stdout,and stderr then print into a richedit, it's ok when i use wsprintf ,but the python using multibyte char that really annoy me. how can I convert all these output to unicode?
UPDATE 2010-01-03:
Thank you for the reply, but it seems the str.encode() only worked with print xxx stuff, if there is an error during the py_runxxx(), my redirected stderr will capture the error message in multibyte string, so is there a way can make python output it's message in unicode way? And there seems to be an available solution in this post.
I'll try it later.
A:
First, please remember that on Windows console may not fully support Unicode.
The example below does make python output to stderr and stdout using UTF-8. If you want you could change it to other encodings.
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import codecs, sys
reload(sys)
sys.setdefaultencoding('utf-8')
print sys.getdefaultencoding()
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
sys.stderr = codecs.getwriter('utf8')(sys.stderr)
print "This is an Е乂αmp١ȅ testing Unicode support using Arabic, Latin, Cyrillic, Greek, Hebrew and CJK code points."
A:
You can work with Unicode in python either by marking strings as Unicode (ie: u'Hello World') or by using the encode() method that all strings have.
Eg. assuming you have a Unicode string, aStringVariable:
aStringVariable.encode('utf-8')
will convert it to UTF-8. 'utf-16' will give you UTF-16 and 'ascii' will convert it to a plain old ASCII string.
For more information, see:
Tutorial - Unicode Strings
Python String Methods
|
python, and unicode stderr
|
I used an anonymous pipe to capture all stdout,and stderr then print into a richedit, it's ok when i use wsprintf ,but the python using multibyte char that really annoy me. how can I convert all these output to unicode?
UPDATE 2010-01-03:
Thank you for the reply, but it seems the str.encode() only worked with print xxx stuff, if there is an error during the py_runxxx(), my redirected stderr will capture the error message in multibyte string, so is there a way can make python output it's message in unicode way? And there seems to be an available solution in this post.
I'll try it later.
|
[
"First, please remember that on Windows console may not fully support Unicode.\nThe example below does make python output to stderr and stdout using UTF-8. If you want you could change it to other encodings.\n#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\nimport codecs, sys\n\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\nprint sys.getdefaultencoding()\n\nsys.stdout = codecs.getwriter('utf8')(sys.stdout)\nsys.stderr = codecs.getwriter('utf8')(sys.stderr)\n\nprint \"This is an Е乂αmp١ȅ testing Unicode support using Arabic, Latin, Cyrillic, Greek, Hebrew and CJK code points.\"\n\n",
"You can work with Unicode in python either by marking strings as Unicode (ie: u'Hello World') or by using the encode() method that all strings have.\nEg. assuming you have a Unicode string, aStringVariable:\naStringVariable.encode('utf-8')\n\nwill convert it to UTF-8. 'utf-16' will give you UTF-16 and 'ascii' will convert it to a plain old ASCII string.\nFor more information, see:\n\nTutorial - Unicode Strings\nPython String Methods\n\n"
] |
[
9,
0
] |
[
"wsprintf?\nThis seems to be a \"C/C++\" question rather than a Python question.\nThe Python interpreter always writes bytestrings to stdout/stderr, rather than unicode (or \"wide\") strings. It means Python first encodes all unicode data using the current encoding (likely sys.getdefaultencoding()).\nIf you want to get at stdout/stderr as unicode data, you must decode it by yourself using the right encoding.\nYour favourite C/C++ library certainly has what it takes to do that.\n"
] |
[
-1
] |
[
"python",
"stderr",
"unicode"
] |
stackoverflow_0001994157_python_stderr_unicode.txt
|
Q:
python hebrew input\filesytem format
import os
import pprint
import subprocess
def Convert (dir):
curDir = dir
pathToBonk = "C:\\Program Files\\BonkEnc\\becmd.exe" #Where the becmd.exe file lives
problemFiles = [] #A list of files that failed conversion
#
for item in os.listdir(curDir):
if item.upper().endswith('.M4A'):
fullPath = os.path.join(curDir,item)
cmd = '"%s" -e LAME -d "%s" "%s"' #The command to convert a single file
cmd = cmd % (pathToBonk, curDir, fullPath)
val = subprocess.call(cmd)
if val == 0: #Successfull conversion, delete the original
os.remove(fullPath)
else:
problemFiles.append(fullPath)
print 'Problem converting %s' % item
os.rename(fullPath, fullPath + ".BAD")
print 'These files had problems converting and have been renamed with .BAD extensions:'
pprint.pprint(problemFiles)
var = raw_input("Insert Path: ")
var.decode("iso-8859-8")
Convert(var)
Hi There,
I want to reformat my music from .m4a into mp3 songs.
i use the bonkenc command line.
The problem is that some of my folders are in Hebrew.
When I use this script in folders which doesn't contain hebrew - It works flawlessly.
but when there's Hebrew in the path- the scrpit doesn't work.
I tried encoding\deconding the hebrew, but nothing helped.
I run windows xps p2.
Thanks in advance,
Liron.
A:
Just use os.listdir(unicode(str)) instead of os.listdir(str) in order to be sure that str is Unicode, otherwise it will just fail.
Same problem can be found on this question
|
python hebrew input\filesytem format
|
import os
import pprint
import subprocess
def Convert (dir):
curDir = dir
pathToBonk = "C:\\Program Files\\BonkEnc\\becmd.exe" #Where the becmd.exe file lives
problemFiles = [] #A list of files that failed conversion
#
for item in os.listdir(curDir):
if item.upper().endswith('.M4A'):
fullPath = os.path.join(curDir,item)
cmd = '"%s" -e LAME -d "%s" "%s"' #The command to convert a single file
cmd = cmd % (pathToBonk, curDir, fullPath)
val = subprocess.call(cmd)
if val == 0: #Successfull conversion, delete the original
os.remove(fullPath)
else:
problemFiles.append(fullPath)
print 'Problem converting %s' % item
os.rename(fullPath, fullPath + ".BAD")
print 'These files had problems converting and have been renamed with .BAD extensions:'
pprint.pprint(problemFiles)
var = raw_input("Insert Path: ")
var.decode("iso-8859-8")
Convert(var)
Hi There,
I want to reformat my music from .m4a into mp3 songs.
i use the bonkenc command line.
The problem is that some of my folders are in Hebrew.
When I use this script in folders which doesn't contain hebrew - It works flawlessly.
but when there's Hebrew in the path- the scrpit doesn't work.
I tried encoding\deconding the hebrew, but nothing helped.
I run windows xps p2.
Thanks in advance,
Liron.
|
[
"Just use os.listdir(unicode(str)) instead of os.listdir(str) in order to be sure that str is Unicode, otherwise it will just fail.\nSame problem can be found on this question\n"
] |
[
0
] |
[] |
[] |
[
"hebrew",
"python",
"unicode"
] |
stackoverflow_0001993402_hebrew_python_unicode.txt
|
Q:
Launch script on any network connection
On linux (ubuntu), is it possible to execute a script upon any incoming network connection?
During long periods inactivity on my home server, I plan on stopping the software raid, parking the data disks and restarting the raid array upon encountering an incoming network connection.
I've been researching this problem and haven't come across an appropriate solution yet, any help is appreciated.
Neil
Note: I'm aware it's unnessecary to stop/start the array and there are downsides (disk wear & tear...). However I'm set in my ways, please do not post advising me not to stop/start the disks.
Edit (1):
Thought I'd share my opinion and hopefully get some feedback on it.
I think I'd need to use xinetd binding a catcher script that catches incoming connection data on all ports, launches my launch script and passes the incoming connection data to the relevant service for that port. Only issue is I don't know what data I would need to catch or how to in python.
Edit (2):
I've hacked together a solution using the python library pypcap http://code.google.com/p/pypcap/ . For future reference, here is the code.
import pcap
...
pc = pcap.pcap(name)
pc.setfilter(' '.join(args))
pc.setnonblock()
try:
for ts, pkt in pc:
# subprocess.call([filename, args])
print 'readying disks...'
break
except OSError, ValueError:
print 'Error: invalid arguements passed to subprocess'
except KeyboardInterrupt:
print 'Error: keyboard interupt'
A:
Take a look at netfilter/iptables. You may be able to write code to use the userspace API libraries to detect incoming packet events.
|
Launch script on any network connection
|
On linux (ubuntu), is it possible to execute a script upon any incoming network connection?
During long periods inactivity on my home server, I plan on stopping the software raid, parking the data disks and restarting the raid array upon encountering an incoming network connection.
I've been researching this problem and haven't come across an appropriate solution yet, any help is appreciated.
Neil
Note: I'm aware it's unnessecary to stop/start the array and there are downsides (disk wear & tear...). However I'm set in my ways, please do not post advising me not to stop/start the disks.
Edit (1):
Thought I'd share my opinion and hopefully get some feedback on it.
I think I'd need to use xinetd binding a catcher script that catches incoming connection data on all ports, launches my launch script and passes the incoming connection data to the relevant service for that port. Only issue is I don't know what data I would need to catch or how to in python.
Edit (2):
I've hacked together a solution using the python library pypcap http://code.google.com/p/pypcap/ . For future reference, here is the code.
import pcap
...
pc = pcap.pcap(name)
pc.setfilter(' '.join(args))
pc.setnonblock()
try:
for ts, pkt in pc:
# subprocess.call([filename, args])
print 'readying disks...'
break
except OSError, ValueError:
print 'Error: invalid arguements passed to subprocess'
except KeyboardInterrupt:
print 'Error: keyboard interupt'
|
[
"Take a look at netfilter/iptables. You may be able to write code to use the userspace API libraries to detect incoming packet events.\n"
] |
[
1
] |
[] |
[] |
[
"linux",
"python",
"ubuntu"
] |
stackoverflow_0002001174_linux_python_ubuntu.txt
|
Q:
Python CGI transaction
I have a Python CGI handling a payment transaction. When the user submits the form, the CGI is called. After submission, the CGI takes a while to perform the credit card transaction. During that time, a user might hit the ESC or refresh button. Doing that will not "kill" the CGI, meaning, the script will keep running completing the transaction but the CGI's HTML output will never reach the client. This means the user will not know the transaction was completed. How can I solve this problem?
A:
Same as you should do with every POST: don't send output, but put the output in a session variable and redirect to a pure-GET request. This one looks in the session for messages, and clears+displays those.
|
Python CGI transaction
|
I have a Python CGI handling a payment transaction. When the user submits the form, the CGI is called. After submission, the CGI takes a while to perform the credit card transaction. During that time, a user might hit the ESC or refresh button. Doing that will not "kill" the CGI, meaning, the script will keep running completing the transaction but the CGI's HTML output will never reach the client. This means the user will not know the transaction was completed. How can I solve this problem?
|
[
"Same as you should do with every POST: don't send output, but put the output in a session variable and redirect to a pure-GET request. This one looks in the session for messages, and clears+displays those.\n"
] |
[
3
] |
[] |
[] |
[
"cgi",
"python"
] |
stackoverflow_0002002180_cgi_python.txt
|
Q:
Python: Separating the GUI process from the core logic process
I'm developing a Python project for dealing with computer simulations, and I'm also developing a GUI for it. (The core logic itself does not require a GUI.) The GUI toolkit I use for is wxPython, but I think my question is general enough not to depend on it.
The way that the GUI currently works is that it starts the core logic package (called garlicsim) on the same process and the same thread as the GUI. This works, but I understand it's a problematic approach, because if the core logic needs to do some hard computation, the GUI will hang, which I consider unacceptable.
What should I do?
I heard about the option of launching the core logic on a separate process from the GUI. This sounds interesting, but I have a lot of questions about this.
Do I use the multiprocessing package or the subprocess package to launch the new process?
How do I have easy access to the simulation data from the GUI process? After all, it will be stored on the other process. The user should be able to browse through the timeline of the simulation easily and smoothly. How can this be done?
A:
You might find some inspiration here: http://wiki.wxpython.org/LongRunningTasks, however it is for multithreading, not multiprocessing.
The basic idea
for multithreading: use an event queue to communicate between the GUI and the processing thread.
for multiprocessing: maybe use the subprocess package, and use stdin/stdout of the child process to communicate with it. For this you need a command-line api, but it would come handy eventually, because you can do gui-independent unit testing.
You may even drive the i/o communication through a socket, this would let easy network management of the simulation.
Edit: I just saw the 2.6-new multiprocessing package you mentioned. Seems a nice pick, you could use queues to communicate between process then. This is a tighter coupling, you can choose based on your needs.
A:
To answer the specific questions.
"Do I use the multiprocessing package or the subprocess package to launch the new process?"
Use multiprocessing
"How do I have easy access to the simulation data from the GUI process?"
You don't have access to the simulation processes objects, if that's what you're asking The simulation is a separate process. You can start it, stop it, and -- most importantly -- make requests via a queue of commands that go to the simulator.
"The user should be able to browse through the timeline of the simulation easily and smoothly. How can this be done?"
This is just design. Single process, multiple processes, multiple threads don't have any impact on this question at all.
Each simulation must have some parameters, it must start, it must produce a log (or timeline). That has to be done no matter what library you use to start and stop the simulation.
The output from the simulation -- which is input to your GUI -- can be done a million ways.
Database. The simulation timeline could be inserted into a SQLite database and queried by the GUI. This doesn't work out terribly well because SQLite doesn't have really clever locking. But it does work.
File. The simulation timeline is written to a file. The GUI reads the file. This works out really, really well.
Request/Reply. The simulation has multiple threads, one of which is dequeueing commands and responding by -- for example -- sending back the timeline up to the moment, or stopping the simulation or changing parameters and restarting it.
A:
The simplest approach that can work for you here is launch the computation in a separate thread, and communicate data between this thread and the GUI using Queue objects. These are completely safe and very convenient for inter-thread communication.
Other solutions are more complex - you may end up running the simulation in a completely separate "server" process and communicate with sockets with the main GUI.
A:
Unfortunately, although you're right that the choice of GUI doesn't affect the answer, the best approach to this problem will depend a lot on what exactly your simulation data is doing.
For example, if it generates sequential data then it can feed it to your GUI via a thread-safe or process-safe queue. But if it mutates the whole data and your GUI needs to be able to see a snapshot at any given time, that might be too expensive to solve by sending the whole state along the queue and might require a mutex-style approach instead to share access to the data structure. So the nature of the work done on your data is paramount here.
As for whether to use multiprocessing or subprocess, that depends on whether you have a completely separate program or not handling the data. The former is for doing multiprocessing in the style of multithreading - it is different parts of the same program running in multiple processes. The latter is when one program wants to run another (which could be a copy of the program, but usually is not). Again, it's hard to know which is the best approach for your specific situation, although it does sound like you could have the core logic as a command line application and communicate via pipes, sockets, etc.
A:
Mutiprocessing or Pyro with distributed data objects.
http://pyro.sourceforge.net/
Your simulation supplies distributed objects to the GUI, the GUI manipulates them and reads their attributes.
Both libraries will provide expandability over a network with no hassle, but can run locally. When your simulation starts crunching too many numbers, add more simulation servers that provide more distributed objects.
|
Python: Separating the GUI process from the core logic process
|
I'm developing a Python project for dealing with computer simulations, and I'm also developing a GUI for it. (The core logic itself does not require a GUI.) The GUI toolkit I use for is wxPython, but I think my question is general enough not to depend on it.
The way that the GUI currently works is that it starts the core logic package (called garlicsim) on the same process and the same thread as the GUI. This works, but I understand it's a problematic approach, because if the core logic needs to do some hard computation, the GUI will hang, which I consider unacceptable.
What should I do?
I heard about the option of launching the core logic on a separate process from the GUI. This sounds interesting, but I have a lot of questions about this.
Do I use the multiprocessing package or the subprocess package to launch the new process?
How do I have easy access to the simulation data from the GUI process? After all, it will be stored on the other process. The user should be able to browse through the timeline of the simulation easily and smoothly. How can this be done?
|
[
"You might find some inspiration here: http://wiki.wxpython.org/LongRunningTasks, however it is for multithreading, not multiprocessing.\nThe basic idea\n\nfor multithreading: use an event queue to communicate between the GUI and the processing thread.\nfor multiprocessing: maybe use the subprocess package, and use stdin/stdout of the child process to communicate with it. For this you need a command-line api, but it would come handy eventually, because you can do gui-independent unit testing.\n\nYou may even drive the i/o communication through a socket, this would let easy network management of the simulation.\nEdit: I just saw the 2.6-new multiprocessing package you mentioned. Seems a nice pick, you could use queues to communicate between process then. This is a tighter coupling, you can choose based on your needs.\n",
"To answer the specific questions.\n\"Do I use the multiprocessing package or the subprocess package to launch the new process?\"\nUse multiprocessing\n\"How do I have easy access to the simulation data from the GUI process?\"\nYou don't have access to the simulation processes objects, if that's what you're asking The simulation is a separate process. You can start it, stop it, and -- most importantly -- make requests via a queue of commands that go to the simulator.\n\"The user should be able to browse through the timeline of the simulation easily and smoothly. How can this be done?\"\nThis is just design. Single process, multiple processes, multiple threads don't have any impact on this question at all.\nEach simulation must have some parameters, it must start, it must produce a log (or timeline). That has to be done no matter what library you use to start and stop the simulation.\nThe output from the simulation -- which is input to your GUI -- can be done a million ways.\n\nDatabase. The simulation timeline could be inserted into a SQLite database and queried by the GUI. This doesn't work out terribly well because SQLite doesn't have really clever locking. But it does work.\nFile. The simulation timeline is written to a file. The GUI reads the file. This works out really, really well.\nRequest/Reply. The simulation has multiple threads, one of which is dequeueing commands and responding by -- for example -- sending back the timeline up to the moment, or stopping the simulation or changing parameters and restarting it.\n\n",
"The simplest approach that can work for you here is launch the computation in a separate thread, and communicate data between this thread and the GUI using Queue objects. These are completely safe and very convenient for inter-thread communication.\nOther solutions are more complex - you may end up running the simulation in a completely separate \"server\" process and communicate with sockets with the main GUI.\n",
"Unfortunately, although you're right that the choice of GUI doesn't affect the answer, the best approach to this problem will depend a lot on what exactly your simulation data is doing.\nFor example, if it generates sequential data then it can feed it to your GUI via a thread-safe or process-safe queue. But if it mutates the whole data and your GUI needs to be able to see a snapshot at any given time, that might be too expensive to solve by sending the whole state along the queue and might require a mutex-style approach instead to share access to the data structure. So the nature of the work done on your data is paramount here.\nAs for whether to use multiprocessing or subprocess, that depends on whether you have a completely separate program or not handling the data. The former is for doing multiprocessing in the style of multithreading - it is different parts of the same program running in multiple processes. The latter is when one program wants to run another (which could be a copy of the program, but usually is not). Again, it's hard to know which is the best approach for your specific situation, although it does sound like you could have the core logic as a command line application and communicate via pipes, sockets, etc.\n",
"Mutiprocessing or Pyro with distributed data objects.\nhttp://pyro.sourceforge.net/\nYour simulation supplies distributed objects to the GUI, the GUI manipulates them and reads their attributes.\nBoth libraries will provide expandability over a network with no hassle, but can run locally. When your simulation starts crunching too many numbers, add more simulation servers that provide more distributed objects.\n"
] |
[
6,
2,
2,
1,
0
] |
[] |
[] |
[
"multiprocessing",
"python",
"user_experience",
"user_interface"
] |
stackoverflow_0001961203_multiprocessing_python_user_experience_user_interface.txt
|
Q:
Why does it print funny characters? unicode problem?
The user entered the word
éclair
into the search box.
Showing results 1 - 10 of about 140 for �air.
Why does it show the weird question mark?
I'm using Django to display it:
Showing results 1 - 10 of about 140 for {{query|safe}}
A:
It's an encoding problem. Most likely your form or the output page is not UTF-8 encoded.
This article is very good reading on the issue: The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)
You need to check the encoding of
the HTML page where the user input the word
the HTML page you are using to output the word
the multi-byte ability of the functions you use to work with the string (though that probably isn't a problem in Python)
If the search is going to apply to a data base, you will need to check the encoding of the database connection, as well as the encoding of your tables and columns.
A:
This is the result when you interpret data that is not encoded in UTF-8 as UTF-8 encoded.
The interpreter expects from the code point of your first character of the word éclair a multibyte encoded character with a length of three characters, consumes the next two characters but can’t decode it (probably invalid byte sequence). For this case the REPLACEMENT CHARACTER � (U+FFFD) is shown.
So in your case you just need to really encode your data with UTF-8.
A:
You are serving the page with the wrong character encoding (charset). Check that you are using the same encoding throughout all your application (for example UTF-8). This includes:
HTTP headers from web server (Content-Type: text/html;charset=utf-8)
Communication with database (i.e SET NAMES 'utf-8')
A:
It would also be good to check your browser encoding setting.
A:
I second the responses above. Some other things from the top of my head:
If you're using e.g. MySQL database, then it could be good to create your database using:
CREATE DATABASE x CHARACTER SET UTF8
You can also check this: http://docs.djangoproject.com/en/dev/ref/settings/#default-charset
|
Why does it print funny characters? unicode problem?
|
The user entered the word
éclair
into the search box.
Showing results 1 - 10 of about 140 for �air.
Why does it show the weird question mark?
I'm using Django to display it:
Showing results 1 - 10 of about 140 for {{query|safe}}
|
[
"It's an encoding problem. Most likely your form or the output page is not UTF-8 encoded.\nThis article is very good reading on the issue: The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)\nYou need to check the encoding of\n\nthe HTML page where the user input the word\nthe HTML page you are using to output the word\nthe multi-byte ability of the functions you use to work with the string (though that probably isn't a problem in Python)\n\nIf the search is going to apply to a data base, you will need to check the encoding of the database connection, as well as the encoding of your tables and columns.\n",
"This is the result when you interpret data that is not encoded in UTF-8 as UTF-8 encoded.\nThe interpreter expects from the code point of your first character of the word éclair a multibyte encoded character with a length of three characters, consumes the next two characters but can’t decode it (probably invalid byte sequence). For this case the REPLACEMENT CHARACTER � (U+FFFD) is shown.\nSo in your case you just need to really encode your data with UTF-8.\n",
"You are serving the page with the wrong character encoding (charset). Check that you are using the same encoding throughout all your application (for example UTF-8). This includes:\n\nHTTP headers from web server (Content-Type: text/html;charset=utf-8)\nCommunication with database (i.e SET NAMES 'utf-8')\n\n",
"It would also be good to check your browser encoding setting.\n",
"I second the responses above. Some other things from the top of my head:\nIf you're using e.g. MySQL database, then it could be good to create your database using:\nCREATE DATABASE x CHARACTER SET UTF8\nYou can also check this: http://docs.djangoproject.com/en/dev/ref/settings/#default-charset\n"
] |
[
8,
1,
0,
0,
0
] |
[] |
[] |
[
"django",
"encoding",
"python",
"unicode"
] |
stackoverflow_0001998967_django_encoding_python_unicode.txt
|
Q:
PyQt4 - Widget Is Not Shown
I've made this program in Python and Qt4.
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtGui
from PyQt4 import QtCore
color = QtGui.QColor(99, 0, 0)
class colorButton(QtGui.QWidget):
def __init__(self, args):
QtGui.QWidget.__init__(self,args)
self.setGeometry(150, 22, 50, 50)
self.setStyleSheet("QWidget { background-color: %s }" % color.name())
class ColorDialog(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.setGeometry(40, 40, 220, 100)
self.setWindowTitle('ColorDialog')
button=colorButton(self)
app = QtGui.QApplication(sys.argv)
cd = ColorDialog()
cd.show()
app.exec_()
The intrpreter doesn't give me any error, but the "colored" widget isn't shown. Why?
thank
A:
Your class colorButton inherits from QWidget, yet you are calling QPushButton.__init__() in the constructor. Maybe you want it to inherit from QPushButton?
By using the following class definition, your code works for me:
class colorButton(QtGui.QPushButton):
def __init__(self, *args):
QtGui.QPushButton.__init__(self, *args)
self.setGeometry(150, 22, 50, 50)
self.setStyleSheet("QWidget { background-color: %s }" % color.name())
A:
You need to give the widget a paintEvent.
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtGui
from PyQt4 import QtCore
color = QtGui.QColor(99, 0, 0)
class colorButton(QtGui.QWidget):
def __init__(self, args):
QtGui.QWidget.__init__(self,args)
self.setGeometry(150, 22, 50, 50)
def paintEvent(self, event):
painter = QtGui.QPainter(self)
painter.fillRect(event.rect(), color)
class ColorDialog(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.setGeometry(40, 40, 220, 100)
self.setWindowTitle('ColorDialog')
button=colorButton(self)
app = QtGui.QApplication(sys.argv)
cd = ColorDialog()
cd.show()
app.exec_()
A:
Try setting autoFillBackground to True before you change the color (before setStylesheet call). AND I think you need to set the pallete. This comment assumes that you meant "the color of the widget is not shown". Please review the syntax as the one illustrated below is for Qt4.3 and I didn't check the latest one. After you set the pallet, there is no need to set the stylesheet.
class colorButton(QtGui.QWidget)
def __init__(self, args):
QtGui.QPushButton.__init__(self,args)
self.setGeometry(150, 22, 50, 50)
self.setAutoFillBackground(True)
plt = QtGui.QPalette()
plt.setColor(QtGui.QPalette.Active,QtGui.QPalette.Window,color)
plt.setColor(QtGui.QPalette.Inactive,QtGui.QPalette.Window,color)
plt.setColor(QtGui.QPalette.Disabled,QtGui.QPalette.Window,color
self.setPalette(plt)
#self.setStyleSheet("QWidget { background-color: %s }" % color.name())
A:
I think you need to give your ColorDialog a Layout using
self.setLayout(SOME_LAYOUT)
then add your button to the layout with something like
self.layout().addItem(button)
Otherwise I am not sure if simply giving your button the ColorDialog as parent is sufficient for display.
|
PyQt4 - Widget Is Not Shown
|
I've made this program in Python and Qt4.
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtGui
from PyQt4 import QtCore
color = QtGui.QColor(99, 0, 0)
class colorButton(QtGui.QWidget):
def __init__(self, args):
QtGui.QWidget.__init__(self,args)
self.setGeometry(150, 22, 50, 50)
self.setStyleSheet("QWidget { background-color: %s }" % color.name())
class ColorDialog(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.setGeometry(40, 40, 220, 100)
self.setWindowTitle('ColorDialog')
button=colorButton(self)
app = QtGui.QApplication(sys.argv)
cd = ColorDialog()
cd.show()
app.exec_()
The intrpreter doesn't give me any error, but the "colored" widget isn't shown. Why?
thank
|
[
"Your class colorButton inherits from QWidget, yet you are calling QPushButton.__init__() in the constructor. Maybe you want it to inherit from QPushButton?\nBy using the following class definition, your code works for me:\nclass colorButton(QtGui.QPushButton):\n def __init__(self, *args):\n QtGui.QPushButton.__init__(self, *args)\n self.setGeometry(150, 22, 50, 50)\n self.setStyleSheet(\"QWidget { background-color: %s }\" % color.name())\n\n",
"You need to give the widget a paintEvent.\n#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport sys\nfrom PyQt4 import QtGui\nfrom PyQt4 import QtCore\n\n\ncolor = QtGui.QColor(99, 0, 0)\n\nclass colorButton(QtGui.QWidget):\n def __init__(self, args):\n QtGui.QWidget.__init__(self,args)\n self.setGeometry(150, 22, 50, 50)\n\n def paintEvent(self, event):\n painter = QtGui.QPainter(self)\n painter.fillRect(event.rect(), color)\n\nclass ColorDialog(QtGui.QWidget):\n def __init__(self, parent=None):\n\n QtGui.QWidget.__init__(self, parent)\n\n self.setGeometry(40, 40, 220, 100)\n self.setWindowTitle('ColorDialog')\n\n button=colorButton(self)\n\n\napp = QtGui.QApplication(sys.argv)\ncd = ColorDialog()\ncd.show()\napp.exec_()\n\n",
"Try setting autoFillBackground to True before you change the color (before setStylesheet call). AND I think you need to set the pallete. This comment assumes that you meant \"the color of the widget is not shown\". Please review the syntax as the one illustrated below is for Qt4.3 and I didn't check the latest one. After you set the pallet, there is no need to set the stylesheet. \nclass colorButton(QtGui.QWidget)\n def __init__(self, args):\n QtGui.QPushButton.__init__(self,args)\n self.setGeometry(150, 22, 50, 50)\n\n\n self.setAutoFillBackground(True)\n plt = QtGui.QPalette() \n plt.setColor(QtGui.QPalette.Active,QtGui.QPalette.Window,color)\n plt.setColor(QtGui.QPalette.Inactive,QtGui.QPalette.Window,color) \n plt.setColor(QtGui.QPalette.Disabled,QtGui.QPalette.Window,color\n self.setPalette(plt) \n\n\n #self.setStyleSheet(\"QWidget { background-color: %s }\" % color.name())\n\n",
"I think you need to give your ColorDialog a Layout using \nself.setLayout(SOME_LAYOUT)\n\nthen add your button to the layout with something like \nself.layout().addItem(button)\n\nOtherwise I am not sure if simply giving your button the ColorDialog as parent is sufficient for display.\n"
] |
[
4,
2,
0,
0
] |
[] |
[] |
[
"pyqt",
"pyqt4",
"python",
"qwidget"
] |
stackoverflow_0002000466_pyqt_pyqt4_python_qwidget.txt
|
Q:
Creating an MS Office document-like file format to expose document properties
Our application's "documents" are single binary files.
Our customers have asked if we can add MS Office-like document properties to our document files so that they are easier for users to manage. By easier to manage, I mean the ability for Windows Explorer to display common document properties in tooltips.
My research seems to indicate we should consider OLE Structured Storage as the basis for our data files. I've seen this technique alternatively described as MS Structured Storage, OLE 2 Compound Document Formats, and Windows file metadata.
My concerns about using OLE Structured Storage is that it does not appear that Office 2007 or 2010 use this file format any more and OLE Structured Storage requires the registration of a DSOFILE.DLL ActiveX component that many of our customers will not be able to use because they run our software on locked down workstations where users do not have admin rights to install software. (Our application software is a pure XCOPY deployment).
Would appreciate hearing ideas on what our options are.
Thank you,
Malcolm
A:
I'm pretty sure your best answer is to use the OLE compound document.
Microsoft may have stopped using this, but that is because they have gone to an XML file format. Unless you are willing to convert from your current file format to XML, I do not think that the new standard for tags will be interesting for you.
You could possibly make your application save two files, the XML one just for tags and the binary data one, but that just means pain for your users. The whole point of the OLE compound document format was to allow multiple "files" bound together in one file.
Also, I would be very surprised if modern Windows did not have support for OLE compound documents built right in. I'm pretty sure that as far back as Microsoft Word 6.0, over a decade ago, documents were saved in this OLE compound document format. Why would Windows XP or newer require an extra .DLL file to be able to parse the tags out?
The best thing about using the OLE compound document format is that the user tags will go with the file, no matter what: if the user writes the file to a file server, if the user drops the file in an email, if the user burns the file to a CD, whatever. (The first answer I wrote, which I deleted, was bad; even if it had worked it would have put the user tags outside the file, and the more I think about it, the less happy I am at that thought.)
So, I suggest that you try creating an OLE compound document, and then just look at the file in Windows Explorer in a standard install of Windows XP. See if you can see the tags without needing to download and install an ActiveX .DLL. I'm pretty sure it will work. (But I don't really do Windows much anymore so I cannot conveniently test this for you.)
EDIT: Okay, I just did a test. I'm at work and I have a Windows computer here. I used Word 2007 to make a document, and I saved the document as Word 97 format. I looked at the document properties in Windows Explorer; the author name was visible in the tags. I added text to "comments" and then opened the file in Word 2007. I was then able to view the comments (click on the "office" icon circle in the upper left, choose "Prepare", choose "Properties").
So, my theory has some evidence to support it: I did not have to install any special software, my Windows Explorer just worked with the OLE compound document format Word file with the tags. (It could be that Microsoft Office installs some special .DLL to use the tags with Windows Explorer; I do have Microsoft Office 2007 installed on that computer. But your customers likely have Microsoft Office too, so even if that is the case, I still think this is the best solution.)
I suggest you Google search for "OLE compound document format" and see how to write this format. I found an example of how to read the tags here: http://support.microsoft.com/kb/186898
A:
On Windows 2000 or higher, instead of using OLE compound document, you can also store the summery information in the NTFS file metadata so applications such as Windows Explorer or Windows Desktop Search can use the attributes in property pages, tooltips, columns and searching.
|
Creating an MS Office document-like file format to expose document properties
|
Our application's "documents" are single binary files.
Our customers have asked if we can add MS Office-like document properties to our document files so that they are easier for users to manage. By easier to manage, I mean the ability for Windows Explorer to display common document properties in tooltips.
My research seems to indicate we should consider OLE Structured Storage as the basis for our data files. I've seen this technique alternatively described as MS Structured Storage, OLE 2 Compound Document Formats, and Windows file metadata.
My concerns about using OLE Structured Storage is that it does not appear that Office 2007 or 2010 use this file format any more and OLE Structured Storage requires the registration of a DSOFILE.DLL ActiveX component that many of our customers will not be able to use because they run our software on locked down workstations where users do not have admin rights to install software. (Our application software is a pure XCOPY deployment).
Would appreciate hearing ideas on what our options are.
Thank you,
Malcolm
|
[
"I'm pretty sure your best answer is to use the OLE compound document.\nMicrosoft may have stopped using this, but that is because they have gone to an XML file format. Unless you are willing to convert from your current file format to XML, I do not think that the new standard for tags will be interesting for you.\nYou could possibly make your application save two files, the XML one just for tags and the binary data one, but that just means pain for your users. The whole point of the OLE compound document format was to allow multiple \"files\" bound together in one file.\nAlso, I would be very surprised if modern Windows did not have support for OLE compound documents built right in. I'm pretty sure that as far back as Microsoft Word 6.0, over a decade ago, documents were saved in this OLE compound document format. Why would Windows XP or newer require an extra .DLL file to be able to parse the tags out?\nThe best thing about using the OLE compound document format is that the user tags will go with the file, no matter what: if the user writes the file to a file server, if the user drops the file in an email, if the user burns the file to a CD, whatever. (The first answer I wrote, which I deleted, was bad; even if it had worked it would have put the user tags outside the file, and the more I think about it, the less happy I am at that thought.)\nSo, I suggest that you try creating an OLE compound document, and then just look at the file in Windows Explorer in a standard install of Windows XP. See if you can see the tags without needing to download and install an ActiveX .DLL. I'm pretty sure it will work. (But I don't really do Windows much anymore so I cannot conveniently test this for you.)\nEDIT: Okay, I just did a test. I'm at work and I have a Windows computer here. I used Word 2007 to make a document, and I saved the document as Word 97 format. I looked at the document properties in Windows Explorer; the author name was visible in the tags. I added text to \"comments\" and then opened the file in Word 2007. I was then able to view the comments (click on the \"office\" icon circle in the upper left, choose \"Prepare\", choose \"Properties\").\nSo, my theory has some evidence to support it: I did not have to install any special software, my Windows Explorer just worked with the OLE compound document format Word file with the tags. (It could be that Microsoft Office installs some special .DLL to use the tags with Windows Explorer; I do have Microsoft Office 2007 installed on that computer. But your customers likely have Microsoft Office too, so even if that is the case, I still think this is the best solution.)\nI suggest you Google search for \"OLE compound document format\" and see how to write this format. I found an example of how to read the tags here: http://support.microsoft.com/kb/186898\n",
"On Windows 2000 or higher, instead of using OLE compound document, you can also store the summery information in the NTFS file metadata so applications such as Windows Explorer or Windows Desktop Search can use the attributes in property pages, tooltips, columns and searching.\n"
] |
[
3,
0
] |
[] |
[] |
[
"file",
"file_properties",
"python",
"winapi"
] |
stackoverflow_0001996162_file_file_properties_python_winapi.txt
|
Q:
how can i use '__set__'
class A(object):
def __get__(self, instance, owner):#why i can't find argument 'key',where is 'key'
#print ower.instance
print instance,owner
def __set__(self,instance,value):
instance=value
class X(object):
a = A()
xx=X()
xx.a='aaa'
print xx.a#None
A:
Hettinger's HowTo Guide for Descriptors covers this well. Quoting from it:
Descriptor Protocol
descr.__get__(self, obj, type=None) --> value
descr.__set__(self, obj, value) --> None
descr.__delete__(self, obj) --> None
That is all there is to it.
So, you can name the arguments however you wish, but there's typically no argument named key to __get__ (no idea why you're trying to find it).
Again an example from that URL:
class RevealAccess(object):
"""A data descriptor that sets and returns values
normally and prints a message logging their access.
"""
def __init__(self, initval=None, name='var'):
self.val = initval
self.name = name
def __get__(self, obj, objtype):
print 'Retrieving', self.name
return self.val
def __set__(self, obj, val):
print 'Updating' , self.name
self.val = val
So normally you set self.something in __init__ (and/or __set__ if you define it), and return something based on self.something in __get__. Of course this example just prints the "something" on getting and setting, normally you'd do something more substantial;-).
A:
Do you mean to be using __getattribute__? It has a parameter that is commonly called key; although it can be any name at all. And the definition that you have for __set__ looks like it should be for __setattribute__
A:
I think you could read about descriptors:
http://users.rcn.com/python/download/Descriptor.htm
Or maybe what you want is to customize attribute access:
http://docs.python.org/reference/datamodel.html#customizing-attribute-access
Maybe this pointers can help you, or maybe you can be more specific?
|
how can i use '__set__'
|
class A(object):
def __get__(self, instance, owner):#why i can't find argument 'key',where is 'key'
#print ower.instance
print instance,owner
def __set__(self,instance,value):
instance=value
class X(object):
a = A()
xx=X()
xx.a='aaa'
print xx.a#None
|
[
"Hettinger's HowTo Guide for Descriptors covers this well. Quoting from it:\n\nDescriptor Protocol\ndescr.__get__(self, obj, type=None) --> value\ndescr.__set__(self, obj, value) --> None\ndescr.__delete__(self, obj) --> None\nThat is all there is to it.\n\nSo, you can name the arguments however you wish, but there's typically no argument named key to __get__ (no idea why you're trying to find it).\nAgain an example from that URL:\nclass RevealAccess(object):\n \"\"\"A data descriptor that sets and returns values\n normally and prints a message logging their access.\n \"\"\"\ndef __init__(self, initval=None, name='var'):\n self.val = initval\n self.name = name\n\ndef __get__(self, obj, objtype):\n print 'Retrieving', self.name\n return self.val\n\ndef __set__(self, obj, val):\n print 'Updating' , self.name\n self.val = val\n\nSo normally you set self.something in __init__ (and/or __set__ if you define it), and return something based on self.something in __get__. Of course this example just prints the \"something\" on getting and setting, normally you'd do something more substantial;-).\n",
"Do you mean to be using __getattribute__? It has a parameter that is commonly called key; although it can be any name at all. And the definition that you have for __set__ looks like it should be for __setattribute__\n",
"I think you could read about descriptors:\nhttp://users.rcn.com/python/download/Descriptor.htm\nOr maybe what you want is to customize attribute access:\nhttp://docs.python.org/reference/datamodel.html#customizing-attribute-access\nMaybe this pointers can help you, or maybe you can be more specific?\n"
] |
[
4,
2,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002003284_python.txt
|
Q:
Alternative to PyGObject?
Does anyone have an alternative to using PyGObject? I can't seem to get it to run at all in Mac OS X. I'm trying to use papyon, which fails amazingly well if GObject isn't around.
A:
By its description, it is used for async I/O only. You can try to rework the library to use any of the other Python async libraries, like asyncore, Twisted, or any other.
Also, getting PyGObject on Mac OS X is hard, but you can try to use the one from macports, macports being the new name for darwinports
A:
You can instally PyGobject on Mac OS X with Darwinports, instructions here .
|
Alternative to PyGObject?
|
Does anyone have an alternative to using PyGObject? I can't seem to get it to run at all in Mac OS X. I'm trying to use papyon, which fails amazingly well if GObject isn't around.
|
[
"By its description, it is used for async I/O only. You can try to rework the library to use any of the other Python async libraries, like asyncore, Twisted, or any other.\nAlso, getting PyGObject on Mac OS X is hard, but you can try to use the one from macports, macports being the new name for darwinports\n",
"You can instally PyGobject on Mac OS X with Darwinports, instructions here .\n"
] |
[
3,
0
] |
[] |
[] |
[
"gobject",
"pygobject",
"python"
] |
stackoverflow_0002002119_gobject_pygobject_python.txt
|
Q:
Javascript lexer / tokenizer (in Python?)
Does anyone know of a Javascript lexical analyzer or tokenizer (preferably in Python?)
Basically, given an arbitrary Javascript file, I want to grab the tokens.
e.g.
foo = 1
becomes something like:
variable name : "foo"
whitespace
operator : equals
whitespace
integer : 1
A:
http://code.google.com/p/pynarcissus/ has one.
Also I made one but it doesn't support automatic semicolon insertion so it is pretty useless for javascript that you have no control over (as almost all real life javascript programs lack at least one semicolon) :) Here is mine:
http://bitbucket.org/santagada/jaspyon/src/tip/jaspyon/
the grammar is in jsgrammar.txt, it is parsed by the PyPy parsing lib (which you will have to download and extract from the pypy source) and it build a parse tree which I walk on astbuilder.py
But if you don't have licensing problems I would go with pynarcissus. heres a direct link to look at the code (ported from narcissus):
http://code.google.com/p/pynarcissus/source/browse/trunk/jsparser.py
|
Javascript lexer / tokenizer (in Python?)
|
Does anyone know of a Javascript lexical analyzer or tokenizer (preferably in Python?)
Basically, given an arbitrary Javascript file, I want to grab the tokens.
e.g.
foo = 1
becomes something like:
variable name : "foo"
whitespace
operator : equals
whitespace
integer : 1
|
[
"http://code.google.com/p/pynarcissus/ has one.\nAlso I made one but it doesn't support automatic semicolon insertion so it is pretty useless for javascript that you have no control over (as almost all real life javascript programs lack at least one semicolon) :) Here is mine:\nhttp://bitbucket.org/santagada/jaspyon/src/tip/jaspyon/\nthe grammar is in jsgrammar.txt, it is parsed by the PyPy parsing lib (which you will have to download and extract from the pypy source) and it build a parse tree which I walk on astbuilder.py\nBut if you don't have licensing problems I would go with pynarcissus. heres a direct link to look at the code (ported from narcissus):\nhttp://code.google.com/p/pynarcissus/source/browse/trunk/jsparser.py\n"
] |
[
2
] |
[] |
[] |
[
"javascript",
"lex",
"python",
"tokenize",
"yacc"
] |
stackoverflow_0002001796_javascript_lex_python_tokenize_yacc.txt
|
Q:
Should I use Lex or a home-brewed solution to parse a formula?
I'm in the process of writing a small, rule-based 'math' engine. I realize this is unclear, so I'll provide a small example.
Let's say you have some variable a, that holds an integer. You also have some functions you can apply to the number, i.e.
sqr - square the number
flp - flip the bits of the number
dec - decrement the number
inc - increment the number
You can then say, do_formula(a, "2sqr+inc+flp"). If a were 3, it'd square it twice (81), increment it (82), and flip the bits of it (~82 -- which is -83, if dealing with signed integers, I believe).
What would be the best way of parsing the formula? It's relatively simple, and I'm thinking of making all the opcodes be 3 characters... would it be overkill to use Lex? Should I just write a simple home-brewed solution or use something else entirely?
I realize the above example is silly; I'm not building a calculator that'll do that, but it illustrates what I'm trying to do well enough.
A:
If your grammar isn't super-complex and you don't mind doing it in Python, pyparsing could be just what the doctor ordered. I implemented something fairly similar for parsing chemical equations and it took me an hour or so to do it. I'd add the code here, but it wouldn't be particularly relevant.
A:
Yes, seems like an overkill in this case. Just split the string on '=", and then apply the operations one after another. Thank god for dictionaries and functions as first-class citizen your engine can be written in 0.5 - 1 pages of code.
dct = {'sqr' : lambda a: a * a, ...}
ntimes, op = token[:-3], token[-3:]
ntimes = 0 if len(ntimes) == 0 else int(ntimes)
..
dct[op](a)
A:
It really depends on how big your project is going to end up being: If you're looking at creating a new language or something that's parsing more interesting grammars than just + then I'd say lex would be a fun and entertaining way to spend an afternoon.
On the other hand, writing your own parser is extremely informative and not particularly hard if you've really thought out the grammar beforehand.
The question really ends up being which language to do the parsing in? Haskell would be a really fun choice and provided a lot of interesting revelations for me when I wrote my first parser a couple years ago.
A:
What's your host language? For Ruby, I really like treetop. It's a bit hard to get started, but I've used it with success for parsing more complicated math expressions.
|
Should I use Lex or a home-brewed solution to parse a formula?
|
I'm in the process of writing a small, rule-based 'math' engine. I realize this is unclear, so I'll provide a small example.
Let's say you have some variable a, that holds an integer. You also have some functions you can apply to the number, i.e.
sqr - square the number
flp - flip the bits of the number
dec - decrement the number
inc - increment the number
You can then say, do_formula(a, "2sqr+inc+flp"). If a were 3, it'd square it twice (81), increment it (82), and flip the bits of it (~82 -- which is -83, if dealing with signed integers, I believe).
What would be the best way of parsing the formula? It's relatively simple, and I'm thinking of making all the opcodes be 3 characters... would it be overkill to use Lex? Should I just write a simple home-brewed solution or use something else entirely?
I realize the above example is silly; I'm not building a calculator that'll do that, but it illustrates what I'm trying to do well enough.
|
[
"If your grammar isn't super-complex and you don't mind doing it in Python, pyparsing could be just what the doctor ordered. I implemented something fairly similar for parsing chemical equations and it took me an hour or so to do it. I'd add the code here, but it wouldn't be particularly relevant. \n",
"Yes, seems like an overkill in this case. Just split the string on '=\", and then apply the operations one after another. Thank god for dictionaries and functions as first-class citizen your engine can be written in 0.5 - 1 pages of code.\ndct = {'sqr' : lambda a: a * a, ...}\n\nntimes, op = token[:-3], token[-3:]\nntimes = 0 if len(ntimes) == 0 else int(ntimes)\n\n..\ndct[op](a)\n\n",
"It really depends on how big your project is going to end up being: If you're looking at creating a new language or something that's parsing more interesting grammars than just + then I'd say lex would be a fun and entertaining way to spend an afternoon. \nOn the other hand, writing your own parser is extremely informative and not particularly hard if you've really thought out the grammar beforehand.\nThe question really ends up being which language to do the parsing in? Haskell would be a really fun choice and provided a lot of interesting revelations for me when I wrote my first parser a couple years ago. \n",
"What's your host language? For Ruby, I really like treetop. It's a bit hard to get started, but I've used it with success for parsing more complicated math expressions.\n"
] |
[
3,
1,
0,
0
] |
[
"If you have some free time and want to learn a new programming paradigm, give Prolog a spin!\n"
] |
[
-1
] |
[
"lex",
"ply",
"python"
] |
stackoverflow_0002001504_lex_ply_python.txt
|
Q:
How to force Python to ignore re.DOTALL in re.findall() statement?
I have been banging my head against the keyboard in search of enlightenment through Google and all Python docs I could get my hands on, but could not find an answer to an issue I'm encountering.
I have the following regex that I run against a website, but Python insists in setting re.DOTALL on it, even though my code does not tell it to:
\d+. +(?P<season>\d+) *\- *(?P<episode>\d+).*?(?P<day>\d+)(?:\/|\s)+(?P<month>[A-Za-z]+)(?:\/|\s)+(?P<year>\d+) +(?:<a .+><img .+></a>)? ?<a .*?>(?P<name>.*?)</a>
This creates an array of seasons/episodes for TV show listings, and it works fine except on epguides.com/BurnNotice (when using the TVRage listings), due to some spacing before newlines (I guess).
Using http://re-try.appspot.com to test, I've narrowed down the issue to the use of re.DOTALL. If I enable it on re-try, it replicates the results I get when I run it standalone on my script. If I untick DOTALL, then it gives me the results I expect.
How can I force Python NOT to use re.DOTALL?
The script runs both on Ubuntu and OS X.
A:
.+> should change to [^>]+> and
.*?> to [^>]*>
You can try replacing others dots into [^\r\n] too, but above 2 changes should be enough.
|
How to force Python to ignore re.DOTALL in re.findall() statement?
|
I have been banging my head against the keyboard in search of enlightenment through Google and all Python docs I could get my hands on, but could not find an answer to an issue I'm encountering.
I have the following regex that I run against a website, but Python insists in setting re.DOTALL on it, even though my code does not tell it to:
\d+. +(?P<season>\d+) *\- *(?P<episode>\d+).*?(?P<day>\d+)(?:\/|\s)+(?P<month>[A-Za-z]+)(?:\/|\s)+(?P<year>\d+) +(?:<a .+><img .+></a>)? ?<a .*?>(?P<name>.*?)</a>
This creates an array of seasons/episodes for TV show listings, and it works fine except on epguides.com/BurnNotice (when using the TVRage listings), due to some spacing before newlines (I guess).
Using http://re-try.appspot.com to test, I've narrowed down the issue to the use of re.DOTALL. If I enable it on re-try, it replicates the results I get when I run it standalone on my script. If I untick DOTALL, then it gives me the results I expect.
How can I force Python NOT to use re.DOTALL?
The script runs both on Ubuntu and OS X.
|
[
".+> should change to [^>]+> and\n.*?> to [^>]*>\nYou can try replacing others dots into [^\\r\\n] too, but above 2 changes should be enough.\n"
] |
[
2
] |
[] |
[] |
[
"flags",
"python",
"regex"
] |
stackoverflow_0002003461_flags_python_regex.txt
|
Q:
Convert a curl POST request to Python only using standard library
I would like to convert this curl command to something that I can use in Python for an existing script.
curl -u 7898678:X -H 'Content-Type: application/json' \
-d '{"message":{"body":"TEXT"}}' http://sample.com/36576/speak.json
TEXT is what i would like to replace with a message generated by the rest of the script.(Which is already working reasonable, although I don't think it is following best practices or particularity reliable. - need to find out how to properly learn to program (ie not use google for assembling stuff))
I would like this to work with the standard library if possible.
A:
I would like this to work with the standard library if possible.
The standard library provides urllib and httplib for working with URLs:
>>> import httplib, urllib
>>> params = urllib.urlencode({'apple': 1, 'banana': 2, 'coconut': 'yummy'})
>>> headers = {"Content-type": "application/x-www-form-urlencoded",
... "Accept": "text/plain"}
>>> conn = httplib.HTTPConnection("example.com:80")
>>> conn.request("POST", "/some/path/to/site", params, headers)
>>> response = conn.getresponse()
>>> print response.status, response.reason
200 OK
If you want to execute curl itself, though, you can just invoke os.system():
import os
TEXT = ...
cmd = """curl -u 7898678:X -H 'Content-Type: application/json'""" \
"""-d '{"message":{"body":"%{t}"}}' http://sample.com/36576/speak.json""" % \
{'t': TEXT}
If you're willing to relax the standard-library-only restriction, you can use PycURL. Beware that it isn't very Pythonic (it's pretty much just a thin veneer over libcurl), and I'm not sure how compatible it is with Python 3.
A:
While there are ways to handle authentication in urllib2, if you're doing Basic Authorization (which means effectively sending the username and password in clear text) then you can do all of what you want with a urllib2.Request and urllib2.urlopen:
import urllib2
def basic_authorization(user, password):
s = user + ":" + password
return "Basic " + s.encode("base64").rstrip()
req = urllib2.Request("http://localhost:8000/36576/speak.json",
headers = {
"Authorization": basic_authorization("7898678", "X"),
"Content-Type": "application/json",
# Some extra headers for fun
"Accept": "*/*", # curl does this
"User-Agent": "my-python-app/1", # otherwise it uses "Python-urllib/..."
},
data = '{"message":{"body":"TEXT"}}')
f = urllib2.urlopen(req)
I tested this with netcat so I could see that the data sent was, excepting sort order, identical in both cases. Here the first one was done with curl and the second with urllib2
% nc -l 8000
POST /36576/speak.json HTTP/1.1
Authorization: Basic Nzg5ODY3ODpY
User-Agent: curl/7.19.4 (universal-apple-darwin10.0) libcurl/7.19.4 OpenSSL/0.9.8k zlib/1.2.3
Host: localhost:8000
Accept: */*
Content-Type: application/json
Content-Length: 27
{"message":{"body":"TEXT"}} ^C
% nc -l 8000
POST /36576/speak.json HTTP/1.1
Accept-Encoding: identity
Content-Length: 27
Connection: close
Accept: */*
User-Agent: my-python-app/1
Host: localhost:8000
Content-Type: application/json
Authorization: Nzg5ODY3ODpY
{"message":{"body":"TEXT"}}^C
(This is slightly tweaked from the output. My test case didn't use the same url path you used.)
There's no need to use the underlying httplib, which doesn't support things that urllib2 gives you like proxy support. On the other hand, I do find urllib2 to be complicated outside of this simple sort of request and if you want better support for which headers are sent and the order they are sent then use httplib.
A:
Thanks every
this works
import urllib2
def speak(status):
def basic_authorization(user, password):
s = user + ":" + password
return "Basic " + s.encode("base64").rstrip()
req = urllib2.Request("http://example.com/60/speak.json",
headers = {
"Authorization": basic_authorization("2345670", "X"),
"Content-Type": "application/json",
"Accept": "*/*",
"User-Agent": "my-python-app/1",
},
data = '{"message":{"body":'+ status +'}}')
f = urllib2.urlopen(req)
speak('Yay')
A:
Take a look at pycurl http://pycurl.sourceforge.net/
|
Convert a curl POST request to Python only using standard library
|
I would like to convert this curl command to something that I can use in Python for an existing script.
curl -u 7898678:X -H 'Content-Type: application/json' \
-d '{"message":{"body":"TEXT"}}' http://sample.com/36576/speak.json
TEXT is what i would like to replace with a message generated by the rest of the script.(Which is already working reasonable, although I don't think it is following best practices or particularity reliable. - need to find out how to properly learn to program (ie not use google for assembling stuff))
I would like this to work with the standard library if possible.
|
[
"\nI would like this to work with the standard library if possible.\n\nThe standard library provides urllib and httplib for working with URLs:\n>>> import httplib, urllib\n>>> params = urllib.urlencode({'apple': 1, 'banana': 2, 'coconut': 'yummy'})\n>>> headers = {\"Content-type\": \"application/x-www-form-urlencoded\",\n... \"Accept\": \"text/plain\"}\n>>> conn = httplib.HTTPConnection(\"example.com:80\")\n>>> conn.request(\"POST\", \"/some/path/to/site\", params, headers)\n>>> response = conn.getresponse()\n>>> print response.status, response.reason\n200 OK\n\nIf you want to execute curl itself, though, you can just invoke os.system():\nimport os\nTEXT = ...\ncmd = \"\"\"curl -u 7898678:X -H 'Content-Type: application/json'\"\"\" \\\n \"\"\"-d '{\"message\":{\"body\":\"%{t}\"}}' http://sample.com/36576/speak.json\"\"\" % \\\n {'t': TEXT}\n\nIf you're willing to relax the standard-library-only restriction, you can use PycURL. Beware that it isn't very Pythonic (it's pretty much just a thin veneer over libcurl), and I'm not sure how compatible it is with Python 3.\n",
"While there are ways to handle authentication in urllib2, if you're doing Basic Authorization (which means effectively sending the username and password in clear text) then you can do all of what you want with a urllib2.Request and urllib2.urlopen:\nimport urllib2\n\ndef basic_authorization(user, password):\n s = user + \":\" + password\n return \"Basic \" + s.encode(\"base64\").rstrip()\n\nreq = urllib2.Request(\"http://localhost:8000/36576/speak.json\",\n headers = {\n \"Authorization\": basic_authorization(\"7898678\", \"X\"),\n \"Content-Type\": \"application/json\",\n\n # Some extra headers for fun\n \"Accept\": \"*/*\", # curl does this\n \"User-Agent\": \"my-python-app/1\", # otherwise it uses \"Python-urllib/...\"\n },\n data = '{\"message\":{\"body\":\"TEXT\"}}')\n\nf = urllib2.urlopen(req)\n\nI tested this with netcat so I could see that the data sent was, excepting sort order, identical in both cases. Here the first one was done with curl and the second with urllib2\n% nc -l 8000\nPOST /36576/speak.json HTTP/1.1\nAuthorization: Basic Nzg5ODY3ODpY\nUser-Agent: curl/7.19.4 (universal-apple-darwin10.0) libcurl/7.19.4 OpenSSL/0.9.8k zlib/1.2.3\nHost: localhost:8000\nAccept: */*\nContent-Type: application/json\nContent-Length: 27\n\n{\"message\":{\"body\":\"TEXT\"}} ^C\n\n% nc -l 8000\nPOST /36576/speak.json HTTP/1.1\nAccept-Encoding: identity\nContent-Length: 27\nConnection: close\nAccept: */*\nUser-Agent: my-python-app/1\nHost: localhost:8000\nContent-Type: application/json\nAuthorization: Nzg5ODY3ODpY\n\n{\"message\":{\"body\":\"TEXT\"}}^C\n\n(This is slightly tweaked from the output. My test case didn't use the same url path you used.)\nThere's no need to use the underlying httplib, which doesn't support things that urllib2 gives you like proxy support. On the other hand, I do find urllib2 to be complicated outside of this simple sort of request and if you want better support for which headers are sent and the order they are sent then use httplib.\n",
"Thanks every\nthis works\nimport urllib2\n\ndef speak(status):\n\n def basic_authorization(user, password):\n s = user + \":\" + password\n return \"Basic \" + s.encode(\"base64\").rstrip()\n\n req = urllib2.Request(\"http://example.com/60/speak.json\",\n headers = {\n \"Authorization\": basic_authorization(\"2345670\", \"X\"),\n \"Content-Type\": \"application/json\",\n\n\n \"Accept\": \"*/*\", \n \"User-Agent\": \"my-python-app/1\", \n },\n data = '{\"message\":{\"body\":'+ status +'}}')\n\n f = urllib2.urlopen(req)\n\n\nspeak('Yay')\n\n",
"Take a look at pycurl http://pycurl.sourceforge.net/\n"
] |
[
24,
12,
2,
1
] |
[] |
[] |
[
"curl",
"json",
"python"
] |
stackoverflow_0001990976_curl_json_python.txt
|
Q:
ImageFont's getsize() does not get correct text size?
I use the following two methods to to generate text preview image for a .ttf font file
PIL method:
def make_preview(text, fontfile, imagefile, fontsize=30):
try:
font = ImageFont.truetype(fontfile, fontsize)
text_width, text_height = font.getsize(text)
img = Image.new('RGBA', (text_width, text_height))
draw = ImageDraw.Draw(img)
draw.text((0, 0), text, font=font, fill=(0, 0, 0))
return True
except:
return False
ImageMagick method:
def make_preview(text, fontfile, imagefile, fontsize=30):
p = subprocess.Popen(['convert', '-font', fontfile, '-background',
'transparent', '-gravity', 'center', '-pointsize', str(fontsize),
'-trim', '+repage', 'label:%s' % text, image_file])
return p==0
Both methods create correct preview images most of time but in some rare cases (<2%), the font.getsize(text) just cannot get the correct text size which result in text overflowed provided canvas. ImageMagick has same problem.
Sample fonts and previews:
HANFORD.TTF
http://download.appfile.com/HANFORD.png
NEWTOW.TTF
http://download.appfile.com/NEWTOW.png
MILF.TTF
http://download.appfile.com/MILF.png
SWANSE.TTF
http://download.appfile.com/SWANSE.png
I have looked into ImageMagick's documentations and found the explanation of this problem at http://www.imagemagick.org/Usage/text/#overflow.
Is it possible to detect such text overflows and draw text to fit the canvas as we expected?
A:
Not a programming solution, but when I regenerate your problem, its only happens on your fonts (other fonts like Arial is no problem at all), so I have fixed your font files (by changing ascent/decent metrics). you can download here,
And sorry about Hanford Script Font, its not perfect as you see, height seems ok, but left side is not get drawed, its out of my understanding.
UPDATE: Regarding Hanford Font, Here is a work around, pass extra space in text like " Handford Script", and then crop the extra space in image like img=img.crop(img.getbbox())
alt text http://img64.imageshack.us/img64/1903/hanfordfontworkaround.jpg
UPDATE2:I had to pass color=(255,255,255) in Image.New to get Black Text on White background
img = Image.new('RGBA', (text_width, text_height),color=(255,255,255))
A:
I had a similar issue once in PHP and ImageMagick.
In the end, I solved this by drawing the text on a very large canvas, and then trimming it using the trim/auto-crop functions that shave extra space off the image.
If I understand your preview function right, it is actually already doing exactly that: It should be enough to just remove the width and height settings.
A:
In this case, just specify ImageMagick to use a larger canvas size with a fixed font size and it will draw text at specified point size while keeping its integrity.
def make_preview(text, fontfile, imagefile, fontsize=30):
p = subprocess.call(['convert', '-font', fontfile, '-background',
'transparent', '-gravity', 'center', '-size', '1500x300',
'-pointsize', str(fontsize), '-trim', '+repage', 'label:%s' % text, image_file])
return p==0
If you need to fit text into specified canvas rather than using a fixed point size, you may need to resize the output image after it's created.
PIL doesn't do this very well drawing exotic fonts, no matter what point size you specify to load a font, it always overflows text outside output image.
|
ImageFont's getsize() does not get correct text size?
|
I use the following two methods to to generate text preview image for a .ttf font file
PIL method:
def make_preview(text, fontfile, imagefile, fontsize=30):
try:
font = ImageFont.truetype(fontfile, fontsize)
text_width, text_height = font.getsize(text)
img = Image.new('RGBA', (text_width, text_height))
draw = ImageDraw.Draw(img)
draw.text((0, 0), text, font=font, fill=(0, 0, 0))
return True
except:
return False
ImageMagick method:
def make_preview(text, fontfile, imagefile, fontsize=30):
p = subprocess.Popen(['convert', '-font', fontfile, '-background',
'transparent', '-gravity', 'center', '-pointsize', str(fontsize),
'-trim', '+repage', 'label:%s' % text, image_file])
return p==0
Both methods create correct preview images most of time but in some rare cases (<2%), the font.getsize(text) just cannot get the correct text size which result in text overflowed provided canvas. ImageMagick has same problem.
Sample fonts and previews:
HANFORD.TTF
http://download.appfile.com/HANFORD.png
NEWTOW.TTF
http://download.appfile.com/NEWTOW.png
MILF.TTF
http://download.appfile.com/MILF.png
SWANSE.TTF
http://download.appfile.com/SWANSE.png
I have looked into ImageMagick's documentations and found the explanation of this problem at http://www.imagemagick.org/Usage/text/#overflow.
Is it possible to detect such text overflows and draw text to fit the canvas as we expected?
|
[
"\n\nNot a programming solution, but when I regenerate your problem, its only happens on your fonts (other fonts like Arial is no problem at all), so I have fixed your font files (by changing ascent/decent metrics). you can download here, \nAnd sorry about Hanford Script Font, its not perfect as you see, height seems ok, but left side is not get drawed, its out of my understanding.\nUPDATE: Regarding Hanford Font, Here is a work around, pass extra space in text like \" Handford Script\", and then crop the extra space in image like img=img.crop(img.getbbox())\nalt text http://img64.imageshack.us/img64/1903/hanfordfontworkaround.jpg\nUPDATE2:I had to pass color=(255,255,255) in Image.New to get Black Text on White background\nimg = Image.new('RGBA', (text_width, text_height),color=(255,255,255))\n\n\n\n",
"I had a similar issue once in PHP and ImageMagick. \nIn the end, I solved this by drawing the text on a very large canvas, and then trimming it using the trim/auto-crop functions that shave extra space off the image. \nIf I understand your preview function right, it is actually already doing exactly that: It should be enough to just remove the width and height settings. \n",
"In this case, just specify ImageMagick to use a larger canvas size with a fixed font size and it will draw text at specified point size while keeping its integrity.\ndef make_preview(text, fontfile, imagefile, fontsize=30):\n p = subprocess.call(['convert', '-font', fontfile, '-background', \n 'transparent', '-gravity', 'center', '-size', '1500x300',\n '-pointsize', str(fontsize), '-trim', '+repage', 'label:%s' % text, image_file]) \n return p==0 \n\nIf you need to fit text into specified canvas rather than using a fixed point size, you may need to resize the output image after it's created. \nPIL doesn't do this very well drawing exotic fonts, no matter what point size you specify to load a font, it always overflows text outside output image.\n"
] |
[
5,
2,
1
] |
[] |
[] |
[
"fonts",
"imagemagick",
"python",
"python_imaging_library"
] |
stackoverflow_0001965466_fonts_imagemagick_python_python_imaging_library.txt
|
Q:
where is the '__path__' comes from
i can't find who defined the '__path__',why '__path__' can be use.
import os
import sys
import warnings
import ConfigParser # ConfigParser is not a virtualenv module, so we can use it to find the stdlib
dirname = os.path.dirname
distutils_path = os.path.join(os.path.dirname(ConfigParser.__file__), 'distutils')
if os.path.normpath(distutils_path) == os.path.dirname(os.path.normpath(__file__)):
warnings.warn(
"The virtualenv distutils package at %s appears to be in the same location as the system distutils?")
else:
__path__.insert(0, distutils_path)#who defined me.???
exec open(os.path.join(distutils_path, '__init__.py')).read()
A:
You really need to read some Python documentation and learn the basics of the language.
I checked, and you seem to speak Chinese. Here are Python documentation resources in Chinese:
http://www6.uniovi.es/python/doc/NonEnglish.html#chinese
Now, to answer your question. I wasn't sure what the answer was, so I used Google. I did a Google search for "Python __path__" and very quickly found:
http://docs.python.org/tutorial/modules.html
6.4.3. Packages in Multiple Directories
Packages support one more special
attribute, __path__. This is
initialized to be a list containing
the name of the directory holding the
package’s __init__.py before the code
in that file is executed. This
variable can be modified; doing so
affects future searches for modules
and subpackages contained in the
package.
While this feature is not often
needed, it can be used to extend the
set of modules found in a package.
A:
I found the following description of the __path__ variable:
It is initialized to a list of one
item, containing the directory name of
the package (a subdirectory of a
directory on sys.path). Changing
__path__ changes the list of directories that are searched for
submodules of the package.
here: http://www.python.org/doc/essays/packages.html
That page discusses 'built-in package support' in Python 1.5, but it might still apply.
I can't tell you more because I don't use Python. I found this link with a Google search.
EDIT: Yes! I was going to remind you about what we discussed yesterday but a good start will be to read steveha's Chinese Python documentation.
|
where is the '__path__' comes from
|
i can't find who defined the '__path__',why '__path__' can be use.
import os
import sys
import warnings
import ConfigParser # ConfigParser is not a virtualenv module, so we can use it to find the stdlib
dirname = os.path.dirname
distutils_path = os.path.join(os.path.dirname(ConfigParser.__file__), 'distutils')
if os.path.normpath(distutils_path) == os.path.dirname(os.path.normpath(__file__)):
warnings.warn(
"The virtualenv distutils package at %s appears to be in the same location as the system distutils?")
else:
__path__.insert(0, distutils_path)#who defined me.???
exec open(os.path.join(distutils_path, '__init__.py')).read()
|
[
"You really need to read some Python documentation and learn the basics of the language.\nI checked, and you seem to speak Chinese. Here are Python documentation resources in Chinese:\nhttp://www6.uniovi.es/python/doc/NonEnglish.html#chinese\nNow, to answer your question. I wasn't sure what the answer was, so I used Google. I did a Google search for \"Python __path__\" and very quickly found:\nhttp://docs.python.org/tutorial/modules.html\n\n6.4.3. Packages in Multiple Directories\nPackages support one more special\n attribute, __path__. This is\n initialized to be a list containing\n the name of the directory holding the\n package’s __init__.py before the code\n in that file is executed. This\n variable can be modified; doing so\n affects future searches for modules\n and subpackages contained in the\n package.\nWhile this feature is not often\n needed, it can be used to extend the\n set of modules found in a package.\n\n",
"I found the following description of the __path__ variable:\n\nIt is initialized to a list of one\n item, containing the directory name of\n the package (a subdirectory of a\n directory on sys.path). Changing\n __path__ changes the list of directories that are searched for\n submodules of the package.\n\nhere: http://www.python.org/doc/essays/packages.html\nThat page discusses 'built-in package support' in Python 1.5, but it might still apply.\nI can't tell you more because I don't use Python. I found this link with a Google search.\nEDIT: Yes! I was going to remind you about what we discussed yesterday but a good start will be to read steveha's Chinese Python documentation.\n"
] |
[
7,
3
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002003859_python.txt
|
Q:
Python ftplib: Overwriting a File doesn't work with STOR
I want to overwrite an existing file "test.txt" on my ftp server with this code:
from ftplib import FTP
HOST = 'host.com'
FTP_NAME = 'username'
FTP_PASS = 'password'
ftp = FTP(HOST)
ftp.login(FTP_NAME, FTP_PASS)
file = open('test.txt', 'r')
ftp.storlines('STOR test.txt', file)
ftp.quit()
file.close()
I don't get any error messages and the file test.txt has NOT been overwritten (the old test.txt is still on the server). I thought STOR overwrites files... Can somebody please help?
Thanks!
A:
nvm, it's my fault...
I forgot to change the current working directory to /public_html
thanks anyway!
|
Python ftplib: Overwriting a File doesn't work with STOR
|
I want to overwrite an existing file "test.txt" on my ftp server with this code:
from ftplib import FTP
HOST = 'host.com'
FTP_NAME = 'username'
FTP_PASS = 'password'
ftp = FTP(HOST)
ftp.login(FTP_NAME, FTP_PASS)
file = open('test.txt', 'r')
ftp.storlines('STOR test.txt', file)
ftp.quit()
file.close()
I don't get any error messages and the file test.txt has NOT been overwritten (the old test.txt is still on the server). I thought STOR overwrites files... Can somebody please help?
Thanks!
|
[
"nvm, it's my fault...\nI forgot to change the current working directory to /public_html\nthanks anyway!\n"
] |
[
1
] |
[
"I think you need to open the file in write mode\nfile = open('test.txt', 'w')\n\n"
] |
[
-2
] |
[
"file_upload",
"ftp",
"python"
] |
stackoverflow_0002003863_file_upload_ftp_python.txt
|
Q:
Ready-made Javascript library for modelling card games?
MVC 'architecture'. I would like a convenient way of specifying the rules of a card game including aspects such as hands or tricks, scoring, which cards from the deck or pack are used, and so on. Does anyone know of anything like this, preferably in Javascript?
Thanks for any guidance.
A:
There's a good article here (and as a complement I suggest the companion article about displaying playing cards with CSS that's here). Nothing much to do with Python though!-) If you do want an example of handling a card game (including showing the cards as images in Tkinter) with Python, try this one (which however has nothing to do with Javascript: not sure why you've tagged your question with both languages).
A:
C++ and Javascript have enough similarities that you should be able to at least understand general concepts and how things work from C++ code..?
http://drac-cardlib.sourceforge.net/
I found DRAC to be a good reference for general card game programming. I ended up applying a few of their approaches in my own poker AI simulations.
|
Ready-made Javascript library for modelling card games?
|
MVC 'architecture'. I would like a convenient way of specifying the rules of a card game including aspects such as hands or tricks, scoring, which cards from the deck or pack are used, and so on. Does anyone know of anything like this, preferably in Javascript?
Thanks for any guidance.
|
[
"There's a good article here (and as a complement I suggest the companion article about displaying playing cards with CSS that's here). Nothing much to do with Python though!-) If you do want an example of handling a card game (including showing the cards as images in Tkinter) with Python, try this one (which however has nothing to do with Javascript: not sure why you've tagged your question with both languages).\n",
"C++ and Javascript have enough similarities that you should be able to at least understand general concepts and how things work from C++ code..?\nhttp://drac-cardlib.sourceforge.net/\nI found DRAC to be a good reference for general card game programming. I ended up applying a few of their approaches in my own poker AI simulations.\n"
] |
[
3,
1
] |
[] |
[] |
[
"game_engine",
"javascript",
"model_view_controller",
"playing_cards",
"python"
] |
stackoverflow_0001996285_game_engine_javascript_model_view_controller_playing_cards_python.txt
|
Q:
Python equivalent of PyErr_Print()
What is the Python API equivalent of PyErr_Print(), from the C interface?
I'm assuming a call in either the sys, or traceback modules, but can't find any functions therein that make calls to PyErr_Print().
Addendum
I'm after the Python call to get the same functionality as PyErr_PrintEx(), described as:
Print a standard traceback to sys.stderr and clear the error indicator.
That is I want to make the Python call that has this effect.
A:
There's no Python function that's exactly equivalent to PyErr_PrintEx (the real name of PyErr_Print;-), including for example setting sys.last_traceback and friends (which are only supposed to be set to help a post-mortem debugging from the interactive interpreter for exceptions which have not been caught). What exact combination of functionality are you looking for?
|
Python equivalent of PyErr_Print()
|
What is the Python API equivalent of PyErr_Print(), from the C interface?
I'm assuming a call in either the sys, or traceback modules, but can't find any functions therein that make calls to PyErr_Print().
Addendum
I'm after the Python call to get the same functionality as PyErr_PrintEx(), described as:
Print a standard traceback to sys.stderr and clear the error indicator.
That is I want to make the Python call that has this effect.
|
[
"There's no Python function that's exactly equivalent to PyErr_PrintEx (the real name of PyErr_Print;-), including for example setting sys.last_traceback and friends (which are only supposed to be set to help a post-mortem debugging from the interactive interpreter for exceptions which have not been caught). What exact combination of functionality are you looking for?\n"
] |
[
2
] |
[] |
[] |
[
"c",
"cpython",
"python",
"sys",
"traceback"
] |
stackoverflow_0002004400_c_cpython_python_sys_traceback.txt
|
Q:
Nested Scopes and Lambdas
def funct():
x = 4
action = (lambda n: x ** n)
return action
x = funct()
print(x(2)) # prints 16
... I don't quite understand why 2 is assigned to n automatically?
A:
n is the argument of the anonymous function returned by funct. An exactly equivalent defintion of funct is
def funct():
x = 4
def action(n):
return x ** n
return action
Does this form make any more sense?
A:
It's not assigned "automatically": it's assigned very explicitly and non-automatically by your passing it as the actual argument corresponding to the n parameter. That complicated way to set x is almost identical (net of x.__name__ and other minor introspective details) to def x(n): return 4**n.
|
Nested Scopes and Lambdas
|
def funct():
x = 4
action = (lambda n: x ** n)
return action
x = funct()
print(x(2)) # prints 16
... I don't quite understand why 2 is assigned to n automatically?
|
[
"n is the argument of the anonymous function returned by funct. An exactly equivalent defintion of funct is \ndef funct():\n x = 4\n def action(n):\n return x ** n\n return action\n\nDoes this form make any more sense?\n",
"It's not assigned \"automatically\": it's assigned very explicitly and non-automatically by your passing it as the actual argument corresponding to the n parameter. That complicated way to set x is almost identical (net of x.__name__ and other minor introspective details) to def x(n): return 4**n.\n"
] |
[
5,
3
] |
[] |
[] |
[
"lambda",
"nested",
"python"
] |
stackoverflow_0002004398_lambda_nested_python.txt
|
Q:
How to mimic vb's control array in python for win32com?
I need to dynamically create com objects from an activex dll and each of the objects can raise events which should be handled with event handlers.
I can do this easily with win32com.client.Dispatch and win32com.client.WithEvents and associate a "separate" class of event handlers with each of the objects. Like so:
class evt_1:
def OnEvent(self):
print "got event from object 1"
class evt_2:
def OnEvent(self):
print "got event from object 2"
obj_1 = win32com.client.Dispatch("mycom")
ev_1 = win32com.client.WithEvents(obj_1, evt_1)
obj_2 = win32com.client.Dispatch("mycom")
ev_1 = win32com.client.WithEvents(obj_2, evt_2)
But if I dynamically create the objects, lets say in a list:
listOfObjects = []
for i in range(10):
obj = win32com.client.Dispatch("mycom")
listOfObjects.append(obj)
ev = win32com.client.WithEvents(obj, MyEventHandlerClass)
I want to code the event handlers only once, since I don't know how many objects I would be creating until run time. And I don't know how to get the object that raised the event from inside the event handler.
In VB 6, I've used the activex control using control arrays, and the event handlers simply get an "index" value of the control that raised the event.
Do you think something similar can be done in python ?
I am not sure what python decorators work for, but can they be used to "decorate" the MyEventHandlerClass for each index of the com object?
A:
Control Arrays were removed in VB.NET so I don't think they would be supported in the win32com.
Not sure if this would work for you but can you pass the index to the EventHandler class?
class MyEventHandler:
def __init__(self, index):
self.obj_index = index
def OnEvent(self):
print "got event from object %d" % self.obj_index
listOfObjects = []
for i in range(10):
obj = win32com.client.Dispatch("mycom")
listOfObjects.append(obj)
ev = win32com.client.WithEvents(obj, MyEventHandlerClass(i))
If the event needs access to all of the controls in the array (not just the index), you can mimic a control array by looping through your listOfObjects in the EventHandler, and determining which object raised the Event... so for example, a RadioButton_CheckChanged() event would look like:
def RadioButton_CheckChanged():
for radiobutton in listOfRadioButtons:
if radiobutton.Checked:
# this is the one that was clicked on
A:
It's a major flaw of win32com's event handling that you have to pass in a class object rather than a class instance.
You can attach state to your classes using win32com, however, by creating classes dynamically using new.classobj:
from win32com.client import Dispatch, WithEvents
from new import classobj
class MyEventHandler(object):
def OnVisible(self, visible):
print "got event from object %d" % self.obj_index
listOfObjects = []
for i in range(3):
handler = classobj('Handler_%s' % i,(MyEventHandler,),{})
handler.obj_index = i
ie = Dispatch("InternetExplorer.Application")
listOfObjects.append(ie)
WithEvents(ie, handler)
listOfObjects[0].Visible = 1
listOfObjects[2].Visible = 1
Output:
got event from object 0
got event from object 2
You might want to look into the comtypes module (see event handling) if you want to do this in a saner way.
|
How to mimic vb's control array in python for win32com?
|
I need to dynamically create com objects from an activex dll and each of the objects can raise events which should be handled with event handlers.
I can do this easily with win32com.client.Dispatch and win32com.client.WithEvents and associate a "separate" class of event handlers with each of the objects. Like so:
class evt_1:
def OnEvent(self):
print "got event from object 1"
class evt_2:
def OnEvent(self):
print "got event from object 2"
obj_1 = win32com.client.Dispatch("mycom")
ev_1 = win32com.client.WithEvents(obj_1, evt_1)
obj_2 = win32com.client.Dispatch("mycom")
ev_1 = win32com.client.WithEvents(obj_2, evt_2)
But if I dynamically create the objects, lets say in a list:
listOfObjects = []
for i in range(10):
obj = win32com.client.Dispatch("mycom")
listOfObjects.append(obj)
ev = win32com.client.WithEvents(obj, MyEventHandlerClass)
I want to code the event handlers only once, since I don't know how many objects I would be creating until run time. And I don't know how to get the object that raised the event from inside the event handler.
In VB 6, I've used the activex control using control arrays, and the event handlers simply get an "index" value of the control that raised the event.
Do you think something similar can be done in python ?
I am not sure what python decorators work for, but can they be used to "decorate" the MyEventHandlerClass for each index of the com object?
|
[
"Control Arrays were removed in VB.NET so I don't think they would be supported in the win32com. \nNot sure if this would work for you but can you pass the index to the EventHandler class?\nclass MyEventHandler:\n def __init__(self, index):\n self.obj_index = index\n\n def OnEvent(self):\n print \"got event from object %d\" % self.obj_index\n\nlistOfObjects = []\nfor i in range(10):\n obj = win32com.client.Dispatch(\"mycom\")\n listOfObjects.append(obj)\n ev = win32com.client.WithEvents(obj, MyEventHandlerClass(i))\n\nIf the event needs access to all of the controls in the array (not just the index), you can mimic a control array by looping through your listOfObjects in the EventHandler, and determining which object raised the Event... so for example, a RadioButton_CheckChanged() event would look like:\ndef RadioButton_CheckChanged():\n for radiobutton in listOfRadioButtons:\n if radiobutton.Checked:\n # this is the one that was clicked on\n\n",
"It's a major flaw of win32com's event handling that you have to pass in a class object rather than a class instance.\nYou can attach state to your classes using win32com, however, by creating classes dynamically using new.classobj:\nfrom win32com.client import Dispatch, WithEvents\nfrom new import classobj\n\nclass MyEventHandler(object):\n def OnVisible(self, visible):\n print \"got event from object %d\" % self.obj_index\n\nlistOfObjects = []\nfor i in range(3):\n handler = classobj('Handler_%s' % i,(MyEventHandler,),{})\n handler.obj_index = i\n ie = Dispatch(\"InternetExplorer.Application\")\n listOfObjects.append(ie)\n WithEvents(ie, handler)\n\nlistOfObjects[0].Visible = 1\nlistOfObjects[2].Visible = 1\n\nOutput:\ngot event from object 0\ngot event from object 2\n\nYou might want to look into the comtypes module (see event handling) if you want to do this in a saner way.\n"
] |
[
0,
0
] |
[] |
[] |
[
"python",
"win32com"
] |
stackoverflow_0001998186_python_win32com.txt
|
Q:
Regex match of hexdigest in google app engine webapp WSGIApplication
application = webapp.WSGIApplication(
[(r'/main/profile/([a-f0-9]{40})', ProfileHandler)],
debug=True)
The regex in the above parameter will not recognize a 40 hex long hexdigest in Google App Engine.
I'm getting 404s instead of ProfileHandler being passed the matching 40 hex long profile ID. My app.yaml passes everything /main/.* to the correct python script so that's not the issue. The regex looks sane and resembles the example regex in GAE docs. What is wrong with this regex?
A:
I can not reproduce your problem. Here is an exact code I have:
index.py
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
class ProfileHandler(webapp.RequestHandler):
def get(self, *ar, **kw):
self.response.out.write("PROFILE IS:" + ar[0])
run_wsgi_app(webapp.WSGIApplication(
[(r'/main/profile/([a-f0-9]{40})', ProfileHandler),],
debug=True))
app.yaml
application: someapp
version: 1
runtime: python
api_version: 1
handlers:
- url: /main/.*
script: index.py
Application is listening on port 8082
GET: http://localhost:8082/main/profile/4c4f630aef49c0065c22eb3dd35a00f5787f4816
RESPONSE: PROFILE IS:4c4f630aef49c0065c22eb3dd35a00f5787f4816
A:
I have no experience with the Google App Engine, but:
what happens if you change ([a-f0-9]{40}) in to ([a-fA-F0-9]{40})
are you sure group $1 is used and not the entire match (including /main/profile/)?
|
Regex match of hexdigest in google app engine webapp WSGIApplication
|
application = webapp.WSGIApplication(
[(r'/main/profile/([a-f0-9]{40})', ProfileHandler)],
debug=True)
The regex in the above parameter will not recognize a 40 hex long hexdigest in Google App Engine.
I'm getting 404s instead of ProfileHandler being passed the matching 40 hex long profile ID. My app.yaml passes everything /main/.* to the correct python script so that's not the issue. The regex looks sane and resembles the example regex in GAE docs. What is wrong with this regex?
|
[
"I can not reproduce your problem. Here is an exact code I have:\nindex.py\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext.webapp.util import run_wsgi_app\n\nclass ProfileHandler(webapp.RequestHandler): \n def get(self, *ar, **kw):\n self.response.out.write(\"PROFILE IS:\" + ar[0])\n\nrun_wsgi_app(webapp.WSGIApplication(\n[(r'/main/profile/([a-f0-9]{40})', ProfileHandler),],\n debug=True))\n\napp.yaml\napplication: someapp\nversion: 1\nruntime: python\napi_version: 1\n\nhandlers:\n- url: /main/.*\n script: index.py\n\nApplication is listening on port 8082\nGET: http://localhost:8082/main/profile/4c4f630aef49c0065c22eb3dd35a00f5787f4816\nRESPONSE: PROFILE IS:4c4f630aef49c0065c22eb3dd35a00f5787f4816\n\n",
"I have no experience with the Google App Engine, but:\n\nwhat happens if you change ([a-f0-9]{40}) in to ([a-fA-F0-9]{40})\nare you sure group $1 is used and not the entire match (including /main/profile/)?\n\n"
] |
[
2,
0
] |
[] |
[] |
[
"google_app_engine",
"python",
"regex",
"web_applications"
] |
stackoverflow_0002004691_google_app_engine_python_regex_web_applications.txt
|
Q:
How to debug Jinja2 template?
I am using jinja2 template system into django.
It is really fast and I like it a lot.
Nevertheless, I have some problem to debug templates :
If I make some errors into a template (bad tag, bad filtername, bad end of block...), I do not have at all information about this error.
For example, In a django view, I write this :
from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('main', 'templates'))
def jinja(req):
template = env.get_template('jinja.html')
output=template.render(myvar='hello')
return HttpResponse(output)
I write a jinja2 template : jinja.html :
{{myvar|notexistingfilter()}} Jinja !
Notice, I put on purpose an non existing filter to generate an error :
I was expecting something like "notexistingfilter() not defined", but I got only a simple black on white traceback (not the usual django debug message) :
Traceback (most recent call last):
File "/usr/local/lib/python2.6/dist-packages/django/core/servers/basehttp.py", line 279, in run
self.result = application(self.environ, self.start_response)
File "/usr/local/lib/python2.6/dist-packages/django/core/servers/basehttp.py", line 651, in __call__
return self.application(environ, start_response)
File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/wsgi.py", line 241, in __call__
response = self.get_response(request)
File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py", line 134, in get_response
return self.handle_uncaught_exception(request, resolver, exc_info)
File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py", line 154, in handle_uncaught_exception
return debug.technical_500_response(request, *exc_info)
File "/usr/local/lib/python2.6/dist-packages/django/views/debug.py", line 40, in technical_500_response
html = reporter.get_traceback_html()
File "/usr/local/lib/python2.6/dist-packages/django/views/debug.py", line 84, in get_traceback_html
self.get_template_exception_info()
File "/usr/local/lib/python2.6/dist-packages/django/views/debug.py", line 117, in get_template_exception_info
origin, (start, end) = self.exc_value.source
TypeError: 'Template' object is not iterable
I do not get the template filename where the error occured, no information about the error itself, so it is very difficult to debug jinja2.
What should I do to have more debug information and find where an error is inside a jinja2 template ?
Thank you in advance,
A:
After doing some more test, I found the answer :
By doing the same template test, directly under python, without using django, debug messages are present. So it comes from django.
The fix is in settings.py : One have to set DEBUG to True AND set TEMPLATE_DEBUG to False.
A:
From the Jinja2 Documentation:
My tracebacks look weird. What’s happening?
If the speedups module is not compiled and you are using a Python installation without ctypes (Python 2.4 without ctypes, Jython or Google’s AppEngine) Jinja2 is unable to provide correct debugging information and the traceback may be incomplete. There is currently no good workaround for Jython or the AppEngine as ctypes is unavailable there and it’s not possible to use the speedups extension.
http://jinja.pocoo.org/2/documentation/faq#my-tracebacks-look-weird-what-s-happening
|
How to debug Jinja2 template?
|
I am using jinja2 template system into django.
It is really fast and I like it a lot.
Nevertheless, I have some problem to debug templates :
If I make some errors into a template (bad tag, bad filtername, bad end of block...), I do not have at all information about this error.
For example, In a django view, I write this :
from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('main', 'templates'))
def jinja(req):
template = env.get_template('jinja.html')
output=template.render(myvar='hello')
return HttpResponse(output)
I write a jinja2 template : jinja.html :
{{myvar|notexistingfilter()}} Jinja !
Notice, I put on purpose an non existing filter to generate an error :
I was expecting something like "notexistingfilter() not defined", but I got only a simple black on white traceback (not the usual django debug message) :
Traceback (most recent call last):
File "/usr/local/lib/python2.6/dist-packages/django/core/servers/basehttp.py", line 279, in run
self.result = application(self.environ, self.start_response)
File "/usr/local/lib/python2.6/dist-packages/django/core/servers/basehttp.py", line 651, in __call__
return self.application(environ, start_response)
File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/wsgi.py", line 241, in __call__
response = self.get_response(request)
File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py", line 134, in get_response
return self.handle_uncaught_exception(request, resolver, exc_info)
File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py", line 154, in handle_uncaught_exception
return debug.technical_500_response(request, *exc_info)
File "/usr/local/lib/python2.6/dist-packages/django/views/debug.py", line 40, in technical_500_response
html = reporter.get_traceback_html()
File "/usr/local/lib/python2.6/dist-packages/django/views/debug.py", line 84, in get_traceback_html
self.get_template_exception_info()
File "/usr/local/lib/python2.6/dist-packages/django/views/debug.py", line 117, in get_template_exception_info
origin, (start, end) = self.exc_value.source
TypeError: 'Template' object is not iterable
I do not get the template filename where the error occured, no information about the error itself, so it is very difficult to debug jinja2.
What should I do to have more debug information and find where an error is inside a jinja2 template ?
Thank you in advance,
|
[
"After doing some more test, I found the answer :\nBy doing the same template test, directly under python, without using django, debug messages are present. So it comes from django.\nThe fix is in settings.py : One have to set DEBUG to True AND set TEMPLATE_DEBUG to False.\n",
"From the Jinja2 Documentation:\n\nMy tracebacks look weird. What’s happening?\nIf the speedups module is not compiled and you are using a Python installation without ctypes (Python 2.4 without ctypes, Jython or Google’s AppEngine) Jinja2 is unable to provide correct debugging information and the traceback may be incomplete. There is currently no good workaround for Jython or the AppEngine as ctypes is unavailable there and it’s not possible to use the speedups extension.\n\nhttp://jinja.pocoo.org/2/documentation/faq#my-tracebacks-look-weird-what-s-happening\n"
] |
[
16,
7
] |
[] |
[] |
[
"django",
"jinja2",
"python"
] |
stackoverflow_0002002357_django_jinja2_python.txt
|
Q:
Qt Python Calendar: selected day direct access
I have calendar that is working fine.
Here is the function that display the full date:
def selectDate(self,date):
self.fullDate = str(date.day()) + " / " + str(date.month()) + " / " + str(date.year())
print "full date: %s" % self.fullDate
And here the code with the calendar:
def TabCalendar(self):
self.calendar = QtGui.QCalendarWidget(self.tab)
self.calendar.setGeometry(QtCore.QRect(self.x1, self.y1, self.x2, self.y2))
QtCore.QObject.connect(self.calendar, QtCore.SIGNAL("selectionChanged()"), self.selectDate)
QtCore.QObject.connect(self.calendar, QtCore.SIGNAL("clicked(QDate)"), self.selectDate)
To have direct access to selected day, I am calling the function selectDate based on connect event, and then using the 'date' to obtain the precise date.day and so on -- which is working fine.
The only awkward thing that is annoying me is that it gives the following warning..
TypeError: turbSchedule_selectDate() takes exactly 2 arguments (1 given)
Any suggestion to stop this TypeError warning?
All comments and suggestions are highly appreciated.
A:
I guess that the slot called by the selectdate signal shouldn't have any argument. You can access the selectedDate by the corresponding calendar method.
See the c++ docs: http://doc.trolltech.com/4.3/widgets-calendarwidget.html
So your code should be something like:
def selectDate(self):
date = self.calendar.selectedDate()
self.fullDate = str(date.day()) + " / " + str(date.month()) + " / " + str(date.year())
print "full date: %s" % self.fullDate
|
Qt Python Calendar: selected day direct access
|
I have calendar that is working fine.
Here is the function that display the full date:
def selectDate(self,date):
self.fullDate = str(date.day()) + " / " + str(date.month()) + " / " + str(date.year())
print "full date: %s" % self.fullDate
And here the code with the calendar:
def TabCalendar(self):
self.calendar = QtGui.QCalendarWidget(self.tab)
self.calendar.setGeometry(QtCore.QRect(self.x1, self.y1, self.x2, self.y2))
QtCore.QObject.connect(self.calendar, QtCore.SIGNAL("selectionChanged()"), self.selectDate)
QtCore.QObject.connect(self.calendar, QtCore.SIGNAL("clicked(QDate)"), self.selectDate)
To have direct access to selected day, I am calling the function selectDate based on connect event, and then using the 'date' to obtain the precise date.day and so on -- which is working fine.
The only awkward thing that is annoying me is that it gives the following warning..
TypeError: turbSchedule_selectDate() takes exactly 2 arguments (1 given)
Any suggestion to stop this TypeError warning?
All comments and suggestions are highly appreciated.
|
[
"I guess that the slot called by the selectdate signal shouldn't have any argument. You can access the selectedDate by the corresponding calendar method.\nSee the c++ docs: http://doc.trolltech.com/4.3/widgets-calendarwidget.html\nSo your code should be something like:\ndef selectDate(self):\n date = self.calendar.selectedDate()\n self.fullDate = str(date.day()) + \" / \" + str(date.month()) + \" / \" + str(date.year())\n print \"full date: %s\" % self.fullDate\n\n"
] |
[
2
] |
[] |
[] |
[
"calendar",
"date",
"python",
"qt",
"typeerror"
] |
stackoverflow_0002004916_calendar_date_python_qt_typeerror.txt
|
Q:
String manipulation in Python
I am trying to write a command but I do not want one long line that looks untidy. I am looking to add the strings together to be executed as on command. I have some code below which is part of an email function:
msg = MIMEText("The nightly build status was a SUCCESS\n\nBuild File: http://www.python.org\n\n Build Results File: http://10.51.54.57/sandboxes/", project, "\n")
This shows the one line, I am hoping for a better way to do this. I have tried the below code but it does not work.
msg = MIMEText("The nightly build status was a SUCCESS\n\nBuild File: ")
msg += MIMEText("http://www.python.org\n\n Build Results File: ")
msg += MIMEText("http://10.51.54.57/sandboxes/", project, "\n")
Thanks for any help.
I have tried the below code but get:
msg = MIMEText("""The nightly build status was a SUCCESS\n\n
Build File: """,
build_file, """
\n\n
Build Results File: """,
build_file, """
\n\n
Sandbox Folder:""",
sandbox, """
\n\n
Antibrick File: """,
antibrick, "\n\n")
Now I get the message:
Traceback (most recent call last):
File "test_email.py", line 45, in <module>
if __name__ == '__main__': myObject = email_success()
File "test_email.py", line 32, in email_success
antibrick, "\n\n")
TypeError: __init__() takes at most 4 arguments (10 given)
Any ideas?
Thanks S.Mark, I tried this but when the email is sent it is not as a hyperlink but sent as:
The nightly build status was a SUCCESS
Build File: ('http://10.67.54.57/sandboxes/', '2010-01-05/new_sandbox', 'basebuild')
Build Results File: ('http://10.67.54.57/sandboxes/', '2010-01-05/new_sandbox', 'basebuild')
Sandbox Folder: ('http://10.67.54.57/sandboxes/', '2010-01-05/new_sandbox')
Antibrick File:
A:
Try:
msg = MIMEText("""The nightly build status was a SUCCESS
Build File:
http://www.python.org
Build Results File:
http://10.51.54.57/sandboxes/""", project, "\n")
If the additional space at the beginning of each line is a problem, remove them with a regexp (r'^\s+')
A:
How about
msg = MIMEText(
"The nightly build status was a SUCCESS\n\n"
"Build File: http://www.python.org\n\n"
"Build Results File: http://10.51.54.57/sandboxes/"
, project
, "\n"
)
Or
msg = MIMEText("""The nightly build status was a SUCCESS
Build File: http://www.python.org
Build Results File: http://10.51.54.57/sandboxes/""", project, "\n")
Or
msg = MIMEText("The nightly build status was a SUCCESS\n\n"
"Build File: http://www.python.org\n\n"
"Build Results File: http://10.51.54.57/sandboxes/"
, project, "\n")
UPDATE: because OP added another question
msg=MIMEText("""The nightly build status was a SUCCESS\n\n
Build File: %s
\n\n
Build Results File: %s
\n\n
Sandbox Folder: %s
\n\n
Antibrick File: """ % (build_file,build_file,sandbox),
antibrick,
"\n\n"
)
A:
Why not
msg= MIMEText("The nightly build status was a SUCCESS\n\nBuild File: "+ \
"http://www.python.org\n\n Bu..... ")
etc.
(I.e., use the line continuation backslash).
Also note that the following each give you abcdef
s ="abc" "def"
s= "abc" \
"def"
Also,
s="""xyz
wvu"""
gives you
'xyz\nwvu'
A:
Python supports multi-line strings using triple quotes:
text = """The nightly build status was a SUCCESS\n\nBuild File:
http://www.python.org\n\n Build Results File:
http://10.51.54.57/sandboxes/"""
msg = MIMEText(text, project, "\n")
A:
you can use triple quotes
>>> s="""The nightly build status was a SUCCESS
Build File: http://www.python.org
Build Results File: http://10.51.54.57/sandboxes/"""
>>> msg=MimeType(s,project,"\n")
|
String manipulation in Python
|
I am trying to write a command but I do not want one long line that looks untidy. I am looking to add the strings together to be executed as on command. I have some code below which is part of an email function:
msg = MIMEText("The nightly build status was a SUCCESS\n\nBuild File: http://www.python.org\n\n Build Results File: http://10.51.54.57/sandboxes/", project, "\n")
This shows the one line, I am hoping for a better way to do this. I have tried the below code but it does not work.
msg = MIMEText("The nightly build status was a SUCCESS\n\nBuild File: ")
msg += MIMEText("http://www.python.org\n\n Build Results File: ")
msg += MIMEText("http://10.51.54.57/sandboxes/", project, "\n")
Thanks for any help.
I have tried the below code but get:
msg = MIMEText("""The nightly build status was a SUCCESS\n\n
Build File: """,
build_file, """
\n\n
Build Results File: """,
build_file, """
\n\n
Sandbox Folder:""",
sandbox, """
\n\n
Antibrick File: """,
antibrick, "\n\n")
Now I get the message:
Traceback (most recent call last):
File "test_email.py", line 45, in <module>
if __name__ == '__main__': myObject = email_success()
File "test_email.py", line 32, in email_success
antibrick, "\n\n")
TypeError: __init__() takes at most 4 arguments (10 given)
Any ideas?
Thanks S.Mark, I tried this but when the email is sent it is not as a hyperlink but sent as:
The nightly build status was a SUCCESS
Build File: ('http://10.67.54.57/sandboxes/', '2010-01-05/new_sandbox', 'basebuild')
Build Results File: ('http://10.67.54.57/sandboxes/', '2010-01-05/new_sandbox', 'basebuild')
Sandbox Folder: ('http://10.67.54.57/sandboxes/', '2010-01-05/new_sandbox')
Antibrick File:
|
[
"Try:\nmsg = MIMEText(\"\"\"The nightly build status was a SUCCESS\n\nBuild File:\nhttp://www.python.org\n\nBuild Results File: \nhttp://10.51.54.57/sandboxes/\"\"\", project, \"\\n\")\n\nIf the additional space at the beginning of each line is a problem, remove them with a regexp (r'^\\s+')\n",
"How about\nmsg = MIMEText(\n\"The nightly build status was a SUCCESS\\n\\n\"\n\"Build File: http://www.python.org\\n\\n\"\n\"Build Results File: http://10.51.54.57/sandboxes/\"\n, project\n, \"\\n\"\n)\n\nOr\nmsg = MIMEText(\"\"\"The nightly build status was a SUCCESS\n\nBuild File: http://www.python.org\n\nBuild Results File: http://10.51.54.57/sandboxes/\"\"\", project, \"\\n\")\n\nOr\nmsg = MIMEText(\"The nightly build status was a SUCCESS\\n\\n\"\n\"Build File: http://www.python.org\\n\\n\"\n\"Build Results File: http://10.51.54.57/sandboxes/\"\n, project, \"\\n\")\n\nUPDATE: because OP added another question\nmsg=MIMEText(\"\"\"The nightly build status was a SUCCESS\\n\\n\n Build File: %s\n \\n\\n \n Build Results File: %s\n \\n\\n\n Sandbox Folder: %s \n \\n\\n\n Antibrick File: \"\"\" % (build_file,build_file,sandbox),\n antibrick, \n \"\\n\\n\"\n)\n\n",
"Why not\nmsg= MIMEText(\"The nightly build status was a SUCCESS\\n\\nBuild File: \"+ \\\n \"http://www.python.org\\n\\n Bu..... \") \n\netc.\n(I.e., use the line continuation backslash).\nAlso note that the following each give you abcdef\ns =\"abc\" \"def\"\n\ns= \"abc\" \\\n \"def\"\n\nAlso, \n s=\"\"\"xyz\n wvu\"\"\"\n\ngives you \n'xyz\\nwvu'\n\n",
"Python supports multi-line strings using triple quotes:\ntext = \"\"\"The nightly build status was a SUCCESS\\n\\nBuild File: \nhttp://www.python.org\\n\\n Build Results File: \nhttp://10.51.54.57/sandboxes/\"\"\"\nmsg = MIMEText(text, project, \"\\n\")\n\n",
"you can use triple quotes\n>>> s=\"\"\"The nightly build status was a SUCCESS\n\nBuild File: http://www.python.org\n\nBuild Results File: http://10.51.54.57/sandboxes/\"\"\"\n\n>>> msg=MimeType(s,project,\"\\n\")\n\n"
] |
[
5,
5,
3,
1,
0
] |
[
"Hmm, what exactly is the module are you using? I am guessing, that it is deprecated, because the modern interface is email (if I've guessed your intentions correctly). More specifically, to create a MIMEText object you use this class. The signature is \nemail.mime.text.MIMEText(_text[, _subtype[, _charset]])\n\n"
] |
[
-1
] |
[
"python"
] |
stackoverflow_0002005345_python.txt
|
Q:
Slow pyinotify.ThreadedNotifier.stop()
I have a wxPython application that uses pyinotify (via ThreadedNotifier) to check when a certain file gets modified. When this happens, the application stops watching the file and does some stuff. Everything works fine, except that often the call to ThreadedNotifier.stop() takes a noticeable time, about 4 seconds... Other times, it exits immediately.
Anyone else experienced this? Is this expected?
(Xubuntu 9.04)
A:
Could it be that it is a polling mechanism with a timeout of about 4 seconds? And that the thread is only really stopped when it is entering the run() stage?
That might have something to do with the threading library.
You could test that by using a notifier with a different timeout.
|
Slow pyinotify.ThreadedNotifier.stop()
|
I have a wxPython application that uses pyinotify (via ThreadedNotifier) to check when a certain file gets modified. When this happens, the application stops watching the file and does some stuff. Everything works fine, except that often the call to ThreadedNotifier.stop() takes a noticeable time, about 4 seconds... Other times, it exits immediately.
Anyone else experienced this? Is this expected?
(Xubuntu 9.04)
|
[
"Could it be that it is a polling mechanism with a timeout of about 4 seconds? And that the thread is only really stopped when it is entering the run() stage?\nThat might have something to do with the threading library. \nYou could test that by using a notifier with a different timeout.\n"
] |
[
1
] |
[] |
[] |
[
"inotify",
"pyinotify",
"python"
] |
stackoverflow_0002005443_inotify_pyinotify_python.txt
|
Q:
Reading Alpha of a PNG Pixel. Fast way via pure Python?
I am having an issue with an embedded 64bit Python instance not liking PIL. Before i start exhausting more methods to get a compiled image editor to read the pixels for me (such as ImageMagick) i am hoping perhaps anyone here can think of a purely Python solution that will be comparable in speeds to the compiled counterparts.
Now i am aware that the compiled friends will always be much faster, but i am hoping that because i "just" want to read the alpha of a group of pixels, that perhaps a fast enough pure Python solution can be conjured up. Anyone have any bright ideas?
Though, i have tried PyPNG and that is far too slow, so i'm not expecting any magic solutions. None the less, i had to ask.
Thanks to any replies!
And just for reference, the images i'll be reading will be on average around 512*512 to 2048*2048, and i'll be reading anywhere from one to all of the pixels alpha (multiplied by a few million times, but the values can be stored so reading twice isn't done).
A:
Getting data out of a PNG requires unpacking data and decompressing it. These are likely going to be too slow in Python for your application. One possibility is to start with PyPNG and get rid of anything in it that you don't need. For example, it is probably storing all of the data it reads from the PNG, and some of the slow speed you see may be due to the memory allocations.
A:
When you say PyPNG is too slow, how slow is it? To put it another way, how fast would be fast enough? PyPNG doesn't do anything stupid to make itself slow, but it is written in Python.
Make sure you're using read() to read the image row by row, and make sure you're using row[3::4] to extract the alpha channel. Extracting the alpha channel by using slice notation is no slower than reading the whole image.
I've added some notes to the PyPNG documentation about its speed.
|
Reading Alpha of a PNG Pixel. Fast way via pure Python?
|
I am having an issue with an embedded 64bit Python instance not liking PIL. Before i start exhausting more methods to get a compiled image editor to read the pixels for me (such as ImageMagick) i am hoping perhaps anyone here can think of a purely Python solution that will be comparable in speeds to the compiled counterparts.
Now i am aware that the compiled friends will always be much faster, but i am hoping that because i "just" want to read the alpha of a group of pixels, that perhaps a fast enough pure Python solution can be conjured up. Anyone have any bright ideas?
Though, i have tried PyPNG and that is far too slow, so i'm not expecting any magic solutions. None the less, i had to ask.
Thanks to any replies!
And just for reference, the images i'll be reading will be on average around 512*512 to 2048*2048, and i'll be reading anywhere from one to all of the pixels alpha (multiplied by a few million times, but the values can be stored so reading twice isn't done).
|
[
"Getting data out of a PNG requires unpacking data and decompressing it. These are likely going to be too slow in Python for your application. One possibility is to start with PyPNG and get rid of anything in it that you don't need. For example, it is probably storing all of the data it reads from the PNG, and some of the slow speed you see may be due to the memory allocations.\n",
"When you say PyPNG is too slow, how slow is it? To put it another way, how fast would be fast enough? PyPNG doesn't do anything stupid to make itself slow, but it is written in Python.\nMake sure you're using read() to read the image row by row, and make sure you're using row[3::4] to extract the alpha channel. Extracting the alpha channel by using slice notation is no slower than reading the whole image.\nI've added some notes to the PyPNG documentation about its speed.\n"
] |
[
2,
0
] |
[] |
[] |
[
"png",
"python"
] |
stackoverflow_0001732761_png_python.txt
|
Q:
Get original filename google app engine
When receiving a file upload on google app engine, the example assumes you're receiving a .png. However you only konw what the type of the image is by the extension on the filename.
How do you get the original filename uploaded on GAE?
A:
The filename of the file that is being uploaded can be determined by looking at the filename property of the variable that holds the file. For example, let's say that your form has a field named content:
<input type="file" name="content" />
Inside your Handler, you could find the name of the file with:
filename = self.request.POST["content"].filename
A:
It seems that the newly introduced BlobStore has direct support for original filename in the blob's properties.
http://code.google.com/appengine/docs/python/blobstore/blobinfoclass.html#BlobInfo_filename
You will need to register a credit card with App Engine to be able to use the BlobStore in production though, even if you don't plan on exceeding the free quotas.
|
Get original filename google app engine
|
When receiving a file upload on google app engine, the example assumes you're receiving a .png. However you only konw what the type of the image is by the extension on the filename.
How do you get the original filename uploaded on GAE?
|
[
"The filename of the file that is being uploaded can be determined by looking at the filename property of the variable that holds the file. For example, let's say that your form has a field named content:\n<input type=\"file\" name=\"content\" />\n\nInside your Handler, you could find the name of the file with:\nfilename = self.request.POST[\"content\"].filename\n\n",
"It seems that the newly introduced BlobStore has direct support for original filename in the blob's properties.\nhttp://code.google.com/appengine/docs/python/blobstore/blobinfoclass.html#BlobInfo_filename\nYou will need to register a credit card with App Engine to be able to use the BlobStore in production though, even if you don't plan on exceeding the free quotas.\n"
] |
[
8,
3
] |
[] |
[] |
[
"google_app_engine",
"python",
"upload"
] |
stackoverflow_0002004476_google_app_engine_python_upload.txt
|
Q:
Visual module in python assign objects
I am a newb in Visual module in python, not really understand how does it assign a value to an objects.
say
from visual import *
stars=[]
galaxies=[]
for i in range(10):
stars+=[sphere('pos,radius,color.....')]
for j in range(20):
galaxies+=[sphere('pos,radius,color......')]
for k in range(30):
stars[k].pos=position[k]
galaxies[k].pos=G_position[k]
i just can not understand, normally, when python read this code, the list would be fully finished after the for loop, but after import visual module, those spheres can show up on screen and update their positions by each iteration of the last for loop!...
or my question may also link to what and where the "show()","print" "start the animation" statement in the visual module and how does it work? how may I use it?
kind of like if I add print state with in the for loop or after it finished.
Thanks alot in advance
A:
First things first. Your code uses list concatenation to add stuff to the list. It is better to use the .append() method of lists. Also, the last loop could iterate directly on the objects instead of using an index. It is more elegant and easy to understand this way.
The pseudo-code below is equivalent to yours, but with the above corrections applied:
from visual import *
stars = []
galaxies = []
for i in range(10):
stars.append(sphere(...))
for j in range(20):
galaxies.append(sphere(...))
for star, galaxy, starpos, galaxypos in zip(stars, galaxies,
position, G_position):
star.pos = starpos
galaxy.pos = galaxypos
With that out of the way, I can explain how visual works.
Visual module updates the screen as soon as the object is changed. The animation is done by that alteration, in realtime, there's no need for a show() or start_animation() - it happens as it goes. An example you can run on python command line:
>>> from visual import sphere
>>> s = sphere()
That line creates a sphere, and a window, and shows the sphere in the window already!!!
>>> s.x = -100
That line changes the sphere position on x axis to -100. The change happens immediatelly on the screen. Just after this line runs, you see the sphere appear to the left of the window.
So the animation happens by changing the values of the objects.
|
Visual module in python assign objects
|
I am a newb in Visual module in python, not really understand how does it assign a value to an objects.
say
from visual import *
stars=[]
galaxies=[]
for i in range(10):
stars+=[sphere('pos,radius,color.....')]
for j in range(20):
galaxies+=[sphere('pos,radius,color......')]
for k in range(30):
stars[k].pos=position[k]
galaxies[k].pos=G_position[k]
i just can not understand, normally, when python read this code, the list would be fully finished after the for loop, but after import visual module, those spheres can show up on screen and update their positions by each iteration of the last for loop!...
or my question may also link to what and where the "show()","print" "start the animation" statement in the visual module and how does it work? how may I use it?
kind of like if I add print state with in the for loop or after it finished.
Thanks alot in advance
|
[
"First things first. Your code uses list concatenation to add stuff to the list. It is better to use the .append() method of lists. Also, the last loop could iterate directly on the objects instead of using an index. It is more elegant and easy to understand this way.\nThe pseudo-code below is equivalent to yours, but with the above corrections applied:\nfrom visual import *\nstars = []\ngalaxies = [] \nfor i in range(10):\n stars.append(sphere(...))\nfor j in range(20):\n galaxies.append(sphere(...))\nfor star, galaxy, starpos, galaxypos in zip(stars, galaxies, \n position, G_position):\n star.pos = starpos\n galaxy.pos = galaxypos\n\nWith that out of the way, I can explain how visual works.\nVisual module updates the screen as soon as the object is changed. The animation is done by that alteration, in realtime, there's no need for a show() or start_animation() - it happens as it goes. An example you can run on python command line:\n>>> from visual import sphere\n>>> s = sphere()\n\nThat line creates a sphere, and a window, and shows the sphere in the window already!!!\n>>> s.x = -100\n\nThat line changes the sphere position on x axis to -100. The change happens immediatelly on the screen. Just after this line runs, you see the sphere appear to the left of the window.\nSo the animation happens by changing the values of the objects.\n"
] |
[
1
] |
[] |
[] |
[
"python",
"python_visual"
] |
stackoverflow_0002005759_python_python_visual.txt
|
Q:
Python Debugging
I'm not sure if 'debugging' is the right word, but I'm looking for a tool/IDE that would show my which statement/block will be executed next in a particular module. This feature I remember was available in Turbo C++ years back so I assume something similar might be available in some Python IDE?
Thanks
A:
pdb has this feature - there's a nice hands-on tutorial about it here.
pydev, the eclipse python plugin, might help if you're looking for an IDE solution.
A:
Ulipad IDE's debugging feature is very good, its just works like Turbo C++ IDE's debugger.
A:
At the commandline, there's pdb
In an IDE, Netbeans has a GUI debugger that some people like.
A:
I use Netbeans IDE.. very good (and improving) python support..
you will have to install the python plugin if you download the standard installer..
|
Python Debugging
|
I'm not sure if 'debugging' is the right word, but I'm looking for a tool/IDE that would show my which statement/block will be executed next in a particular module. This feature I remember was available in Turbo C++ years back so I assume something similar might be available in some Python IDE?
Thanks
|
[
"pdb has this feature - there's a nice hands-on tutorial about it here.\npydev, the eclipse python plugin, might help if you're looking for an IDE solution.\n",
"Ulipad IDE's debugging feature is very good, its just works like Turbo C++ IDE's debugger.\n",
"At the commandline, there's pdb\nIn an IDE, Netbeans has a GUI debugger that some people like.\n",
"I use Netbeans IDE.. very good (and improving) python support.. \nyou will have to install the python plugin if you download the standard installer.. \n"
] |
[
2,
1,
0,
0
] |
[] |
[] |
[
"breakpoints",
"debugging",
"ide",
"python"
] |
stackoverflow_0002006034_breakpoints_debugging_ide_python.txt
|
Q:
Executing python script in background in init.d
to interact with my iPhone, i have created a python script that sends and recives data through a socket, the script must be started after emule in order to work,
i have thought of something like this:
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/local/bin/amuled
WEB=/usr/local/bin/amuleweb
NAME=amuled
DESC=amuled
RUNAMULE=no
USER=piros
# ADDED FOR iPhone
SOCKET= /home/piros/amule_scripts/aMuleSocket/aMuleSocket.py
#
And then
case "$1" in
start)
echo -n "Starting $DESC: "
su $USER -c "$DAEMON -f"
while ! netstat -l -n -p -t | grep -q amuled ; do sleep 1 ; done
su $USER -c "$WEB --quiet & "
##iPhone
su $USER -c "$SOCKET & "
##
echo "$NAME."
;;
The big problem is, although i specified the & sign the process dosen't want to run in background :( any ideas??
Thanks!
A:
Put the su process in the background, not its child. For example:
su $USER -c "$WEB --quiet" &
Notice that the ampersand is outside the quotes.
A:
try launching with nohup process.py &
|
Executing python script in background in init.d
|
to interact with my iPhone, i have created a python script that sends and recives data through a socket, the script must be started after emule in order to work,
i have thought of something like this:
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/local/bin/amuled
WEB=/usr/local/bin/amuleweb
NAME=amuled
DESC=amuled
RUNAMULE=no
USER=piros
# ADDED FOR iPhone
SOCKET= /home/piros/amule_scripts/aMuleSocket/aMuleSocket.py
#
And then
case "$1" in
start)
echo -n "Starting $DESC: "
su $USER -c "$DAEMON -f"
while ! netstat -l -n -p -t | grep -q amuled ; do sleep 1 ; done
su $USER -c "$WEB --quiet & "
##iPhone
su $USER -c "$SOCKET & "
##
echo "$NAME."
;;
The big problem is, although i specified the & sign the process dosen't want to run in background :( any ideas??
Thanks!
|
[
"Put the su process in the background, not its child. For example:\nsu $USER -c \"$WEB --quiet\" &\n\nNotice that the ampersand is outside the quotes.\n",
"try launching with nohup process.py &\n"
] |
[
5,
2
] |
[] |
[] |
[
"bash",
"init.d",
"python",
"sysv"
] |
stackoverflow_0002006483_bash_init.d_python_sysv.txt
|
Q:
web2py Exception in sql rows
when i do the following code:
family_members =db(db.member.id == membership_id).select
(db.member.name,db.member.id)
family_members.colnames = ('Name','Membership ID')
It cause the following error...
Traceback (most recent call last):
File "/home/abeer/Desktop/web2py/New_version/web2py_src/web2py/gluon/
restricted.py", line 184, in restricted
File "/home/abeer/Desktop/resources/web2py/New_version/web2py_src/
web2py/applications/init/views/default/updateMember.html", line 142,
in <module>
File "/home/abeer/Desktop/web2py/New_version/web2py_src/web2py/gluon/
globals.py", line 112, in write
File "/home/abeer/Desktop/web2py/New_version/web2py_src/web2py/gluon/
html.py", line 103, in xmlescape
File "/home/abeer/Desktop/web2py/New_version/web2py_src/web2py/gluon/
sql.py", line 3326, in xml
File "/home/abeer/Desktop/web2py/New_version/web2py_src/web2py/gluon/
sqlhtml.py", line 980, in __init__
File "/home/abeer/Desktop/web2py/New_version/web2py_src/web2py/gluon/
sql.py", line 621, in __getattr__
KeyError: '_extra'
P.S. : when i commented the line (family_members.colnames = ('Name','Membership ID')), it works fine, but I don't understand why.
A:
Do not use colnames. That attribute is internal to web2py. Use db.table.field.label='..' or SQLTABLE(rows, headers={...}) depending on what you need.
|
web2py Exception in sql rows
|
when i do the following code:
family_members =db(db.member.id == membership_id).select
(db.member.name,db.member.id)
family_members.colnames = ('Name','Membership ID')
It cause the following error...
Traceback (most recent call last):
File "/home/abeer/Desktop/web2py/New_version/web2py_src/web2py/gluon/
restricted.py", line 184, in restricted
File "/home/abeer/Desktop/resources/web2py/New_version/web2py_src/
web2py/applications/init/views/default/updateMember.html", line 142,
in <module>
File "/home/abeer/Desktop/web2py/New_version/web2py_src/web2py/gluon/
globals.py", line 112, in write
File "/home/abeer/Desktop/web2py/New_version/web2py_src/web2py/gluon/
html.py", line 103, in xmlescape
File "/home/abeer/Desktop/web2py/New_version/web2py_src/web2py/gluon/
sql.py", line 3326, in xml
File "/home/abeer/Desktop/web2py/New_version/web2py_src/web2py/gluon/
sqlhtml.py", line 980, in __init__
File "/home/abeer/Desktop/web2py/New_version/web2py_src/web2py/gluon/
sql.py", line 621, in __getattr__
KeyError: '_extra'
P.S. : when i commented the line (family_members.colnames = ('Name','Membership ID')), it works fine, but I don't understand why.
|
[
"Do not use colnames. That attribute is internal to web2py. Use db.table.field.label='..' or SQLTABLE(rows, headers={...}) depending on what you need.\n"
] |
[
0
] |
[] |
[] |
[
"python",
"web2py"
] |
stackoverflow_0002006259_python_web2py.txt
|
Q:
Click overlay for html page with click stats
How would you setup click overlay for html page that has click stats with number of clicks stored. Is there a jquery example for something like this. The ideal click overlay will have have a little box on top on each link with how many times it was clicked.
A:
Not sure if you want to use a 3rd party service, but Crazy Egg does this exact thing: http://crazyegg.com/
Or a tutorial here: http://css-tricks.com/tracking-clicks-building-a-clickmap-with-php-and-jquery/
A:
I think this tutorial is perfect for you: http://celeryproject.org/tutorials/clickcounter.html
You can make a json service for get the click stats.
|
Click overlay for html page with click stats
|
How would you setup click overlay for html page that has click stats with number of clicks stored. Is there a jquery example for something like this. The ideal click overlay will have have a little box on top on each link with how many times it was clicked.
|
[
"Not sure if you want to use a 3rd party service, but Crazy Egg does this exact thing: http://crazyegg.com/\nOr a tutorial here: http://css-tricks.com/tracking-clicks-building-a-clickmap-with-php-and-jquery/\n",
"I think this tutorial is perfect for you: http://celeryproject.org/tutorials/clickcounter.html\nYou can make a json service for get the click stats.\n"
] |
[
1,
0
] |
[] |
[] |
[
"django",
"jquery",
"python"
] |
stackoverflow_0002006320_django_jquery_python.txt
|
Q:
google app engine jsonpickle
Has anyone got jsonpickle working on the google app engine? My logs say there is no module but there is a module as sure as you're born. i'm using jsonpickle 0.32.
<type 'exceptions.ImportError'>: No module named jsonpickle
Traceback (most recent call last):
File "/base/data/home/apps/xxxxx/xxxxxxxxxxxxxxxxx/main.py", line 4, in <module>
import jsonpickle
A:
I have managed to make it work registering django.utils.simplejson as a json encoder/decoder. In this real file index.py class Pizza is encoded and decoded back:
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
import jsonpickle
class Pizza:
pass
class Example(webapp.RequestHandler):
def get(self):
jsonpickle.load_backend('django.utils.simplejson',
'dumps','loads',ValueError)
encoded = jsonpickle.encode(Pizza())
self.response.out.write( jsonpickle.decode(encoded).__class__ )
run_wsgi_app(webapp.WSGIApplication([('/', Example),],debug=True))
A:
As this post explains, jsonpickle requires one of a few underlying JSON modules. I would fix the issue as follows -- put at the top of your module(s) that need jsonpickle the following few lines:
import sys
import django.utils.simplejson
sys.modules['simplejson'] = django.utils.simplejson
This addresses the problem: jsonpickle needs simplejson (as one of the JSON modules it can use), but GAE has it as django.utils.simplejson, so you need to "alias" it appropriately.
|
google app engine jsonpickle
|
Has anyone got jsonpickle working on the google app engine? My logs say there is no module but there is a module as sure as you're born. i'm using jsonpickle 0.32.
<type 'exceptions.ImportError'>: No module named jsonpickle
Traceback (most recent call last):
File "/base/data/home/apps/xxxxx/xxxxxxxxxxxxxxxxx/main.py", line 4, in <module>
import jsonpickle
|
[
"I have managed to make it work registering django.utils.simplejson as a json encoder/decoder. In this real file index.py class Pizza is encoded and decoded back:\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext.webapp.util import run_wsgi_app\n\nimport jsonpickle\n\nclass Pizza:\n pass \n\nclass Example(webapp.RequestHandler):\n def get(self):\n jsonpickle.load_backend('django.utils.simplejson',\n 'dumps','loads',ValueError)\n encoded = jsonpickle.encode(Pizza())\n self.response.out.write( jsonpickle.decode(encoded).__class__ )\n\nrun_wsgi_app(webapp.WSGIApplication([('/', Example),],debug=True))\n\n",
"As this post explains, jsonpickle requires one of a few underlying JSON modules. I would fix the issue as follows -- put at the top of your module(s) that need jsonpickle the following few lines:\nimport sys\nimport django.utils.simplejson\nsys.modules['simplejson'] = django.utils.simplejson\n\nThis addresses the problem: jsonpickle needs simplejson (as one of the JSON modules it can use), but GAE has it as django.utils.simplejson, so you need to \"alias\" it appropriately.\n"
] |
[
4,
3
] |
[] |
[] |
[
"google_app_engine",
"json",
"jsonpickle",
"python"
] |
stackoverflow_0002003817_google_app_engine_json_jsonpickle_python.txt
|
Q:
Multithreading python application hangs while running its threads
I am trying to create a MainObject which is availible as a DBus service. This MainObject should always stay responsive to other objects/processes and for this non-blocking even while processing its items. for that reason items are processed in a seperate thread one after another (queue-style). You can add items to the MainObject via DBus or CommandLine. I simplified the sample (no dbus, no commandline) to show my problem.
My problem is, that if i reenable 'tt.join()' the application works as expected, but it is blocking to other processes. No wonder, tt.join makes the application wait until the seperate Thread has finished its work. On the other hand, if 'tt.join()' stays disabled, the application does not block to external dbus events, but never comes to 'ThreadTest done!' (look at real output)
What i want is, my expected output but the applications should stay responsive.
#!/usr/bin/python2.5
import gobject
import threading
import re
import time
class ThreadTest(threading.Thread):
def __init__(self):
threading.Thread.__init__ (self)
print ' ThreadTest created!'
def run(self):
print ' ThreadTest running ...'
time.sleep(1)
print ' ThreadTest done!'
return True
class MainObject():
def __init__(self):
self.timer = gobject.timeout_add(1000, self.update)
self.loop = gobject.MainLoop()
print 'MainObject created!'
def update(self):
print 'MainObject updating ...'
if self.check_running() == False:
tt = ThreadTest()
tt.start()
#tt.join()
return True
def check_running(self):
running = False
expr = re.compile('ThreadTest')
for threadstr in threading.enumerate():
matches = expr.findall(str(threadstr))
if matches:
running = True
return running
mo = MainObject()
mo.loop.run()
expected output:
MainObject created!
MainObject updating ...
ThreadTest created!
ThreadTest running ...
ThreadTest done!
MainObject updating ...
ThreadTest created!
ThreadTest running ...
ThreadTest done!
MainObject updating ...
ThreadTest created!
ThreadTest running ...
ThreadTest done!
MainObject updating ...
ThreadTest created!
ThreadTest running ...
ThreadTest done!
MainObject updating ...
ThreadTest created!
ThreadTest running ...
ThreadTest done!
real output:
MainObject created!
MainObject updating ...
ThreadTest created!
ThreadTest running ...
MainObject updating ...
MainObject updating ...
MainObject updating ...
MainObject updating ...
MainObject updating ...
MainObject updating ...
MainObject updating ...
MainObject updating ...
MainObject updating ...
A:
The gobject bindings by default aren't multithread-aware. Please try to do the following just after you have imported gobject:
gobject.threads_init()
A:
Threads in python can be a trap -- it is an open problem, actually.
The main problem is the GIL - Python's Global Interpreter Lock.
One of the ways they invented to overcome this is the "multiprocessing" module (new in python 2.6) - it preserves the "threading" interface, but actually runs the code in a separate process:
You could try jsut replacing htreading by multiprocessing -- but: do all the dbus interaction, GUI, etc.. on a main "thread" - (i.e. a single process) - and trade data with the sub-proccesses (strings, lists, dictionaries, etc)... that would work fine.
Also, I can't figure out why all this regexp Voodo just to check if a given string is present on the return value of threading.enumerate??
Python has even the "in" operator (so you don't even have to use the str's index, or find methods):
you can replace that entire check_running method for:
def check_running(self):
return 'ThreadTest' in str(threading.enumerate())
|
Multithreading python application hangs while running its threads
|
I am trying to create a MainObject which is availible as a DBus service. This MainObject should always stay responsive to other objects/processes and for this non-blocking even while processing its items. for that reason items are processed in a seperate thread one after another (queue-style). You can add items to the MainObject via DBus or CommandLine. I simplified the sample (no dbus, no commandline) to show my problem.
My problem is, that if i reenable 'tt.join()' the application works as expected, but it is blocking to other processes. No wonder, tt.join makes the application wait until the seperate Thread has finished its work. On the other hand, if 'tt.join()' stays disabled, the application does not block to external dbus events, but never comes to 'ThreadTest done!' (look at real output)
What i want is, my expected output but the applications should stay responsive.
#!/usr/bin/python2.5
import gobject
import threading
import re
import time
class ThreadTest(threading.Thread):
def __init__(self):
threading.Thread.__init__ (self)
print ' ThreadTest created!'
def run(self):
print ' ThreadTest running ...'
time.sleep(1)
print ' ThreadTest done!'
return True
class MainObject():
def __init__(self):
self.timer = gobject.timeout_add(1000, self.update)
self.loop = gobject.MainLoop()
print 'MainObject created!'
def update(self):
print 'MainObject updating ...'
if self.check_running() == False:
tt = ThreadTest()
tt.start()
#tt.join()
return True
def check_running(self):
running = False
expr = re.compile('ThreadTest')
for threadstr in threading.enumerate():
matches = expr.findall(str(threadstr))
if matches:
running = True
return running
mo = MainObject()
mo.loop.run()
expected output:
MainObject created!
MainObject updating ...
ThreadTest created!
ThreadTest running ...
ThreadTest done!
MainObject updating ...
ThreadTest created!
ThreadTest running ...
ThreadTest done!
MainObject updating ...
ThreadTest created!
ThreadTest running ...
ThreadTest done!
MainObject updating ...
ThreadTest created!
ThreadTest running ...
ThreadTest done!
MainObject updating ...
ThreadTest created!
ThreadTest running ...
ThreadTest done!
real output:
MainObject created!
MainObject updating ...
ThreadTest created!
ThreadTest running ...
MainObject updating ...
MainObject updating ...
MainObject updating ...
MainObject updating ...
MainObject updating ...
MainObject updating ...
MainObject updating ...
MainObject updating ...
MainObject updating ...
|
[
"The gobject bindings by default aren't multithread-aware. Please try to do the following just after you have imported gobject:\ngobject.threads_init()\n\n",
"Threads in python can be a trap -- it is an open problem, actually.\nThe main problem is the GIL - Python's Global Interpreter Lock.\nOne of the ways they invented to overcome this is the \"multiprocessing\" module (new in python 2.6) - it preserves the \"threading\" interface, but actually runs the code in a separate process:\nYou could try jsut replacing htreading by multiprocessing -- but: do all the dbus interaction, GUI, etc.. on a main \"thread\" - (i.e. a single process) - and trade data with the sub-proccesses (strings, lists, dictionaries, etc)... that would work fine. \nAlso, I can't figure out why all this regexp Voodo just to check if a given string is present on the return value of threading.enumerate?? \nPython has even the \"in\" operator (so you don't even have to use the str's index, or find methods):\nyou can replace that entire check_running method for:\ndef check_running(self):\n return 'ThreadTest' in str(threading.enumerate())\n\n"
] |
[
2,
0
] |
[] |
[] |
[
"blocking",
"loops",
"multithreading",
"python",
"sleep"
] |
stackoverflow_0002006132_blocking_loops_multithreading_python_sleep.txt
|
Q:
Python Encoding Issue
I am really lost in all the encoding/decoding issues with Python. Having read quite few docs about how to handle incoming perfectly, i still have issues with few languages, like Korean. Anyhow, here is the what i am doing.
korean_text = korean_text.encode('utf-8', 'ignore')
korean_text = unicode(korean_text, 'utf-8')
I save the above data to database, which goes through fine.
Later when i need to display data, i fetch content from db, and do the following:
korean_text = korean_text.encode( 'utf-8' )
print korean_text
And all i see is '???' echoed on the browser. Can someone please let me know what is the right way to save and display above data.
Thanks
A:
Even having read some docs, you seem to be confused on how unicode works.
Unicode is not an encoding. Unicode is the absence of encodings.
utf-8 is not unicode. utf-8 is an encoding.
You decode utf-8 bytestrings to get unicode. You encode unicode using an encoding, say, utf-8, to get an encoded bytestring.
Only bytestrings can be saved to disk, database, or sent on a network, or printed on a printer, or screen. Unicode only exists inside your code.
The good practice is to decode everything you get as early as possible, work with it decoded, as unicode, in all your code, and then encode it as late as possible, when the text is ready to leave your program, to screen, database or network.
Now for your problem:
If you have a text that came from the browser, say, from a form, then it is encoded. It is a bytestring. It is not unicode.
You must then decode it to get unicode. Decode it using the encoding the browser used to encode. The correct encoding comes from the browser itself, in the correct HTTP REQUEST header.
Don't use 'ignore' when decoding. Since the browser said which encoding it is using, you shouldn't get any errors. Using 'ignore' means you will hide a bug if there is one.
Perhaps your web framework of choice already does that. I know that django, pylons, werkzeug, cherrypy all do that. In that case you already get unicode.
Now that you have a decoded unicode string, you can encode it using whatever encoding you like to store on the database. utf-8 is a good choice, since it can encode all unicode codepoints.
When you retrieve the data from the database, decode it using the same encoding you used to store it. And then encode it using the encoding you want to use on the page - the one declared in the html meta header <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>. If the encoding is the same used on the previous step, you can skip the decode/reencode since it is already encoded in utf-8.
If you see ??? then the data is being lost on any step above. To know exactly, more information is needed.
A:
Read through this post about handling Unicode in Python.
You basically want to be doing these things:
.encode() text to a particular encoding (such as utf-8) before sending it to the database.
.decode() text back to unicode (from your encoding) when reading it from the database
A:
The problem is most certainly (especially if other non-ASCII characters appear to work fine) that your browser or OS doesn't have the right fonts to display Korean text, or that the default font used by your browser doesn't support Korean. Try to choose another font until it works.
|
Python Encoding Issue
|
I am really lost in all the encoding/decoding issues with Python. Having read quite few docs about how to handle incoming perfectly, i still have issues with few languages, like Korean. Anyhow, here is the what i am doing.
korean_text = korean_text.encode('utf-8', 'ignore')
korean_text = unicode(korean_text, 'utf-8')
I save the above data to database, which goes through fine.
Later when i need to display data, i fetch content from db, and do the following:
korean_text = korean_text.encode( 'utf-8' )
print korean_text
And all i see is '???' echoed on the browser. Can someone please let me know what is the right way to save and display above data.
Thanks
|
[
"Even having read some docs, you seem to be confused on how unicode works.\n\nUnicode is not an encoding. Unicode is the absence of encodings.\nutf-8 is not unicode. utf-8 is an encoding. \nYou decode utf-8 bytestrings to get unicode. You encode unicode using an encoding, say, utf-8, to get an encoded bytestring.\nOnly bytestrings can be saved to disk, database, or sent on a network, or printed on a printer, or screen. Unicode only exists inside your code.\n\nThe good practice is to decode everything you get as early as possible, work with it decoded, as unicode, in all your code, and then encode it as late as possible, when the text is ready to leave your program, to screen, database or network.\n\nNow for your problem:\nIf you have a text that came from the browser, say, from a form, then it is encoded. It is a bytestring. It is not unicode.\nYou must then decode it to get unicode. Decode it using the encoding the browser used to encode. The correct encoding comes from the browser itself, in the correct HTTP REQUEST header. \nDon't use 'ignore' when decoding. Since the browser said which encoding it is using, you shouldn't get any errors. Using 'ignore' means you will hide a bug if there is one.\nPerhaps your web framework of choice already does that. I know that django, pylons, werkzeug, cherrypy all do that. In that case you already get unicode.\nNow that you have a decoded unicode string, you can encode it using whatever encoding you like to store on the database. utf-8 is a good choice, since it can encode all unicode codepoints.\nWhen you retrieve the data from the database, decode it using the same encoding you used to store it. And then encode it using the encoding you want to use on the page - the one declared in the html meta header <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>. If the encoding is the same used on the previous step, you can skip the decode/reencode since it is already encoded in utf-8.\nIf you see ??? then the data is being lost on any step above. To know exactly, more information is needed.\n",
"Read through this post about handling Unicode in Python.\nYou basically want to be doing these things:\n.encode() text to a particular encoding (such as utf-8) before sending it to the database.\n.decode() text back to unicode (from your encoding) when reading it from the database\n\n",
"The problem is most certainly (especially if other non-ASCII characters appear to work fine) that your browser or OS doesn't have the right fonts to display Korean text, or that the default font used by your browser doesn't support Korean. Try to choose another font until it works.\n"
] |
[
11,
0,
0
] |
[] |
[] |
[
"encoding",
"python",
"utf_8"
] |
stackoverflow_0002006115_encoding_python_utf_8.txt
|
Q:
How to Use Mathematic Equations as Filters in SQLAlchemy
I'm using the SQLAlchemy ORM to construct the MySQL queries in my application, and am perfectly able to add basic filters to the query, like so:
query = meta.Session.query(User).filter(User.user_id==1)
Which gives me something basically equivalent to this:
SELECT * FROM users WHERE user_id = 1
My question is how I would integrate some basic MySQL math functions into my query. So, say for instance I wanted to get users near a certain latitude and longitude. So I need to generate this SQL ($mylatitude and $mylongitude are the static latitude and longitude I'm comparing against):
SELECT * FROM users
WHERE SQRT(POW(69.1 * (latitude - $mylatitude),2) + POW(53.0 * (longitude - $mylongitude),2)) < 5
Is there a way I can incorporate these functions into a query using the SQLAlchemy ORM?
A:
You can use literal SQL in your filter, see here: http://www.sqlalchemy.org/docs/05/ormtutorial.html?highlight=text#using-literal-sql
For example:
clause = "SQRT(POW(69.1 * (latitude - :lat),2) + POW(53.0 * (longitude - :long),2)) < 5"
query = meta.Session.query(User).filter(clause).params(lat=my_latitude, long=my_longitude)
A:
I'd use the query builder interface and the func SQL function constructor to abstract the calculation as a function. This way you can use it freely with aliases or joins.
User.coords = classmethod(lambda s: (s.latitude, s.longitude))
def calc_distance(latlong1, latlong2):
return func.sqrt(func.pow(69.1 * (latlong1[0] - latlong2[0]),2)
+ func.pow(53.0 * (latlong1[1] - latlong2[1]),2))
meta.Session.query(User).filter(calc_distance(User.coords(), (my_lat, my_long)) < 5)
|
How to Use Mathematic Equations as Filters in SQLAlchemy
|
I'm using the SQLAlchemy ORM to construct the MySQL queries in my application, and am perfectly able to add basic filters to the query, like so:
query = meta.Session.query(User).filter(User.user_id==1)
Which gives me something basically equivalent to this:
SELECT * FROM users WHERE user_id = 1
My question is how I would integrate some basic MySQL math functions into my query. So, say for instance I wanted to get users near a certain latitude and longitude. So I need to generate this SQL ($mylatitude and $mylongitude are the static latitude and longitude I'm comparing against):
SELECT * FROM users
WHERE SQRT(POW(69.1 * (latitude - $mylatitude),2) + POW(53.0 * (longitude - $mylongitude),2)) < 5
Is there a way I can incorporate these functions into a query using the SQLAlchemy ORM?
|
[
"You can use literal SQL in your filter, see here: http://www.sqlalchemy.org/docs/05/ormtutorial.html?highlight=text#using-literal-sql\nFor example:\nclause = \"SQRT(POW(69.1 * (latitude - :lat),2) + POW(53.0 * (longitude - :long),2)) < 5\"\nquery = meta.Session.query(User).filter(clause).params(lat=my_latitude, long=my_longitude)\n\n",
"I'd use the query builder interface and the func SQL function constructor to abstract the calculation as a function. This way you can use it freely with aliases or joins.\nUser.coords = classmethod(lambda s: (s.latitude, s.longitude))\n\ndef calc_distance(latlong1, latlong2):\n return func.sqrt(func.pow(69.1 * (latlong1[0] - latlong2[0]),2)\n + func.pow(53.0 * (latlong1[1] - latlong2[1]),2))\n\nmeta.Session.query(User).filter(calc_distance(User.coords(), (my_lat, my_long)) < 5)\n\n"
] |
[
5,
4
] |
[] |
[] |
[
"mysql",
"orm",
"python",
"sqlalchemy"
] |
stackoverflow_0002002024_mysql_orm_python_sqlalchemy.txt
|
Q:
making undo in python
first of all .. sorry if my english was bad. its my 3rd language
im working on a paint software that draw over images and save them again ( for commenting propose ) i use pile and wxpython.
but im still having problems with some features ..
what is the ideal way to make the undo option ?
another question .. when the user scale the picture ( by enlarging the drawing frame)
the lines doesn't scale . how do i make that happen .
i got rid of all those problems by saving temporary images to the hard disk whenever the user finishes a line and assign that new picture ( the old one with a line on it) to the frame .
undo and redo will is done by switching between those images ...
so when user scale image the line will scale too . but that is bad since it takes a lot of HDD space ( when you draw 1000 lines ) and its slow because it assigns a new image every time a user draw a line
hope my idea is clear
does anyone have a better solution ?
A:
The canonical strategy is to use the Command pattern. You'll represent the things you can do as Command objects, and each object is placed on a stack. The state of the application is then defined by an initial state plus everything that the stack has. Thus, the "undo" operation is then just popping the top stack item and reapplying the remaining items to the initial state.
In practice, sometimes it's expensive to keep applying those operations to the initial state to generate the current state. For example, this might be true with something like a complex series of image adjustments, like you might find in Photoshop. In cases like that, it's common to keep an alternating state-stack series in memory:
+---------+
| state_0 |
+---------+ +---------+
| next -------> | stack_0 |
+---------+ +---------+
| data | +---------+
| next -------> | state_1 |
+---------+ +---------+
| next ----- ...
+---------+
Each stack_i holds commands until it exceeds some pre-set complexity (e.g., the commands exceed computational cost X) or ordinal (e.g. the stack holds X or more commands) limit. At that point, a new intermediate state object state_i+1 is created to encapsulate the state, and a new, empty stack stack_i+1 is created to hold new commands.
In this way, you only have to apply a small sequence of commands to the last snapshotted state to get the current state. This comes at the expense of memorizing entire states, which may not be feasible for very large applications, but you can choose to snapshot only a set of the state to optimize.
A:
Also, keep in mind that Python's functions are first-class objects, which can make implementing the Command pattern very smooth:
actions = []
def do_action1(arg1, arg2):
# .. do the action ..
# remember we did the action:
actions.append(do_action1, (arg1, arg2))
def do_action2(arg1, arg2):
# .. do the action ..
actions.append(do_action2, (arg1, arg2))
def replay_actions():
for fn, args in actions:
fn(*args)
|
making undo in python
|
first of all .. sorry if my english was bad. its my 3rd language
im working on a paint software that draw over images and save them again ( for commenting propose ) i use pile and wxpython.
but im still having problems with some features ..
what is the ideal way to make the undo option ?
another question .. when the user scale the picture ( by enlarging the drawing frame)
the lines doesn't scale . how do i make that happen .
i got rid of all those problems by saving temporary images to the hard disk whenever the user finishes a line and assign that new picture ( the old one with a line on it) to the frame .
undo and redo will is done by switching between those images ...
so when user scale image the line will scale too . but that is bad since it takes a lot of HDD space ( when you draw 1000 lines ) and its slow because it assigns a new image every time a user draw a line
hope my idea is clear
does anyone have a better solution ?
|
[
"The canonical strategy is to use the Command pattern. You'll represent the things you can do as Command objects, and each object is placed on a stack. The state of the application is then defined by an initial state plus everything that the stack has. Thus, the \"undo\" operation is then just popping the top stack item and reapplying the remaining items to the initial state.\nIn practice, sometimes it's expensive to keep applying those operations to the initial state to generate the current state. For example, this might be true with something like a complex series of image adjustments, like you might find in Photoshop. In cases like that, it's common to keep an alternating state-stack series in memory:\n+---------+\n| state_0 |\n+---------+ +---------+\n| next -------> | stack_0 |\n+---------+ +---------+\n | data | +---------+\n | next -------> | state_1 |\n +---------+ +---------+\n | next ----- ...\n +---------+\n\nEach stack_i holds commands until it exceeds some pre-set complexity (e.g., the commands exceed computational cost X) or ordinal (e.g. the stack holds X or more commands) limit. At that point, a new intermediate state object state_i+1 is created to encapsulate the state, and a new, empty stack stack_i+1 is created to hold new commands.\nIn this way, you only have to apply a small sequence of commands to the last snapshotted state to get the current state. This comes at the expense of memorizing entire states, which may not be feasible for very large applications, but you can choose to snapshot only a set of the state to optimize.\n",
"Also, keep in mind that Python's functions are first-class objects, which can make implementing the Command pattern very smooth:\nactions = []\n\ndef do_action1(arg1, arg2):\n # .. do the action ..\n\n # remember we did the action:\n actions.append(do_action1, (arg1, arg2))\n\ndef do_action2(arg1, arg2):\n # .. do the action ..\n actions.append(do_action2, (arg1, arg2))\n\ndef replay_actions():\n for fn, args in actions:\n fn(*args)\n\n"
] |
[
13,
9
] |
[] |
[] |
[
"image",
"python",
"python_imaging_library",
"undo",
"wxpython"
] |
stackoverflow_0002006404_image_python_python_imaging_library_undo_wxpython.txt
|
Q:
Why is Django's Meta an old-style class?
I noticed that in Django models, there is a class Meta which makes some additional definitions about the model.
My question is, why is this done as an old-style class? (i.e. not subclassing object?) Is there a reason for this or is this just a custom? Could I do it as a new-style class in my projects?
A:
I believe that there is no real reason (including history, since new-style classes exist since Python 2.2) and that not only can you choose to use a new-style class instead, but that it would probably be a good idea for you to do so (for all the usual reasons).
A:
Since class Meta is never anything but a simple namespace container, there is zero advantage to subclassing object; just eight extra characters to type. Won't hurt anything to do so if you feel like it, though.
|
Why is Django's Meta an old-style class?
|
I noticed that in Django models, there is a class Meta which makes some additional definitions about the model.
My question is, why is this done as an old-style class? (i.e. not subclassing object?) Is there a reason for this or is this just a custom? Could I do it as a new-style class in my projects?
|
[
"I believe that there is no real reason (including history, since new-style classes exist since Python 2.2) and that not only can you choose to use a new-style class instead, but that it would probably be a good idea for you to do so (for all the usual reasons).\n",
"Since class Meta is never anything but a simple namespace container, there is zero advantage to subclassing object; just eight extra characters to type. Won't hurt anything to do so if you feel like it, though.\n"
] |
[
16,
9
] |
[] |
[] |
[
"class",
"django",
"python"
] |
stackoverflow_0002005150_class_django_python.txt
|
Q:
Why are django projects python packages?
Why aren't they simply directories? Any good advice says to keep as much as possible in the apps and not to couple them to the project. The very ability to import an app as project.application discourages this. Why does django-admin.py create the __init__.py at all? The project is perfectly useful without it. What is the justification?
A:
We have a single project that we "subclass" of sorts for other projects. So we have other projects that import stuff from the main project. I guess for us it provides the common namespace that contains all the other apps.
We could move to a package with all our apps in it separate from the projects i guess. Our system has grown rather than been planned.
So I guess my answer is, it provides a good root namespace. (for our needs) :)
A:
There isn't a requirement that apps be inside the project's namespace, to my knowledge. Just that they be on the $PYTHONPATH. As such, they are usable by any other code on the system which shares the same PYTHONPATH.
A:
The core of a project is a settings.py and a root urls.py. Both of those are Python modules, thus they need to be importable somehow. You can put the project directory directly on the Python path and thus make them importable as top-level modules, but that's arguably even worse practice. Better to have the project be a package and the settings and urls be modules within it.
A:
I think the idea is that you can reuse the applications but you don't need to move them from the project where they were initially created. If the project weren't a package you would need to copy/move the application you want to reuse to a python package. Because of that being the project itself a proper python package you can reuse the applications in it without moving the applications to other place.
|
Why are django projects python packages?
|
Why aren't they simply directories? Any good advice says to keep as much as possible in the apps and not to couple them to the project. The very ability to import an app as project.application discourages this. Why does django-admin.py create the __init__.py at all? The project is perfectly useful without it. What is the justification?
|
[
"We have a single project that we \"subclass\" of sorts for other projects. So we have other projects that import stuff from the main project. I guess for us it provides the common namespace that contains all the other apps.\nWe could move to a package with all our apps in it separate from the projects i guess. Our system has grown rather than been planned.\nSo I guess my answer is, it provides a good root namespace. (for our needs) :)\n",
"There isn't a requirement that apps be inside the project's namespace, to my knowledge. Just that they be on the $PYTHONPATH. As such, they are usable by any other code on the system which shares the same PYTHONPATH. \n",
"The core of a project is a settings.py and a root urls.py. Both of those are Python modules, thus they need to be importable somehow. You can put the project directory directly on the Python path and thus make them importable as top-level modules, but that's arguably even worse practice. Better to have the project be a package and the settings and urls be modules within it.\n",
"I think the idea is that you can reuse the applications but you don't need to move them from the project where they were initially created. If the project weren't a package you would need to copy/move the application you want to reuse to a python package. Because of that being the project itself a proper python package you can reuse the applications in it without moving the applications to other place.\n"
] |
[
2,
1,
1,
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002003527_django_python.txt
|
Q:
How to use C# client to consume Django/Python web service (all methods are returning null)?
I have a C# command-line client that I'm testing the consumption of SOAP/WSDL via Django/Python/soaplib created WSDL. I've managed to successfully connect to the web service by adding a service reference. I then call one of service's methods, and the service processes the data I send, but it returns null instead of the integer I'm expecting. Any ideas on how to get back something other than a null response? Thanks for any help or suggestions!
A:
One thing you can do is start by building a manual proxy using WebClient, or WebRequest/WebResponse. Construct your manual proxy to send the desired data to the WS for testing.
Couple of things to check on the WSDL implementation:
The WSDL definition needs to match exactly, including case, for the C# proxy to recognize the values
Namespace definitions need to match exactly, including trailing slashes
Check the profile of the generated proxy and make sure it conforms with what your desired profile is (i.e. basic or none if needed)
If you post your generated proxy we can look at it and see if there is anything out of the ordinary.
A:
We faced the similar problem while consuming a web service it was the type of data returned we were getting data in UTF-16 format.
Please check if you have proper data type in use.
|
How to use C# client to consume Django/Python web service (all methods are returning null)?
|
I have a C# command-line client that I'm testing the consumption of SOAP/WSDL via Django/Python/soaplib created WSDL. I've managed to successfully connect to the web service by adding a service reference. I then call one of service's methods, and the service processes the data I send, but it returns null instead of the integer I'm expecting. Any ideas on how to get back something other than a null response? Thanks for any help or suggestions!
|
[
"One thing you can do is start by building a manual proxy using WebClient, or WebRequest/WebResponse. Construct your manual proxy to send the desired data to the WS for testing.\nCouple of things to check on the WSDL implementation:\n\nThe WSDL definition needs to match exactly, including case, for the C# proxy to recognize the values\nNamespace definitions need to match exactly, including trailing slashes\nCheck the profile of the generated proxy and make sure it conforms with what your desired profile is (i.e. basic or none if needed)\n\nIf you post your generated proxy we can look at it and see if there is anything out of the ordinary.\n",
"We faced the similar problem while consuming a web service it was the type of data returned we were getting data in UTF-16 format. \nPlease check if you have proper data type in use.\n"
] |
[
0,
0
] |
[] |
[] |
[
"c#",
"django",
"python",
"soap",
"wsdl"
] |
stackoverflow_0002007908_c#_django_python_soap_wsdl.txt
|
Q:
How to share data between python processes without writing to disk
Helllo,
I would like to share small amounts of data (< 1K) between python and processes. The data is physical pc/104 IO data which changes rapidly and often (24x7x365). There will be a single "server" writing the data and multiple clients reading portions of it.
The system this will run on uses flash memory (CF card) rather than a hard drive, so I'm worried about wearing out the flash memory with a file based scheme. I'd also like to use less power (processor time) as we are 100% solar powered.
Is this a valid worry? We could possibly change the CF card to a SSD.
Does changing a value using mmap physically write the data to disk or is this a virtual file?
We will be running on Debian so perhaps the POSIX IPC for python module is the best solution. Has anyone used it?
Has anyone tried the Python Object Sharing (POSH) module? It looks promising at first glance but it is in "Alpha" and doesn't seem to be actively being developed.
Thank You
UPDATE:
We slowed down the maximum data update rate to about 10 Hz, but more typically 1 Hz. Clients will only be notified when a value changes rather than at a constant update rate.
We have gone to a multiple servers/multiple clients model where each server specializes in a certain type of instrument or function.
Since it turned out that most of the programming was going to be done by Java programmers, we ended up using JSON-RPC over TCP. The servers wil be written in Java but I still hope to write the main client in Python and am investigation JSON-RPC implementations.
A:
An alternative to writing the data to file in the server process might be to directly write to the client processes:
Use UNIX domain sockets (or TCP/IP sockets if the clients run on different machines) to connect each client to the server, and have the server write into those sockets. Depending on your particular processing model, choosing a client/socket may be done by the server (e.g. round-robin) or by the clients signalling that they're ready for more.
A:
Create a ramfs partition and write to that. (You could use tmpfs, but unlike tmpfs, ramfs is not swapped to disk). However, as ramfs doesn't have a size limit, you must take care that you don't run out of memory; since you're only writing a tiny bit of data there, it shouldn't be a problem.
This way, your data won't ever be written to a disk (note: you will lose them if power fails).
See also the ramfs docs.
A:
According to the Wikipedia article about the mmap system call, memory mapped files contents are written back to disk when updated.
Have you looked at the multiprocessing module (in standard library) - especially the part Sharing state between processes?
Ramfs as mentioned by Piskvor also seems like a good solution - especially when not all processes are written in Python.
A:
When running on flash systems, make sure your filesystem is designed properly to maximize the life of the flash memory (wear levelling). JFFS and, I believe, others are now capable of doing this effectively. If you use such a system, you shouldn't be overly concerned about using the flash, but certainly if you're writing a constant stream of data you'd want to avoid doing that on the flash.
Using a RAM filesystem is a good idea. Better yet is to avoid filesystems entirely if the system design will let you. To that end you mention POSH. I've never tried it, but we've found Pyro ("PYthon Remote Objects") to be an elegant and effective solution in some similar cases.
And of course there's the standard library multiprocessing module, which bears some similarities in terms of how it communicates between processes. I'd start there for any new development in this area, and go elsewhere only if it failed to pan out.
|
How to share data between python processes without writing to disk
|
Helllo,
I would like to share small amounts of data (< 1K) between python and processes. The data is physical pc/104 IO data which changes rapidly and often (24x7x365). There will be a single "server" writing the data and multiple clients reading portions of it.
The system this will run on uses flash memory (CF card) rather than a hard drive, so I'm worried about wearing out the flash memory with a file based scheme. I'd also like to use less power (processor time) as we are 100% solar powered.
Is this a valid worry? We could possibly change the CF card to a SSD.
Does changing a value using mmap physically write the data to disk or is this a virtual file?
We will be running on Debian so perhaps the POSIX IPC for python module is the best solution. Has anyone used it?
Has anyone tried the Python Object Sharing (POSH) module? It looks promising at first glance but it is in "Alpha" and doesn't seem to be actively being developed.
Thank You
UPDATE:
We slowed down the maximum data update rate to about 10 Hz, but more typically 1 Hz. Clients will only be notified when a value changes rather than at a constant update rate.
We have gone to a multiple servers/multiple clients model where each server specializes in a certain type of instrument or function.
Since it turned out that most of the programming was going to be done by Java programmers, we ended up using JSON-RPC over TCP. The servers wil be written in Java but I still hope to write the main client in Python and am investigation JSON-RPC implementations.
|
[
"An alternative to writing the data to file in the server process might be to directly write to the client processes:\nUse UNIX domain sockets (or TCP/IP sockets if the clients run on different machines) to connect each client to the server, and have the server write into those sockets. Depending on your particular processing model, choosing a client/socket may be done by the server (e.g. round-robin) or by the clients signalling that they're ready for more.\n",
"Create a ramfs partition and write to that. (You could use tmpfs, but unlike tmpfs, ramfs is not swapped to disk). However, as ramfs doesn't have a size limit, you must take care that you don't run out of memory; since you're only writing a tiny bit of data there, it shouldn't be a problem.\nThis way, your data won't ever be written to a disk (note: you will lose them if power fails).\nSee also the ramfs docs.\n",
"According to the Wikipedia article about the mmap system call, memory mapped files contents are written back to disk when updated.\nHave you looked at the multiprocessing module (in standard library) - especially the part Sharing state between processes?\nRamfs as mentioned by Piskvor also seems like a good solution - especially when not all processes are written in Python.\n",
"When running on flash systems, make sure your filesystem is designed properly to maximize the life of the flash memory (wear levelling). JFFS and, I believe, others are now capable of doing this effectively. If you use such a system, you shouldn't be overly concerned about using the flash, but certainly if you're writing a constant stream of data you'd want to avoid doing that on the flash.\nUsing a RAM filesystem is a good idea. Better yet is to avoid filesystems entirely if the system design will let you. To that end you mention POSH. I've never tried it, but we've found Pyro (\"PYthon Remote Objects\") to be an elegant and effective solution in some similar cases.\nAnd of course there's the standard library multiprocessing module, which bears some similarities in terms of how it communicates between processes. I'd start there for any new development in this area, and go elsewhere only if it failed to pan out.\n"
] |
[
8,
4,
2,
0
] |
[] |
[] |
[
"ipc",
"json_rpc",
"mmap",
"pc104",
"python"
] |
stackoverflow_0002006624_ipc_json_rpc_mmap_pc104_python.txt
|
Q:
Lua vs PHP/Python/JSP/etc
I'm about to begin my next web development project and wanted to hear about the merits of Lua within the web-development space.
How does Lua compare to PHP/Python/JSP/etc.. for web development?
Any reason why Lua would be a poor choice for a web application language vs the others?
A:
In brief:
Lua gives you a smaller, simpler system that you can understand in its entirety, but it is in a much smaller ecosystem; Kepler is all you get, and you will probably have to build some of your own stuff. I find this easy and fun (I make heavy use of the Lua bindings to the Expat parser and the Lua Object Model, which are part of Kepler), but others may prefer to use what everyone else is using.
PHP started out as more of a macro processor than a language, and although it has improved over the years, when people say "X has really gotten a lot better", I tend to be wary of X. I find PHP offputting, but there is a huge ecosystem for web development.
Python is a nice language but much bigger than Lua, and in the throes of a major revision (transition from 2.5 to 3.x). Again you get a big ecosystem; the problem I have with Python is that the language and system are too big for any one person to understand all of. I don't like to be in this situation if I don't have to.
Ruby is a bit of a cleaner language design, and the large Rails ecosystem is a winner. Ruby is less complex than Python but more complex than Lua. Rails is a bit of a beast.
It comes down to this question:
Would you rather understand all the software in your system, even if you have to build a lot of things yourself?
Or would you rather have a lot of things already built for you, even if you wind up not understanding exactly how every piece works?
If you want to understand everything, Lua is your game. If you want a lot of stuff already built for you, I can't advise you how to pick among PHP/Python/JSP/Rails and so on.
More on Lua and Python at Which language is better to use, Lua or Python?
A:
Using Lua for web development is pretty rare...you could do it, but it will be a lot more time consuming than using a language that has matured as a web developing language (PHP) or has good web related libraries (python/ruby/etc.) If you do go with Lua, this means you may end up "recreating the wheel" a lot for what may be easily available in mature web languages.
The better question is, what does Lua offer that you need which is not offered in the other languages you listed? Or do you want to help Lua become a better web development platform by creating a Lua MVC framework like Rails did for Ruby?
A:
The Kepler project is probably the best known starting point for web application development in Lua. They have a mailing list whose archives will have a lot of discussion of the merits of various approaches.
The Kepler site is itself built in a CMS framework called Sputnik written almost entirely in Lua, and based on the Kepler project.
The typical approach with Lua is to use a language suited to interfacing to various system components to implement those interfaces, and to use Lua for business logic and glue. Kepler provides libraries written largely in C that provide access to file systems, databases, and the network to Lua code. It also provides a defined API layer to interface with the web server, with implementations for Apache, any CGI capable server, and Xavante which is a complete web server implemented mostly in Lua.
A:
I'm coming a little late ... but i wanted to throw in another language: Haxe
why?
Haxe is an open source language, driven by a quite small, but active community
Haxe is a platform indepented language ... targets are:
flash player 6-8 and 9-10 bytecode or ActionScript 3 source code
JavaScript source code
PHP source code
NekoVM bytecode or Neko source code (NekoVM is a lightweight and extensible VM, suitable for both server developement, and desktop apps)
C++ source code
Android Java source code is currently being worked on
this means, that as a web developer, you can write both rich clients as well as servers in the same language ... the same code can be later reused for desktop/mobile apps
Haxe is a very expressive and powerful language, featuring:
first class functions (anonymous functions and methods, which are the same in Haxe) and closures as well as Enums with parameters (much like algebraic types) that allow the use of functional approaches
good type system, including generics, structural subtyping etc. ... to simplify its use, the compiler has a very helpful type inference, that ensures code is strictly typed, but saves you a lot of redundancy (variable type is determined by initialization, function return type by type of returned expressions) ...
cross-platform API, including everything from dynamic arrays, to reflection/introspection and a remoting package, that alows you to send whole objects from client to server, from one platform to another ...
consistent and radical language design ... of course it has a few flaws, but these mostly come from the fact, that it targets extremely different platforms ...
girls love it and it'll make you real rich ... :D
the biggest flaw about Haxe is, that it allows untyped coding, at the cost of platform specific execution of untyped code ... when well typed (which is not a lot of work with Haxe in fact), code will be executed the same way on all platforms ... if not, result vary depending on runtime handling of the platform itself ...
to put it in a few words: it's a great language, that allows you to target many platforms ... it's young, it's growing, and you can participate ...
A:
As far as Lua web frameworks, there is also LuCI. It is mostly used for small embedded systems. We're just starting a project using it, so I can't comment on it too much right now. We're just doing some simple configuration screens similar to what is already provided as examples, so I'm sure it will be sufficient for our needs.
A:
If it's only the language, then I agree with Norman. If the web development framework is important to you, then you have to consider Ruby because RoR is a very mature framework. I love Python, but there seems to be quite a few frameworks to choose from, none of them is dominant. CherryPy, Django, Pylons, web2py, Zope 2, Zope 3, etc. One important indicator to me is that there are more RoR jobs on the market than any other (language, framework).
|
Lua vs PHP/Python/JSP/etc
|
I'm about to begin my next web development project and wanted to hear about the merits of Lua within the web-development space.
How does Lua compare to PHP/Python/JSP/etc.. for web development?
Any reason why Lua would be a poor choice for a web application language vs the others?
|
[
"In brief:\n\nLua gives you a smaller, simpler system that you can understand in its entirety, but it is in a much smaller ecosystem; Kepler is all you get, and you will probably have to build some of your own stuff. I find this easy and fun (I make heavy use of the Lua bindings to the Expat parser and the Lua Object Model, which are part of Kepler), but others may prefer to use what everyone else is using.\nPHP started out as more of a macro processor than a language, and although it has improved over the years, when people say \"X has really gotten a lot better\", I tend to be wary of X. I find PHP offputting, but there is a huge ecosystem for web development.\nPython is a nice language but much bigger than Lua, and in the throes of a major revision (transition from 2.5 to 3.x). Again you get a big ecosystem; the problem I have with Python is that the language and system are too big for any one person to understand all of. I don't like to be in this situation if I don't have to.\nRuby is a bit of a cleaner language design, and the large Rails ecosystem is a winner. Ruby is less complex than Python but more complex than Lua. Rails is a bit of a beast.\n\nIt comes down to this question:\n\nWould you rather understand all the software in your system, even if you have to build a lot of things yourself?\nOr would you rather have a lot of things already built for you, even if you wind up not understanding exactly how every piece works?\n\nIf you want to understand everything, Lua is your game. If you want a lot of stuff already built for you, I can't advise you how to pick among PHP/Python/JSP/Rails and so on.\nMore on Lua and Python at Which language is better to use, Lua or Python?\n",
"Using Lua for web development is pretty rare...you could do it, but it will be a lot more time consuming than using a language that has matured as a web developing language (PHP) or has good web related libraries (python/ruby/etc.) If you do go with Lua, this means you may end up \"recreating the wheel\" a lot for what may be easily available in mature web languages.\nThe better question is, what does Lua offer that you need which is not offered in the other languages you listed? Or do you want to help Lua become a better web development platform by creating a Lua MVC framework like Rails did for Ruby?\n",
"The Kepler project is probably the best known starting point for web application development in Lua. They have a mailing list whose archives will have a lot of discussion of the merits of various approaches.\nThe Kepler site is itself built in a CMS framework called Sputnik written almost entirely in Lua, and based on the Kepler project.\nThe typical approach with Lua is to use a language suited to interfacing to various system components to implement those interfaces, and to use Lua for business logic and glue. Kepler provides libraries written largely in C that provide access to file systems, databases, and the network to Lua code. It also provides a defined API layer to interface with the web server, with implementations for Apache, any CGI capable server, and Xavante which is a complete web server implemented mostly in Lua.\n",
"I'm coming a little late ... but i wanted to throw in another language: Haxe\nwhy?\n\nHaxe is an open source language, driven by a quite small, but active community\nHaxe is a platform indepented language ... targets are:\n\nflash player 6-8 and 9-10 bytecode or ActionScript 3 source code\nJavaScript source code\nPHP source code\nNekoVM bytecode or Neko source code (NekoVM is a lightweight and extensible VM, suitable for both server developement, and desktop apps)\nC++ source code\nAndroid Java source code is currently being worked on\n\nthis means, that as a web developer, you can write both rich clients as well as servers in the same language ... the same code can be later reused for desktop/mobile apps\nHaxe is a very expressive and powerful language, featuring:\n\n\nfirst class functions (anonymous functions and methods, which are the same in Haxe) and closures as well as Enums with parameters (much like algebraic types) that allow the use of functional approaches\ngood type system, including generics, structural subtyping etc. ... to simplify its use, the compiler has a very helpful type inference, that ensures code is strictly typed, but saves you a lot of redundancy (variable type is determined by initialization, function return type by type of returned expressions) ...\ncross-platform API, including everything from dynamic arrays, to reflection/introspection and a remoting package, that alows you to send whole objects from client to server, from one platform to another ...\nconsistent and radical language design ... of course it has a few flaws, but these mostly come from the fact, that it targets extremely different platforms ...\n\ngirls love it and it'll make you real rich ... :D\n\nthe biggest flaw about Haxe is, that it allows untyped coding, at the cost of platform specific execution of untyped code ... when well typed (which is not a lot of work with Haxe in fact), code will be executed the same way on all platforms ... if not, result vary depending on runtime handling of the platform itself ...\nto put it in a few words: it's a great language, that allows you to target many platforms ... it's young, it's growing, and you can participate ...\n",
"As far as Lua web frameworks, there is also LuCI. It is mostly used for small embedded systems. We're just starting a project using it, so I can't comment on it too much right now. We're just doing some simple configuration screens similar to what is already provided as examples, so I'm sure it will be sufficient for our needs.\n",
"If it's only the language, then I agree with Norman. If the web development framework is important to you, then you have to consider Ruby because RoR is a very mature framework. I love Python, but there seems to be quite a few frameworks to choose from, none of them is dominant. CherryPy, Django, Pylons, web2py, Zope 2, Zope 3, etc. One important indicator to me is that there are more RoR jobs on the market than any other (language, framework).\n"
] |
[
21,
7,
4,
2,
1,
1
] |
[] |
[] |
[
"lua",
"php",
"python",
"web_applications"
] |
stackoverflow_0001303270_lua_php_python_web_applications.txt
|
Q:
Can you recommend an Amazon AMI for Python?
I want to remove as much complexity as I can from administering Python in on Amazon EC2 following some truly awful experiences with hosting providers who claim support for Python. I am looking for some guidance on which AMI to choose so that I have a stable and easily managed environment which already included Python and ideally an Apache web server and a database.
I am agnostic to Python version, web server, DB and OS as I am still early enough in my development cycle that I can influence those choices. Cost is not a consideration (within bounds) so Windows will work fine if it means easy administration.
Anyone have any practical experience or recommendations they can share?
A:
Try the Ubuntu EC2 images. Python 2.7 is installed by default. The rest you just apt-get install and optionally create an image when the baseline is the way you want it (or just maintain a script that installs all the pieces and run after you create the base Ubuntu instance).
A:
If you can get by with using the Amazon provided ones, I'd recommend it. I tend to use ami-84db39ed.
Honestly though, if you plan on leaving this running all the time, you would probably save a bit of money by just going with a VPS. Amazon tends to be cheaper if you are turning the service on and off over time.
|
Can you recommend an Amazon AMI for Python?
|
I want to remove as much complexity as I can from administering Python in on Amazon EC2 following some truly awful experiences with hosting providers who claim support for Python. I am looking for some guidance on which AMI to choose so that I have a stable and easily managed environment which already included Python and ideally an Apache web server and a database.
I am agnostic to Python version, web server, DB and OS as I am still early enough in my development cycle that I can influence those choices. Cost is not a consideration (within bounds) so Windows will work fine if it means easy administration.
Anyone have any practical experience or recommendations they can share?
|
[
"Try the Ubuntu EC2 images. Python 2.7 is installed by default. The rest you just apt-get install and optionally create an image when the baseline is the way you want it (or just maintain a script that installs all the pieces and run after you create the base Ubuntu instance).\n",
"If you can get by with using the Amazon provided ones, I'd recommend it. I tend to use ami-84db39ed.\nHonestly though, if you plan on leaving this running all the time, you would probably save a bit of money by just going with a VPS. Amazon tends to be cheaper if you are turning the service on and off over time.\n"
] |
[
4,
2
] |
[] |
[] |
[
"amazon_ec2",
"python"
] |
stackoverflow_0002008055_amazon_ec2_python.txt
|
Q:
python struct pack double
I want to convert -123.456 into a C double for network transmission in python. So I tried this:
struct.pack('d', -123.456)
I get this as a result:
'w\xbe\x9f\x1a/\xdd^\xc0'
Obviously there is some hex in there, but what is with the w, /, and ^ sprinkled in there?
A:
They are, respectively, a "w", "/", and "^". Some byte sequences do correspond to ASCII characters.
|
python struct pack double
|
I want to convert -123.456 into a C double for network transmission in python. So I tried this:
struct.pack('d', -123.456)
I get this as a result:
'w\xbe\x9f\x1a/\xdd^\xc0'
Obviously there is some hex in there, but what is with the w, /, and ^ sprinkled in there?
|
[
"They are, respectively, a \"w\", \"/\", and \"^\". Some byte sequences do correspond to ASCII characters.\n"
] |
[
1
] |
[] |
[] |
[
"networking",
"python",
"struct.pack"
] |
stackoverflow_0002008871_networking_python_struct.pack.txt
|
Q:
Any ideas on optimizing this script? (Python)
I'm working on a little script to help me learn the Japanese Kana (Hiragana/Katakana). In total, there are probably 100+ (+||-).
Basically, all it would do is take in the english version and convert it to the character.
ie. a = 'あ' which is 12354 in decimal
What I have so far is this:
hiraDict = { "a" : 12354, "i" : 12356 ...}
if __name__ == "__main__":
if hiraDict.has_key(sys.argv[1]):
print(unichr(hiraDict[sys.argv[1]]))
With 100+ characters, would this work OK or is there a better way to approach this?
A:
No need to check for presence, just get it and provide a default argument if you don't want an exception:
# -*- coding: utf-8 -*-
import sys
hiraDict = {'a': 'あ', 'i': 'い', }
print(hiraDict.get(sys.argv[1], None))
... and for python 2.x:
# -*- coding: utf-8 -*-
import sys
hiraDict = {'a': u'あ', 'i': u'い', }
print hiraDict.get(sys.argv[1], None)
[edit] I just noticed that you want to do this for a number of characters. The following will let you print out a series of characters given as arguments (python 3+):
# -*- coding: utf-8 -*-
import sys
hiraDict = {ord('a'): 'あ', ord('i'): 'い' }
text = " ".join(sys.argv[1:])
print(text.translate(hiraDict))
A:
Put an encoding header as per PEP 263, then use the characters directly:
# -*- coding: utf-8 -*-
hiraDict = {'a': u'あ', 'i': u'い', ...}
A:
From the docs:
has_key(key)
Test for the presence of key in the dictionary. has_key() is
deprecated in favor of key in d.
So rewrite to
if sys.argv[1] in hiraDict:
A:
Not only 100, this would work fine with 100k characters too.
So no need to worry about optimizing performance really, unless you will be using this routine thousands times per second, which you probably would not.
|
Any ideas on optimizing this script? (Python)
|
I'm working on a little script to help me learn the Japanese Kana (Hiragana/Katakana). In total, there are probably 100+ (+||-).
Basically, all it would do is take in the english version and convert it to the character.
ie. a = 'あ' which is 12354 in decimal
What I have so far is this:
hiraDict = { "a" : 12354, "i" : 12356 ...}
if __name__ == "__main__":
if hiraDict.has_key(sys.argv[1]):
print(unichr(hiraDict[sys.argv[1]]))
With 100+ characters, would this work OK or is there a better way to approach this?
|
[
"No need to check for presence, just get it and provide a default argument if you don't want an exception:\n# -*- coding: utf-8 -*-\nimport sys\nhiraDict = {'a': 'あ', 'i': 'い', }\nprint(hiraDict.get(sys.argv[1], None))\n\n... and for python 2.x:\n# -*- coding: utf-8 -*-\nimport sys\nhiraDict = {'a': u'あ', 'i': u'い', }\nprint hiraDict.get(sys.argv[1], None)\n\n[edit] I just noticed that you want to do this for a number of characters. The following will let you print out a series of characters given as arguments (python 3+):\n# -*- coding: utf-8 -*-\nimport sys\nhiraDict = {ord('a'): 'あ', ord('i'): 'い' }\ntext = \" \".join(sys.argv[1:])\nprint(text.translate(hiraDict))\n\n",
"Put an encoding header as per PEP 263, then use the characters directly:\n# -*- coding: utf-8 -*-\nhiraDict = {'a': u'あ', 'i': u'い', ...}\n\n",
"From the docs:\n\nhas_key(key)\nTest for the presence of key in the dictionary. has_key() is\ndeprecated in favor of key in d.\n\nSo rewrite to\nif sys.argv[1] in hiraDict:\n",
"Not only 100, this would work fine with 100k characters too.\nSo no need to worry about optimizing performance really, unless you will be using this routine thousands times per second, which you probably would not.\n"
] |
[
5,
3,
1,
1
] |
[] |
[] |
[
"python",
"unicode"
] |
stackoverflow_0002008891_python_unicode.txt
|
Q:
Learn Go Or Improve My Python/Ruby Knowledge
I was reading about Go, and I can see that it's very good and can be a language used by many developers in some months, but I want to decide a simple thing: Learn Go or improve my Python or Ruby knowledge?
Years developing with Python: 1
Years developing with Ruby: 0.3
A:
If you're just looking to have fun and expand your horizons, then I'd learn Go, since you already know some Python.
If you're looking to improve as a developer, I'd personally recommend working on an actual project (using Python, as it's the language you have the most experience with):
This will take your (Python and general) programming skills to a whole new level
If you choose an interesting project, for example a semi-popular open source project, you'll even have some concrete result to show for your extra work. This will help your resume, help you meet other people interested in programming, etc.
I personally believe that spending the time you would have spent learning a new language by coding actual things you can use, is usually a net win (unless of course, like I said, you're just doing it for some fun recreation or relaxation).
A:
In reality, you should do both; if it's what you want. For me though, out of the two, I'd only look at Python. I have no real interest in languages that are so new.
A:
It depends on what your goals and your needs are.
If you're looking to develop your skills for a job, then go with Python or Ruby. You're unlikely to see Go show up in the workplace for quite some time (if ever) unless you're working at Google. (Even then it's questionable.)
If you want to have fun, do what you want. I think the best decider is, pick a project you want to work on and then choose the language that is best suited for that project.
Other things to consider:
Each language is suited to certain tasks. Go is compiled into machine code, whereas Python and Ruby run in interpreters. Go lends itself to somewhat lower level work. It's also good for concurrent tasks. Higher level tasks might be more suited for Python or Ruby.
Go is an experimental language that's likely to experience changes. These changes may be backward incompatible. If you learn it now, in 6 months or a year you may have to re-learn some of it because it's changed. That said, it can be fun to be a part of something that's on the bleeding edge. And if it does happen to become "the next big thing," you're in on the ground level.
A:
How long have you been working with Python?
If it were me, I'd do my best to maybe get a working knowledge of Go (basic syntax, some familiarity with unique language features), and continue with Python as I normally would.
Eventually you might come up with a small project that Go seems suited for (or you can come up with one now!) and really dive into the language that way.
There's no reason to limit yourself to just one. :)
A:
It's up to you. You should probably do both if you can, because that way you will have more tools on your metaphorical programmer's belt.
There are a number of things that I think are worth considering whenever I'm in a similar dilemma.
Is a new language (not just unfamiliar, but actually new, like Go) likely to catch on? (If so, it will become practically NECESSARY to learn it, rather than just a good idea.)
You will need to spend some time to learn the unfamiliar language. Will this time investment result in some sort of positive return? The obvious one here is development time (i.e., can you eventually get more done and get back the time you spent to learn it), but if the language is superior in other ways (runs faster or with less memory, is best for your particular problem domain) those might factor in too.
Will learning the unfamiliar language allow you to solve a relevant/important/urgent problem that cannot be solved with what you already know?
Unfortunately, none of us can tell you how to weigh each of these concerns. You'll need to think about it really carefully and come to the answer on your own.
A:
First of all, it's a very very personal question, and my first recommendation will be , if you think so, try Go for one month or so, learning the basics, and then deciding... Each one has the mind fitted more to some particular languages than another...
I also would recommend keep using both Python and Ruby, if you're interested, you have enough experience to use them comfortably (I think), so the next months you could experience a great boost in your experience using them...
For an strict utilitarian point of view, learning Go extensively could be a risk move, but worthy if begins to being using and you're one of the very few people with some experience when everyone are just beginning to learn the syntax...
A:
These two languages accomplish different goals. Go is only 20% slower than C. If you want crazy speed and easy parallelism, then learn Go. However, readability was not a design goal. Also, it has no exceptions. It can be used for real-time products though ...
A:
IMO you should improve your Python knowledge. Python is a widely adopted language, whereas
Go is still at a very, very early stage and there's no reason to believe that it will become successful.
From a purely utilitarian perspective, you will get a lot more value from learning Python.
A:
It's not easy to answer this without knowing how good your Python is, or what you do, or where you'd use Go. If you're looking for employment, I suspect Python is the way to go. I'd be surprised to find anyone is using Go for major projects at the moment (outside Google).
Note also that Go is by no means finalised. See here for the Go roadmap, and note the potential changes in the future. So you may be trying to hit a moving target currently.
A:
Python is a available for most operating systems, it's generally accepted as a scriptin language, and it has matured to production quality.
Go is a research language that's only available in beta quality on Linux and OS X. Nowhere else. It's interesting from an intellectual point of view in that you can learn and apply a few concepts (typed channels combined with easy multitasking) that are otherwise difficult to use.
As for Go, you might perhaps take a look at AT&T's "Plan 9" operating system first. It comes with a programming language called "Aleph" with also is C-based, has channels and multitasking. Looks to me like Go is a reimplementation of Aleph on more main-stream operating systems.
|
Learn Go Or Improve My Python/Ruby Knowledge
|
I was reading about Go, and I can see that it's very good and can be a language used by many developers in some months, but I want to decide a simple thing: Learn Go or improve my Python or Ruby knowledge?
Years developing with Python: 1
Years developing with Ruby: 0.3
|
[
"If you're just looking to have fun and expand your horizons, then I'd learn Go, since you already know some Python.\nIf you're looking to improve as a developer, I'd personally recommend working on an actual project (using Python, as it's the language you have the most experience with):\n\nThis will take your (Python and general) programming skills to a whole new level\nIf you choose an interesting project, for example a semi-popular open source project, you'll even have some concrete result to show for your extra work. This will help your resume, help you meet other people interested in programming, etc.\n\nI personally believe that spending the time you would have spent learning a new language by coding actual things you can use, is usually a net win (unless of course, like I said, you're just doing it for some fun recreation or relaxation).\n",
"In reality, you should do both; if it's what you want. For me though, out of the two, I'd only look at Python. I have no real interest in languages that are so new.\n",
"It depends on what your goals and your needs are.\nIf you're looking to develop your skills for a job, then go with Python or Ruby. You're unlikely to see Go show up in the workplace for quite some time (if ever) unless you're working at Google. (Even then it's questionable.)\nIf you want to have fun, do what you want. I think the best decider is, pick a project you want to work on and then choose the language that is best suited for that project.\nOther things to consider:\n\nEach language is suited to certain tasks. Go is compiled into machine code, whereas Python and Ruby run in interpreters. Go lends itself to somewhat lower level work. It's also good for concurrent tasks. Higher level tasks might be more suited for Python or Ruby.\nGo is an experimental language that's likely to experience changes. These changes may be backward incompatible. If you learn it now, in 6 months or a year you may have to re-learn some of it because it's changed. That said, it can be fun to be a part of something that's on the bleeding edge. And if it does happen to become \"the next big thing,\" you're in on the ground level.\n\n",
"How long have you been working with Python?\nIf it were me, I'd do my best to maybe get a working knowledge of Go (basic syntax, some familiarity with unique language features), and continue with Python as I normally would.\nEventually you might come up with a small project that Go seems suited for (or you can come up with one now!) and really dive into the language that way.\nThere's no reason to limit yourself to just one. :)\n",
"It's up to you. You should probably do both if you can, because that way you will have more tools on your metaphorical programmer's belt.\nThere are a number of things that I think are worth considering whenever I'm in a similar dilemma.\nIs a new language (not just unfamiliar, but actually new, like Go) likely to catch on? (If so, it will become practically NECESSARY to learn it, rather than just a good idea.)\nYou will need to spend some time to learn the unfamiliar language. Will this time investment result in some sort of positive return? The obvious one here is development time (i.e., can you eventually get more done and get back the time you spent to learn it), but if the language is superior in other ways (runs faster or with less memory, is best for your particular problem domain) those might factor in too.\nWill learning the unfamiliar language allow you to solve a relevant/important/urgent problem that cannot be solved with what you already know?\nUnfortunately, none of us can tell you how to weigh each of these concerns. You'll need to think about it really carefully and come to the answer on your own.\n",
"First of all, it's a very very personal question, and my first recommendation will be , if you think so, try Go for one month or so, learning the basics, and then deciding... Each one has the mind fitted more to some particular languages than another...\nI also would recommend keep using both Python and Ruby, if you're interested, you have enough experience to use them comfortably (I think), so the next months you could experience a great boost in your experience using them...\nFor an strict utilitarian point of view, learning Go extensively could be a risk move, but worthy if begins to being using and you're one of the very few people with some experience when everyone are just beginning to learn the syntax... \n",
"These two languages accomplish different goals. Go is only 20% slower than C. If you want crazy speed and easy parallelism, then learn Go. However, readability was not a design goal. Also, it has no exceptions. It can be used for real-time products though ...\n",
"IMO you should improve your Python knowledge. Python is a widely adopted language, whereas\nGo is still at a very, very early stage and there's no reason to believe that it will become successful.\nFrom a purely utilitarian perspective, you will get a lot more value from learning Python.\n",
"It's not easy to answer this without knowing how good your Python is, or what you do, or where you'd use Go. If you're looking for employment, I suspect Python is the way to go. I'd be surprised to find anyone is using Go for major projects at the moment (outside Google).\nNote also that Go is by no means finalised. See here for the Go roadmap, and note the potential changes in the future. So you may be trying to hit a moving target currently.\n",
"Python is a available for most operating systems, it's generally accepted as a scriptin language, and it has matured to production quality.\nGo is a research language that's only available in beta quality on Linux and OS X. Nowhere else. It's interesting from an intellectual point of view in that you can learn and apply a few concepts (typed channels combined with easy multitasking) that are otherwise difficult to use. \nAs for Go, you might perhaps take a look at AT&T's \"Plan 9\" operating system first. It comes with a programming language called \"Aleph\" with also is C-based, has channels and multitasking. Looks to me like Go is a reimplementation of Aleph on more main-stream operating systems.\n"
] |
[
19,
9,
8,
3,
2,
2,
1,
1,
1,
1
] |
[] |
[] |
[
"go",
"python",
"ruby"
] |
stackoverflow_0002009194_go_python_ruby.txt
|
Q:
How to debug dynamically defined functions in Python?
Is there a way to debug a function that is defined dynamically in run time?
Or at least is there an easy way to find out where this function is produced?
Update to give more detail:
I used inspect module:
ipdb> inspect.getmodule(im.get_thumbnail_url)
Out[0]: <module 'django.utils.functional' from 'C:\java\python\Python25\Lib\site
-packages\django\utils\functional.pyc'>
ipdb> inspect.getsource(im.get_thumbnail_url)
Out[0]: ' def _curried(*moreargs, **morekwargs):\n return _curried_fun
c(*(args+moreargs), **dict(kwargs, **morekwargs))\n'
Here inspect shows that the get_thumbnail_url method of photos.models.Image class of pinax is produced by django.utils.functional.curry._curried function. But it still doesn't show where the method is produced, namely where is _curried function called. This information is necessary to find out how get_thumbnail_url is implemented.
I can put pdb inside _curried function, but then it breaks lots of times there because this is a very frequently used function call. I need to have some distinguishing feature to use breakpoint condition.
Update about solution:
Thanks for all suggestions. I found out the solution. Let me explain how I found it. Maybe it will help other people:
First, I searched for 'get_thumbnail_url' term in pinax source code. No result.
Second, I searched for 'thumbnail' term in pinax source code. No useful result.
Lastly, I searched for 'curry' term in pinax source code. The following was one of several results:
def add_accessor_methods(self, *args, **kwargs):
for size in PhotoSizeCache().sizes.keys():
setattr(self, 'get_%s_size' % size,
curry(self._get_SIZE_size, size=size))
setattr(self, 'get_%s_photosize' % size,
curry(self._get_SIZE_photosize, size=size))
setattr(self, 'get_%s_url' % size,
curry(self._get_SIZE_url, size=size))
setattr(self, 'get_%s_filename' % size,
curry(self._get_SIZE_filename, size=size))
get_thumbnail_url method is produced by this call: curry(self._get_SIZE_url, size=size)).
But of course this is not a general solution method. If you can share alternative ways to find out where a dynamically defined function is actually produced, this would be of great use.
Edit:
The best general solution is written below by Jason Orendorff.
A:
Not sure, but you can get a function to print out the source file and line number it was defined in using the inspect module:
import inspect
f = lambda: inspect.currentframe().f_code.co_filename + ':' + \
str(inspect.currentframe().f_lineno);
print f()
It prints:
script.py:2
A:
Given a function f, in CPython you can print f.func_code.co_filename and f.func_code.co_firstlineno to get the file and first line number. This will not help if the function was created using eval or exec.
Tracebacks contain file and line information too.
If you import dis you can use dis.dis(f) to see the CPython bytecodes; this might not be useful, but it might show some strings that help you find your way to the right place.
Another thing to look at is PDB, the Python text-mode debugger. After an exception, import pdb; pdb.pm() launches PDB. It's primitive, but useful; type help for a list of commands. where shows the stack.
EDIT: You mention this is a curried function. If it was created using functools.partial, then it has a .func attribute that refers to the underlying function.
EDIT 2: The general way would be to set a breakpoint on im.get_thumbnail_url and then immediately call it. Your breakpoint should hit right away. Then step until you reach the code you're interested in.
Since the curried function was, in this case, produced by code like:
def curry(_curried_func, *args, **kwargs):
def _curried(*moreargs, **morekwargs):
return _curried_func(*(args+moreargs), **dict(kwargs, **morekwargs))
return _curried
another approach is to examine f.func_closure, like this:
>>> f
<function _curried at 0xb77d64fc>
>>> f.func_closure
(<cell at 0xb77eb44c: tuple object at 0xb77dfa0c>, <cell at 0xb77eb5e4: dict object at 0xb77d93e4>, <cell at 0xb77eb5cc: function object at 0xb77d1d84>)
The function closes on three variables: a tuple, a dict, and a function. Obviously the function is the one we're interested in (but fyi these three cells correspond to the variables args, kwargs, and _curried_func that are defined in the enclosing function curry but used by the closure _curried).
>>> f.func_closure[2].cell_contents
<function say at 0xb77d1d84>
>>> import inspect
>>> inspect.getsource(_)
'def say(x):\n print x\n'
|
How to debug dynamically defined functions in Python?
|
Is there a way to debug a function that is defined dynamically in run time?
Or at least is there an easy way to find out where this function is produced?
Update to give more detail:
I used inspect module:
ipdb> inspect.getmodule(im.get_thumbnail_url)
Out[0]: <module 'django.utils.functional' from 'C:\java\python\Python25\Lib\site
-packages\django\utils\functional.pyc'>
ipdb> inspect.getsource(im.get_thumbnail_url)
Out[0]: ' def _curried(*moreargs, **morekwargs):\n return _curried_fun
c(*(args+moreargs), **dict(kwargs, **morekwargs))\n'
Here inspect shows that the get_thumbnail_url method of photos.models.Image class of pinax is produced by django.utils.functional.curry._curried function. But it still doesn't show where the method is produced, namely where is _curried function called. This information is necessary to find out how get_thumbnail_url is implemented.
I can put pdb inside _curried function, but then it breaks lots of times there because this is a very frequently used function call. I need to have some distinguishing feature to use breakpoint condition.
Update about solution:
Thanks for all suggestions. I found out the solution. Let me explain how I found it. Maybe it will help other people:
First, I searched for 'get_thumbnail_url' term in pinax source code. No result.
Second, I searched for 'thumbnail' term in pinax source code. No useful result.
Lastly, I searched for 'curry' term in pinax source code. The following was one of several results:
def add_accessor_methods(self, *args, **kwargs):
for size in PhotoSizeCache().sizes.keys():
setattr(self, 'get_%s_size' % size,
curry(self._get_SIZE_size, size=size))
setattr(self, 'get_%s_photosize' % size,
curry(self._get_SIZE_photosize, size=size))
setattr(self, 'get_%s_url' % size,
curry(self._get_SIZE_url, size=size))
setattr(self, 'get_%s_filename' % size,
curry(self._get_SIZE_filename, size=size))
get_thumbnail_url method is produced by this call: curry(self._get_SIZE_url, size=size)).
But of course this is not a general solution method. If you can share alternative ways to find out where a dynamically defined function is actually produced, this would be of great use.
Edit:
The best general solution is written below by Jason Orendorff.
|
[
"Not sure, but you can get a function to print out the source file and line number it was defined in using the inspect module:\nimport inspect\nf = lambda: inspect.currentframe().f_code.co_filename + ':' + \\\n str(inspect.currentframe().f_lineno);\nprint f()\n\nIt prints:\nscript.py:2\n\n",
"Given a function f, in CPython you can print f.func_code.co_filename and f.func_code.co_firstlineno to get the file and first line number. This will not help if the function was created using eval or exec.\nTracebacks contain file and line information too.\nIf you import dis you can use dis.dis(f) to see the CPython bytecodes; this might not be useful, but it might show some strings that help you find your way to the right place.\nAnother thing to look at is PDB, the Python text-mode debugger. After an exception, import pdb; pdb.pm() launches PDB. It's primitive, but useful; type help for a list of commands. where shows the stack.\nEDIT: You mention this is a curried function. If it was created using functools.partial, then it has a .func attribute that refers to the underlying function.\nEDIT 2: The general way would be to set a breakpoint on im.get_thumbnail_url and then immediately call it. Your breakpoint should hit right away. Then step until you reach the code you're interested in.\nSince the curried function was, in this case, produced by code like:\ndef curry(_curried_func, *args, **kwargs):\n def _curried(*moreargs, **morekwargs):\n return _curried_func(*(args+moreargs), **dict(kwargs, **morekwargs))\n return _curried\n\nanother approach is to examine f.func_closure, like this:\n>>> f\n<function _curried at 0xb77d64fc>\n>>> f.func_closure\n(<cell at 0xb77eb44c: tuple object at 0xb77dfa0c>, <cell at 0xb77eb5e4: dict object at 0xb77d93e4>, <cell at 0xb77eb5cc: function object at 0xb77d1d84>)\n\nThe function closes on three variables: a tuple, a dict, and a function. Obviously the function is the one we're interested in (but fyi these three cells correspond to the variables args, kwargs, and _curried_func that are defined in the enclosing function curry but used by the closure _curried).\n>>> f.func_closure[2].cell_contents\n<function say at 0xb77d1d84>\n>>> import inspect\n>>> inspect.getsource(_)\n'def say(x):\\n print x\\n'\n\n"
] |
[
1,
1
] |
[] |
[] |
[
"debugging",
"dynamic",
"python"
] |
stackoverflow_0002008496_debugging_dynamic_python.txt
|
Q:
Display objects within a function, how to NOT terminate the program after close the display?
see the example:
from visual import *
def hello():
newyear=2010
sphere()
return newyear
my problem here is when I call function hello(), a sphere display window shows up, and also prints 2010, however if I close the display window, the program terminates. That is not what I want, how can I avoid this?
also, in my code, I will also use newyear, say b=hello(), but I dont want it show the sphere when I want use newyear, how can I do this?
Thanks in advance!
A:
You need to fork the process before hand.
(Totally untested)
import os
if os.fork() == 0: exit()
Placing that stanza at the start of your program should cause execution to continue in a forked process, detached from your tty. Someone can probably correct me though.
|
Display objects within a function, how to NOT terminate the program after close the display?
|
see the example:
from visual import *
def hello():
newyear=2010
sphere()
return newyear
my problem here is when I call function hello(), a sphere display window shows up, and also prints 2010, however if I close the display window, the program terminates. That is not what I want, how can I avoid this?
also, in my code, I will also use newyear, say b=hello(), but I dont want it show the sphere when I want use newyear, how can I do this?
Thanks in advance!
|
[
"You need to fork the process before hand.\n(Totally untested)\nimport os\nif os.fork() == 0: exit()\n\nPlacing that stanza at the start of your program should cause execution to continue in a forked process, detached from your tty. Someone can probably correct me though.\n"
] |
[
0
] |
[] |
[] |
[
"python",
"python_visual"
] |
stackoverflow_0002008641_python_python_visual.txt
|
Q:
Accessing py2exe program over network in Windows 98 throws ImportErrors
I'm running a py2exe-compiled python program from one server machine on a number of client machines (mapped to a network drive on every machine, say W:).
For Windows XP and later machines, have so far had zero problems with Python picking up W:\python23.dll (yes, I'm using Python 2.3.5 for W98 compatibility and all that). It will then use W:\zlib.pyd to decompress W:\library.zip containing all the .pyc files like os and such, which are then imported and the program runs no problems.
The issue I'm getting is on some Windows 98 SE machines (note: SOME Windows 98 SE machines, others seem to work with no apparent issues). What happens is, the program runs from W:, the W:\python23.dll is, I assume, found (since I'm getting Python ImportErrors, we'd need to be able to execute a Python import statement), but a couple of things don't work:
1) If W:\library.zip contains the only copy of the .pyc files, I get
ZipImportError: can't decompress data; zlib not available (nonsense, considering W:\zlib.pyd IS available and works fine with the XP and higher machines on the same network).
2) If the .pyc files are actually bundled INSIDE the python exe by py2exe, OR put in the same directory as the .exe, OR put into a named subdirectory which is then set as part of the PYTHONPATH variable (e.g W:\pylib), I get ImportError: no module named os (os is the first module imported, before sys and anything else).
Come to think of it, sys.path wouldn't be available to search if os was imported before it maybe? I'll try switching the order of those imports but my question still stands: Why is this a sporadic issue, working on some networks but not on others? And how would I force Python to find the files that are bundled inside the very executable I run?
I have immediate access to the working Windows 98 SE machine, but I only get access to the non-working one (a customer of mine) every morning before their store opens.
Thanks in advance!
EDIT: Okay, big step forward. After debugging with PY2EXE_VERBOSE, the problem occurring on the specific W98SE machine is that it's not using the right path syntax when looking for imports. Firstly, it doesn't seem to read the PYTHONPATH environment variable (there may be a py2exe-specific one I'm not aware of, like PY2EXE_VERBOSE).
Secondly, it only looks in one place before giving up (if the files are bundled inside the EXE, it looks there. If not, it looks in library.zip).
EDIT 2: In fact, according to this, there is a difference between the sys.path in the Python interpreter and that of Py2exe executables. Specifically, sys.path contains only a single entry: the full pathname of the shared code archive. Blah. No fallbacks? Not even the current working directory? I'd try adding W:\ to PATH, but py2exe doesn't conform to any sort of standards for locating system libraries, so it won't work.
Now for the interesting bit. The path it tries to load atexit, os, etc. from is:
W:\\library.zip\<module>.<ext>
Note the single slash after library.zip, but the double slash after the drive letter (someone correct me if this is intended and should work). It looks like if this is a string literal, then since the slash isn't doubled, it's read as an (invalid) escape sequence and the raw character is printed (giving W:\library.zipos.pyd, W:\library.zipos.dll, ... instead of with a slash); if it is NOT a string literal, the double slash might not be normpath'd automatically (as it should be) and so the double slash confuses the module loader. Like I said, I can't just set PYTHONPATH=W:\\library.zip\\ because it ignores that variable.
It may be worth using sys.path.append at the start of my program but hard-coding module paths is an absolute LAST resort, especially since the problem occurs in ONE configuration of an outdated OS.
Any ideas? I have one, which is to normpath the sys.path.. pity I need os for that. Another is to just append os.getenv('PATH') or os.getenv('PYTHONPATH') to sys.path... again, needing the os module. The site module also fails to initialise, so I can't use a .pth file.
I also recently tried the following code at the start of the program:
for pth in sys.path:
fErr.write(pth)
fErr.write(' to ')
pth.replace('\\\\','\\') # Fix Windows 98 pathing issues
fErr.write(pth)
fErr.write('\n')
But it can't load linecache.pyc, or anything else for that matter; it can't actually execute those commands from the looks of things. Is there any way to use built-in functionality which doesn't need linecache to modify the sys.path dynamically? Or am I reduced to hard-coding the correct sys.path?
A:
This isn't a direct answer, but possibly some help. Are you familiar with the -v option in Python. Type python -h to learn more. Note the equivalent to the PYTHONVERBOSE environment variable for py2exe'd scripts is PY2EXE_VERBOSE, as described almost nowhere except in this post by its author. Apparently it can take values of 1 or 2, basically like -v and -vv, though that's slightly different from how PYTHONVERBOSE works.
Note also about your sys.path idea: whether you have imported sys already or not would have no effect on whether you could import os. That is, the Python path (visible in sys.path) is always available, in the sense that it reflects an internal feature of the interpreter which is there whether you've imported the sys module or not.
As with a number of other modules, sys is built-in, so it should always be importable even if your app is almost totally crippled. If it will help, you may be able to use sys.builtin_module_names to see what they are for your version of Python. If the interpreter is running at all that information would be available, so the following may be the smallest useful program you can make to see what you've got:
import sys
print sys.builtin_module_names
Also, I'd advise against trying anything fancy like bundling the .pyc files inside the .exe. You've already got enough working against you being stuck supporting Win98, and if I were you I'd go for the simplest approach that would let me get the job done and move on to more interesting areas. If you could just install Python normally and run from source, you should definitely consider it! :)
Edited to include link to PY2EXE_VERBOSE info per comment by darvids0n.
|
Accessing py2exe program over network in Windows 98 throws ImportErrors
|
I'm running a py2exe-compiled python program from one server machine on a number of client machines (mapped to a network drive on every machine, say W:).
For Windows XP and later machines, have so far had zero problems with Python picking up W:\python23.dll (yes, I'm using Python 2.3.5 for W98 compatibility and all that). It will then use W:\zlib.pyd to decompress W:\library.zip containing all the .pyc files like os and such, which are then imported and the program runs no problems.
The issue I'm getting is on some Windows 98 SE machines (note: SOME Windows 98 SE machines, others seem to work with no apparent issues). What happens is, the program runs from W:, the W:\python23.dll is, I assume, found (since I'm getting Python ImportErrors, we'd need to be able to execute a Python import statement), but a couple of things don't work:
1) If W:\library.zip contains the only copy of the .pyc files, I get
ZipImportError: can't decompress data; zlib not available (nonsense, considering W:\zlib.pyd IS available and works fine with the XP and higher machines on the same network).
2) If the .pyc files are actually bundled INSIDE the python exe by py2exe, OR put in the same directory as the .exe, OR put into a named subdirectory which is then set as part of the PYTHONPATH variable (e.g W:\pylib), I get ImportError: no module named os (os is the first module imported, before sys and anything else).
Come to think of it, sys.path wouldn't be available to search if os was imported before it maybe? I'll try switching the order of those imports but my question still stands: Why is this a sporadic issue, working on some networks but not on others? And how would I force Python to find the files that are bundled inside the very executable I run?
I have immediate access to the working Windows 98 SE machine, but I only get access to the non-working one (a customer of mine) every morning before their store opens.
Thanks in advance!
EDIT: Okay, big step forward. After debugging with PY2EXE_VERBOSE, the problem occurring on the specific W98SE machine is that it's not using the right path syntax when looking for imports. Firstly, it doesn't seem to read the PYTHONPATH environment variable (there may be a py2exe-specific one I'm not aware of, like PY2EXE_VERBOSE).
Secondly, it only looks in one place before giving up (if the files are bundled inside the EXE, it looks there. If not, it looks in library.zip).
EDIT 2: In fact, according to this, there is a difference between the sys.path in the Python interpreter and that of Py2exe executables. Specifically, sys.path contains only a single entry: the full pathname of the shared code archive. Blah. No fallbacks? Not even the current working directory? I'd try adding W:\ to PATH, but py2exe doesn't conform to any sort of standards for locating system libraries, so it won't work.
Now for the interesting bit. The path it tries to load atexit, os, etc. from is:
W:\\library.zip\<module>.<ext>
Note the single slash after library.zip, but the double slash after the drive letter (someone correct me if this is intended and should work). It looks like if this is a string literal, then since the slash isn't doubled, it's read as an (invalid) escape sequence and the raw character is printed (giving W:\library.zipos.pyd, W:\library.zipos.dll, ... instead of with a slash); if it is NOT a string literal, the double slash might not be normpath'd automatically (as it should be) and so the double slash confuses the module loader. Like I said, I can't just set PYTHONPATH=W:\\library.zip\\ because it ignores that variable.
It may be worth using sys.path.append at the start of my program but hard-coding module paths is an absolute LAST resort, especially since the problem occurs in ONE configuration of an outdated OS.
Any ideas? I have one, which is to normpath the sys.path.. pity I need os for that. Another is to just append os.getenv('PATH') or os.getenv('PYTHONPATH') to sys.path... again, needing the os module. The site module also fails to initialise, so I can't use a .pth file.
I also recently tried the following code at the start of the program:
for pth in sys.path:
fErr.write(pth)
fErr.write(' to ')
pth.replace('\\\\','\\') # Fix Windows 98 pathing issues
fErr.write(pth)
fErr.write('\n')
But it can't load linecache.pyc, or anything else for that matter; it can't actually execute those commands from the looks of things. Is there any way to use built-in functionality which doesn't need linecache to modify the sys.path dynamically? Or am I reduced to hard-coding the correct sys.path?
|
[
"This isn't a direct answer, but possibly some help. Are you familiar with the -v option in Python. Type python -h to learn more. Note the equivalent to the PYTHONVERBOSE environment variable for py2exe'd scripts is PY2EXE_VERBOSE, as described almost nowhere except in this post by its author. Apparently it can take values of 1 or 2, basically like -v and -vv, though that's slightly different from how PYTHONVERBOSE works.\nNote also about your sys.path idea: whether you have imported sys already or not would have no effect on whether you could import os. That is, the Python path (visible in sys.path) is always available, in the sense that it reflects an internal feature of the interpreter which is there whether you've imported the sys module or not. \nAs with a number of other modules, sys is built-in, so it should always be importable even if your app is almost totally crippled. If it will help, you may be able to use sys.builtin_module_names to see what they are for your version of Python. If the interpreter is running at all that information would be available, so the following may be the smallest useful program you can make to see what you've got:\nimport sys\nprint sys.builtin_module_names\n\nAlso, I'd advise against trying anything fancy like bundling the .pyc files inside the .exe. You've already got enough working against you being stuck supporting Win98, and if I were you I'd go for the simplest approach that would let me get the job done and move on to more interesting areas. If you could just install Python normally and run from source, you should definitely consider it! :)\nEdited to include link to PY2EXE_VERBOSE info per comment by darvids0n.\n"
] |
[
2
] |
[] |
[] |
[
"importerror",
"py2exe",
"python",
"python_module",
"windows_98"
] |
stackoverflow_0002009873_importerror_py2exe_python_python_module_windows_98.txt
|
Q:
Python decorator with instantiation-time variable?
I want to make a decorator that creates a new function/method that makes use of an object obj. If the decorated object is a function, obj must be instantiated when the function is created. If the decorated object is a method, a new obj must be instantiated and bound to each instance of the class whose method is decorated. I can't put the decoration in __init__ because the decorator modifies the function documentation. I have something like this now, but it only instantiates time once, which is not what I want:
__all__ = ['dec', 'A']
from time import time
import inspect
def dec(f):
obj = time() # want to set on object instantiation
def new(*args, **kwargs):
f(*args, **kwargs) # Validate against definition so it doesn't go
# out of sync
print obj
# ...
try:
d = inspect.getsourcelines(f)
except IOError:
d = "<unable to fetch definition>"
else:
d = d[0][1].rstrip('\n').rstrip(':').lstrip(' ').lstrip('def')
new.__doc__ = d + "\n" + (f.__doc__ or '')
return new
class A(object):
@dec
def f(self, x):
"""something"""
print '%s.f(%s)' % (self, x)
if __name__ == '__main__':
A().f(123)
A().f(123)
A().f(123)
My idea to solve this is to check if the object passed to the decorator takes an argument self, if so, return a method that binds obj to self if it's not already there, and then uses self.obj. And then if there is no self argument to the object passed to the decorator, just instantiate obj inside the decorator and return a function that makes use of that.
However... what I said doesn't really work for me because in my real decorator, I return an object that is derived from list and has a __call__ attribute. Furthermore in the real decorator, self is not even defined in the objects that get decorated by it because they don't make use of their instance variables (what I'm really decorating are just events to be subscribed to by external objects, the events have documented signatures).
Edit: Actually, if there's a way to make a list subclass instance get bound to an instance so that it's __call__ attribute implicitly receives the class instance (like in any normal instance method), this would be a perfect solution, this was what I was originally trying to figure out how to do. But maybe there is an even better solution such that I don't have to define the decorated methods with the self attribute? Either is perfect.
A:
Since a decorator is just syntactic sugar for saying
def func():
...
func = decorator(func)
Why not do that in the object constructor?
class A(object):
def __init__(self):
# apply decorator at instance creation
self.f = dec(self.f)
def f(self, x):
"""something"""
print '%s.f(%s)' % (self, x)
A:
It's a little difficult to figure out what you're after exactly. The list and __call__ stuff is confusing me so I'm mainly sticking with your first paragraph:
__all__ = ['dec', 'A']
from types import InstanceType
from functools import wraps
import inspect
def dec(func):
#get the sig of the function
sig = []
@wraps(func)
def wrapper(*args, **kwargs):
ret = None
#if this is a method belonging to an object...
if args and getattr(args[0], func.__name__, None):
instance, args = args[0], args[1:]
#if sig of object is not already set
if not hasattr(instance, "sig"):
instance.sig = []
ret = func(instance, *args, **kwargs)
print "Sig of %s is %s" % (func.__name__, id(instance.sig))
#else this is a function
else:
ret = func(*args, **kwargs)
print "Sig of %s is %s" % (func.__name__, id(sig))
return ret
#modify the doc string
try:
docs = inspect.getsourcelines(func)
except:
docs = "<unable to fetch defintion>"
else:
docs = docs[0][1].rstrip('\n').rstrip(':').lstrip(' ').lstrip('def')
wrapper.__doc__ = docs + "\n" + (func.__doc__ or '')
return wrapper
class A(object):
def __init__(self):
super(A, self).__init__()
@dec
def f(self, x):
"""something"""
print '%s.f(%s)' % (self, x)
@dec
def myfunc():
print "myfunc"
@dec
def myfunc2():
print "myfunc2"
@dec
def myfunc3():
print "myfunc3"
if __name__ == "__main__":
list = []
for x in xrange(3):
list.append(A())
[a.f(123) for a in list]
myfunc()
myfunc()
myfunc2()
myfunc2()
myfunc3()
myfunc3()
Output:
<__main__.A object at 0x00B9F2D0>.f(123)
Sig of f is 11932616
<__main__.A object at 0x00B9F430>.f(123)
Sig of f is 11925464
<__main__.A object at 0x00B9F450>.f(123)
Sig of f is 11918112
myfunc
Sig of myfunc is 11925624
myfunc
Sig of myfunc is 11925624
myfunc2
Sig of myfunc2 is 11794592
myfunc2
Sig of myfunc2 is 11794592
myfunc3
Sig of myfunc3 is 11925144
myfunc3
Sig of myfunc3 is 11925144
A:
Your writing style is really hard to read. Normal sentences are half as long as yours :P
Do you want this or what?
__all__ = ['dec', 'A']
from time import time, sleep
import inspect
def dec(f):
def new(self, *args, **kwargs):
print self.initiated # print the time the objecte was initiated ...
return f(self, *args, **kwargs) # Validate against definition so it doesn't go
# out of sync
try:
d = inspect.getsourcelines(f)
except IOError:
d = "<unable to fetch definition>"
else:
d = d[0][1].rstrip('\n').rstrip(':').lstrip(' ').lstrip('def')
new.__doc__ = d + "\n" + (f.__doc__ or '')
return new
class A(object):
def __init__(self):
self.initiated = time() # save the time the object was initiated
@dec
def f(self, x):
"""something"""
print '%s.f(%s)' % (self, x)
if __name__ == '__main__':
A().f(123)
sleep(1)
A().f(123)
sleep(1)
A().f(123)
A:
Okay based on manifest's code, I've got a solution.
As you can see, pydoc will still have decent documentation about the decorated thing:
class A(__builtin__.object)
| Methods defined here:
|
| f(*args, **kwargs)
| f(self, x)
| something
As well, each instance of the class with the decorated method will have a different obj. Also functions each have their own obj.
<__main__.A object at 0x7c209bee4a50>.f(123)
obj of <__main__.A object at 0x7c209bee4a50>.f is 136479497243752
<__main__.A object at 0x7c209bee4a10>.f(123)
obj of <__main__.A object at 0x7c209bee4a10>.f is 136479497250720
<__main__.A object at 0x7c209bee4a90>.f(123)
obj of <__main__.A object at 0x7c209bee4a90>.f is 136479497446824
myfunc
obj of myfunc is 136479497243392
myfunc
obj of myfunc is 136479497243392
myfunc2
obj of myfunc2 is 136479497245688
myfunc2
obj of myfunc2 is 136479497245688
myfunc3
obj of myfunc3 is 136479497246408
myfunc3
obj of myfunc3 is 136479497246408
Here is the code:
__all__ = ['dec', 'A']
from functools import wraps
import inspect
def dec(cls=None):
# cls will be closed in subdec
def subdec(func):
# closed in wrapper, guaranteed to be unique per decorator evaluation
obj = []
@wraps(func)
def wrapper(*args, **kwargs):
if (args and type(args[0]) == cls):
instance = args[0]
# We will attach to instance a dict _objs of
# function_name:obj. This way we don't pollute the namespace
# when decorating many functions.
# Alternatively, you could make a dict external to instance
# of instance:{function_name:obj}, but that takes more work
# because you need to make it not prevent garbage collection
# of instance.
if not hasattr(instance, "_objs"):
instance._objs = {}
if func.__name__ not in instance._objs:
instance._objs[func.__name__] = []
func(*args, **kwargs) # This is only used to check the arity.
# My real code is all to do with
# manipulating obj.
print "obj of %s.%s is %s" % (
instance,
func.__name__,
id(instance._objs[func.__name__])
)
else:
# Functions are identified by the closed obj
func(*args, **kwargs)
print "obj of %s is %s" % (func.__name__, id(obj))
# Find function/method signature and prepend it to the new object's doc
try:
doc = inspect.getsourcelines(func)
except IOError:
line = "<unable to fetch definition>"
else:
line = '@'
i = 0
while line.lstrip(' ').startswith("@"):
try:
line = doc[0][i]
except IndexError:
line = "<unable to fetch definition>"
i += 1
line = line.rstrip('\n').rstrip(':').lstrip(' ').lstrip('def')
wrapper.__doc__ = line + "\n" + (func.__doc__ or '')
return wrapper
return subdec
class A(object):
def f(self, x):
"""something"""
print '%s.f(%s)' % (self, x)
A.f = dec(A)(A.f)
@dec()
def myfunc():
print "myfunc"
@dec()
def myfunc2():
print "myfunc2"
@dec()
def myfunc3():
print "myfunc3"
if __name__ == "__main__":
a, b, c = A(), A(), A()
# a, b, and c each have their own instance of obj:
a.f(123)
b.f(123)
c.f(123)
myfunc()
myfunc()
myfunc2()
myfunc2()
myfunc3()
myfunc3()
The added outer decorator, cls is just used to get the identity of the class, so the decorated function can tell for sure weather it is a function or method. I'm not sure how well this will go with [multiple] inheritance though... Maybe manifest's idea for checking that part is better.
|
Python decorator with instantiation-time variable?
|
I want to make a decorator that creates a new function/method that makes use of an object obj. If the decorated object is a function, obj must be instantiated when the function is created. If the decorated object is a method, a new obj must be instantiated and bound to each instance of the class whose method is decorated. I can't put the decoration in __init__ because the decorator modifies the function documentation. I have something like this now, but it only instantiates time once, which is not what I want:
__all__ = ['dec', 'A']
from time import time
import inspect
def dec(f):
obj = time() # want to set on object instantiation
def new(*args, **kwargs):
f(*args, **kwargs) # Validate against definition so it doesn't go
# out of sync
print obj
# ...
try:
d = inspect.getsourcelines(f)
except IOError:
d = "<unable to fetch definition>"
else:
d = d[0][1].rstrip('\n').rstrip(':').lstrip(' ').lstrip('def')
new.__doc__ = d + "\n" + (f.__doc__ or '')
return new
class A(object):
@dec
def f(self, x):
"""something"""
print '%s.f(%s)' % (self, x)
if __name__ == '__main__':
A().f(123)
A().f(123)
A().f(123)
My idea to solve this is to check if the object passed to the decorator takes an argument self, if so, return a method that binds obj to self if it's not already there, and then uses self.obj. And then if there is no self argument to the object passed to the decorator, just instantiate obj inside the decorator and return a function that makes use of that.
However... what I said doesn't really work for me because in my real decorator, I return an object that is derived from list and has a __call__ attribute. Furthermore in the real decorator, self is not even defined in the objects that get decorated by it because they don't make use of their instance variables (what I'm really decorating are just events to be subscribed to by external objects, the events have documented signatures).
Edit: Actually, if there's a way to make a list subclass instance get bound to an instance so that it's __call__ attribute implicitly receives the class instance (like in any normal instance method), this would be a perfect solution, this was what I was originally trying to figure out how to do. But maybe there is an even better solution such that I don't have to define the decorated methods with the self attribute? Either is perfect.
|
[
"Since a decorator is just syntactic sugar for saying\ndef func():\n ...\nfunc = decorator(func)\n\nWhy not do that in the object constructor?\nclass A(object):\n def __init__(self):\n # apply decorator at instance creation\n self.f = dec(self.f)\n\n def f(self, x):\n \"\"\"something\"\"\"\n print '%s.f(%s)' % (self, x)\n\n",
"It's a little difficult to figure out what you're after exactly. The list and __call__ stuff is confusing me so I'm mainly sticking with your first paragraph:\n__all__ = ['dec', 'A']\n\nfrom types import InstanceType\nfrom functools import wraps\nimport inspect\n\ndef dec(func):\n\n #get the sig of the function\n sig = []\n @wraps(func)\n def wrapper(*args, **kwargs):\n ret = None\n #if this is a method belonging to an object...\n if args and getattr(args[0], func.__name__, None):\n instance, args = args[0], args[1:]\n #if sig of object is not already set\n if not hasattr(instance, \"sig\"):\n instance.sig = []\n ret = func(instance, *args, **kwargs)\n print \"Sig of %s is %s\" % (func.__name__, id(instance.sig))\n #else this is a function\n else:\n ret = func(*args, **kwargs)\n print \"Sig of %s is %s\" % (func.__name__, id(sig))\n return ret\n\n #modify the doc string\n try:\n docs = inspect.getsourcelines(func)\n except:\n docs = \"<unable to fetch defintion>\"\n else:\n docs = docs[0][1].rstrip('\\n').rstrip(':').lstrip(' ').lstrip('def')\n wrapper.__doc__ = docs + \"\\n\" + (func.__doc__ or '')\n return wrapper\n\nclass A(object):\n def __init__(self):\n super(A, self).__init__()\n\n @dec\n def f(self, x):\n \"\"\"something\"\"\"\n print '%s.f(%s)' % (self, x)\n\n\n@dec\ndef myfunc():\n print \"myfunc\"\n\n@dec\ndef myfunc2():\n print \"myfunc2\"\n\n@dec\ndef myfunc3():\n print \"myfunc3\"\n\nif __name__ == \"__main__\":\n list = []\n for x in xrange(3):\n list.append(A())\n\n [a.f(123) for a in list]\n myfunc()\n myfunc()\n myfunc2()\n myfunc2()\n myfunc3()\n myfunc3()\n\nOutput:\n<__main__.A object at 0x00B9F2D0>.f(123)\nSig of f is 11932616\n<__main__.A object at 0x00B9F430>.f(123)\nSig of f is 11925464\n<__main__.A object at 0x00B9F450>.f(123)\nSig of f is 11918112\nmyfunc\nSig of myfunc is 11925624\nmyfunc\nSig of myfunc is 11925624\nmyfunc2\nSig of myfunc2 is 11794592\nmyfunc2\nSig of myfunc2 is 11794592\nmyfunc3\nSig of myfunc3 is 11925144\nmyfunc3\nSig of myfunc3 is 11925144\n\n",
"Your writing style is really hard to read. Normal sentences are half as long as yours :P\nDo you want this or what?\n__all__ = ['dec', 'A']\n\nfrom time import time, sleep\nimport inspect\n\ndef dec(f):\n def new(self, *args, **kwargs):\n print self.initiated # print the time the objecte was initiated ...\n return f(self, *args, **kwargs) # Validate against definition so it doesn't go\n # out of sync\n try:\n d = inspect.getsourcelines(f)\n except IOError:\n d = \"<unable to fetch definition>\"\n else:\n d = d[0][1].rstrip('\\n').rstrip(':').lstrip(' ').lstrip('def')\n new.__doc__ = d + \"\\n\" + (f.__doc__ or '')\n return new\n\nclass A(object):\n def __init__(self):\n self.initiated = time() # save the time the object was initiated\n\n\n @dec\n def f(self, x):\n \"\"\"something\"\"\"\n print '%s.f(%s)' % (self, x)\n\nif __name__ == '__main__':\n A().f(123)\n sleep(1)\n A().f(123)\n sleep(1)\n A().f(123)\n\n",
"Okay based on manifest's code, I've got a solution.\nAs you can see, pydoc will still have decent documentation about the decorated thing:\n\nclass A(__builtin__.object)\n | Methods defined here:\n | \n | f(*args, **kwargs)\n | f(self, x)\n | something\n\n\nAs well, each instance of the class with the decorated method will have a different obj. Also functions each have their own obj.\n\n <__main__.A object at 0x7c209bee4a50>.f(123)\n obj of <__main__.A object at 0x7c209bee4a50>.f is 136479497243752\n <__main__.A object at 0x7c209bee4a10>.f(123)\n obj of <__main__.A object at 0x7c209bee4a10>.f is 136479497250720\n <__main__.A object at 0x7c209bee4a90>.f(123)\n obj of <__main__.A object at 0x7c209bee4a90>.f is 136479497446824\n myfunc\n obj of myfunc is 136479497243392\n myfunc\n obj of myfunc is 136479497243392\n myfunc2\n obj of myfunc2 is 136479497245688\n myfunc2\n obj of myfunc2 is 136479497245688\n myfunc3\n obj of myfunc3 is 136479497246408\n myfunc3\n obj of myfunc3 is 136479497246408\n\n\nHere is the code:\n__all__ = ['dec', 'A']\n\nfrom functools import wraps\nimport inspect\n\ndef dec(cls=None):\n # cls will be closed in subdec\n def subdec(func):\n # closed in wrapper, guaranteed to be unique per decorator evaluation\n obj = []\n\n @wraps(func)\n def wrapper(*args, **kwargs):\n if (args and type(args[0]) == cls):\n instance = args[0]\n # We will attach to instance a dict _objs of\n # function_name:obj. This way we don't pollute the namespace\n # when decorating many functions.\n\n # Alternatively, you could make a dict external to instance\n # of instance:{function_name:obj}, but that takes more work\n # because you need to make it not prevent garbage collection\n # of instance.\n if not hasattr(instance, \"_objs\"):\n instance._objs = {}\n if func.__name__ not in instance._objs:\n instance._objs[func.__name__] = []\n func(*args, **kwargs) # This is only used to check the arity.\n # My real code is all to do with\n # manipulating obj.\n print \"obj of %s.%s is %s\" % (\n instance,\n func.__name__,\n id(instance._objs[func.__name__])\n )\n else:\n # Functions are identified by the closed obj\n func(*args, **kwargs)\n print \"obj of %s is %s\" % (func.__name__, id(obj))\n\n # Find function/method signature and prepend it to the new object's doc\n try:\n doc = inspect.getsourcelines(func)\n except IOError:\n line = \"<unable to fetch definition>\"\n else:\n line = '@'\n i = 0\n while line.lstrip(' ').startswith(\"@\"):\n try:\n line = doc[0][i]\n except IndexError:\n line = \"<unable to fetch definition>\"\n i += 1\n line = line.rstrip('\\n').rstrip(':').lstrip(' ').lstrip('def')\n wrapper.__doc__ = line + \"\\n\" + (func.__doc__ or '')\n\n return wrapper\n return subdec\n\nclass A(object):\n def f(self, x):\n \"\"\"something\"\"\"\n print '%s.f(%s)' % (self, x)\n\nA.f = dec(A)(A.f)\n\n@dec()\ndef myfunc():\n print \"myfunc\"\n\n@dec()\ndef myfunc2():\n print \"myfunc2\"\n\n@dec()\ndef myfunc3():\n print \"myfunc3\"\n\nif __name__ == \"__main__\":\n a, b, c = A(), A(), A()\n # a, b, and c each have their own instance of obj:\n a.f(123)\n b.f(123)\n c.f(123)\n myfunc()\n myfunc()\n myfunc2()\n myfunc2()\n myfunc3()\n myfunc3()\n\nThe added outer decorator, cls is just used to get the identity of the class, so the decorated function can tell for sure weather it is a function or method. I'm not sure how well this will go with [multiple] inheritance though... Maybe manifest's idea for checking that part is better.\n"
] |
[
2,
1,
0,
0
] |
[] |
[] |
[
"decorator",
"python"
] |
stackoverflow_0002007786_decorator_python.txt
|
Q:
How to get the difference between two list based on substrings withing each string in the seperate lists
I have two long list, one from a log file that contains lines formatted like
201001050843 blah blah blah <email@site.com> blah blah
and a second file in csv format. I need to generate a list of all the entries in file2 that do not contain a email address in the log file, while maintaining the csv format.
Example
Log file contains:
201001050843 blah blah blah <email@site.com> blah blah
201001050843 blah blah blah <email2@site.com> blah blah
File2 contains:
156456,bob,sagget,email@site.com,4564456
156464,bob,otherguy,email@anothersite.com,45644562
the output should be:
156464,bob,otherguy,email@anothersite.com,45644562
Currently I grab the emails from the log and load them into another list with:
sent_emails =[]
for line in sent:
try:
temp1= line.index('<')
temp2 = line.index('>')
sent_emails.append(line[temp1+1:temp2])
except ValueError:
pass
And then compare to file2 with either:
lista = mail_lista.readlines()
for line in lista:
temp = line.split()
for thing in temp:
try:
if thing.index('@'):
if thing in sent_emails:
lista.remove(temp)
except ValueError:
pass
newa.writelines(lista)
or:
for line in mail_listb:
temp = line.split()
for thing in temp:
try:
if thing.index('@'):
if thing not in sent_emails:
newb.write(line)
except ValueError:
pass
However both return all of file2!
Thanks for any help you can give.
EDIT: Thanks for the recommendations for sets, it made a larger speed difference than I would have thought possible. Way to go hash tables! I will definitively be using sets more often from now on.
A:
line.split() splits at whitespace. Use line.split(',') instead.
Also: Does the order of the lines matter? If not, then you should really use a set() instead of a list. That will make the code much faster.
A:
You could create the set of emails as you do and then:
# emails is a set of emails
for line in fileinput.input("csvfile.csv",inplace =1):
parts = line.split(',')
if parts[3] not in emails:
print line
This only works, if the email in the CSV file is always at position 4.
fileinput enables in place editing.
And use a set for the emails instead of a list as Aaron said, not only because of speed but also to eliminate duplicates.
A:
here's another way, with minimalistic check on email addr's position.
import fileinput
emails=[]
for line in open("file1"):
start=line.find("<")
end=line.find(">")
if start != -1 and end !=-1:
emails.append(line[start+1:end])
for line in fileinput.FileInput("file2",inplace=1):
p = line.split(",")
for item in p:
if "@" in item and item not in emails:
print line.strip()
output
$ ./python.py
156464,bob,otherguy,email@anothersite.com,45644562
|
How to get the difference between two list based on substrings withing each string in the seperate lists
|
I have two long list, one from a log file that contains lines formatted like
201001050843 blah blah blah <email@site.com> blah blah
and a second file in csv format. I need to generate a list of all the entries in file2 that do not contain a email address in the log file, while maintaining the csv format.
Example
Log file contains:
201001050843 blah blah blah <email@site.com> blah blah
201001050843 blah blah blah <email2@site.com> blah blah
File2 contains:
156456,bob,sagget,email@site.com,4564456
156464,bob,otherguy,email@anothersite.com,45644562
the output should be:
156464,bob,otherguy,email@anothersite.com,45644562
Currently I grab the emails from the log and load them into another list with:
sent_emails =[]
for line in sent:
try:
temp1= line.index('<')
temp2 = line.index('>')
sent_emails.append(line[temp1+1:temp2])
except ValueError:
pass
And then compare to file2 with either:
lista = mail_lista.readlines()
for line in lista:
temp = line.split()
for thing in temp:
try:
if thing.index('@'):
if thing in sent_emails:
lista.remove(temp)
except ValueError:
pass
newa.writelines(lista)
or:
for line in mail_listb:
temp = line.split()
for thing in temp:
try:
if thing.index('@'):
if thing not in sent_emails:
newb.write(line)
except ValueError:
pass
However both return all of file2!
Thanks for any help you can give.
EDIT: Thanks for the recommendations for sets, it made a larger speed difference than I would have thought possible. Way to go hash tables! I will definitively be using sets more often from now on.
|
[
"line.split() splits at whitespace. Use line.split(',') instead.\nAlso: Does the order of the lines matter? If not, then you should really use a set() instead of a list. That will make the code much faster.\n",
"You could create the set of emails as you do and then:\n# emails is a set of emails\nfor line in fileinput.input(\"csvfile.csv\",inplace =1):\n parts = line.split(',')\n if parts[3] not in emails:\n print line\n\nThis only works, if the email in the CSV file is always at position 4.\nfileinput enables in place editing.\nAnd use a set for the emails instead of a list as Aaron said, not only because of speed but also to eliminate duplicates.\n",
"here's another way, with minimalistic check on email addr's position.\nimport fileinput\nemails=[]\nfor line in open(\"file1\"):\n start=line.find(\"<\")\n end=line.find(\">\")\n if start != -1 and end !=-1:\n emails.append(line[start+1:end])\n\nfor line in fileinput.FileInput(\"file2\",inplace=1):\n p = line.split(\",\")\n for item in p:\n if \"@\" in item and item not in emails:\n print line.strip()\n\noutput\n$ ./python.py\n156464,bob,otherguy,email@anothersite.com,45644562\n\n"
] |
[
1,
1,
0
] |
[] |
[] |
[
"list",
"list_manipulation",
"python",
"string"
] |
stackoverflow_0002007755_list_list_manipulation_python_string.txt
|
Q:
How to load modules dynamically on package import?
Given the following example layout:
test/
test.py
formats/
__init__.py
format_a.py
format_b.py
What I try to archive is, that whenever I import formats, the __init__.py looks for all available modules in the formats subdir, loads them and makes them available (right now simply through a variable, supported_formats). If theres a better, more pythonic or otherwise approach to dynamically loading stuff on runtime, based on physical available files, please tell.
My Approach
I tried something like this (in __init__.py):
supported_formats = [__import__(f[:f.index('.py')]) for f in glob.glob('*.py')]
So far I just get it to work, when I run __init__.py from the command line (from the formats subdir or from other directories) . But when I import it from test.py, it bails on me like this:
ImportError: No module named format_a.py
Same when I import it from the python interpreter, when I started the interpreter in an other directory but the formats subdir.
Here's the whole code. It also looks for a specific class and stores one instance of each class in an dict, but loading the modules dynamically is the main part I don't get:
def dload(get_cls=True, get_mod=True, key=None, fstring_mod='*.py', fstring_class=''):
if p.dirname(__file__):
path = p.split(p.abspath(__file__))[0]
fstring_mod = p.join(path, fstring_mod)
print >> sys.stderr, 'Path-Glob:', fstring_mod
modules = [p.split(fn)[1][:fn.index('.py')] for fn in glob.glob(fstring_mod)]
print >> sys.stderr, 'Modules:', ', '.join(modules)
modules = [__import__(m) for m in modules]
if get_cls:
classes = {} if key else []
for m in modules:
print >> sys.stderr, "-", m
for c in [m.__dict__[c]() for c in m.__dict__ if c.startswith(fstring_class)]:
print >> sys.stderr, " ", c
if key:
classes[getattr(c, key)] = c
else:
classes.append(c)
if get_mod:
return (modules, classes)
else:
return classes
elif get_mod:
return modules
_supported_formats = dload(get_mod=False, key='fid', fstring_mod='format_*.py', fstring_class='Format')
My Idea
The whole messing with filesystem-paths and the like is probably messy anyway. I would like to handle this with module namespaces or something similar, but I'm kinda lost right now on how start and how to address the modules, so they reachable from anywhere.
A:
There are two fixes you need to make to your code:
You should call __import__(m, globals(), locals()) instead of __import__(m). This is needed for Python to locate the modules within the package.
Your code doesn't remove the .py extension properly since you call index() on the wrong string. If it will always be a .py extension, you can simply use p.split(fn)[1][:-3] instead.
A:
First you must make it so that your code works regardless of the current working directory. For that you use the __file__ variable. You should also use absolute imports.
So something like (untested):
supported_formats = {}
for fn in os.listdir(os.path.dirname(__file__)):
if fn.endswith('.py'):
exec ("from formats import %s" % fn[:-3]) in supported_formats
A:
A module is searched in sys.path. You should be able to extend sys.path with the path to your module. I'm also not really sure whether you can load a module on sys.path with a 'module.py' convention, I would think without '.py' is preferred.
This is obviously not a solution, but may be handy nonetheless.
A:
I thought if you did something that, 'formats' would be your package, so when you tell it import formats you should be able to access the rest of the modules inside that package, so, you would have something like formats.format_a.your_method
Not sure though, I'm just a n00b.
A:
Here's the code I came up with after the corrections from interjay. Still not sure if this is good style.
def load_modules(filemask='*.py', ignore_list=('__init__.py', )):
modules = {}
dirname = os.path.dirname(__file__)
if dirname:
filemask = os.path.join(dirname, filemask)
for fn in glob.glob(filemask):
fn = os.path.split(fn)[1]
if fn in ignore_list:
continue
fn = os.path.splitext(fn)[0]
modules[fn] = __import__(fn, globals(), locals())
return modules
|
How to load modules dynamically on package import?
|
Given the following example layout:
test/
test.py
formats/
__init__.py
format_a.py
format_b.py
What I try to archive is, that whenever I import formats, the __init__.py looks for all available modules in the formats subdir, loads them and makes them available (right now simply through a variable, supported_formats). If theres a better, more pythonic or otherwise approach to dynamically loading stuff on runtime, based on physical available files, please tell.
My Approach
I tried something like this (in __init__.py):
supported_formats = [__import__(f[:f.index('.py')]) for f in glob.glob('*.py')]
So far I just get it to work, when I run __init__.py from the command line (from the formats subdir or from other directories) . But when I import it from test.py, it bails on me like this:
ImportError: No module named format_a.py
Same when I import it from the python interpreter, when I started the interpreter in an other directory but the formats subdir.
Here's the whole code. It also looks for a specific class and stores one instance of each class in an dict, but loading the modules dynamically is the main part I don't get:
def dload(get_cls=True, get_mod=True, key=None, fstring_mod='*.py', fstring_class=''):
if p.dirname(__file__):
path = p.split(p.abspath(__file__))[0]
fstring_mod = p.join(path, fstring_mod)
print >> sys.stderr, 'Path-Glob:', fstring_mod
modules = [p.split(fn)[1][:fn.index('.py')] for fn in glob.glob(fstring_mod)]
print >> sys.stderr, 'Modules:', ', '.join(modules)
modules = [__import__(m) for m in modules]
if get_cls:
classes = {} if key else []
for m in modules:
print >> sys.stderr, "-", m
for c in [m.__dict__[c]() for c in m.__dict__ if c.startswith(fstring_class)]:
print >> sys.stderr, " ", c
if key:
classes[getattr(c, key)] = c
else:
classes.append(c)
if get_mod:
return (modules, classes)
else:
return classes
elif get_mod:
return modules
_supported_formats = dload(get_mod=False, key='fid', fstring_mod='format_*.py', fstring_class='Format')
My Idea
The whole messing with filesystem-paths and the like is probably messy anyway. I would like to handle this with module namespaces or something similar, but I'm kinda lost right now on how start and how to address the modules, so they reachable from anywhere.
|
[
"There are two fixes you need to make to your code:\n\nYou should call __import__(m, globals(), locals()) instead of __import__(m). This is needed for Python to locate the modules within the package.\nYour code doesn't remove the .py extension properly since you call index() on the wrong string. If it will always be a .py extension, you can simply use p.split(fn)[1][:-3] instead.\n\n",
"First you must make it so that your code works regardless of the current working directory. For that you use the __file__ variable. You should also use absolute imports.\nSo something like (untested):\nsupported_formats = {}\nfor fn in os.listdir(os.path.dirname(__file__)):\n if fn.endswith('.py'):\n exec (\"from formats import %s\" % fn[:-3]) in supported_formats\n\n",
"A module is searched in sys.path. You should be able to extend sys.path with the path to your module. I'm also not really sure whether you can load a module on sys.path with a 'module.py' convention, I would think without '.py' is preferred.\nThis is obviously not a solution, but may be handy nonetheless.\n",
"I thought if you did something that, 'formats' would be your package, so when you tell it import formats you should be able to access the rest of the modules inside that package, so, you would have something like formats.format_a.your_method\nNot sure though, I'm just a n00b.\n",
"Here's the code I came up with after the corrections from interjay. Still not sure if this is good style.\ndef load_modules(filemask='*.py', ignore_list=('__init__.py', )):\n modules = {}\n dirname = os.path.dirname(__file__)\n if dirname:\n filemask = os.path.join(dirname, filemask)\n for fn in glob.glob(filemask):\n fn = os.path.split(fn)[1]\n if fn in ignore_list:\n continue\n fn = os.path.splitext(fn)[0]\n modules[fn] = __import__(fn, globals(), locals())\n return modules\n\n"
] |
[
1,
1,
0,
0,
0
] |
[] |
[] |
[
"dynamic",
"import",
"packaging",
"python"
] |
stackoverflow_0002001940_dynamic_import_packaging_python.txt
|
Q:
Cannot decode/encode in UTF-8
I have a text-box which allows users to enter a word.
The user enters: über
In the backend, I get the word like this:
def form_process(request):
word = request.GET.get('the_word')
word = word.encode('utf-8')
#word = word.decode('utf-8')
print word
For some reason, I cannot decode or encode this!!
It gives me the error:
UnicodeEncodeError
('ascii', u'\ufffd', 0, 1, 'ordinal not in range(128)')
Edit: When I do "repr(word)", this is what I get:
u'\ufffd'
A:
Did you remember to put:
accept-charset="utf-8"
in the form tag?
EDIT: Is the DEFAULT_CHARSET in settings.py set to 'utf-8' ?
A:
Solved!
I had escape(word) ...in the javascript ...before I passed it to the server.
A:
Is there any reason to use print word? If not, its should work without those lines.
def form_process(request):
word = request.GET.get('the_word')
|
Cannot decode/encode in UTF-8
|
I have a text-box which allows users to enter a word.
The user enters: über
In the backend, I get the word like this:
def form_process(request):
word = request.GET.get('the_word')
word = word.encode('utf-8')
#word = word.decode('utf-8')
print word
For some reason, I cannot decode or encode this!!
It gives me the error:
UnicodeEncodeError
('ascii', u'\ufffd', 0, 1, 'ordinal not in range(128)')
Edit: When I do "repr(word)", this is what I get:
u'\ufffd'
|
[
"Did you remember to put:\naccept-charset=\"utf-8\"\n\nin the form tag?\nEDIT: Is the DEFAULT_CHARSET in settings.py set to 'utf-8' ?\n",
"Solved!\nI had escape(word) ...in the javascript ...before I passed it to the server.\n",
"Is there any reason to use print word? If not, its should work without those lines.\ndef form_process(request):\n word = request.GET.get('the_word')\n\n"
] |
[
1,
1,
0
] |
[] |
[] |
[
"decoding",
"django",
"encoding",
"python",
"utf_8"
] |
stackoverflow_0002010323_decoding_django_encoding_python_utf_8.txt
|
Q:
the official name of this programming approach to compute the union and the intersection
I [surely re] invented this [wheel] when I wanted to compute the union and the intersection and diff of two sets (stored as lists) at the same time. Initial code (not the tightest):
dct = {}
for a in lst1:
dct[a] = 1
for b in lst2:
if b in dct:
dct[b] -= 1
else:
dct[b] = -1
union = [k for k in dct]
inter = [k for k in dct if dct[k] == 0]
oneminustwo = [k for k in dct if dct[k] == 1]
twominusone = [k for k in dct if dct[k] == -1]
Then I realized that I should use 00, 01, 10, and 11 instead of -1, 1, 0, ...
So, a bit at position n indicates membership in set n.
This can be generalized to up to 32 sets using an 32-bit int, or to any number of sets using a bitarray, or a string. So, you pre-compute this dictionary once, and then use very fast O(n) queries to extract elements of interest. For instance, all 1s means intersection of all sets. All 0s is a special one - will not occur.
Anyhow, this is not to toot my own horn. This surely was invented before and has a name. What is it called? Is this approach used in databases somewhere?
A:
Using an N bit integer to represent N booleans is a special case of the data structure known as a perfect hash table. Notice you're explicitly using dicts (which are general hash tables) in the idea that prompted you to think about bitsets. It's a hash table because you use hashes to find a value, and it's perfect because you never have collisions. The special case is because of how the table is packed and stored.
Formulate the hash function, which shows how it's different from an array:
int bitset_hash(int n) {
// domain of this function is only non-negative ints
return 1 << n;
}
Notice bitset_hash(3) is 0b1000, which corresponds to the 4th item (offset/index 3) when using a C int and bitwise operations. (Because of the storage implementation detail, bitwise operations are also used to manipulate a specific item from the hash.)
Extending the approach to use bitwise-and/-or/-xor for set operations is common, and doesn't require any special name other than "set operations" or, if you need a buzzword, "set theory".
Finally, here's another example use of it in a prime sieve (I've used this code on Project Euler solutions):
class Sieve(object):
def __init__(self, stop):
self.stop = stop
self.data = [0] * (stop // 32 // 2 + 1)
self.len = 1 if stop >= 2 else 0
for n in xrange(3, stop, 2):
if self[n]:
self.len += 1
for n2 in xrange(n * 3, stop, n * 2):
self[n2] = False
def __getitem__(self, idx):
assert idx >= 2
if idx % 2 == 0:
return idx == 2
int_n, bit_n = divmod(idx // 2, 32)
return not bool(self.data[int_n] & (1 << bit_n))
def __setitem__(self, idx, value):
assert idx >= 2 and idx % 2 != 0
assert value is False
int_n, bit_n = divmod(idx // 2, 32)
self.data[int_n] |= (1 << bit_n)
def __len__(self):
return self.len
def __iter__(self):
yield 2
for n in xrange(3, self.stop, 2):
if self[n]:
yield n
A:
Yes, it is sometimes used in databases, for example PostgreSQL. As mentions Wikipedia:
Some database systems that do not
offer persistent bitmap indexes use
bitmaps internally to speed up query
processing. For example, PostgreSQL
versions 8.1 and later implement a
"bitmap index scan" optimization to
speed up arbitrarily complex logical
operations between available indexes
on a single table.
(from http://en.wikipedia.org/wiki/Bitmap_index)
A:
It's very common to use an integer to represent a set of small integers; it's often called a bitset or bitvector. Here you're using an integer to represent "the set of input sequences that contain this value".
The operation you're doing reminds me of reversing a multimap.
In your case, the input is a list of lists:
[["a", "b"], ["a", "c", "d"]]
But you could instead think of it as a bag of ordered pairs, like this:
0, "a"
0, "b"
1, "a"
1, "c"
1, "d"
You're simply constructing a table that contains the reversed pairs
"a", 0
"b", 0
"a", 1
"c", 1
"d", 1
which looks like this:
{"a": [0, 1],
"b": [0],
"c": [1],
"d": [1]}
and you happen to be representing those arrays of integers using bitvectors.
The original data structure (the list of lists) made it easy to iterate over all values for a given list. The reversed data structure (the dictionary of lists) makes it easy to find all lists that have a given value.
A:
Is the idea of a bit field what you're looking for? Every bit of your ... field (for lack of a better word) represents a flag. In this case, your flag is membership in set N.
Edit - I think I misunderstood which idea you were referring to. Disregard?
|
the official name of this programming approach to compute the union and the intersection
|
I [surely re] invented this [wheel] when I wanted to compute the union and the intersection and diff of two sets (stored as lists) at the same time. Initial code (not the tightest):
dct = {}
for a in lst1:
dct[a] = 1
for b in lst2:
if b in dct:
dct[b] -= 1
else:
dct[b] = -1
union = [k for k in dct]
inter = [k for k in dct if dct[k] == 0]
oneminustwo = [k for k in dct if dct[k] == 1]
twominusone = [k for k in dct if dct[k] == -1]
Then I realized that I should use 00, 01, 10, and 11 instead of -1, 1, 0, ...
So, a bit at position n indicates membership in set n.
This can be generalized to up to 32 sets using an 32-bit int, or to any number of sets using a bitarray, or a string. So, you pre-compute this dictionary once, and then use very fast O(n) queries to extract elements of interest. For instance, all 1s means intersection of all sets. All 0s is a special one - will not occur.
Anyhow, this is not to toot my own horn. This surely was invented before and has a name. What is it called? Is this approach used in databases somewhere?
|
[
"Using an N bit integer to represent N booleans is a special case of the data structure known as a perfect hash table. Notice you're explicitly using dicts (which are general hash tables) in the idea that prompted you to think about bitsets. It's a hash table because you use hashes to find a value, and it's perfect because you never have collisions. The special case is because of how the table is packed and stored.\nFormulate the hash function, which shows how it's different from an array:\nint bitset_hash(int n) {\n // domain of this function is only non-negative ints\n return 1 << n;\n}\n\nNotice bitset_hash(3) is 0b1000, which corresponds to the 4th item (offset/index 3) when using a C int and bitwise operations. (Because of the storage implementation detail, bitwise operations are also used to manipulate a specific item from the hash.)\nExtending the approach to use bitwise-and/-or/-xor for set operations is common, and doesn't require any special name other than \"set operations\" or, if you need a buzzword, \"set theory\".\nFinally, here's another example use of it in a prime sieve (I've used this code on Project Euler solutions):\nclass Sieve(object):\n def __init__(self, stop):\n self.stop = stop\n self.data = [0] * (stop // 32 // 2 + 1)\n self.len = 1 if stop >= 2 else 0\n for n in xrange(3, stop, 2):\n if self[n]:\n self.len += 1\n for n2 in xrange(n * 3, stop, n * 2):\n self[n2] = False\n\n def __getitem__(self, idx):\n assert idx >= 2\n if idx % 2 == 0:\n return idx == 2\n int_n, bit_n = divmod(idx // 2, 32)\n return not bool(self.data[int_n] & (1 << bit_n))\n\n def __setitem__(self, idx, value):\n assert idx >= 2 and idx % 2 != 0\n assert value is False\n int_n, bit_n = divmod(idx // 2, 32)\n self.data[int_n] |= (1 << bit_n)\n\n def __len__(self):\n return self.len\n\n def __iter__(self):\n yield 2\n for n in xrange(3, self.stop, 2):\n if self[n]:\n yield n\n\n",
"Yes, it is sometimes used in databases, for example PostgreSQL. As mentions Wikipedia:\n\nSome database systems that do not\n offer persistent bitmap indexes use\n bitmaps internally to speed up query\n processing. For example, PostgreSQL\n versions 8.1 and later implement a\n \"bitmap index scan\" optimization to\n speed up arbitrarily complex logical\n operations between available indexes\n on a single table.\n\n(from http://en.wikipedia.org/wiki/Bitmap_index)\n",
"It's very common to use an integer to represent a set of small integers; it's often called a bitset or bitvector. Here you're using an integer to represent \"the set of input sequences that contain this value\".\nThe operation you're doing reminds me of reversing a multimap.\nIn your case, the input is a list of lists:\n[[\"a\", \"b\"], [\"a\", \"c\", \"d\"]]\n\nBut you could instead think of it as a bag of ordered pairs, like this:\n0, \"a\"\n0, \"b\"\n1, \"a\"\n1, \"c\"\n1, \"d\"\n\nYou're simply constructing a table that contains the reversed pairs\n\"a\", 0\n\"b\", 0\n\"a\", 1\n\"c\", 1\n\"d\", 1\n\nwhich looks like this:\n{\"a\": [0, 1],\n \"b\": [0],\n \"c\": [1],\n \"d\": [1]}\n\nand you happen to be representing those arrays of integers using bitvectors.\nThe original data structure (the list of lists) made it easy to iterate over all values for a given list. The reversed data structure (the dictionary of lists) makes it easy to find all lists that have a given value.\n",
"Is the idea of a bit field what you're looking for? Every bit of your ... field (for lack of a better word) represents a flag. In this case, your flag is membership in set N.\nEdit - I think I misunderstood which idea you were referring to. Disregard?\n"
] |
[
7,
4,
2,
1
] |
[] |
[] |
[
"algorithm",
"bit_fields",
"language_agnostic",
"python",
"set"
] |
stackoverflow_0002010132_algorithm_bit_fields_language_agnostic_python_set.txt
|
Q:
Python: why aren't variables updating?
A python program that I'm debugging has the following code (including print statements for debugging):
print "BEFORE..."
print "oup[\"0\"] = " + str(oup["0"])
print "oup[\"2008\"] = " + str(oup["2008"])
print "oup[\"2009\"] = " + str(oup["2009"])
oup0 = oup["0"]
oup2008 = oup["2008"]
oup2009 = oup["2009"]
ouptotal = oup2008 + oup2009
print "ouptotal = " + str(ouptotal)
if ouptotal > 0:
oup["2008"] = oup2008 + oup0 * (oup2008 / ouptotal)
oup["2009"] = oup2009 + oup0 * (oup2009 / ouptotal)
print "AFTER..."
print "oup[\"0\"] = " + str(oup["0"])
print "oup[\"2008\"] = " + str(oup["2008"])
print "oup[\"2009\"] = " + str(oup["2009"])
Up until that point, the variables update correctly. When I run that code, I get the following on the screen:
BEFORE...
oup["0"] = 22032
oup["2008"] = 541
oup["2009"] = 15223
ouptotal = 15764
AFTER...
oup["0"] = 22032
oup["2008"] = 541
oup["2009"] = 15223
Why aren't oup["2008"] and oup["2009"] updating?
(Python version is 2.6.2 on a "Jaunty" Ubuntu machine.)
A:
If the values are integers, then (oup2008 / ouptotal) will be zero, so they will be updated to their own value + 0, hence no change.
Convert them to floats for the calculation, then back if required, and it should work as expected.
Example:
oup["2008"] = oup2008 + int(oup0 * (float(oup2008) / ouptotal))
A:
Integer division results in integer results. either use float() on one of the division terms or add from __future__ import division at the top.
A:
They are, you're just updating them with the same value. In Python 2.6, / is still an integer division operator(reference), so dividing (oup2008 / ouptotal) is dividing a number by a bigger number, which always results in zero. If you want the behavior from later versions, were / is a floating-point operator, you can get it with a future statement importing division.
|
Python: why aren't variables updating?
|
A python program that I'm debugging has the following code (including print statements for debugging):
print "BEFORE..."
print "oup[\"0\"] = " + str(oup["0"])
print "oup[\"2008\"] = " + str(oup["2008"])
print "oup[\"2009\"] = " + str(oup["2009"])
oup0 = oup["0"]
oup2008 = oup["2008"]
oup2009 = oup["2009"]
ouptotal = oup2008 + oup2009
print "ouptotal = " + str(ouptotal)
if ouptotal > 0:
oup["2008"] = oup2008 + oup0 * (oup2008 / ouptotal)
oup["2009"] = oup2009 + oup0 * (oup2009 / ouptotal)
print "AFTER..."
print "oup[\"0\"] = " + str(oup["0"])
print "oup[\"2008\"] = " + str(oup["2008"])
print "oup[\"2009\"] = " + str(oup["2009"])
Up until that point, the variables update correctly. When I run that code, I get the following on the screen:
BEFORE...
oup["0"] = 22032
oup["2008"] = 541
oup["2009"] = 15223
ouptotal = 15764
AFTER...
oup["0"] = 22032
oup["2008"] = 541
oup["2009"] = 15223
Why aren't oup["2008"] and oup["2009"] updating?
(Python version is 2.6.2 on a "Jaunty" Ubuntu machine.)
|
[
"If the values are integers, then (oup2008 / ouptotal) will be zero, so they will be updated to their own value + 0, hence no change.\nConvert them to floats for the calculation, then back if required, and it should work as expected.\nExample:\noup[\"2008\"] = oup2008 + int(oup0 * (float(oup2008) / ouptotal))\n\n",
"Integer division results in integer results. either use float() on one of the division terms or add from __future__ import division at the top.\n",
"They are, you're just updating them with the same value. In Python 2.6, / is still an integer division operator(reference), so dividing (oup2008 / ouptotal) is dividing a number by a bigger number, which always results in zero. If you want the behavior from later versions, were / is a floating-point operator, you can get it with a future statement importing division.\n"
] |
[
6,
3,
1
] |
[] |
[] |
[
"integer",
"python",
"variables"
] |
stackoverflow_0002010566_integer_python_variables.txt
|
Q:
draw text with GLUT / OpenGL in Python
I m drawing text with OpenGL in Python. It all works ok, however the font is really bad.
If I make it thick the letters start to look very occurred (especially the ones which are round like 'o' or 'g'. For the purpose of my program it must be thick. Is there any font I could use which does not look so bad when thickened, or is there another way to draw it?
I am really stuck and will appreciate any answer,
A:
Try a more sophisticated text rendering solution. Perhaps something like pyftgl would get you better results, by rendering full-quality TrueType fonts.
A:
http://nehe.gamedev.net/data/lessons/lesson.asp?lesson=43
At the bottom is the python version of this lesson which shows you how to load freetype fonts with the Python Image Library (PIL) http://www.pythonware.com/products/pil/
|
draw text with GLUT / OpenGL in Python
|
I m drawing text with OpenGL in Python. It all works ok, however the font is really bad.
If I make it thick the letters start to look very occurred (especially the ones which are round like 'o' or 'g'. For the purpose of my program it must be thick. Is there any font I could use which does not look so bad when thickened, or is there another way to draw it?
I am really stuck and will appreciate any answer,
|
[
"Try a more sophisticated text rendering solution. Perhaps something like pyftgl would get you better results, by rendering full-quality TrueType fonts.\n",
"http://nehe.gamedev.net/data/lessons/lesson.asp?lesson=43\nAt the bottom is the python version of this lesson which shows you how to load freetype fonts with the Python Image Library (PIL) http://www.pythonware.com/products/pil/\n"
] |
[
1,
0
] |
[] |
[] |
[
"draw",
"opengl",
"python",
"text"
] |
stackoverflow_0000730952_draw_opengl_python_text.txt
|
Q:
python crypto high level wrapper
I'm using PyCrypto (on google app engine) for AES encryption.
PyCrypto gives I guess a raw interface to AES--i need to pad my keys and my inputs to 16 byte multiples.
Is there a higher level library which takes care of this stuff for me?
A:
An easy, friendly wrapper on top of PyCrypto is ezPyCrypto.
|
python crypto high level wrapper
|
I'm using PyCrypto (on google app engine) for AES encryption.
PyCrypto gives I guess a raw interface to AES--i need to pad my keys and my inputs to 16 byte multiples.
Is there a higher level library which takes care of this stuff for me?
|
[
"An easy, friendly wrapper on top of PyCrypto is ezPyCrypto.\n"
] |
[
5
] |
[] |
[] |
[
"aes",
"google_app_engine",
"pycrypto",
"python"
] |
stackoverflow_0002010575_aes_google_app_engine_pycrypto_python.txt
|
Q:
What's the suggested way of importing modules within a django project
This has always bothered me, and I've never really come up with my own preferred way of doing this.
When importing something from one of your own applications in a django project, do you import with:
from myproject.mymodule.model import SomeModel
from myproject.anotherone.model import AnotherModel
or, do you do:
from mymodule.model imoprt SomeModel
from anotherone.model import AnotherModel
Of course, either will work as long as you set your PYTHONPATH correctly when deploying. Even a combination of the two within a given project will work.
My issue with the second form is when you have a utils.py or the like sitting in the your project.
# This feels wrong
import utils
But, that could just be me.
Which one is better and why?
A:
I would recommend using the second alternative:
from mymodule.model import SomeModel
from anotherone.model import AnotherModel
In Django, it's recommended to write reusable applications, that you may deploy in multiple projects. Specifying the name of the project would hinder this possibility. It would even complicate the case where you simply change the name of the top project folder!
This is the tradition that most django applications use (e.g. pinax, django contrib, etc).
For more details, you should listen to DjangoCon 2008: Reusable Apps.
A:
I prefer to use absolute imports whenever possible. The first reason is that relative imports are on their way out in Python 3, so it's best not to get into that habit. (Based on the way you phrased the question, I'm assuming that you put the application packages inside your project package.) The second reason is that it makes the intent of what you're importing more explicit.
Though my absolute best practice is to not put my application packages inside the project package. That way, it's easier to move the applications around, and when you use absolute imports inside the package, if you use the same application later inside a differently-named project, you won't have to rewrite all the imports to reflect the different project name.
A:
How are you packaging your modules normally? If you're packaging them all under the "myproject" module, you should just keep doing that. If you're not, there's no reason to start. I don't see that being in a Django project has anything to do with the question--if you're not reusing code, why bother segregating your packages?
But really, the bigger point is that you're not thinking about how to package and distribute your libraries in a broader sense. Even if they're just a collection of handy utility routines, and you don't intend to share them, you should be thinking about namespace issues. The Python Tutorial has a good basic discussion of the concepts.
|
What's the suggested way of importing modules within a django project
|
This has always bothered me, and I've never really come up with my own preferred way of doing this.
When importing something from one of your own applications in a django project, do you import with:
from myproject.mymodule.model import SomeModel
from myproject.anotherone.model import AnotherModel
or, do you do:
from mymodule.model imoprt SomeModel
from anotherone.model import AnotherModel
Of course, either will work as long as you set your PYTHONPATH correctly when deploying. Even a combination of the two within a given project will work.
My issue with the second form is when you have a utils.py or the like sitting in the your project.
# This feels wrong
import utils
But, that could just be me.
Which one is better and why?
|
[
"I would recommend using the second alternative:\nfrom mymodule.model import SomeModel\nfrom anotherone.model import AnotherModel\n\nIn Django, it's recommended to write reusable applications, that you may deploy in multiple projects. Specifying the name of the project would hinder this possibility. It would even complicate the case where you simply change the name of the top project folder!\nThis is the tradition that most django applications use (e.g. pinax, django contrib, etc).\nFor more details, you should listen to DjangoCon 2008: Reusable Apps.\n",
"I prefer to use absolute imports whenever possible. The first reason is that relative imports are on their way out in Python 3, so it's best not to get into that habit. (Based on the way you phrased the question, I'm assuming that you put the application packages inside your project package.) The second reason is that it makes the intent of what you're importing more explicit.\nThough my absolute best practice is to not put my application packages inside the project package. That way, it's easier to move the applications around, and when you use absolute imports inside the package, if you use the same application later inside a differently-named project, you won't have to rewrite all the imports to reflect the different project name.\n",
"How are you packaging your modules normally? If you're packaging them all under the \"myproject\" module, you should just keep doing that. If you're not, there's no reason to start. I don't see that being in a Django project has anything to do with the question--if you're not reusing code, why bother segregating your packages?\nBut really, the bigger point is that you're not thinking about how to package and distribute your libraries in a broader sense. Even if they're just a collection of handy utility routines, and you don't intend to share them, you should be thinking about namespace issues. The Python Tutorial has a good basic discussion of the concepts.\n"
] |
[
5,
1,
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002010746_django_python.txt
|
Q:
Cherrypy hanging on form post
I'm currently trying to remove a legacy python framework (webware 0.8.1) and layer cherrypy 3.1.2 on top of it. Instead of converting all the webware pages to cherrypy pages, I'm merely processing it through webware and passing it to cherrypy like so.
def default(self, url, *suburl, **kwarg):
...snip...
strmout = DispatcherIO()
request = HTTPRequest(local_req)
transaction = self.create_transaction(request)
response = self.create_response(transaction, strmout)
transaction.setServlet(servlet)
transaction.awake()
transaction.respond()
return str(strmout)
This works fine for any page that doesn't include a POST. But with any page including a post such as the login, cherrypy would hang at:
request = HTTPRequest(local_req)
This calls FieldStorage which will call the constructor for the parant cgi.FieldStorage. This is where it finally hangs.
However, if I were to press ctrl-c on the terminal, it would continue processing and then terminate after the page successfully loads. So with the login page, I would click "login", it would hang, I will then press ctrl-c on the terminal, it will log me in and then shutdown cherrypy.
I found that if I used cherrypy.engine.start instead of quickstart it would not initiate any signal handlers. What would happen in this case would result in something similar as to the previous behaviour however cherrypy would continue running.
What could be causing this problem? I would really appreciate any help. Cheers.
HTTPRequest
FieldStorage
A:
I don't really have experience with Webware, but based on the appearance of your code, Webware is trying to use cgi.FieldStorage to retrieve your field variables, but FieldStorage can't get the length, or gets the length incorrectly (probably because whatever Webware does to get the Content-Length header doesn't work in your CherryPy WSGI environment - the default implementation retrieves the HTTP_CONTENT_LENGTH environment variable, and Webware probably does something similarly hacky), so it's reading and then it hangs. I had a similar problem often when working with CGI.
The best solution is to not use cgi.FieldStorage. If the HTTPRequest object in question is coming from Webware, my recommendation is to either port your site to CherryPy completely (or some other Web framework), or just use Webware in its native environment. Hacking something up might be possible, but WSGI is very different from Webware's native environment of its own application server.
|
Cherrypy hanging on form post
|
I'm currently trying to remove a legacy python framework (webware 0.8.1) and layer cherrypy 3.1.2 on top of it. Instead of converting all the webware pages to cherrypy pages, I'm merely processing it through webware and passing it to cherrypy like so.
def default(self, url, *suburl, **kwarg):
...snip...
strmout = DispatcherIO()
request = HTTPRequest(local_req)
transaction = self.create_transaction(request)
response = self.create_response(transaction, strmout)
transaction.setServlet(servlet)
transaction.awake()
transaction.respond()
return str(strmout)
This works fine for any page that doesn't include a POST. But with any page including a post such as the login, cherrypy would hang at:
request = HTTPRequest(local_req)
This calls FieldStorage which will call the constructor for the parant cgi.FieldStorage. This is where it finally hangs.
However, if I were to press ctrl-c on the terminal, it would continue processing and then terminate after the page successfully loads. So with the login page, I would click "login", it would hang, I will then press ctrl-c on the terminal, it will log me in and then shutdown cherrypy.
I found that if I used cherrypy.engine.start instead of quickstart it would not initiate any signal handlers. What would happen in this case would result in something similar as to the previous behaviour however cherrypy would continue running.
What could be causing this problem? I would really appreciate any help. Cheers.
HTTPRequest
FieldStorage
|
[
"I don't really have experience with Webware, but based on the appearance of your code, Webware is trying to use cgi.FieldStorage to retrieve your field variables, but FieldStorage can't get the length, or gets the length incorrectly (probably because whatever Webware does to get the Content-Length header doesn't work in your CherryPy WSGI environment - the default implementation retrieves the HTTP_CONTENT_LENGTH environment variable, and Webware probably does something similarly hacky), so it's reading and then it hangs. I had a similar problem often when working with CGI.\nThe best solution is to not use cgi.FieldStorage. If the HTTPRequest object in question is coming from Webware, my recommendation is to either port your site to CherryPy completely (or some other Web framework), or just use Webware in its native environment. Hacking something up might be possible, but WSGI is very different from Webware's native environment of its own application server.\n"
] |
[
2
] |
[] |
[] |
[
"cherrypy",
"python"
] |
stackoverflow_0002010766_cherrypy_python.txt
|
Q:
Python halts while iteratively processing my 1GB csv file
I have two files:
metadata.csv: contains an ID, followed by vendor name, a filename, etc
hashes.csv: contains an ID, followed by a hash
The ID is essentially a foreign key of sorts, relating file metadata to its hash.
I wrote this script to quickly extract out all hashes associated with a particular vendor. It craps out before it finishes processing hashes.csv
stored_ids = []
# this file is about 1 MB
entries = csv.reader(open(options.entries, "rb"))
for row in entries:
# row[2] is the vendor
if row[2] == options.vendor:
# row[0] is the ID
stored_ids.append(row[0])
# this file is 1 GB
hashes = open(options.hashes, "rb")
# I iteratively read the file here,
# just in case the csv module doesn't do this.
for line in hashes:
# not sure if stored_ids contains strings or ints here...
# this probably isn't the problem though
if line.split(",")[0] in stored_ids:
# if its one of the IDs we're looking for, print the file and hash to STDOUT
print "%s,%s" % (line.split(",")[2], line.split(",")[4])
hashes.close()
This script gets about 2000 entries through hashes.csv before it halts. What am I doing wrong? I thought I was processing it line by line.
ps. the csv files are the popular HashKeeper format and the files I am parsing are the NSRL hash sets. http://www.nsrl.nist.gov/Downloads.htm#converter
UPDATE: working solution below. Thanks everyone who commented!
entries = csv.reader(open(options.entries, "rb"))
stored_ids = dict((row[0],1) for row in entries if row[2] == options.vendor)
hashes = csv.reader(open(options.hashes, "rb"))
matches = dict((row[2], row[4]) for row in hashes if row[0] in stored_ids)
for k, v in matches.iteritems():
print "%s,%s" % (k, v)
A:
"Craps out" is not a particularly good description. What does it do? Does it swap? Fill all memory? Or just eats CPU without appearing to do anything?
However, just for a start, use a dictionnary rather than a list for stored_ids. Searching in a dictionnary is usually done in O(1) time while searching in a list is O(n).
Edit: here is a trivial micro-benchmark:
$ python -m timeit -s "l=range(1000000)" "1000001 in l"
10 loops, best of 3: 71.1 msec per loop
$ python -m timeit -s "s=set(range(1000000))" "1000001 in s"
10000000 loops, best of 3: 0.174 usec per loop
As you can see, a set (which has the same performance characteristics as a dict) does searches among one million integers more than 10000 times faster than a similar list (much less than a microsecond vs. almost 100 milliseconds per lookup). Consider that such a lookup happens for each line of your 1GB file and you understand how big the issue can be.
A:
This code would die on any line that does not have at least 4 commas; for example, it would die on an empty line. If you are sure you dont want to use csv reader, then at least catch IndexError on line.split(',')[4]
A:
Please explain what do you mean by halt? it hangs or quits? are there any error traceback?
a) It will fail on any line not having ","
>>> 'hmmm'.split(",")[2]
Traceback (most recent call last):
File "<string>", line 1, in <string>
IndexError: list index out of range
b) why are you splitting line multiple times, instead do this
tokens = line.split(",")
if len(tokens) >=5 and tokens[0] in stored_ids:
print "%s,%s" % (tokens[2], tokens[4])
c) create a dict of stored_ids, so tokens[0] in stored_id will be fast
d) wrap your inner code in try/exept and see if there are any errors
e) where are you running it on command line or some IDE ?
A:
Searching in array took O(n), so use dict instead
stored_ids = dict((row[0],1) for row in entries if row[2] == options.vendor)
Or Use set
a=set(row[0] for row in entries if row[2] == options.vendor)
b=set(line.split(",")[0] for line in hashes)
c=a.intersection(b)
in c you will only have found strings for both hashes, and csv
|
Python halts while iteratively processing my 1GB csv file
|
I have two files:
metadata.csv: contains an ID, followed by vendor name, a filename, etc
hashes.csv: contains an ID, followed by a hash
The ID is essentially a foreign key of sorts, relating file metadata to its hash.
I wrote this script to quickly extract out all hashes associated with a particular vendor. It craps out before it finishes processing hashes.csv
stored_ids = []
# this file is about 1 MB
entries = csv.reader(open(options.entries, "rb"))
for row in entries:
# row[2] is the vendor
if row[2] == options.vendor:
# row[0] is the ID
stored_ids.append(row[0])
# this file is 1 GB
hashes = open(options.hashes, "rb")
# I iteratively read the file here,
# just in case the csv module doesn't do this.
for line in hashes:
# not sure if stored_ids contains strings or ints here...
# this probably isn't the problem though
if line.split(",")[0] in stored_ids:
# if its one of the IDs we're looking for, print the file and hash to STDOUT
print "%s,%s" % (line.split(",")[2], line.split(",")[4])
hashes.close()
This script gets about 2000 entries through hashes.csv before it halts. What am I doing wrong? I thought I was processing it line by line.
ps. the csv files are the popular HashKeeper format and the files I am parsing are the NSRL hash sets. http://www.nsrl.nist.gov/Downloads.htm#converter
UPDATE: working solution below. Thanks everyone who commented!
entries = csv.reader(open(options.entries, "rb"))
stored_ids = dict((row[0],1) for row in entries if row[2] == options.vendor)
hashes = csv.reader(open(options.hashes, "rb"))
matches = dict((row[2], row[4]) for row in hashes if row[0] in stored_ids)
for k, v in matches.iteritems():
print "%s,%s" % (k, v)
|
[
"\"Craps out\" is not a particularly good description. What does it do? Does it swap? Fill all memory? Or just eats CPU without appearing to do anything?\nHowever, just for a start, use a dictionnary rather than a list for stored_ids. Searching in a dictionnary is usually done in O(1) time while searching in a list is O(n).\nEdit: here is a trivial micro-benchmark:\n$ python -m timeit -s \"l=range(1000000)\" \"1000001 in l\"\n10 loops, best of 3: 71.1 msec per loop\n$ python -m timeit -s \"s=set(range(1000000))\" \"1000001 in s\"\n10000000 loops, best of 3: 0.174 usec per loop\n\nAs you can see, a set (which has the same performance characteristics as a dict) does searches among one million integers more than 10000 times faster than a similar list (much less than a microsecond vs. almost 100 milliseconds per lookup). Consider that such a lookup happens for each line of your 1GB file and you understand how big the issue can be.\n",
"This code would die on any line that does not have at least 4 commas; for example, it would die on an empty line. If you are sure you dont want to use csv reader, then at least catch IndexError on line.split(',')[4]\n",
"Please explain what do you mean by halt? it hangs or quits? are there any error traceback?\na) It will fail on any line not having \",\"\n>>> 'hmmm'.split(\",\")[2]\nTraceback (most recent call last):\n File \"<string>\", line 1, in <string>\nIndexError: list index out of range\n\nb) why are you splitting line multiple times, instead do this\ntokens = line.split(\",\")\n\nif len(tokens) >=5 and tokens[0] in stored_ids:\n print \"%s,%s\" % (tokens[2], tokens[4])\n\nc) create a dict of stored_ids, so tokens[0] in stored_id will be fast\nd) wrap your inner code in try/exept and see if there are any errors\ne) where are you running it on command line or some IDE ?\n",
"Searching in array took O(n), so use dict instead\nstored_ids = dict((row[0],1) for row in entries if row[2] == options.vendor)\n\nOr Use set\na=set(row[0] for row in entries if row[2] == options.vendor)\nb=set(line.split(\",\")[0] for line in hashes)\nc=a.intersection(b)\n\nin c you will only have found strings for both hashes, and csv\n"
] |
[
3,
0,
0,
0
] |
[] |
[] |
[
"csv",
"large_files",
"memory",
"python"
] |
stackoverflow_0002010451_csv_large_files_memory_python.txt
|
Q:
How to implement a voice chat functionality using Python?
My goal is a cross-platform voice chat application. The part I am a bit confused about it's the voice transferring one : )
What can you suggest? Maybe a binding to some low-level library or even a framework?
BTW, I don't have to use Python, so if you think that Python is not a good idea for this purpose, please show me the true way : )
A:
You should look into Telepathy:
http://telepathy.freedesktop.org/wiki/
There are Python bindings available:
http://telepathy.freedesktop.org/wiki/Telepathy%20Python
See also; the end of this presentation features an IM/Voip client in 20 lines:
http://raphael.slinckx.net/files/telepathy-guadec-2007.pdf
|
How to implement a voice chat functionality using Python?
|
My goal is a cross-platform voice chat application. The part I am a bit confused about it's the voice transferring one : )
What can you suggest? Maybe a binding to some low-level library or even a framework?
BTW, I don't have to use Python, so if you think that Python is not a good idea for this purpose, please show me the true way : )
|
[
"You should look into Telepathy:\nhttp://telepathy.freedesktop.org/wiki/\nThere are Python bindings available:\nhttp://telepathy.freedesktop.org/wiki/Telepathy%20Python\nSee also; the end of this presentation features an IM/Voip client in 20 lines:\nhttp://raphael.slinckx.net/files/telepathy-guadec-2007.pdf\n"
] |
[
4
] |
[] |
[] |
[
"chat",
"python",
"voice"
] |
stackoverflow_0002011042_chat_python_voice.txt
|
Q:
how to check the character count of a file in python
I have a python code which reads many files.
but some files are extremely large due to which i have errors coming in other codes.
i want a way in which i can check for the character count of the files so that i avoid reading those extremely large files.
Thanks.
A:
os.stat(filepath).st_size
Assuming by ‘characters’ you mean bytes. ETA:
i need total character count just like what the command 'wc filename' gives me unix
In which mode? wc on it own will give you a line, word and byte count (same as stat), not Unicode characters.
There is a switch -m which will use the locale's current encoding to convert bytes to Unicode and then count code-points: is that really what you want? It doesn't make any sense to decode into Unicode if all you are looking for is too-long files. If you really must:
import sys, codecs
def getUnicodeFileLength(filepath, charset= None):
if charset is None:
charset= sys.getfilesystemencoding()
readerclass= codecs.getReader(charset)
reader= readerclass(open(filepath, 'rb'), 'replace')
nchar= 0
while True:
chars= reader.read(1024*32) # arbitrary chunk size
if chars=='':
break
nchar+= len(chars)
reader.close()
return nchar
sys.getfilesystemencoding() gets the locale encoding, reproducing what wc -m does. If you know the encoding yourself (eg. 'utf-8') then pass that in instead.
I don't think you want to do this.
A:
If you want the unicode character count for a text file given a specific encoding, you will have to read in the entire file to do that.
However, if you want the byte count for a given file, you want os.path.getsize(), which should only need to do a stat on the file as long as your OS has stat() or an equivalent call (all Unixes and Windows do).
A:
Try
import os
os.path.getsize(filePath)
to get the size of your file, in bytes.
A:
os.path.getsize(path)
Return the size, in bytes, of path.
Raise os.error if the file does not
exist or is inaccessible.
A:
alternative way
f=open("file")
os.fstat( f.fileno() ).st_size
f.close()
|
how to check the character count of a file in python
|
I have a python code which reads many files.
but some files are extremely large due to which i have errors coming in other codes.
i want a way in which i can check for the character count of the files so that i avoid reading those extremely large files.
Thanks.
|
[
"os.stat(filepath).st_size\n\nAssuming by ‘characters’ you mean bytes. ETA:\n\ni need total character count just like what the command 'wc filename' gives me unix\n\nIn which mode? wc on it own will give you a line, word and byte count (same as stat), not Unicode characters.\nThere is a switch -m which will use the locale's current encoding to convert bytes to Unicode and then count code-points: is that really what you want? It doesn't make any sense to decode into Unicode if all you are looking for is too-long files. If you really must:\nimport sys, codecs\n\ndef getUnicodeFileLength(filepath, charset= None):\n if charset is None:\n charset= sys.getfilesystemencoding()\n readerclass= codecs.getReader(charset)\n reader= readerclass(open(filepath, 'rb'), 'replace')\n nchar= 0\n while True:\n chars= reader.read(1024*32) # arbitrary chunk size\n if chars=='':\n break\n nchar+= len(chars)\n reader.close()\n return nchar\n\nsys.getfilesystemencoding() gets the locale encoding, reproducing what wc -m does. If you know the encoding yourself (eg. 'utf-8') then pass that in instead.\nI don't think you want to do this.\n",
"If you want the unicode character count for a text file given a specific encoding, you will have to read in the entire file to do that.\nHowever, if you want the byte count for a given file, you want os.path.getsize(), which should only need to do a stat on the file as long as your OS has stat() or an equivalent call (all Unixes and Windows do).\n",
"Try\nimport os\nos.path.getsize(filePath)\n\nto get the size of your file, in bytes.\n",
"os.path.getsize(path) \n\n\nReturn the size, in bytes, of path.\n Raise os.error if the file does not\n exist or is inaccessible.\n\n",
"alternative way\nf=open(\"file\")\nos.fstat( f.fileno() ).st_size\nf.close()\n\n"
] |
[
7,
7,
5,
4,
2
] |
[] |
[] |
[
"character",
"python",
"size"
] |
stackoverflow_0002011048_character_python_size.txt
|
Q:
Retrieve module object from stack frame
Given a frame object, I need to get the corresponding module object. In other words, implement callers_module so this works:
import sys
from some_other_module import callers_module
assert sys.modules[__name__] is callers_module()
(That would be equivalent because I can generate a stack trace in the function for this test case. The imports are there simply to make that example complete and testable, and prevent callers_module from taking the shortcut of using __name__, since it's in a different module.)
I've attempted this:
import inspect
def callers_module():
return inspect.currentframe().f_back
Which gets a frame object, on which f_code will give me a code object, but I can't find out how to get the corresponding module or its name (to use with sys.modules). If I could get function objects, those have a __module__ attribute (and also have code objects), but that's not present in the frame. Indeed, not all code objects belong to function objects, such as the code for my test case (with assert, above). The same can be said of frame/code objects not having a module—but many of them do, and in my case they will, so that doesn't need to be handled; however, a simple None or exception is fine in that case, too.
It feels like I'm missing something simple. What needs to be done for this to work?
A:
While inspect.getmodule works great, and I was indeed looking in the wrong place to find it, I found a slightly better solution for me:
def callers_module():
module_name = inspect.currentframe().f_back.f_globals["__name__"]
return sys.modules[module_name]
It still uses inspect.currentframe (which I prefer over the exactly identical sys._getframe), but doesn't invoke inspect's module-filename mapping (in inspect.getmodule).
Additionally, this question inspired an interesting way to manage __all__:
from export import export
@export
class Example: pass
@export
def example: pass
answer = 42
export.name("answer")
assert __all__ == ["Example", "example", "answer"]
A:
import inspect
def callers_module():
module = inspect.getmodule(inspect.currentframe().f_back)
return module
|
Retrieve module object from stack frame
|
Given a frame object, I need to get the corresponding module object. In other words, implement callers_module so this works:
import sys
from some_other_module import callers_module
assert sys.modules[__name__] is callers_module()
(That would be equivalent because I can generate a stack trace in the function for this test case. The imports are there simply to make that example complete and testable, and prevent callers_module from taking the shortcut of using __name__, since it's in a different module.)
I've attempted this:
import inspect
def callers_module():
return inspect.currentframe().f_back
Which gets a frame object, on which f_code will give me a code object, but I can't find out how to get the corresponding module or its name (to use with sys.modules). If I could get function objects, those have a __module__ attribute (and also have code objects), but that's not present in the frame. Indeed, not all code objects belong to function objects, such as the code for my test case (with assert, above). The same can be said of frame/code objects not having a module—but many of them do, and in my case they will, so that doesn't need to be handled; however, a simple None or exception is fine in that case, too.
It feels like I'm missing something simple. What needs to be done for this to work?
|
[
"While inspect.getmodule works great, and I was indeed looking in the wrong place to find it, I found a slightly better solution for me:\ndef callers_module():\n module_name = inspect.currentframe().f_back.f_globals[\"__name__\"]\n return sys.modules[module_name]\n\nIt still uses inspect.currentframe (which I prefer over the exactly identical sys._getframe), but doesn't invoke inspect's module-filename mapping (in inspect.getmodule).\nAdditionally, this question inspired an interesting way to manage __all__:\nfrom export import export\n\n@export\nclass Example: pass\n\n@export\ndef example: pass\n\nanswer = 42\nexport.name(\"answer\")\n\nassert __all__ == [\"Example\", \"example\", \"answer\"]\n\n",
"import inspect\ndef callers_module():\n module = inspect.getmodule(inspect.currentframe().f_back)\n return module\n\n"
] |
[
13,
7
] |
[] |
[] |
[
"introspection",
"python"
] |
stackoverflow_0002000861_introspection_python.txt
|
Q:
Creating and deploying a python chat application using Twisted
I have created a chat server application using the Twisted framework. I am running it on my local machine and now I want to go global. The application is similar to omegle.com.
How can I develop on a third party commercial server so that it runs continuously?
Do I need to get a dedicated server for it?
A:
As per this SO answer,
You can deploy Twisted on any hosting
provider who gives you a shell prompt
and doesn't limit your long-running
processes.
Some examples that I've used include:
Tummy ltd. and Slicehost.
The hosting server need not be dedicated, in other words, as long as those conditions are met (and of course as long as you have enough quota of RAM, disk, bandwidth, etc, for your purposes).
A:
Take a look at Python friendly hosts to get an idea of what is available and what it will cost you. Typically, you could get away with a shared hosting package as long as you have a shell. However, if your program begins serving tons of clients, you might need to move it to a dedicated host.
|
Creating and deploying a python chat application using Twisted
|
I have created a chat server application using the Twisted framework. I am running it on my local machine and now I want to go global. The application is similar to omegle.com.
How can I develop on a third party commercial server so that it runs continuously?
Do I need to get a dedicated server for it?
|
[
"As per this SO answer,\n\nYou can deploy Twisted on any hosting\n provider who gives you a shell prompt\n and doesn't limit your long-running\n processes.\nSome examples that I've used include:\n Tummy ltd. and Slicehost.\n\nThe hosting server need not be dedicated, in other words, as long as those conditions are met (and of course as long as you have enough quota of RAM, disk, bandwidth, etc, for your purposes).\n",
"Take a look at Python friendly hosts to get an idea of what is available and what it will cost you. Typically, you could get away with a shared hosting package as long as you have a shell. However, if your program begins serving tons of clients, you might need to move it to a dedicated host. \n"
] |
[
3,
0
] |
[] |
[] |
[
"chat",
"hosting",
"python",
"twisted"
] |
stackoverflow_0002011136_chat_hosting_python_twisted.txt
|
Q:
X-Sendfile and VERY big files on Apache2
Any filesize over about 4GB is not going to work with the mod_xsendfile for Apache2 (as it sets the content length to a long).
I am willing to rewrite it to support this; however, I can find no documentation on how to set content length from the apache api to something larger than a long and thus serve large files through Apache. I know Apache can do this as it is compiled with Large File Support and is serving the files through the directory index without any issue.
I need to use Apache as I am using WSGI. I do not want to use FastCGI or switch off Apache2 for various reasons I do not feel like getting into.
Thanks.
A:
Location of the Beta for mod_xsendfile on Apache2
A:
I have discovered the answer. Use the BETA version provided. It seems to fix this issue.
|
X-Sendfile and VERY big files on Apache2
|
Any filesize over about 4GB is not going to work with the mod_xsendfile for Apache2 (as it sets the content length to a long).
I am willing to rewrite it to support this; however, I can find no documentation on how to set content length from the apache api to something larger than a long and thus serve large files through Apache. I know Apache can do this as it is compiled with Large File Support and is serving the files through the directory index without any issue.
I need to use Apache as I am using WSGI. I do not want to use FastCGI or switch off Apache2 for various reasons I do not feel like getting into.
Thanks.
|
[
"Location of the Beta for mod_xsendfile on Apache2\n",
"I have discovered the answer. Use the BETA version provided. It seems to fix this issue.\n"
] |
[
4,
1
] |
[] |
[] |
[
"apache2",
"python",
"wsgi",
"x_sendfile"
] |
stackoverflow_0001693564_apache2_python_wsgi_x_sendfile.txt
|
Q:
How to use ipython's IPShellEmbed from within a running doctest
Please help me get an embedded ipython console to run inside a doctest. The example code demonstrates the problem and will hang your terminal. On bash shell I type ctrl-Z and then kill %1 to break out and kill, since ctrl-C won't work.
def some_function():
"""
>>> some_function()
'someoutput'
"""
# now try to drop into an ipython shell to help
# with development
import IPython.Shell; IPython.Shell.IPShellEmbed(argv=[])()
return 'someoutput'
if __name__ == '__main__':
import doctest
print "Running doctest . . ."
doctest.testmod()
I like to use ipython to help write code. A common trick is to use ipython as a breakpoint in my code by calling IPython.Shell.IPShellEmbed. This trick works everywhere I've tried (inside a django manage.py runserver, unit tests), but it doesn't work within doctests. I think it has to do with doctest controlling stdin/stdout.
Thanks in advance for your help.
- Philip
A:
I emailed the ipython user group and got some help. There is now a support ticket to get this feature fixed in future versions of ipython. Here is a code snippet with a workaround:
import sys
from IPython.Shell import IPShellEmbed
class IPShellDoctest(IPShellEmbed):
def __call__(self, *a, **kw):
sys_stdout_saved = sys.stdout
sys.stdout = sys.stderr
try:
IPShellEmbed.__call__(self, *a, **kw)
finally:
sys.stdout = sys_stdout_saved
def some_function():
"""
>>> some_function()
'someoutput'
"""
# now try to drop into an ipython shell to help
# with development
IPShellDoctest()(local_ns=locals())
return 'someoutput'
if __name__ == '__main__':
import doctest
print "Running doctest . . ."
doctest.testmod()
|
How to use ipython's IPShellEmbed from within a running doctest
|
Please help me get an embedded ipython console to run inside a doctest. The example code demonstrates the problem and will hang your terminal. On bash shell I type ctrl-Z and then kill %1 to break out and kill, since ctrl-C won't work.
def some_function():
"""
>>> some_function()
'someoutput'
"""
# now try to drop into an ipython shell to help
# with development
import IPython.Shell; IPython.Shell.IPShellEmbed(argv=[])()
return 'someoutput'
if __name__ == '__main__':
import doctest
print "Running doctest . . ."
doctest.testmod()
I like to use ipython to help write code. A common trick is to use ipython as a breakpoint in my code by calling IPython.Shell.IPShellEmbed. This trick works everywhere I've tried (inside a django manage.py runserver, unit tests), but it doesn't work within doctests. I think it has to do with doctest controlling stdin/stdout.
Thanks in advance for your help.
- Philip
|
[
"I emailed the ipython user group and got some help. There is now a support ticket to get this feature fixed in future versions of ipython. Here is a code snippet with a workaround:\nimport sys\n\nfrom IPython.Shell import IPShellEmbed\n\nclass IPShellDoctest(IPShellEmbed):\n def __call__(self, *a, **kw):\n sys_stdout_saved = sys.stdout\n sys.stdout = sys.stderr\n try:\n IPShellEmbed.__call__(self, *a, **kw)\n finally:\n sys.stdout = sys_stdout_saved\n\n\ndef some_function():\n \"\"\"\n >>> some_function()\n 'someoutput'\n \"\"\"\n # now try to drop into an ipython shell to help\n # with development\n IPShellDoctest()(local_ns=locals())\n return 'someoutput'\n\nif __name__ == '__main__':\n import doctest\n print \"Running doctest . . .\"\n doctest.testmod()\n\n"
] |
[
0
] |
[] |
[] |
[
"doctest",
"ipython",
"python",
"unit_testing"
] |
stackoverflow_0001986805_doctest_ipython_python_unit_testing.txt
|
Q:
Django dynamic number of filter for a objects request
How can I do something like this :
products_list = Product.objects.all()
for key in keywords:
products_list = products_list.filter(name__icontains=q)
This don't work.
A:
You are filtering the list with several AND statements, and you want OR statements. Try something like this:
from django.db.models import Q
products_list = Product.objects.all()
orq = None
for key in keywords:
thisq = Q(name__icontains=q)
if orq:
orq = thisq | orq
else:
orq = thisq
products_list = products_list.filter(orq)
You could probably clean up the above code, but the idea is to create a variable called orq that is basically Q(name__icontains='prod1') | Q(name__icontains='prod2').
|
Django dynamic number of filter for a objects request
|
How can I do something like this :
products_list = Product.objects.all()
for key in keywords:
products_list = products_list.filter(name__icontains=q)
This don't work.
|
[
"You are filtering the list with several AND statements, and you want OR statements. Try something like this:\nfrom django.db.models import Q\nproducts_list = Product.objects.all()\norq = None \nfor key in keywords:\n thisq = Q(name__icontains=q)\n if orq:\n orq = thisq | orq\n else:\n orq = thisq\nproducts_list = products_list.filter(orq)\n\nYou could probably clean up the above code, but the idea is to create a variable called orq that is basically Q(name__icontains='prod1') | Q(name__icontains='prod2').\n"
] |
[
2
] |
[] |
[] |
[
"django",
"django_models",
"python"
] |
stackoverflow_0002011752_django_django_models_python.txt
|
Q:
Display random choice (Python)
I have a list[] of items from which I'd like to display one randomly, but the displayed item must not repeat more than once in last x requests.
list1 = item1, item2, item3, item4,
item5, item6, item7, item8, item9,
item 10
Display a random selection
from the list above
list2 = store the last displayed item in list2 which should only store 7
items, not more
Display a random
selection from the list but make
sure it doesn't exist in the
list2
Is that the right way to do it? Either way, I'd like to know how to limit a list to store only 7 items?
Thanks
A:
collections.deque is the only sequence type in python that naturally supports being bounded (and only in Python 2.6 and up.) If using python 2.6 or newer:
# Setup
from collections import deque
from random import choice
used = deque(maxlen=7)
# Now your sampling bit
item = random.choice([x for x in list1 if x not in used])
used.append(item)
If using python 2.5 or less, you can't use the maxlen argument, and will need to do one more operation to chop off the front of the deque:
while len(used) > 7:
used.popleft()
This isn't exactly the most efficient method, but it works. If you need speed, and your objects are hashable (most immutable types), consider using a dictionary instead as your "used" list.
Also, if you only need to do this once, the random.shuffle method works too.
A:
Is this what you want?
list1 = range(10)
import random
random.shuffle(list1)
list2 = list1[:7]
for item in list2:
print item
print list1[7]
In other words, look at random.shuffle(). If you want to keep the original list intact, you can copy it: list_copy = list1[:].
A:
You could try using a generator function and call .next() whenever you need a new item.
import random
def randomizer(l, x):
penalty_box = []
random.shuffle(l)
while True:
element = l.pop(0)
# for show
print penalty_box, l
yield element
penalty_box.append(element)
if len(penalty_box) > x:
# penalty time over for the first element in the box
# reinsert randomly into the list
element = penalty_box.pop(0)
i = random.randint(0, len(l))
l.insert(i, element)
Usage example:
>>> r = randomizer([1,2, 3, 4, 5, 6, 7, 8], 3)
>>> r.next()
[] [1, 5, 2, 6, 4, 8, 7]
3
>>> r.next()
[3] [5, 2, 6, 4, 8, 7]
1
>>> r.next()
[3, 1] [2, 6, 4, 8, 7]
5
>>> r.next()
[3, 1, 5] [6, 4, 8, 7]
2
>>> r.next()
[1, 5, 2] [4, 3, 8, 7]
6
>>> r.next()
[5, 2, 6] [4, 3, 8, 7]
1
>>> r.next()
[2, 6, 1] [5, 3, 8, 7]
4
>>> r.next()
[6, 1, 4] [3, 8, 2, 7]
5
A:
Something like:
# Setup
import random
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
list2 = []
# Loop for as long as you want to display items
while loopCondition:
index = random.randint(0, len(list1)-1)
item = list1.pop(index)
print item
list2.append(item)
if(len(list2) > 7):
list1.append(list2.pop(0))
A:
I'd use set objects to get a list of items in list1 but not in list2:
import random
list1 = set(["item1", "item2", "item3", "item4", "item5",
"item6", "item7", "item8", "item9", "item10"])
list2 = []
while True: # Or something
selection = random.choice(tuple(list1.difference(set(list2))))
print(selection)
list2.append(selection)
if len(list2) > 7:
list2 = list2[-7:]
|
Display random choice (Python)
|
I have a list[] of items from which I'd like to display one randomly, but the displayed item must not repeat more than once in last x requests.
list1 = item1, item2, item3, item4,
item5, item6, item7, item8, item9,
item 10
Display a random selection
from the list above
list2 = store the last displayed item in list2 which should only store 7
items, not more
Display a random
selection from the list but make
sure it doesn't exist in the
list2
Is that the right way to do it? Either way, I'd like to know how to limit a list to store only 7 items?
Thanks
|
[
"collections.deque is the only sequence type in python that naturally supports being bounded (and only in Python 2.6 and up.) If using python 2.6 or newer:\n# Setup\nfrom collections import deque\nfrom random import choice\nused = deque(maxlen=7)\n\n# Now your sampling bit\nitem = random.choice([x for x in list1 if x not in used])\nused.append(item)\n\nIf using python 2.5 or less, you can't use the maxlen argument, and will need to do one more operation to chop off the front of the deque:\nwhile len(used) > 7:\n used.popleft()\n\nThis isn't exactly the most efficient method, but it works. If you need speed, and your objects are hashable (most immutable types), consider using a dictionary instead as your \"used\" list.\nAlso, if you only need to do this once, the random.shuffle method works too.\n",
"Is this what you want?\nlist1 = range(10)\nimport random\nrandom.shuffle(list1)\nlist2 = list1[:7]\nfor item in list2:\n print item\nprint list1[7]\n\nIn other words, look at random.shuffle(). If you want to keep the original list intact, you can copy it: list_copy = list1[:].\n",
"You could try using a generator function and call .next() whenever you need a new item.\nimport random\ndef randomizer(l, x):\n penalty_box = []\n random.shuffle(l)\n while True:\n element = l.pop(0)\n # for show\n print penalty_box, l\n yield element\n penalty_box.append(element)\n if len(penalty_box) > x:\n # penalty time over for the first element in the box\n # reinsert randomly into the list\n element = penalty_box.pop(0)\n i = random.randint(0, len(l))\n l.insert(i, element)\n\nUsage example:\n>>> r = randomizer([1,2, 3, 4, 5, 6, 7, 8], 3)\n>>> r.next()\n[] [1, 5, 2, 6, 4, 8, 7]\n3\n>>> r.next()\n[3] [5, 2, 6, 4, 8, 7]\n1\n>>> r.next()\n[3, 1] [2, 6, 4, 8, 7]\n5\n>>> r.next()\n[3, 1, 5] [6, 4, 8, 7]\n2\n>>> r.next()\n[1, 5, 2] [4, 3, 8, 7]\n6\n>>> r.next()\n[5, 2, 6] [4, 3, 8, 7]\n1\n>>> r.next()\n[2, 6, 1] [5, 3, 8, 7]\n4\n>>> r.next()\n[6, 1, 4] [3, 8, 2, 7]\n5\n\n",
"Something like:\n# Setup\nimport random\nlist1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\nlist2 = []\n\n# Loop for as long as you want to display items\nwhile loopCondition:\n index = random.randint(0, len(list1)-1)\n item = list1.pop(index)\n\n print item\n\n list2.append(item)\n if(len(list2) > 7):\n list1.append(list2.pop(0))\n\n",
"I'd use set objects to get a list of items in list1 but not in list2:\nimport random\n\nlist1 = set([\"item1\", \"item2\", \"item3\", \"item4\", \"item5\",\n \"item6\", \"item7\", \"item8\", \"item9\", \"item10\"])\nlist2 = []\nwhile True: # Or something\n selection = random.choice(tuple(list1.difference(set(list2))))\n print(selection)\n list2.append(selection)\n if len(list2) > 7:\n list2 = list2[-7:]\n\n"
] |
[
7,
4,
2,
1,
1
] |
[] |
[] |
[
"limit",
"list",
"python",
"random"
] |
stackoverflow_0002011583_limit_list_python_random.txt
|
Q:
pycurl module not available after installation on Snow Leopard
I'm running Python 2.6.4 on Mac Snow Leopard. I installed pycurl using:
sudo env ARCHFLAGS="-arch x86_64" easy_install setuptools pycurl==7.16.2.1
The installation completes with no issues and says pycurl is installed in subsequent installation attempts. However, when I try to "import pycurl" in a script, I get a message that pycurl isn't found. I'm not sure what else to do to fix this.
A:
I would suspect you have 2 versions of python on your system. How about removing easy install and reinstalling it.
Remove the current easy install script by typing which easy_install and then rm [easy install full path].
To install easy install
wget http://peak.telecommunity.com/dist/ez_setup.py
python ez_setup.py
Then, try your command again:
sudo env ARCHFLAGS="-arch x86_64" easy_install setuptools pycurl==7.16.2.1
A:
I guess you have 2 different versions of python, you can find out by running command which python
A:
If you have installed Python 2.6.4 using the python.org OS X installer, you need to install the optional 10.4u SDK from the 10.6 Xcode mpkg to install any python packages that include C extension modules.
|
pycurl module not available after installation on Snow Leopard
|
I'm running Python 2.6.4 on Mac Snow Leopard. I installed pycurl using:
sudo env ARCHFLAGS="-arch x86_64" easy_install setuptools pycurl==7.16.2.1
The installation completes with no issues and says pycurl is installed in subsequent installation attempts. However, when I try to "import pycurl" in a script, I get a message that pycurl isn't found. I'm not sure what else to do to fix this.
|
[
"I would suspect you have 2 versions of python on your system. How about removing easy install and reinstalling it. \nRemove the current easy install script by typing which easy_install and then rm [easy install full path].\nTo install easy install\nwget http://peak.telecommunity.com/dist/ez_setup.py\npython ez_setup.py\n\nThen, try your command again:\nsudo env ARCHFLAGS=\"-arch x86_64\" easy_install setuptools pycurl==7.16.2.1\n\n",
"I guess you have 2 different versions of python, you can find out by running command which python\n",
"If you have installed Python 2.6.4 using the python.org OS X installer, you need to install the optional 10.4u SDK from the 10.6 Xcode mpkg to install any python packages that include C extension modules.\n"
] |
[
2,
1,
0
] |
[] |
[] |
[
"osx_snow_leopard",
"pycurl",
"python"
] |
stackoverflow_0002011640_osx_snow_leopard_pycurl_python.txt
|
Q:
Compiling Python 3.1.1 32-bit
We're using this configure script with an option we spotted in the configure help menu:
./configure --with-universal-archs=32-bit --prefix="$HOME/python"
make
make install
But when all the dust is settled and we check out what it gives us:
✔python-3.1.1⤿ file ~/python/bin/python3
python/bin/python3: Mach-O 64-bit executable x86_64
How do we compile it so we're given a 32-bit python? We're looking to use the uno module provided by OpenOffice, which requires 32-bit python.
A:
There's no need to build your own. Use the Python 3.1.1 OS X installer from python.org. It's 32-bit only and will work just fine on OS X 10.4 through 10.6. If you need to install any packages with C extension modules on 10.6, you'll need to install the optional 10.4 SDK from the the Snow Leopard Xcode mpkg and you'll need to tell Distutils to use GCC 4.0:
$ export CC=/usr/bin/gcc-4.0
A:
I'd try CFLAGS=-m32 LDFLAGS=-m32 although I don't have the requisite hardware to test that it works.
I'm not familiar with the --with-universal-archs option -- must be specific to OS X?
|
Compiling Python 3.1.1 32-bit
|
We're using this configure script with an option we spotted in the configure help menu:
./configure --with-universal-archs=32-bit --prefix="$HOME/python"
make
make install
But when all the dust is settled and we check out what it gives us:
✔python-3.1.1⤿ file ~/python/bin/python3
python/bin/python3: Mach-O 64-bit executable x86_64
How do we compile it so we're given a 32-bit python? We're looking to use the uno module provided by OpenOffice, which requires 32-bit python.
|
[
"There's no need to build your own. Use the Python 3.1.1 OS X installer from python.org. It's 32-bit only and will work just fine on OS X 10.4 through 10.6. If you need to install any packages with C extension modules on 10.6, you'll need to install the optional 10.4 SDK from the the Snow Leopard Xcode mpkg and you'll need to tell Distutils to use GCC 4.0:\n$ export CC=/usr/bin/gcc-4.0\n\n",
"I'd try CFLAGS=-m32 LDFLAGS=-m32 although I don't have the requisite hardware to test that it works.\nI'm not familiar with the --with-universal-archs option -- must be specific to OS X?\n"
] |
[
2,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002011295_python.txt
|
Q:
how can i get the value '111'
def a():
w='www'
a.a='aaa'
print a.__dict__
a.__dict__={'1':'111','2':'222'}
print a.1#error
print a['1']#error
how can i get the value '111'
thanks
A:
You'll have to do
print a.__dict__['1']
or
print getattr(a, '1')
"1" is not a valid variable name in Python. If you did:
a.__dict__ = {'a1' : '111'}
print a.a1
it would work.
A:
Since you say are just a beginner, perhaps you're just looking for the even easier:
a = {'1':'111','2':'222'}
so a['1'] returns the desired '111'
A:
You can access it thanks to the __dict__ member. See following code
def a():
w='www'
a.a='aaa'
print a.__dict__
a.__dict__={'1':'111','2':'222'}
print a.__dict__['1']
|
how can i get the value '111'
|
def a():
w='www'
a.a='aaa'
print a.__dict__
a.__dict__={'1':'111','2':'222'}
print a.1#error
print a['1']#error
how can i get the value '111'
thanks
|
[
"You'll have to do \nprint a.__dict__['1']\n\nor\nprint getattr(a, '1')\n\n\"1\" is not a valid variable name in Python. If you did:\na.__dict__ = {'a1' : '111'}\nprint a.a1\n\nit would work.\n",
"Since you say are just a beginner, perhaps you're just looking for the even easier: \n a = {'1':'111','2':'222'}\n\nso a['1'] returns the desired '111'\n",
"You can access it thanks to the __dict__ member. See following code \ndef a():\n w='www'\na.a='aaa'\nprint a.__dict__\na.__dict__={'1':'111','2':'222'}\nprint a.__dict__['1']\n\n"
] |
[
10,
3,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002011568_python.txt
|
Q:
How to write last 50 lines from one file to another Python
I am creating an email response to an overnight build, I want to get the last 50 lines from the results file and place it into a summary file. The code that I have done is below, can anyone help?
def email_success():
fp = open(results_file, 'r')
sum_file = (fp.readlines()[-50:])
fp.close()
myfile = open(result_summary,'w')
myfile.write(sum_file)
myfile.close()
I have got the error message below when trying this code:
Traceback (most recent call last):
File "email_success.py", line 76, in <module>
if __name__ == '__main__': myObject = email_success()
File "email_success.py", line 45, in email_success
myfile = open(result_summary,'w')
TypeError: coercing to Unicode: need string or buffer, tuple found
Thanks
The results summary is a variable that stores an address.
result_summary = (t, 'results_summary.txt')
Sorry made a stupid mistake, I forgot to add os.path.join
result_summary = os.path.join(t, 'results_summary.txt')
Thanks for the help
@alok It is a directory address, I forgot to add the os.join to make it one string. This is what was causing the error
A:
TypeError: coercing to Unicode: need string or buffer, tuple found
Error says its expect string or buffer but you are passing tuple, so just join it with "" to make it to string
So, Try
sum_file = "".join(fp.readlines()[-50:])
UPDATE: because OP updated the question
if result_summary = (t, 'results_summary.txt')
Try
myfile = open(result_summary[1],'w')
A:
It's open() raising the exception though... how did you define result_summary?
A:
result_summary is a tuple, it needs to be either a str or buffer. Your explanation has nothing to do with the error you posted.
A:
result_summary = (t, 'results_summary.txt')
and
myfile = open(result_summary,'w')
means
myfile = open((t, 'results_summary.txt'),'w')
which obviously won't work, try:
myfile = open(result_summary[1],'w')
instead
A:
fp.readlines() method returns a list of lines.
Therefore you can't apply [-50:] operator.
|
How to write last 50 lines from one file to another Python
|
I am creating an email response to an overnight build, I want to get the last 50 lines from the results file and place it into a summary file. The code that I have done is below, can anyone help?
def email_success():
fp = open(results_file, 'r')
sum_file = (fp.readlines()[-50:])
fp.close()
myfile = open(result_summary,'w')
myfile.write(sum_file)
myfile.close()
I have got the error message below when trying this code:
Traceback (most recent call last):
File "email_success.py", line 76, in <module>
if __name__ == '__main__': myObject = email_success()
File "email_success.py", line 45, in email_success
myfile = open(result_summary,'w')
TypeError: coercing to Unicode: need string or buffer, tuple found
Thanks
The results summary is a variable that stores an address.
result_summary = (t, 'results_summary.txt')
Sorry made a stupid mistake, I forgot to add os.path.join
result_summary = os.path.join(t, 'results_summary.txt')
Thanks for the help
@alok It is a directory address, I forgot to add the os.join to make it one string. This is what was causing the error
|
[
"TypeError: coercing to Unicode: need string or buffer, tuple found\n\nError says its expect string or buffer but you are passing tuple, so just join it with \"\" to make it to string\nSo, Try\nsum_file = \"\".join(fp.readlines()[-50:])\n\nUPDATE: because OP updated the question\nif result_summary = (t, 'results_summary.txt')\nTry \nmyfile = open(result_summary[1],'w')\n\n",
"It's open() raising the exception though... how did you define result_summary?\n",
"result_summary is a tuple, it needs to be either a str or buffer. Your explanation has nothing to do with the error you posted.\n",
"result_summary = (t, 'results_summary.txt')\n\nand\n myfile = open(result_summary,'w')\n\nmeans\n myfile = open((t, 'results_summary.txt'),'w')\n\nwhich obviously won't work, try:\n myfile = open(result_summary[1],'w')\n\ninstead\n",
"fp.readlines() method returns a list of lines.\nTherefore you can't apply [-50:] operator. \n"
] |
[
5,
2,
2,
1,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002012118_python.txt
|
Q:
Python + Facebook, getting info about a group easily
I have a need to display some basic info about a facebook group on a website i am building. All i am really looking to show is the total number of members, and maybe a list of the few most recent people who joined.
I would like to not have to login to FB to accomplish this, is there an API for groups that allows anonymous access? or do i have to go the screen scraping route?
A:
Use the Python Facebook module on Google Code.
|
Python + Facebook, getting info about a group easily
|
I have a need to display some basic info about a facebook group on a website i am building. All i am really looking to show is the total number of members, and maybe a list of the few most recent people who joined.
I would like to not have to login to FB to accomplish this, is there an API for groups that allows anonymous access? or do i have to go the screen scraping route?
|
[
"Use the Python Facebook module on Google Code.\n"
] |
[
1
] |
[] |
[] |
[
"django",
"facebook",
"python"
] |
stackoverflow_0002008816_django_facebook_python.txt
|
Q:
why my code error? I copied the 'memoize' function in django.utils.functional
my code:
a=[1,2,3,4]
b=a[:2]
c=[]
c[b]='sss'#error
memoize function:
def memoize(func, cache, num_args):
def wrapper(*args):
mem_args = args[:num_args]#<------this
if mem_args in cache:
return cache[mem_args]
result = func(*args)
cache[mem_args] = result#<-----and this
return result
A:
In the memoize function, I'm assuming cache is a dict. Also, since a is a list, b will also be a list, and lists are not hashable. Use a tuple.
Try
a = (1, 2, 3, 4) # Parens, not brackets
b = a[:2]
c = {} # Curly braces, not brackets
c[b] = 'sss'
A:
What has your question got to do with the memoize function you post?
Presumably (although we have to guess, since you didn't post the actual error) you're getting a TypeError. This is due to two mistakes.
Firstly, c is a list. So you can't use arbitrary keys, you can only use integer indexes. Presumably you meant to define a dictionary here: c = {}
Secondly, you're getting a list in statement 2 - b equals [1, 2] - and this is not a valid dictionary index. a should have been a tuple: a = (1, 2, 3, 4).
I must reiterate the advice that other people have been giving you. Please find an introduction to programming and read that before trying to copy advanced Python code that you don't understand.
|
why my code error? I copied the 'memoize' function in django.utils.functional
|
my code:
a=[1,2,3,4]
b=a[:2]
c=[]
c[b]='sss'#error
memoize function:
def memoize(func, cache, num_args):
def wrapper(*args):
mem_args = args[:num_args]#<------this
if mem_args in cache:
return cache[mem_args]
result = func(*args)
cache[mem_args] = result#<-----and this
return result
|
[
"In the memoize function, I'm assuming cache is a dict. Also, since a is a list, b will also be a list, and lists are not hashable. Use a tuple.\nTry\na = (1, 2, 3, 4) # Parens, not brackets\nb = a[:2]\nc = {} # Curly braces, not brackets\nc[b] = 'sss'\n\n",
"What has your question got to do with the memoize function you post? \nPresumably (although we have to guess, since you didn't post the actual error) you're getting a TypeError. This is due to two mistakes.\nFirstly, c is a list. So you can't use arbitrary keys, you can only use integer indexes. Presumably you meant to define a dictionary here: c = {}\nSecondly, you're getting a list in statement 2 - b equals [1, 2] - and this is not a valid dictionary index. a should have been a tuple: a = (1, 2, 3, 4).\nI must reiterate the advice that other people have been giving you. Please find an introduction to programming and read that before trying to copy advanced Python code that you don't understand.\n"
] |
[
2,
2
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002011823_django_python.txt
|
Q:
Parse a string with a date to a datetime object
How can I parse a string like "01-Jan-1995" to a Python datetime object?
A:
On the whole you'd parse date and time strings with the strptime functions in time or datetime modules. Your example could be parsed with:
import datetime
datetime.datetime.strptime("01-Jan-1995", "%d-%b-%Y")
Note that parsing month names is locale-dependent. This table shows the directives for parsing various formats of dates and times.
A:
dateutil can parse this sort of format without you even having to define custom date formats. Just install it with:
pip install python-dateutil
Then use it:
import dateutil.parser
dateutil.parser.parse('01-Jan-1995').date()
A:
If you need to parse natural language date and time strings, consider parsedatetime (and this answer).
|
Parse a string with a date to a datetime object
|
How can I parse a string like "01-Jan-1995" to a Python datetime object?
|
[
"On the whole you'd parse date and time strings with the strptime functions in time or datetime modules. Your example could be parsed with:\nimport datetime\ndatetime.datetime.strptime(\"01-Jan-1995\", \"%d-%b-%Y\")\n\nNote that parsing month names is locale-dependent. This table shows the directives for parsing various formats of dates and times.\n",
"dateutil can parse this sort of format without you even having to define custom date formats. Just install it with:\npip install python-dateutil\n\nThen use it:\nimport dateutil.parser\ndateutil.parser.parse('01-Jan-1995').date()\n\n",
"If you need to parse natural language date and time strings, consider parsedatetime (and this answer).\n"
] |
[
24,
10,
1
] |
[] |
[] |
[
"datetime",
"python"
] |
stackoverflow_0001713594_datetime_python.txt
|
Q:
Standalone Python applications in Linux
How can I distribute a standalone Python application in Linux?
I think I can take for granted the presence of a recent Python interpreter in any modern distribution. The problem is dealing with those libraries that do not belong to the standard library, i.e. wxPython, scipy, python cryptographic toolkit, reportlab, and so on.
Is there a working Linux counterpart to, say, py2exe (which, by the way, I have never tried)?
Is there a free, opensource one?
A:
Create a deb (for everything Debian-derived) and an rpm (for Fedora/SuSE). Add the right dependencies to the packaging and you can be reasonably sure that it will work.
A:
You can use cx_Freeze to do this. It's just like py2exe (bundles together the interpreter and and startup script and all required libraries and modules), but works on both Linux and Windows.
It collects the dependencies from the environment in which it is run, which means that they need to be suitable for the destination as well. If you're doing something like building on 32 bit Debian and deploying on another 32 bit Debian, then that's fine. You can handle 32/64 bit differences by building multiple versions in appropriate environments (e.g. 32 bit and 64 bit chroots) and distributing the appropriate one. If you're wanting something more generic (e.g. build on Debian, deploy on any distribution), then this gets a bit murky, depending on exactly what your dependencies are.
If you're doing a fairly straightforward distribution (i.e. you know that your build environment and deploy environments are similar), then this avoids the rather complex rpm/deb/egg/etc step (using cx_Freeze is very easy, especially if you're familiar with py2exe). If not, then anything from rolling your own dependancy installer to deb/rpm/egg/etc building will work, depending on how much work you want to do, how much flexibility with required versions you want to offer, and what the dependencies are.
A:
You might want to look at the dependency declarations in setuptools. This might provide a way to assure that the right packages are either available in the environment or can be installed by someone with appropriate privileges.
A:
You can't easily do it in a distribution-neutral format. The only reliable dependency tracking mechanisms are built into the package management systems on the distributions and will vary from distribution to distribution. You'll effectively have to do rpm for fedora, debs for ubuntu and debian etc.
Py2exe works fine on Windows. It builds a distribution with all of the necessary DLL's and a wrapper for the python interpreter that starts your program. It's fairly straightforward to install - just drop it in a directory - so making a msi file for it is trivial.
A:
Setuptools is overkill for me since my program's usage is quite limited, so here's my homegrown alternative.
I bundle a "third-party" directory that includes all prerequisites, and use site.addsitedir so they don't need to be installed globally.
# program startup code
import os
import sys
import site
path = os.path.abspath(os.path.dirname(__file__))
ver = 'python%d.%d' % sys.version_info[:2]
thirdparty = os.path.join(path, 'third-party', 'lib', ver, 'site-packages')
site.addsitedir(thirdparty)
Most of my prereqs have setup.py installers. Each bundled module gets its own "install" process, so any customized stuff (e.g. ./configure) can be run automatically. My install script runs this makefile as part of the install process.
# sample third-party/Makefile
PYTHON_VER = `python -c "import sys; \
print 'python%d.%d' % sys.version_info[:2]"`
PYTHON_PATH = lib/$(PYTHON_VER)/site-packages
MODS = egenix-mx-base-3.0.0 # etc
.PHONY: all init clean realclean $(MODS)
all: $(MODS)
$(MODS): init
init:
mkdir -p bin
mkdir -p $(PYTHON_PATH)
clean:
rm -rf $(MODS)
realclean: clean
rm -rf bin
rm -rf lib
egenix-mx-base-3.0.0:
tar xzf $@.tar.gz
cd $@ && python setup.py install --prefix=..
rm -rf $@
A:
The standard python way is to create a python "Egg".
You could have a look at this tutorial, or this page about setuptools.
|
Standalone Python applications in Linux
|
How can I distribute a standalone Python application in Linux?
I think I can take for granted the presence of a recent Python interpreter in any modern distribution. The problem is dealing with those libraries that do not belong to the standard library, i.e. wxPython, scipy, python cryptographic toolkit, reportlab, and so on.
Is there a working Linux counterpart to, say, py2exe (which, by the way, I have never tried)?
Is there a free, opensource one?
|
[
"Create a deb (for everything Debian-derived) and an rpm (for Fedora/SuSE). Add the right dependencies to the packaging and you can be reasonably sure that it will work.\n",
"You can use cx_Freeze to do this. It's just like py2exe (bundles together the interpreter and and startup script and all required libraries and modules), but works on both Linux and Windows.\nIt collects the dependencies from the environment in which it is run, which means that they need to be suitable for the destination as well. If you're doing something like building on 32 bit Debian and deploying on another 32 bit Debian, then that's fine. You can handle 32/64 bit differences by building multiple versions in appropriate environments (e.g. 32 bit and 64 bit chroots) and distributing the appropriate one. If you're wanting something more generic (e.g. build on Debian, deploy on any distribution), then this gets a bit murky, depending on exactly what your dependencies are.\nIf you're doing a fairly straightforward distribution (i.e. you know that your build environment and deploy environments are similar), then this avoids the rather complex rpm/deb/egg/etc step (using cx_Freeze is very easy, especially if you're familiar with py2exe). If not, then anything from rolling your own dependancy installer to deb/rpm/egg/etc building will work, depending on how much work you want to do, how much flexibility with required versions you want to offer, and what the dependencies are.\n",
"You might want to look at the dependency declarations in setuptools. This might provide a way to assure that the right packages are either available in the environment or can be installed by someone with appropriate privileges.\n",
"You can't easily do it in a distribution-neutral format. The only reliable dependency tracking mechanisms are built into the package management systems on the distributions and will vary from distribution to distribution. You'll effectively have to do rpm for fedora, debs for ubuntu and debian etc.\nPy2exe works fine on Windows. It builds a distribution with all of the necessary DLL's and a wrapper for the python interpreter that starts your program. It's fairly straightforward to install - just drop it in a directory - so making a msi file for it is trivial.\n",
"Setuptools is overkill for me since my program's usage is quite limited, so here's my homegrown alternative.\nI bundle a \"third-party\" directory that includes all prerequisites, and use site.addsitedir so they don't need to be installed globally.\n# program startup code\nimport os\nimport sys\nimport site\npath = os.path.abspath(os.path.dirname(__file__))\nver = 'python%d.%d' % sys.version_info[:2]\nthirdparty = os.path.join(path, 'third-party', 'lib', ver, 'site-packages')\nsite.addsitedir(thirdparty)\n\nMost of my prereqs have setup.py installers. Each bundled module gets its own \"install\" process, so any customized stuff (e.g. ./configure) can be run automatically. My install script runs this makefile as part of the install process.\n# sample third-party/Makefile\nPYTHON_VER = `python -c \"import sys; \\\n print 'python%d.%d' % sys.version_info[:2]\"`\nPYTHON_PATH = lib/$(PYTHON_VER)/site-packages\nMODS = egenix-mx-base-3.0.0 # etc\n\n.PHONY: all init clean realclean $(MODS)\nall: $(MODS)\n$(MODS): init\ninit:\n mkdir -p bin\n mkdir -p $(PYTHON_PATH)\nclean:\n rm -rf $(MODS)\nrealclean: clean\n rm -rf bin\n rm -rf lib\n\negenix-mx-base-3.0.0:\n tar xzf $@.tar.gz\n cd $@ && python setup.py install --prefix=..\n rm -rf $@\n\n",
"The standard python way is to create a python \"Egg\".\nYou could have a look at this tutorial, or this page about setuptools.\n"
] |
[
23,
13,
10,
7,
7,
3
] |
[
"I think you can fairly safely take for granted python support on most modern Linux distributions - for the ones without it as long as a sane error message is given, users should probably be able to work how to get it on their own (you can use a simple bash startup script for this):\n#!/bin/bash\nif [ -e /usr/bin/python ]\nthen\n echo \"Python found!\"\nelse\n echo \"Python missing!\"\nfi\n\n",
"Nope.\nPython is notoriously flaky with respect to different setups. The only sane way to deploy a python app is to ship the whole bundle of interpreter and libraries that you are relying on with your code. That will most likely work.\nUpdate 2019: I stand by this. Virtualenv is a way of packaging libraries and interpreters together. Tox is a testing tool to test that interpreter/dependency matrix. Docker is a widely used way of then deploying the bundle.\n"
] |
[
-1,
-9
] |
[
"linux",
"python"
] |
stackoverflow_0000193077_linux_python.txt
|
Q:
Changing schema using cx_Oracle
Well, I hope this is not a duplicate, the search did not yield anything useful.
I have been toying with cx_Oracle for the past few days, installing and using it. Everything went fine until I reached my current problem: I'd like to change my schema. If I were using sqlplus a simple 'alter session set current_schema=toto;' would do, but I don't know how to get around it with cx_Oracle.
I've downloaded the latest source version: cx_Oracle-5.0.2.tar.gz.
According to the documentation changing of schema is a simple case of setting Connection.current_schema which should be a read-write attribute... the trouble is my Connection object does not have any current_schema attribute.
>>> c = cx_Oracle.connect(...)
>>> dir(c)
['__class__', '__delattr__', '__doc__', '__enter__', '__exit__', '__format__',
'__getattribute__', '__hash__', '__init__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__',
'__subclasshook__', 'autocommit', 'begin', 'cancel', 'changepassword', 'close',
'commit', 'cursor', 'dsn', 'encoding', 'inputtypehandler',
'maxBytesPerCharacter', 'nencoding', 'outputtypehandler', 'password', 'prepare',
'register', 'rollback', 'stmtcachesize', 'tnsentry', 'unregister', 'username',
'version']
Trying to set the attribute using
>>> c.current_schema = 'toto'
results in an error... __setattr__ has apparently been overridden to prevent it.
So... does anyone know how to ?
Here is the error I got.
>>> c.current_schema = 'toto'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'cx_Oracle.Connection' object has no attribute 'current_schema'
>>> setattr(c, 'current_schema', 'toto')
# same error
And here are the information about OS and python:
SUSE LINUX Enterprise Server 9 (x86_64)
VERSION = 9
PATCHLEVEL = 3
And I use python 2.6.2 (compiled for 64bits)
I also compiled cx_Oracle for 64bits, on the very same machine.
A:
Okay, I finally, after much trying and error, followed fn suggestion and investigated inside cx_Oracle to find what was wrong.
It turns out that a number of arguments and methods are only available through some flags:
WITH_UNICODE activates encoding and nencoding attributes
ORACLE_10G activates action, module, clientinfo and current_schema
I checked and found out that I had compiled cx_Oracle against the version 9 of the oracle client... so I recompiled against the version 10.2.0.3 of the oracle client and now I have access to these attributes.
Shame that the restriction was not precised in the documentation... and I am very thankful that the source code is available.
A:
Try reinstalling cx_Oracle. Your cx_Oracle is probably messed up. What's your OS and python version?
|
Changing schema using cx_Oracle
|
Well, I hope this is not a duplicate, the search did not yield anything useful.
I have been toying with cx_Oracle for the past few days, installing and using it. Everything went fine until I reached my current problem: I'd like to change my schema. If I were using sqlplus a simple 'alter session set current_schema=toto;' would do, but I don't know how to get around it with cx_Oracle.
I've downloaded the latest source version: cx_Oracle-5.0.2.tar.gz.
According to the documentation changing of schema is a simple case of setting Connection.current_schema which should be a read-write attribute... the trouble is my Connection object does not have any current_schema attribute.
>>> c = cx_Oracle.connect(...)
>>> dir(c)
['__class__', '__delattr__', '__doc__', '__enter__', '__exit__', '__format__',
'__getattribute__', '__hash__', '__init__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__',
'__subclasshook__', 'autocommit', 'begin', 'cancel', 'changepassword', 'close',
'commit', 'cursor', 'dsn', 'encoding', 'inputtypehandler',
'maxBytesPerCharacter', 'nencoding', 'outputtypehandler', 'password', 'prepare',
'register', 'rollback', 'stmtcachesize', 'tnsentry', 'unregister', 'username',
'version']
Trying to set the attribute using
>>> c.current_schema = 'toto'
results in an error... __setattr__ has apparently been overridden to prevent it.
So... does anyone know how to ?
Here is the error I got.
>>> c.current_schema = 'toto'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'cx_Oracle.Connection' object has no attribute 'current_schema'
>>> setattr(c, 'current_schema', 'toto')
# same error
And here are the information about OS and python:
SUSE LINUX Enterprise Server 9 (x86_64)
VERSION = 9
PATCHLEVEL = 3
And I use python 2.6.2 (compiled for 64bits)
I also compiled cx_Oracle for 64bits, on the very same machine.
|
[
"Okay, I finally, after much trying and error, followed fn suggestion and investigated inside cx_Oracle to find what was wrong.\nIt turns out that a number of arguments and methods are only available through some flags:\n\nWITH_UNICODE activates encoding and nencoding attributes\nORACLE_10G activates action, module, clientinfo and current_schema\n\nI checked and found out that I had compiled cx_Oracle against the version 9 of the oracle client... so I recompiled against the version 10.2.0.3 of the oracle client and now I have access to these attributes.\nShame that the restriction was not precised in the documentation... and I am very thankful that the source code is available.\n",
"Try reinstalling cx_Oracle. Your cx_Oracle is probably messed up. What's your OS and python version?\n"
] |
[
10,
2
] |
[] |
[] |
[
"cx_oracle",
"oracle",
"python"
] |
stackoverflow_0002012035_cx_oracle_oracle_python.txt
|
Q:
Django, create_user giving error, manually creating user gives different error
Working with Django 1.1 on Python 2.6.4, trying to execute the following:
user = User.objects.create_user(username, email, password)
The three values are from form.cleaned_data, and have already been validated. i get this error:
'dict' object has no attribute 'strip'
Traceback:
File "/usr/lib/pymodules/python2.6/django/core/handlers/base.py" in get_response
92. response = callback(request, *callback_args, **callback_kwargs)
File "/home/jason/bandistry/../bandistry/musician/views.py" in signup
140. user = User.objects.create_user(username, email_address, password)
File "/usr/lib/pymodules/python2.6/django/contrib/auth/models.py" in create_user
100. user = self.model(None, username, '', '', email.strip().lower(), 'placeholder', False, True, False, now, now)
Exception Type: AttributeError at /musician/signup
Exception Value: 'dict' object has no attribute 'strip'
So then i tried to create a user manually using this:
user = User(username=username, email=email_address)
user.set_password(password)
user.is_active = True
user.save()
and i get this error:
Traceback:
File "/usr/lib/pymodules/python2.6/django/core/handlers/base.py" in get_response
92. response = callback(request, *callback_args, **callback_kwargs)
File "/home/jason/bandistry/../bandistry/musician/views.py" in signup
144. user.save()
File "/usr/lib/pymodules/python2.6/django/db/models/base.py" in save
410. self.save_base(force_insert=force_insert, force_update=force_update)
File "/usr/lib/pymodules/python2.6/django/db/models/base.py" in save_base
495. result = manager._insert(values, return_id=update_pk)
File "/usr/lib/pymodules/python2.6/django/db/models/manager.py" in _insert
177. return insert_query(self.model, values, **kwargs)
File "/usr/lib/pymodules/python2.6/django/db/models/query.py" in insert_query
1087. return query.execute_sql(return_id)
File "/usr/lib/pymodules/python2.6/django/db/models/sql/subqueries.py" in execute_sql
320. cursor = super(InsertQuery, self).execute_sql(None)
File "/usr/lib/pymodules/python2.6/django/db/models/sql/query.py" in execute_sql
2369. cursor.execute(sql, params)
File "/usr/lib/pymodules/python2.6/django/db/backends/util.py" in execute
19. return self.cursor.execute(sql, params)
File "/usr/lib/pymodules/python2.6/django/db/backends/mysql/base.py" in execute
84. return self.cursor.execute(query, args)
File "/usr/lib/pymodules/python2.6/MySQLdb/cursors.py" in execute
151. query = query % db.literal(args)
File "/usr/lib/pymodules/python2.6/MySQLdb/connections.py" in literal
247. return self.escape(o, self.encoders)
File "/usr/lib/pymodules/python2.6/MySQLdb/connections.py" in unicode_literal
185. return db.literal(u.encode(unicode_literal.charset))
File "/usr/lib/pymodules/python2.6/MySQLdb/connections.py" in literal
247. return self.escape(o, self.encoders)
Exception Type: RuntimeError at /musician/signup
Exception Value: maximum recursion depth exceeded
Anyone else gotten these errors and know what i am doing wrong?
A:
Seems like email_address is not really a string ('dict' object has no attribute 'strip'), can you dump for us the values of username, email and password?
|
Django, create_user giving error, manually creating user gives different error
|
Working with Django 1.1 on Python 2.6.4, trying to execute the following:
user = User.objects.create_user(username, email, password)
The three values are from form.cleaned_data, and have already been validated. i get this error:
'dict' object has no attribute 'strip'
Traceback:
File "/usr/lib/pymodules/python2.6/django/core/handlers/base.py" in get_response
92. response = callback(request, *callback_args, **callback_kwargs)
File "/home/jason/bandistry/../bandistry/musician/views.py" in signup
140. user = User.objects.create_user(username, email_address, password)
File "/usr/lib/pymodules/python2.6/django/contrib/auth/models.py" in create_user
100. user = self.model(None, username, '', '', email.strip().lower(), 'placeholder', False, True, False, now, now)
Exception Type: AttributeError at /musician/signup
Exception Value: 'dict' object has no attribute 'strip'
So then i tried to create a user manually using this:
user = User(username=username, email=email_address)
user.set_password(password)
user.is_active = True
user.save()
and i get this error:
Traceback:
File "/usr/lib/pymodules/python2.6/django/core/handlers/base.py" in get_response
92. response = callback(request, *callback_args, **callback_kwargs)
File "/home/jason/bandistry/../bandistry/musician/views.py" in signup
144. user.save()
File "/usr/lib/pymodules/python2.6/django/db/models/base.py" in save
410. self.save_base(force_insert=force_insert, force_update=force_update)
File "/usr/lib/pymodules/python2.6/django/db/models/base.py" in save_base
495. result = manager._insert(values, return_id=update_pk)
File "/usr/lib/pymodules/python2.6/django/db/models/manager.py" in _insert
177. return insert_query(self.model, values, **kwargs)
File "/usr/lib/pymodules/python2.6/django/db/models/query.py" in insert_query
1087. return query.execute_sql(return_id)
File "/usr/lib/pymodules/python2.6/django/db/models/sql/subqueries.py" in execute_sql
320. cursor = super(InsertQuery, self).execute_sql(None)
File "/usr/lib/pymodules/python2.6/django/db/models/sql/query.py" in execute_sql
2369. cursor.execute(sql, params)
File "/usr/lib/pymodules/python2.6/django/db/backends/util.py" in execute
19. return self.cursor.execute(sql, params)
File "/usr/lib/pymodules/python2.6/django/db/backends/mysql/base.py" in execute
84. return self.cursor.execute(query, args)
File "/usr/lib/pymodules/python2.6/MySQLdb/cursors.py" in execute
151. query = query % db.literal(args)
File "/usr/lib/pymodules/python2.6/MySQLdb/connections.py" in literal
247. return self.escape(o, self.encoders)
File "/usr/lib/pymodules/python2.6/MySQLdb/connections.py" in unicode_literal
185. return db.literal(u.encode(unicode_literal.charset))
File "/usr/lib/pymodules/python2.6/MySQLdb/connections.py" in literal
247. return self.escape(o, self.encoders)
Exception Type: RuntimeError at /musician/signup
Exception Value: maximum recursion depth exceeded
Anyone else gotten these errors and know what i am doing wrong?
|
[
"Seems like email_address is not really a string ('dict' object has no attribute 'strip'), can you dump for us the values of username, email and password?\n"
] |
[
2
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002013230_django_python.txt
|
Q:
Is it possible to use KHTMLPart completely from console?
I'm using the KHTMLPart component from the PyKDE (in Python) library to download some webpages in the background and return sizes of certain elements in pixels. I don't really need any visual output from this script, indeed I will probably run it on a server without X installed. The problem is that when I tell my application to run console-only like this:
app = QApplication(sys.argv, False)
my script then segfaults on the line where I initialize KHTMLPart:
browser = KHTMLPart()
Additionally, I need to set the size of the KHTML browser window to 1024x768 by calling:
browser.view.resize(1024, 768)
This doesn't seem to have any effect until I call:
browser.show()
The previous causes the browser window to appear, even if that's for a short while. I could run a simple window manager such as fluxbox on the server and it will do what I want, but I'd be much happier if it were able to function completely as a console application - if that's even possible. Is there a way to achieve this?
A:
If all else fails, you could try using the X Virtual Framebuffer to provide a fake X display to your application, allowing it to run without displaying anywhere.
A:
I doubt it. Most browsers separate the download, the creation of the DOM model and the rendering in different parts of the code. This allows them to download the data in threads, convert it and then use an optimized renderer to display it. This is an expensive operation so they only do it when necessary.
Therefore, I see no way around the fact that you need a running X server. But that server doesn't need to use the display. You can run the command vncserver for this. It will tell you the value you'll seed in for the DISPLAY variable to make your code access this hidden screen.
|
Is it possible to use KHTMLPart completely from console?
|
I'm using the KHTMLPart component from the PyKDE (in Python) library to download some webpages in the background and return sizes of certain elements in pixels. I don't really need any visual output from this script, indeed I will probably run it on a server without X installed. The problem is that when I tell my application to run console-only like this:
app = QApplication(sys.argv, False)
my script then segfaults on the line where I initialize KHTMLPart:
browser = KHTMLPart()
Additionally, I need to set the size of the KHTML browser window to 1024x768 by calling:
browser.view.resize(1024, 768)
This doesn't seem to have any effect until I call:
browser.show()
The previous causes the browser window to appear, even if that's for a short while. I could run a simple window manager such as fluxbox on the server and it will do what I want, but I'd be much happier if it were able to function completely as a console application - if that's even possible. Is there a way to achieve this?
|
[
"If all else fails, you could try using the X Virtual Framebuffer to provide a fake X display to your application, allowing it to run without displaying anywhere.\n",
"I doubt it. Most browsers separate the download, the creation of the DOM model and the rendering in different parts of the code. This allows them to download the data in threads, convert it and then use an optimized renderer to display it. This is an expensive operation so they only do it when necessary.\nTherefore, I see no way around the fact that you need a running X server. But that server doesn't need to use the display. You can run the command vncserver for this. It will tell you the value you'll seed in for the DISPLAY variable to make your code access this hidden screen.\n"
] |
[
1,
1
] |
[] |
[] |
[
"kde_plasma",
"pykde",
"python"
] |
stackoverflow_0002013795_kde_plasma_pykde_python.txt
|
Q:
PNG optimisation tools
A while back I used a PNG optimisation service called (I think) "smush it". You fed it a weblink and it returned a zip of all the PNG images with their filesizes nicely, well, smushed...
I want to implement a similar optimisation feature as part of my website's image upload process; does anyone know of a pre-existing library (PHP or Python preferably) that I can tap into for this? A brief Google has pointed me towards several command line style tools, but I'd rather not go down that route if possible.
A:
Execute with PHP this command line tools
pngcrush -rem gAMA -rem cHRM -rem iCCP -rem sRGB -brute -l 9 -max -reduce -m 0 -q IMAGE
optipng -o7 -q pngout.png
pngout pngout.png -q -y -k0 -s0
advpng -z -4 pngout.png > /dev/null
pngcrush
OptiPNG
pngout
advpng
A:
As long as your PHP is compiled with GD2 support (quite common nowadays):
<?php
$image = imagecreatefromstring(file_get_contents('/path/to/image.original.png'));
imagepng($image, '/path/to/image.smushed.png', 9);
This will read in any image format GD2 understands (not just PNG) and output a PNG gzipped as the maximum compression level without sacrificing quality.
It might be of less use today than years ago though; most image editors already do this, since gzipping doesn't cost as much CPU-wise as it used to.
A:
Have you heard of PNGCrush? You could check out the source, part of PNG and MNG Tools at SourceForge, and transcribe or wrap it in Python.
A:
I would question the wisdom of throwing away other chunks (like gAMA and iCCP), but if that's what you want to do it's fairly easy to use PyPNG to remove chunks:
#!/usr/bin/env python
import png
import sys
input=sys.stdin
out=sys.stdout
def critical_chunks(chunks):
for type,data in chunks:
if type[0].isupper():
yield type,data
chunks = png.Reader(file=input).chunks()
png.write_chunks(out, critical_chunks(chunks))
the critical_chunks function is essentially filtering out all but the critical PNG chunks (the 4 letter type for a critical chunk starts with an uppercase letter).
|
PNG optimisation tools
|
A while back I used a PNG optimisation service called (I think) "smush it". You fed it a weblink and it returned a zip of all the PNG images with their filesizes nicely, well, smushed...
I want to implement a similar optimisation feature as part of my website's image upload process; does anyone know of a pre-existing library (PHP or Python preferably) that I can tap into for this? A brief Google has pointed me towards several command line style tools, but I'd rather not go down that route if possible.
|
[
"Execute with PHP this command line tools\n pngcrush -rem gAMA -rem cHRM -rem iCCP -rem sRGB -brute -l 9 -max -reduce -m 0 -q IMAGE\n optipng -o7 -q pngout.png\n pngout pngout.png -q -y -k0 -s0\n advpng -z -4 pngout.png > /dev/null\n\n\npngcrush\nOptiPNG\npngout\nadvpng\n\n",
"As long as your PHP is compiled with GD2 support (quite common nowadays):\n<?php\n$image = imagecreatefromstring(file_get_contents('/path/to/image.original.png'));\nimagepng($image, '/path/to/image.smushed.png', 9);\n\nThis will read in any image format GD2 understands (not just PNG) and output a PNG gzipped as the maximum compression level without sacrificing quality.\nIt might be of less use today than years ago though; most image editors already do this, since gzipping doesn't cost as much CPU-wise as it used to.\n",
"Have you heard of PNGCrush? You could check out the source, part of PNG and MNG Tools at SourceForge, and transcribe or wrap it in Python.\n",
"I would question the wisdom of throwing away other chunks (like gAMA and iCCP), but if that's what you want to do it's fairly easy to use PyPNG to remove chunks:\n#!/usr/bin/env python\nimport png\nimport sys\n\ninput=sys.stdin\nout=sys.stdout\n\ndef critical_chunks(chunks):\n for type,data in chunks:\n if type[0].isupper():\n yield type,data\n\nchunks = png.Reader(file=input).chunks()\npng.write_chunks(out, critical_chunks(chunks))\n\nthe critical_chunks function is essentially filtering out all but the critical PNG chunks (the 4 letter type for a critical chunk starts with an uppercase letter).\n"
] |
[
14,
4,
3,
2
] |
[] |
[] |
[
"optimization",
"php",
"png",
"python"
] |
stackoverflow_0001993678_optimization_php_png_python.txt
|
Q:
Python: How do you format a string % number with str.format()
How can I format a string like this
"%01.2f" % pr"%01.2f" % some_number
but using the str.format() style? I'm used to this:
'{0} {1}'.format(somevalue1, somevalue2)
Is there a way to use that function style vs the old % style, and still achieve this decimal formatting?
A:
It would be like {0:01.2f}, I believe. See http://docs.python.org/library/string.html#format-string-syntax.
Edit: added in your zero-padding.
|
Python: How do you format a string % number with str.format()
|
How can I format a string like this
"%01.2f" % pr"%01.2f" % some_number
but using the str.format() style? I'm used to this:
'{0} {1}'.format(somevalue1, somevalue2)
Is there a way to use that function style vs the old % style, and still achieve this decimal formatting?
|
[
"It would be like {0:01.2f}, I believe. See http://docs.python.org/library/string.html#format-string-syntax.\nEdit: added in your zero-padding.\n"
] |
[
4
] |
[] |
[] |
[
"python",
"string"
] |
stackoverflow_0002014012_python_string.txt
|
Q:
attribute assignment order in class definition
I want to define a class in this way:
class List(Base):
hp = Column(int,...)
name = Column(str,...)
This class represents a list, I can define/modify/code the Base and the Column class.
There's a way to know the order in which I defined the attributes hp/names?
For example I want to define a method that can do this:
l = List()
l.show()
[(hp,16),(name,roger)] # in this order
A:
Internally, attribute definitions are stored in a dictionary, which does not retain the order of the elements. You could probably change the attribute handling in the Base class, or you store the creation order, like this:
class Column:
creation_counter = 0
def __init__(self):
self.creation_counter = Column.creation_counter
Column.creation_counter += 1
class Base:
def show(self):
fields = [(name, (obj, obj.value)) for name, obj in self.__class__.__dict__.items() if isinstance(obj, Column)]
fields.sort(lambda (name1, (obj1, value1)), (name2, (obj2, value2)): cmp(obj1.creation_counter, obj2.creation_counter))
return fields
Django stores the order of form fields in a similar way, albeit way more sophisticated. If you are interested, look at the source of Django forms and fields
A:
I think you want something like this:
import inspect
class List(Base):
hp = Column(int,...)
name = Column(str,...)
def show(self):
public_bits = [(x, getattr(self, x)) for x in dir(self) if not x.startswith('__')]
return [(x, y) for (x, y) in public_bits if not inspect.ismethod(y)]
Sadly, dir returns attributes in alphabetical order, so this may not exactly solve your problem.
A:
Class and instance attributes are inherently unordered since they are stored in a dictionary.
There are a few options though:
1) classes defined with __slots__ do not use a dictionary, and the space for attributes are pre-allocated. I presume that the attributes are therefore ordered, so it should be possible in principle to get the data out. There are issues with using slots though, and it is not recommended.
2) add a list/tuple attribute to the class with the attribute order.
3) use a collection.namedtuple object to store the attributes. A namedtuple is a tuple where you can give names to the elements, and so is similar to a C struct. This will only work from Python 2.6 onwards. Since tuples are immutable you will not be able modify the attributes once created - this may or may not be a problem depending on the class.
Edit:
On reflection __slots__ will not work, since I think they only apply to instances and not class attributes.
|
attribute assignment order in class definition
|
I want to define a class in this way:
class List(Base):
hp = Column(int,...)
name = Column(str,...)
This class represents a list, I can define/modify/code the Base and the Column class.
There's a way to know the order in which I defined the attributes hp/names?
For example I want to define a method that can do this:
l = List()
l.show()
[(hp,16),(name,roger)] # in this order
|
[
"Internally, attribute definitions are stored in a dictionary, which does not retain the order of the elements. You could probably change the attribute handling in the Base class, or you store the creation order, like this:\nclass Column:\n creation_counter = 0\n\n def __init__(self):\n self.creation_counter = Column.creation_counter\n Column.creation_counter += 1\n\nclass Base:\n def show(self):\n fields = [(name, (obj, obj.value)) for name, obj in self.__class__.__dict__.items() if isinstance(obj, Column)] \n fields.sort(lambda (name1, (obj1, value1)), (name2, (obj2, value2)): cmp(obj1.creation_counter, obj2.creation_counter))\n return fields\n\nDjango stores the order of form fields in a similar way, albeit way more sophisticated. If you are interested, look at the source of Django forms and fields \n",
"I think you want something like this:\nimport inspect\n\nclass List(Base):\n hp = Column(int,...)\n name = Column(str,...)\n\n def show(self):\n public_bits = [(x, getattr(self, x)) for x in dir(self) if not x.startswith('__')]\n return [(x, y) for (x, y) in public_bits if not inspect.ismethod(y)]\n\nSadly, dir returns attributes in alphabetical order, so this may not exactly solve your problem.\n",
"Class and instance attributes are inherently unordered since they are stored in a dictionary.\nThere are a few options though:\n1) classes defined with __slots__ do not use a dictionary, and the space for attributes are pre-allocated. I presume that the attributes are therefore ordered, so it should be possible in principle to get the data out. There are issues with using slots though, and it is not recommended.\n2) add a list/tuple attribute to the class with the attribute order.\n3) use a collection.namedtuple object to store the attributes. A namedtuple is a tuple where you can give names to the elements, and so is similar to a C struct. This will only work from Python 2.6 onwards. Since tuples are immutable you will not be able modify the attributes once created - this may or may not be a problem depending on the class.\nEdit:\nOn reflection __slots__ will not work, since I think they only apply to instances and not class attributes.\n"
] |
[
7,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002013067_python.txt
|
Q:
Vim Python indentation not working?
I have Vim 7 (enhanced) on CentOS 5, and it comes with all the usual Vim plugins/scripts ready to go.
$ find /usr/share/vim/vim70/ -name \*python\*
/usr/share/vim/vim70/syntax/python.vim
/usr/share/vim/vim70/ftplugin/python.vim
/usr/share/vim/vim70/indent/python.vim
/usr/share/vim/vim70/autoload/pythoncomplete.vim
I would think that when opening a file ending in .py (vim file.py) it would automatically load these plugins, but I am not sure that is the case. What I want is:
Press TAB and receive four spaces. Auto indent next line for suites, conditionals, etc.
I have this working by explicitly setting tabstop, shiftwidth, etc. in my .vimrc file. Isn't this what the above Python files are for? Why do I have to set these things in my .vimrc? How do I get these features from the Vim plugins instead?
Current .vimrc:
syntax on
set hls
set expandtab
set textwidth=0
set tabstop=4
set softtabstop=4
set shiftwidth=4
set autoindent
set backspace=indent,eol,start
set incsearch
set ignorecase
set ruler
set wildmenu
set smarttab
filetype indent on
filetype on
filetype plugin on
A:
My understanding is that the python.vim file is just a syntax-highlighting file possibly, because Python files can be indented multiple ways. PEP8 prescribes four spaces, but legacy files could be different including using tabs.
Some of our legacy Python files actually use two spaces per indent. So I leave Python indenting to Vim and configure it per file and per filetype. The following line in .vimrc gives me Python-specific settings which differ from say my xml, xhtml, and html (two spaces).
au FileType python setl shiftwidth=4 tabstop=4
You can also set specific settings by file with a modeline which is handy if you do have legacy files.
# vi: set tabstop=2 expandtab textwidth=70 filetype=python:
A:
Setting tabstop, shiftwidth, etc... in your vimrc is correct. These set your global settings, as well as serve as parameters to the filetype-specific indentation support.
The language indentation plugins use these settings, but typically also set an indent expression (:he inde) appropriate for the language. Thus the Python indenter should be automatically indenting after a block opening statement (def, class, for...), and dedenting after a closing one (return, pass, continue...) and doing so according to the ts,sw,... you have set.
If you're still unsure if the plugin is loading for a buffer, simply do :filetype to show the detection, plugin, and indent settings, and :set ft? to see the detected type.
|
Vim Python indentation not working?
|
I have Vim 7 (enhanced) on CentOS 5, and it comes with all the usual Vim plugins/scripts ready to go.
$ find /usr/share/vim/vim70/ -name \*python\*
/usr/share/vim/vim70/syntax/python.vim
/usr/share/vim/vim70/ftplugin/python.vim
/usr/share/vim/vim70/indent/python.vim
/usr/share/vim/vim70/autoload/pythoncomplete.vim
I would think that when opening a file ending in .py (vim file.py) it would automatically load these plugins, but I am not sure that is the case. What I want is:
Press TAB and receive four spaces. Auto indent next line for suites, conditionals, etc.
I have this working by explicitly setting tabstop, shiftwidth, etc. in my .vimrc file. Isn't this what the above Python files are for? Why do I have to set these things in my .vimrc? How do I get these features from the Vim plugins instead?
Current .vimrc:
syntax on
set hls
set expandtab
set textwidth=0
set tabstop=4
set softtabstop=4
set shiftwidth=4
set autoindent
set backspace=indent,eol,start
set incsearch
set ignorecase
set ruler
set wildmenu
set smarttab
filetype indent on
filetype on
filetype plugin on
|
[
"My understanding is that the python.vim file is just a syntax-highlighting file possibly, because Python files can be indented multiple ways. PEP8 prescribes four spaces, but legacy files could be different including using tabs.\nSome of our legacy Python files actually use two spaces per indent. So I leave Python indenting to Vim and configure it per file and per filetype. The following line in .vimrc gives me Python-specific settings which differ from say my xml, xhtml, and html (two spaces).\nau FileType python setl shiftwidth=4 tabstop=4\n\nYou can also set specific settings by file with a modeline which is handy if you do have legacy files.\n# vi: set tabstop=2 expandtab textwidth=70 filetype=python:\n\n",
"Setting tabstop, shiftwidth, etc... in your vimrc is correct. These set your global settings, as well as serve as parameters to the filetype-specific indentation support.\nThe language indentation plugins use these settings, but typically also set an indent expression (:he inde) appropriate for the language. Thus the Python indenter should be automatically indenting after a block opening statement (def, class, for...), and dedenting after a closing one (return, pass, continue...) and doing so according to the ts,sw,... you have set.\nIf you're still unsure if the plugin is loading for a buffer, simply do :filetype to show the detection, plugin, and indent settings, and :set ft? to see the detected type.\n"
] |
[
5,
2
] |
[] |
[] |
[
"python",
"vim",
"vim_plugin"
] |
stackoverflow_0002011589_python_vim_vim_plugin.txt
|
Q:
zooming pictures with wx.image
im doing a software that paints over images and save them ( for commenting propose ) .
i used the code below to display image to be drown upon.
the problem is:
how can i zoom in and out ? .
or should i use another way to display that image ?
bitmap=wx.bitmap(path,wx.BITMAP_TYPE_ANY)
buffer =wx.EmptyBitmap(500,500,32)
dc = wx.BufferedDC(None, self.buffer)
dc.Clear()
dc.DrawBitmap(bitmap,0,0,True)
thanks in advance
A:
Try dc.SetUserScaling
|
zooming pictures with wx.image
|
im doing a software that paints over images and save them ( for commenting propose ) .
i used the code below to display image to be drown upon.
the problem is:
how can i zoom in and out ? .
or should i use another way to display that image ?
bitmap=wx.bitmap(path,wx.BITMAP_TYPE_ANY)
buffer =wx.EmptyBitmap(500,500,32)
dc = wx.BufferedDC(None, self.buffer)
dc.Clear()
dc.DrawBitmap(bitmap,0,0,True)
thanks in advance
|
[
"Try dc.SetUserScaling\n"
] |
[
3
] |
[] |
[] |
[
"image",
"python",
"wxpython",
"zooming"
] |
stackoverflow_0002014209_image_python_wxpython_zooming.txt
|
Q:
Is it possible to create an end-user facing site using Django admin alone?
I'm very new to Django, having never developed on it.
I'm trying to develop a site which has functionality exposed only to authenticated users (typical enterprise thing: for this discussion, let's say it's a private blogging platform).
The functionality I'm looking for is:
Users can create a new blog.
each user can belong to multiple groups: the user can only view/comment on blogposts created by member of groups (s)he belongs to.
Each user can modify/delete only the posts (s)he creates.
As I see it, this is essentially a CRUD application with access control, and the admin app seems to have a lot of this functionality builtin. Is it feasible to develop this complete application using the admin application alone (not as a prototype, as a release-quality solution), or should I look beyond (Generic views? ModelForms?)
I'm trying to estimate how long this will take (learning + implementation), so your feedback could give me a good idea, in addition to teaching me the ways of this new Django-world :)
Edit: specifically, one of my worries is per-object/per-row permissions. The django wiki says the Permissions system doesn't support that, so can I still use the admin app?
A:
Revised. Up until you want per-object permission, the answer is yes.
As soon as you want permission on a Blog, where a blog is just a row, you're going to have to do some coding.
You can totally reuse the admin interface elements. You have all the source, which you can read.
Much of what you want is done with "wrappers" around the admin functions.
You write a "wrapper" view function checks object permissions.
Your wrapper view function calls the admin view function.
After that, you'll want to fix the style sheets in the admin pages to be your preferred look and feel.
A:
As for row-level permissions in the admin, in the SVN version of Django you can override the has_add_permission, has_change_permission, and has_delete_permission methods on the ModelAdmin object to implement the custom permissions logic yourself in a way that will apply across the entire admin. I'm pretty sure this feature is going to be in the 1.2 release this year. It doesn't seem to be in the documentation yet, but if you can find the default methods in the django/contrib/admin/options.py file of the Django source, exact instructions are in the docstrings.
I wouldn't recommend doing the entire app in the admin, though. It would work fine for the parts of the app where people are writing their posts and creating their blogs, but the admin wouldn't be suited for just displaying the data, unless you write lots of custom code. Writing views that can display objects and submit comments in Django isn't very hard - most of the work is in the templates.
A:
As a point of sense you really shouldn't be basing a potentially large scale project on Django-Admin. It's kind of silly, and so many people are fascinated with Django-Admin that they literally have a chapter in their books about when and when not to use it for evil.
It seems to me that for all the hacking you will have to do to get the admin to look like a reasonably presentable site in terms of personalization, you might as well take the weekend off, actually LEARN the tools you are trying to bastardize, and make a real site. What you are describing wouldn't be heroic by any means in terms of logic.
This scenario reminds me of the old Garfield cartoon where the guy buys the cat an incredibly expensive and awesome looking bed, and the cat chooses to sleep in the box that the bed came in.
|
Is it possible to create an end-user facing site using Django admin alone?
|
I'm very new to Django, having never developed on it.
I'm trying to develop a site which has functionality exposed only to authenticated users (typical enterprise thing: for this discussion, let's say it's a private blogging platform).
The functionality I'm looking for is:
Users can create a new blog.
each user can belong to multiple groups: the user can only view/comment on blogposts created by member of groups (s)he belongs to.
Each user can modify/delete only the posts (s)he creates.
As I see it, this is essentially a CRUD application with access control, and the admin app seems to have a lot of this functionality builtin. Is it feasible to develop this complete application using the admin application alone (not as a prototype, as a release-quality solution), or should I look beyond (Generic views? ModelForms?)
I'm trying to estimate how long this will take (learning + implementation), so your feedback could give me a good idea, in addition to teaching me the ways of this new Django-world :)
Edit: specifically, one of my worries is per-object/per-row permissions. The django wiki says the Permissions system doesn't support that, so can I still use the admin app?
|
[
"Revised. Up until you want per-object permission, the answer is yes.\nAs soon as you want permission on a Blog, where a blog is just a row, you're going to have to do some coding.\nYou can totally reuse the admin interface elements. You have all the source, which you can read. \nMuch of what you want is done with \"wrappers\" around the admin functions.\n\nYou write a \"wrapper\" view function checks object permissions.\nYour wrapper view function calls the admin view function.\n\nAfter that, you'll want to fix the style sheets in the admin pages to be your preferred look and feel.\n",
"As for row-level permissions in the admin, in the SVN version of Django you can override the has_add_permission, has_change_permission, and has_delete_permission methods on the ModelAdmin object to implement the custom permissions logic yourself in a way that will apply across the entire admin. I'm pretty sure this feature is going to be in the 1.2 release this year. It doesn't seem to be in the documentation yet, but if you can find the default methods in the django/contrib/admin/options.py file of the Django source, exact instructions are in the docstrings.\nI wouldn't recommend doing the entire app in the admin, though. It would work fine for the parts of the app where people are writing their posts and creating their blogs, but the admin wouldn't be suited for just displaying the data, unless you write lots of custom code. Writing views that can display objects and submit comments in Django isn't very hard - most of the work is in the templates.\n",
"As a point of sense you really shouldn't be basing a potentially large scale project on Django-Admin. It's kind of silly, and so many people are fascinated with Django-Admin that they literally have a chapter in their books about when and when not to use it for evil.\nIt seems to me that for all the hacking you will have to do to get the admin to look like a reasonably presentable site in terms of personalization, you might as well take the weekend off, actually LEARN the tools you are trying to bastardize, and make a real site. What you are describing wouldn't be heroic by any means in terms of logic.\nThis scenario reminds me of the old Garfield cartoon where the guy buys the cat an incredibly expensive and awesome looking bed, and the cat chooses to sleep in the box that the bed came in.\n"
] |
[
2,
0,
0
] |
[] |
[] |
[
"django",
"django_admin",
"python"
] |
stackoverflow_0002013736_django_django_admin_python.txt
|
Q:
How to move into multiple directories Python
I am creating several directories a day. After seven days I am going to drop a sandbox in these directories and delete them. I use a time stamp to name them. I have got some code below to show you what I have got.
today = datetime.date.today() # Today's date Binary
todaystr = datetime.date.today().isoformat() # Todays date as a string
minus_sevent = today - datetime.timedelta(days = 7) # 7 days ago as a string
minus_seven = minus_sevent.isoformat()
old_folders = minus_seven + '*'
def delete_sandbox():
if os.path.exists(old_folders):
os.chdir(old_folders)
mks_drop_sandbox()
os.chdir(rootDir)
for filename in glob.glob(old_folders):
shutil.rmtree(old_folders)
print 'Sandboxes from 7 days ago removed'
if __name__ == '__main__': myObject = delete_sandbox()
This was similar code I used before to drop a sandbox and delete a one directory. But there may be several builds done in the days and I want to know how to enter each folder and do these tasks.
Folders in the directories will be created with their time as well as their date, I have variables that just remove all folders of a set date regardless of time.
Thanks
A:
old_folders = minus_seven + '*'
This does not do what you think it does. This gives you the name of a folder that literally ends in a *. Later, os.path.exists() will return False.
What you need to do is loop through the directories:
for d in os.listdir(os.getcwd()):
if not os.path.isdir(d) or not d.startswith(minus_seven):
continue
# Do what you need to with 'd' here.
or as a list comprehension:
minus_seven_dirs = [d for d in os.listdir(os.getcwd())
if os.path.isdir(d) and d.startswith(minus_seven)]
Basically, you can't feed os functions a list and expect them to do the right thing. They work on paths one at a time.
A:
" I want to know how to enter each folder"
Are you asking about os.path.join to create the full path name?
http://docs.python.org/library/os.path.html#os.path.join
or os.chdir to change the working directory?
http://docs.python.org/library/os.html#os.chdir
A:
You have two options:
Use os.walk
for root, dirs, files in os.walk('your root'):
for dir in dirs:
os.chdir(os.path.join(root, dir))
delete_sandbox()
Use os.path.walk then change delete_sandbox to be used as the callback.
def delete_sandbox(arg, dirname, names):
|
How to move into multiple directories Python
|
I am creating several directories a day. After seven days I am going to drop a sandbox in these directories and delete them. I use a time stamp to name them. I have got some code below to show you what I have got.
today = datetime.date.today() # Today's date Binary
todaystr = datetime.date.today().isoformat() # Todays date as a string
minus_sevent = today - datetime.timedelta(days = 7) # 7 days ago as a string
minus_seven = minus_sevent.isoformat()
old_folders = minus_seven + '*'
def delete_sandbox():
if os.path.exists(old_folders):
os.chdir(old_folders)
mks_drop_sandbox()
os.chdir(rootDir)
for filename in glob.glob(old_folders):
shutil.rmtree(old_folders)
print 'Sandboxes from 7 days ago removed'
if __name__ == '__main__': myObject = delete_sandbox()
This was similar code I used before to drop a sandbox and delete a one directory. But there may be several builds done in the days and I want to know how to enter each folder and do these tasks.
Folders in the directories will be created with their time as well as their date, I have variables that just remove all folders of a set date regardless of time.
Thanks
|
[
"\nold_folders = minus_seven + '*'\n\nThis does not do what you think it does. This gives you the name of a folder that literally ends in a *. Later, os.path.exists() will return False.\nWhat you need to do is loop through the directories:\nfor d in os.listdir(os.getcwd()):\n if not os.path.isdir(d) or not d.startswith(minus_seven):\n continue\n # Do what you need to with 'd' here.\n\nor as a list comprehension:\nminus_seven_dirs = [d for d in os.listdir(os.getcwd())\n if os.path.isdir(d) and d.startswith(minus_seven)]\n\nBasically, you can't feed os functions a list and expect them to do the right thing. They work on paths one at a time.\n",
"\" I want to know how to enter each folder\"\nAre you asking about os.path.join to create the full path name?\nhttp://docs.python.org/library/os.path.html#os.path.join \nor os.chdir to change the working directory?\nhttp://docs.python.org/library/os.html#os.chdir\n",
"You have two options:\nUse os.walk \nfor root, dirs, files in os.walk('your root'):\nfor dir in dirs:\n os.chdir(os.path.join(root, dir))\n delete_sandbox()\n\nUse os.path.walk then change delete_sandbox to be used as the callback.\ndef delete_sandbox(arg, dirname, names):\n\n"
] |
[
3,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002013204_python.txt
|
Q:
PHP Bayesian Classifier
I'm looking for a Naive Bayesian Classifier for PHP, ideally something equivalent to the Reverend Bayes version written in Python. Does anyone know of such a library?
Basically I need to be able to train it with a set of labels and words i.e. GOOD = okay, happy, fun; BAD = wrong, rubbish, awful etc and then pass it a string value and have it return a best guess. Reverend does this perfectly but unfortunately the app it now has to be used in is not Python based and making a bridge between the two isn't doable.
Any suggestions will be much appreciated as most of the classes I've found seem to be medically orientated with just a few cases or set-up for spam filtering.
A:
This looks like a nice set of tutorials on the subject. A similar question has been asked previously and the only real answer pointed to the same resource.
Bayesian filtering is a general approach. Even if examples you find are medical, the techniques are pretty much the same and can be applied anywhere.
|
PHP Bayesian Classifier
|
I'm looking for a Naive Bayesian Classifier for PHP, ideally something equivalent to the Reverend Bayes version written in Python. Does anyone know of such a library?
Basically I need to be able to train it with a set of labels and words i.e. GOOD = okay, happy, fun; BAD = wrong, rubbish, awful etc and then pass it a string value and have it return a best guess. Reverend does this perfectly but unfortunately the app it now has to be used in is not Python based and making a bridge between the two isn't doable.
Any suggestions will be much appreciated as most of the classes I've found seem to be medically orientated with just a few cases or set-up for spam filtering.
|
[
"This looks like a nice set of tutorials on the subject. A similar question has been asked previously and the only real answer pointed to the same resource.\nBayesian filtering is a general approach. Even if examples you find are medical, the techniques are pretty much the same and can be applied anywhere.\n"
] |
[
3
] |
[] |
[] |
[
"php",
"python"
] |
stackoverflow_0002014432_php_python.txt
|
Q:
Polluting a class's environment
I have an object that holds lots of ids that are accessed statically. I want to split that up into another object which holds only those ids without the need of making modifications to the already existen code base. Take for example:
class _CarType(object):
DIESEL_CAR_ENGINE = 0
GAS_CAR_ENGINE = 1 # lots of these ids
class Car(object):
types = _CarType
I want to be able to access _CarType.DIESEL_CAR_ENGINE either by calling Car.types.DIESEL_CAR_ENGINE, either by Car.DIESEL_CAR_ENGINE for backwards compatibility with the existent code. It's clear that I cannot use __getattr__ so I am trying to find a way of making this work (maybe metaclasses ? )
A:
Although this is not exactly what subclassing is made for, it accomplishes what you describe:
class _CarType(object):
DIESEL_CAR_ENGINE = 0
GAS_CAR_ENGINE = 1 # lots of these ids
class Car(_CarType):
types = _CarType
A:
Something like:
class Car(object):
for attr, value in _CarType.__dict__.items():
it not attr.startswith('_'):
locals()[attr] = value
del attr, value
Or you can do it out of the class declaration:
class Car(object):
# snip
for attr, value in _CarType.__dict__.items():
it not attr.startswith('_'):
setattr(Car, attr, value)
del attr, value
A:
This is how you could do this with a metaclass:
class _CarType(type):
DIESEL_CAR_ENGINE = 0
GAS_CAR_ENGINE = 1 # lots of these ids
def __init__(self,name,bases,dct):
for key in dir(_CarType):
if key.isupper():
setattr(self,key,getattr(_CarType,key))
class Car(object):
__metaclass__=_CarType
print(Car.DIESEL_CAR_ENGINE)
print(Car.GAS_CAR_ENGINE)
A:
Your options fall into two substantial categories: you either copy the attributes from _CarType into Car, or set Car's metaclass to a custom one with a __getattr__ method that delegates to _CarType (so it isn't exactly true that you can't use __getattr__: you can, you just need to put in in Car's metaclass rather than in Car itself;-).
The second choice has implications that you might find peculiar (unless they are specifically desired): the attributes don't show up on dir(Car), and they can't be accessed on an instance of Car, only on Car itself. I.e.:
>>> class MetaGetattr(type):
... def __getattr__(cls, nm):
... return getattr(cls.types, nm)
...
>>> class Car:
... __metaclass__ = MetaGetattr
... types = _CarType
...
>>> Car.GAS_CAR_ENGINE
1
>>> Car().GAS_CAR_ENGINE
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Car' object has no attribute 'GAS_CAR_ENGINE'
You could fix the "not from an instance" issue by also adding a __getattr__ to Car:
>>> class Car:
... __metaclass__ = MetaGetattr
... types = _CarType
... def __getattr__(self, nm):
... return getattr(self.types, nm)
...
to make both kinds of lookup work, as is probably expected:
>>> Car.GAS_CAR_ENGINE
1
>>> Car().GAS_CAR_ENGINE
1
However, defining two, essentially-equal __getattr__s, doesn't seem elegant.
So I suspect that the simpler approach, "copy all attributes", is preferable. In Python 2.6 or better, this is an obvious candidate for a class decorator:
def typesfrom(typesclass):
def decorate(cls):
cls.types = typesclass
for n in dir(typesclass):
if n[0] == '_': continue
v = getattr(typesclass, n)
setattr(cls, n, v)
return cls
return decorate
@typesfrom(_CarType)
class Car(object):
pass
In general, it's worth defining a decorator if you're using it more than once; if you only need to perform this task for one class ever, then expanding the code inline instead (after the class statement) may be better.
If you're stuck with Python 2.5 (or even 2.4), you can still define typesfrom the same way, you just apply it in a slightly less elegant matter, i.e., the Car definition becomes:
class Car(object):
pass
Car = typesfrom(_CarType)(Car)
Do remember decorator syntax (introduced in 2.2 for functions, in 2.6 for classes) is just a handy way to wrap these important and frequently recurring semantics.
A:
class _CarType(object):
DIESEL_CAR_ENGINE = 0
GAS_CAR_ENGINE = 1 # lots of these ids
class Car:
types = _CarType
def __getattr__(self, name):
return getattr(self.types, name)
If an attribute of an object is not found, and it defines that magic method __getattr__, that gets called to try to find it.
Only works on a Car instance, not on the class.
|
Polluting a class's environment
|
I have an object that holds lots of ids that are accessed statically. I want to split that up into another object which holds only those ids without the need of making modifications to the already existen code base. Take for example:
class _CarType(object):
DIESEL_CAR_ENGINE = 0
GAS_CAR_ENGINE = 1 # lots of these ids
class Car(object):
types = _CarType
I want to be able to access _CarType.DIESEL_CAR_ENGINE either by calling Car.types.DIESEL_CAR_ENGINE, either by Car.DIESEL_CAR_ENGINE for backwards compatibility with the existent code. It's clear that I cannot use __getattr__ so I am trying to find a way of making this work (maybe metaclasses ? )
|
[
"Although this is not exactly what subclassing is made for, it accomplishes what you describe:\nclass _CarType(object):\n DIESEL_CAR_ENGINE = 0\n GAS_CAR_ENGINE = 1 # lots of these ids\n\nclass Car(_CarType):\n types = _CarType\n\n",
"Something like:\nclass Car(object):\n for attr, value in _CarType.__dict__.items():\n it not attr.startswith('_'):\n locals()[attr] = value\n del attr, value\n\nOr you can do it out of the class declaration:\nclass Car(object):\n # snip\n\nfor attr, value in _CarType.__dict__.items():\n it not attr.startswith('_'):\n setattr(Car, attr, value)\ndel attr, value\n\n",
"This is how you could do this with a metaclass:\nclass _CarType(type):\n DIESEL_CAR_ENGINE = 0\n GAS_CAR_ENGINE = 1 # lots of these ids\n def __init__(self,name,bases,dct):\n for key in dir(_CarType):\n if key.isupper():\n setattr(self,key,getattr(_CarType,key))\n\nclass Car(object):\n __metaclass__=_CarType\n\nprint(Car.DIESEL_CAR_ENGINE)\nprint(Car.GAS_CAR_ENGINE)\n\n",
"Your options fall into two substantial categories: you either copy the attributes from _CarType into Car, or set Car's metaclass to a custom one with a __getattr__ method that delegates to _CarType (so it isn't exactly true that you can't use __getattr__: you can, you just need to put in in Car's metaclass rather than in Car itself;-).\nThe second choice has implications that you might find peculiar (unless they are specifically desired): the attributes don't show up on dir(Car), and they can't be accessed on an instance of Car, only on Car itself. I.e.:\n>>> class MetaGetattr(type):\n... def __getattr__(cls, nm):\n... return getattr(cls.types, nm)\n... \n>>> class Car:\n... __metaclass__ = MetaGetattr\n... types = _CarType\n... \n>>> Car.GAS_CAR_ENGINE\n1\n>>> Car().GAS_CAR_ENGINE\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nAttributeError: 'Car' object has no attribute 'GAS_CAR_ENGINE'\n\nYou could fix the \"not from an instance\" issue by also adding a __getattr__ to Car:\n>>> class Car:\n... __metaclass__ = MetaGetattr\n... types = _CarType\n... def __getattr__(self, nm):\n... return getattr(self.types, nm)\n... \n\nto make both kinds of lookup work, as is probably expected:\n>>> Car.GAS_CAR_ENGINE\n1\n>>> Car().GAS_CAR_ENGINE\n1\n\nHowever, defining two, essentially-equal __getattr__s, doesn't seem elegant.\nSo I suspect that the simpler approach, \"copy all attributes\", is preferable. In Python 2.6 or better, this is an obvious candidate for a class decorator:\ndef typesfrom(typesclass):\n def decorate(cls):\n cls.types = typesclass\n for n in dir(typesclass):\n if n[0] == '_': continue\n v = getattr(typesclass, n)\n setattr(cls, n, v)\n return cls\n return decorate\n\n@typesfrom(_CarType)\nclass Car(object):\n pass\n\nIn general, it's worth defining a decorator if you're using it more than once; if you only need to perform this task for one class ever, then expanding the code inline instead (after the class statement) may be better.\nIf you're stuck with Python 2.5 (or even 2.4), you can still define typesfrom the same way, you just apply it in a slightly less elegant matter, i.e., the Car definition becomes:\nclass Car(object):\n pass\nCar = typesfrom(_CarType)(Car)\n\nDo remember decorator syntax (introduced in 2.2 for functions, in 2.6 for classes) is just a handy way to wrap these important and frequently recurring semantics.\n",
"class _CarType(object):\n DIESEL_CAR_ENGINE = 0\n GAS_CAR_ENGINE = 1 # lots of these ids\n\nclass Car:\n types = _CarType\n def __getattr__(self, name):\n return getattr(self.types, name)\n\nIf an attribute of an object is not found, and it defines that magic method __getattr__, that gets called to try to find it.\nOnly works on a Car instance, not on the class.\n"
] |
[
4,
3,
2,
2,
0
] |
[] |
[] |
[
"oop",
"python"
] |
stackoverflow_0002012698_oop_python.txt
|
Q:
Forcing tuples within tuples?
I've got a python function that should loop through a tuple of coordinates and print their contents:
def do(coordList):
for element in coordList:
print element
y=((5,5),(4,4))
x=((5,5))
When y is run through the function, it outputs (5,5) and (4,4), the desired result. However, running x through the function outputs 5 and 5.
Is there a way to force x to be defined as a tuple within a tuple, and if not, what is the easiest way to resolve this problem?
A:
Use a trailing comma for singleton tuples.
x = ((5, 5),)
A:
x=((5,5),)
(x) is an expression (x,) is a singleton tuple.
A:
This is an old and infuriating quirk of python syntax. You have to include a trailing comma to make Python see a tuple:
x = ((5,5),)
A:
You need to add a comma after your first tuple.
((5,5),) should work.
A:
Simply add a comma:
x=((5,5),)
|
Forcing tuples within tuples?
|
I've got a python function that should loop through a tuple of coordinates and print their contents:
def do(coordList):
for element in coordList:
print element
y=((5,5),(4,4))
x=((5,5))
When y is run through the function, it outputs (5,5) and (4,4), the desired result. However, running x through the function outputs 5 and 5.
Is there a way to force x to be defined as a tuple within a tuple, and if not, what is the easiest way to resolve this problem?
|
[
"Use a trailing comma for singleton tuples.\nx = ((5, 5),)\n\n",
"x=((5,5),)\n\n(x) is an expression (x,) is a singleton tuple.\n",
"This is an old and infuriating quirk of python syntax. You have to include a trailing comma to make Python see a tuple:\nx = ((5,5),)\n\n",
"You need to add a comma after your first tuple. \n((5,5),) should work.\n",
"Simply add a comma:\nx=((5,5),)\n\n"
] |
[
10,
6,
3,
2,
2
] |
[] |
[] |
[
"list",
"python",
"tuples"
] |
stackoverflow_0002014767_list_python_tuples.txt
|
Q:
assertRaises just catches base exception
I'm running into a strange problem when using unittest.assertRaises. When executing the code below I get the following output:
E
======================================================================
ERROR: testAssertRaises (__main__.Test)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\home\python_test\src\derived.py", line 29, in testAssertRaises
self.assertRaises(MyError, self.raiser.raiseMyError)
File "C:\Programme\Python26\lib\unittest.py", line 336, in failUnlessRaises
callableObj(*args, **kwargs)
File "C:\home\python_test\src\derived.py", line 15, in raiseMyError
raise MyError("My message")
MyError: 'My message'
----------------------------------------------------------------------
Ran 1 test in 0.000s
FAILED (errors=1)
The correct exception gets raised, but the test fails! If I'm catching the BaseError the test succeeds.
Somehow this seems to be a scope issue of unittest not being able to see the MyError exception class. Can someone explain that? Is there some workaround?
I am testing the following Python code which is an implementation for dynamically constructing objects by their class names.
This is the base module "bases.py":
class BaseClass(object):
@staticmethod
def get(className):
module = __import__("derived", globals(), locals(), [className])
theClass = getattr(module, className)
return theClass()
class BaseError(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return repr(self.msg)
This is the module to test, "derived.py":
import unittest
from bases import BaseError
from bases import BaseClass
class MyErrorRaiser(BaseClass):
def raiseMyError(self):
raise MyError("My message")
class MyError(BaseError):
'''
'''
class Test(unittest.TestCase):
def setUp(self):
self.raiser = BaseClass.get("MyErrorRaiser")
def testAssertRaises(self):
self.assertRaises(MyError, self.raiser.raiseMyError)
if __name__ == "__main__":
unittest.main()
A:
As mentioned, the issue is modules __main__ and derived are not one and the same; this answer is about how you fix that.
Don't mix module code and script code. Start to think of if __name__ == "__main__" code as a hack. (It's still very convenient at times and I use it often for debugging, etc., but view it as a hack so you always get a slight mental nudge writing it.) The new script that would then run everything would be simple (and never imported):
#!/usr/bin/env python
import derived
import sys
sys.exit(derived.main(sys.argv[1:]))
Or with various differences by personal preference. Just make sure you add derived.main to do what you want.
I've also seen another hack which is less common, at the top of derived.py:
import sys
if __name__ == "__main__":
import derived # import the same module under its "correct" name
sys.exit(derived.main(sys.argv[1:]))
While wasteful in parsing the same code twice, this is self-contained in exchange.
A:
When you run derived.py, it is run as the __main__ module (since you ran it directly rather than importing it). When you later import it explicitly, another copy of the module is created, this time under the name derived. So __main__.MyError is not the same as derived.MyError, and the exception isn't caught.
A:
The problem is probably that your BaseClass.get() method is returning you another class. By the way, that method is horrible in itself, I wonder why you're doing this.
|
assertRaises just catches base exception
|
I'm running into a strange problem when using unittest.assertRaises. When executing the code below I get the following output:
E
======================================================================
ERROR: testAssertRaises (__main__.Test)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\home\python_test\src\derived.py", line 29, in testAssertRaises
self.assertRaises(MyError, self.raiser.raiseMyError)
File "C:\Programme\Python26\lib\unittest.py", line 336, in failUnlessRaises
callableObj(*args, **kwargs)
File "C:\home\python_test\src\derived.py", line 15, in raiseMyError
raise MyError("My message")
MyError: 'My message'
----------------------------------------------------------------------
Ran 1 test in 0.000s
FAILED (errors=1)
The correct exception gets raised, but the test fails! If I'm catching the BaseError the test succeeds.
Somehow this seems to be a scope issue of unittest not being able to see the MyError exception class. Can someone explain that? Is there some workaround?
I am testing the following Python code which is an implementation for dynamically constructing objects by their class names.
This is the base module "bases.py":
class BaseClass(object):
@staticmethod
def get(className):
module = __import__("derived", globals(), locals(), [className])
theClass = getattr(module, className)
return theClass()
class BaseError(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return repr(self.msg)
This is the module to test, "derived.py":
import unittest
from bases import BaseError
from bases import BaseClass
class MyErrorRaiser(BaseClass):
def raiseMyError(self):
raise MyError("My message")
class MyError(BaseError):
'''
'''
class Test(unittest.TestCase):
def setUp(self):
self.raiser = BaseClass.get("MyErrorRaiser")
def testAssertRaises(self):
self.assertRaises(MyError, self.raiser.raiseMyError)
if __name__ == "__main__":
unittest.main()
|
[
"As mentioned, the issue is modules __main__ and derived are not one and the same; this answer is about how you fix that.\nDon't mix module code and script code. Start to think of if __name__ == \"__main__\" code as a hack. (It's still very convenient at times and I use it often for debugging, etc., but view it as a hack so you always get a slight mental nudge writing it.) The new script that would then run everything would be simple (and never imported):\n#!/usr/bin/env python\nimport derived\nimport sys\nsys.exit(derived.main(sys.argv[1:]))\n\nOr with various differences by personal preference. Just make sure you add derived.main to do what you want.\nI've also seen another hack which is less common, at the top of derived.py:\nimport sys\nif __name__ == \"__main__\":\n import derived # import the same module under its \"correct\" name\n sys.exit(derived.main(sys.argv[1:]))\n\nWhile wasteful in parsing the same code twice, this is self-contained in exchange.\n",
"When you run derived.py, it is run as the __main__ module (since you ran it directly rather than importing it). When you later import it explicitly, another copy of the module is created, this time under the name derived. So __main__.MyError is not the same as derived.MyError, and the exception isn't caught.\n",
"The problem is probably that your BaseClass.get() method is returning you another class. By the way, that method is horrible in itself, I wonder why you're doing this.\n"
] |
[
2,
1,
0
] |
[] |
[] |
[
"assertraises",
"python",
"unit_testing"
] |
stackoverflow_0002013018_assertraises_python_unit_testing.txt
|
Q:
How does this formatting code work?
I always have to know why, rather than just how, so here I go:
How does this work:
'{0:01.2f}'.format(5.555) #returns '5.55'
'{0:01.1f}'.format(5.555) #returns '5.5'
'{0:1.2f}'.format(5.555) #returns '5.55' again
'{0:1.1f}'.format(5.555) #returns '5.5' again
Why does this not add zero padding by returning '05.5' instead of just '5.5' when I have the extra zero. It just doesn't seem to work.
Also, why is the string 0:1.1f instead of 0:0.1f, etc. Is it just a convention to use the number 1 before the decimal instead of a zero, or is that the syntax?
A:
Its because the 0 character enables zero-padding, but you have a width of 1 set. Set the width to 2 (like '{0:02.1f}' and you will see a leading 0.
Edit - actually, I'm not sure if 2 will suffice, because I don't know how it behaves with more digits after the decimal point. So to be safe, make it something like 5 and see what it does then.
Edit 2 - ok, I just tried it. The width corresponds to the TOTAL width, including all digits and the decimal point. So you'll get this:
>>> '{0:05.2f}'.format(5.555)
'05.55'
Note that the total length of the string is 5 now, with a leading 0 because zero-padding is enabled, and that it truncates to 2 digits after the decimal point because of .2
A:
You should specify a width taking into account all the characters, including the decimals and the dot. If you want 05.55 that's 5 characters, so:
>>>'{0:05.2f}'.format(5.555)
'05.55'
|
How does this formatting code work?
|
I always have to know why, rather than just how, so here I go:
How does this work:
'{0:01.2f}'.format(5.555) #returns '5.55'
'{0:01.1f}'.format(5.555) #returns '5.5'
'{0:1.2f}'.format(5.555) #returns '5.55' again
'{0:1.1f}'.format(5.555) #returns '5.5' again
Why does this not add zero padding by returning '05.5' instead of just '5.5' when I have the extra zero. It just doesn't seem to work.
Also, why is the string 0:1.1f instead of 0:0.1f, etc. Is it just a convention to use the number 1 before the decimal instead of a zero, or is that the syntax?
|
[
"Its because the 0 character enables zero-padding, but you have a width of 1 set. Set the width to 2 (like '{0:02.1f}' and you will see a leading 0.\nEdit - actually, I'm not sure if 2 will suffice, because I don't know how it behaves with more digits after the decimal point. So to be safe, make it something like 5 and see what it does then.\nEdit 2 - ok, I just tried it. The width corresponds to the TOTAL width, including all digits and the decimal point. So you'll get this:\n>>> '{0:05.2f}'.format(5.555)\n'05.55'\n\nNote that the total length of the string is 5 now, with a leading 0 because zero-padding is enabled, and that it truncates to 2 digits after the decimal point because of .2\n",
"You should specify a width taking into account all the characters, including the decimals and the dot. If you want 05.55 that's 5 characters, so:\n>>>'{0:05.2f}'.format(5.555)\n'05.55'\n\n"
] |
[
6,
2
] |
[] |
[] |
[
"python",
"string"
] |
stackoverflow_0002015117_python_string.txt
|
Q:
python gtk module opens display on import
I'm using the trick "python -c 'import myscript.py'" to perform a syntax check on a script which uses 'import gtk'.
I get the following error when performing the syntax check, which implies that the gtk module is executing a check for the X display, even though all that's being done at this point is to import the module.
Traceback (most recent call last):
File "<stdin>", line 15, in ?
File "myscript.py", line 21, in ?
import gtk
File "/usr/src/build/463937-i386/install/usr/lib/python2.3/site-packages/gtk-2.0/gtk/__init__.py", line 37, in ?
RuntimeError: could not open display
Is there a way to avoid this error when performing the syntax check?
Before you ask - I'm not able to set $DISPLAY before the syntax check is run. The check is being run on remote servers as part of a distributed build system. These servers do not have an X display available.
A:
Importing modules in Python executes their code!
Well-behaved modules use the if __name__ == '__main__' trick to avoid side effects, but they can still fail - as happened to you.
[BTW, getting to ImportError means the whole file already has correct syntax.]
If you just want to check syntax, without running at all:
python -m py_compile my_script.py
will check one file (and produce a .pyc as a side effect).
python -m compileall ./
will check a whole dir recursively.
python -c 'compile(open("myscript.py").read(), "myscript.py", "exec")'
avoids creating a .pyc.
But note that merely checking the syntax in Python catches very few bugs! Importing does catch more, e.g. mispelled names. For even better checks, use tools like Pychecker / Pyflakes.
A:
What exactly do you mean by 'syntax checking'?
Can't you use a tool like pylint to check for syntax errors?
Otherwise: a very ugly (but probably possible hack):
In your python script detect whether X is present.
If it's not => use GTK on DirectFramebuffer (no X needed then). You'll need to compile GTK on DirectFB (and/or pygtk) from source (some pointers here).
A:
If the remote machine has vncserver installed, you can have a dummy server running and connect to that. Sample instructions:
remotemachine $ vncserver -depth 16 -geometry 800x600 :7
New 'X' desktop is remotemachine:7
Starting applications specified in /home/user/.vnc/xstartup
Log file is /home/user/.vnc/userve:7.log
remotemachine $ DISPLAY=:7 python -c 'import myscript.py'
…
remotemachine $ vncserver -kill :7
Killing Xtightvnc process ID 32058
A:
In your myscript.py, you could do like this
if __name__=="__main__":
import gtk
That will not execute gtk's __init__.py when you do "python -c 'import myscript.py'"
A:
If you are editing with IDLE, Alt+X will check syntax of current file without running it.
|
python gtk module opens display on import
|
I'm using the trick "python -c 'import myscript.py'" to perform a syntax check on a script which uses 'import gtk'.
I get the following error when performing the syntax check, which implies that the gtk module is executing a check for the X display, even though all that's being done at this point is to import the module.
Traceback (most recent call last):
File "<stdin>", line 15, in ?
File "myscript.py", line 21, in ?
import gtk
File "/usr/src/build/463937-i386/install/usr/lib/python2.3/site-packages/gtk-2.0/gtk/__init__.py", line 37, in ?
RuntimeError: could not open display
Is there a way to avoid this error when performing the syntax check?
Before you ask - I'm not able to set $DISPLAY before the syntax check is run. The check is being run on remote servers as part of a distributed build system. These servers do not have an X display available.
|
[
"Importing modules in Python executes their code!\nWell-behaved modules use the if __name__ == '__main__' trick to avoid side effects, but they can still fail - as happened to you.\n[BTW, getting to ImportError means the whole file already has correct syntax.]\nIf you just want to check syntax, without running at all:\n\npython -m py_compile my_script.py\nwill check one file (and produce a .pyc as a side effect).\npython -m compileall ./\nwill check a whole dir recursively.\npython -c 'compile(open(\"myscript.py\").read(), \"myscript.py\", \"exec\")'\navoids creating a .pyc.\n\nBut note that merely checking the syntax in Python catches very few bugs! Importing does catch more, e.g. mispelled names. For even better checks, use tools like Pychecker / Pyflakes.\n",
"What exactly do you mean by 'syntax checking'?\nCan't you use a tool like pylint to check for syntax errors?\nOtherwise: a very ugly (but probably possible hack):\n\nIn your python script detect whether X is present.\nIf it's not => use GTK on DirectFramebuffer (no X needed then). You'll need to compile GTK on DirectFB (and/or pygtk) from source (some pointers here).\n\n",
"If the remote machine has vncserver installed, you can have a dummy server running and connect to that. Sample instructions:\nremotemachine $ vncserver -depth 16 -geometry 800x600 :7\nNew 'X' desktop is remotemachine:7\n\nStarting applications specified in /home/user/.vnc/xstartup\nLog file is /home/user/.vnc/userve:7.log\nremotemachine $ DISPLAY=:7 python -c 'import myscript.py'\n…\nremotemachine $ vncserver -kill :7\nKilling Xtightvnc process ID 32058\n\n",
"In your myscript.py, you could do like this\nif __name__==\"__main__\":\n import gtk\n\nThat will not execute gtk's __init__.py when you do \"python -c 'import myscript.py'\"\n",
"If you are editing with IDLE, Alt+X will check syntax of current file without running it.\n"
] |
[
3,
0,
0,
0,
0
] |
[] |
[] |
[
"gtk",
"python"
] |
stackoverflow_0001841949_gtk_python.txt
|
Q:
How to create class instance inside that class method?
I want to create class instance inside itself. I tried to it by this way:
class matrix:
(...)
def det(self):
(...)
m = self(sz-1, sz-1)
(...)
(...)
but I got error:
m = self(sz-1, sz-1)
AttributeError: matrix instance has no __call__ method
So, I tried to do it by this way:
class matrix:
(...)
def det(self):
(...)
m = matrix(sz-1, sz-1)
(...)
(...)
and I got another error:
m = matrix(sz-1, sz-1)
NameError: global name 'matrix' is not defined
Of course matrix is not global class. I have no idea how to solve this problem.
A:
m = self.__class__(sz-1, sz-1)
or
m = type(self)(sz-1, sz-1)
|
How to create class instance inside that class method?
|
I want to create class instance inside itself. I tried to it by this way:
class matrix:
(...)
def det(self):
(...)
m = self(sz-1, sz-1)
(...)
(...)
but I got error:
m = self(sz-1, sz-1)
AttributeError: matrix instance has no __call__ method
So, I tried to do it by this way:
class matrix:
(...)
def det(self):
(...)
m = matrix(sz-1, sz-1)
(...)
(...)
and I got another error:
m = matrix(sz-1, sz-1)
NameError: global name 'matrix' is not defined
Of course matrix is not global class. I have no idea how to solve this problem.
|
[
"m = self.__class__(sz-1, sz-1)\n\nor\nm = type(self)(sz-1, sz-1)\n\n"
] |
[
15
] |
[] |
[] |
[
"class",
"instance",
"python"
] |
stackoverflow_0002015306_class_instance_python.txt
|
Q:
What encoding do I need to display a GBP sign (pound sign) using python on cygwin in Windows XP?
I have a python (2.5.4) script which I run in cygwin (in a DOS box on Windows XP). I want to include a pound sign (£) in the output. If I do so, I get this error:
SyntaxError: Non-ASCII character '\xa3' in file dbscan.py on line 253, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details
OK. So I looked at that PEP, and now tried adding this to the beginning of my script:
# coding=cp437
That stopped the error, but the output shows ú where it should show £.
I've tried ISO-8859-1 as well, with the same result.
Does anyone know which encoding I need?
Or where I could look to find out?
A:
The Unicode for a pound sign is 163 (decimal) or A3 in hex, so the following should work regardless of the encoding of your script, as long as the output encoding is working correctly.
print u"\xA3"
A:
try the encoding :
# -*- coding: utf-8 -*-
and then to display the '£' sign:
print unichr(163)
A:
There are two encodings involved here:
The encoding of your source code, which must be correct in order for your input file to mean what you think it means
The encoding of the output, which must be correct in order for the symbols emitted to display as expected.
It seems your output encoding is off now. If this is running in a terminal window in Cygwin, it is that terminal's encoding that you need to match.
EDIT: I just ran the following Python program in a (native) Windows XP terminal window, thought it was slightly interesting:
>>> ord("£")
156
156 is certainly not the codepoint for the pound sign in the Latin1 encoding you tried. It doesn't seem to be in Window's Codepage 1252 either, which I would expect my terminal to use ... Weird.
|
What encoding do I need to display a GBP sign (pound sign) using python on cygwin in Windows XP?
|
I have a python (2.5.4) script which I run in cygwin (in a DOS box on Windows XP). I want to include a pound sign (£) in the output. If I do so, I get this error:
SyntaxError: Non-ASCII character '\xa3' in file dbscan.py on line 253, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details
OK. So I looked at that PEP, and now tried adding this to the beginning of my script:
# coding=cp437
That stopped the error, but the output shows ú where it should show £.
I've tried ISO-8859-1 as well, with the same result.
Does anyone know which encoding I need?
Or where I could look to find out?
|
[
"The Unicode for a pound sign is 163 (decimal) or A3 in hex, so the following should work regardless of the encoding of your script, as long as the output encoding is working correctly.\nprint u\"\\xA3\"\n\n",
"try the encoding :\n# -*- coding: utf-8 -*-\nand then to display the '£' sign: \nprint unichr(163)\n\n",
"There are two encodings involved here:\n\nThe encoding of your source code, which must be correct in order for your input file to mean what you think it means\nThe encoding of the output, which must be correct in order for the symbols emitted to display as expected.\n\nIt seems your output encoding is off now. If this is running in a terminal window in Cygwin, it is that terminal's encoding that you need to match.\nEDIT: I just ran the following Python program in a (native) Windows XP terminal window, thought it was slightly interesting:\n>>> ord(\"£\")\n156\n\n156 is certainly not the codepoint for the pound sign in the Latin1 encoding you tried. It doesn't seem to be in Window's Codepage 1252 either, which I would expect my terminal to use ... Weird.\n"
] |
[
11,
4,
2
] |
[] |
[] |
[
"encoding",
"python",
"python_2.5"
] |
stackoverflow_0000705434_encoding_python_python_2.5.txt
|
Q:
Using a list objects to look up items in a dictionary in Python
I have a a wxPython checklist box that returns a list of integers. I want to use the integers to look up items in a dictionary. I am not really sure the best way to do this. Any suggestions?
A:
Are you asking for
[ someDict[k] for k in someList ]
?
|
Using a list objects to look up items in a dictionary in Python
|
I have a a wxPython checklist box that returns a list of integers. I want to use the integers to look up items in a dictionary. I am not really sure the best way to do this. Any suggestions?
|
[
"Are you asking for\n[ someDict[k] for k in someList ]\n\n?\n"
] |
[
7
] |
[] |
[] |
[
"dictionary",
"list",
"python"
] |
stackoverflow_0002015385_dictionary_list_python.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.