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:
Python convert formatted string to list
I have a string "[u'foo']" (Yes, it includes the square brackets and the u''). I have to convert that to a list which looks like [u'foo'].
list("[u'foo']") won't work.
Any suggestions?
A:
>>> import ast
>>> s = "[u'foo']"
>>> ast.literal_eval(s)
[u'foo']
documentation
A:
eval("[u'foo']", {'__builtins__':[]}, {})
| Python convert formatted string to list | I have a string "[u'foo']" (Yes, it includes the square brackets and the u''). I have to convert that to a list which looks like [u'foo'].
list("[u'foo']") won't work.
Any suggestions?
| [
">>> import ast\n>>> s = \"[u'foo']\"\n>>> ast.literal_eval(s)\n[u'foo']\n\ndocumentation\n",
"eval(\"[u'foo']\", {'__builtins__':[]}, {})\n\n"
] | [
18,
1
] | [] | [] | [
"list",
"python",
"string"
] | stackoverflow_0003622643_list_python_string.txt |
Q:
Python programmer: Learning ruby (for rails)
I'm a moderately competent Python programmer, and am considering working on my first web-app; it seems a very large number of FOSS webapp code is written in Ruby (i.e. Rails), and I suspect that might help with my learning curve (i.e. for building a decent, if useless webapp).
There is lots of material for learning Ruby on the interwebs ofcourse, but wondering if there are any particular tips / resources / approaches that might be handy in moving from Python to rails?
A:
Michael Hartl's Ruby on Rails Tutorial is by far the best introduction to Rails I've been able to find online. It's very easy to understand what's going on if you've already got experience in web application development in general. Versions of the tutorial for Rails 2.3.8 and Rails 3 are available. The introduction also discusses learning Ruby first vs learning Rails first.
Not only does it teach how to use Rails, it explains common Rails conventions (the Rails Way). I think this, in particular, is what you are looking for. It also encourages the use of good practices such as git source control and test-driven development, which is cool.
A:
To start getting your head around the similarities/differences between Ruby & Python, you may want to take a look @ this page on ruby-lang.org. It is super basic, but at a minimum gives you the terminology & concept translation you may need to get started. I tend to learn new things best by making mental comparisons to concepts I am familiar with.
| Python programmer: Learning ruby (for rails) | I'm a moderately competent Python programmer, and am considering working on my first web-app; it seems a very large number of FOSS webapp code is written in Ruby (i.e. Rails), and I suspect that might help with my learning curve (i.e. for building a decent, if useless webapp).
There is lots of material for learning Ruby on the interwebs ofcourse, but wondering if there are any particular tips / resources / approaches that might be handy in moving from Python to rails?
| [
"Michael Hartl's Ruby on Rails Tutorial is by far the best introduction to Rails I've been able to find online. It's very easy to understand what's going on if you've already got experience in web application development in general. Versions of the tutorial for Rails 2.3.8 and Rails 3 are available. The introduc... | [
7,
2
] | [] | [] | [
"python",
"ruby",
"ruby_on_rails"
] | stackoverflow_0003622611_python_ruby_ruby_on_rails.txt |
Q:
Returning a file to a WSGI GET request
I'm new to WSGI on python; but have a windows server that's got isapi_wsgi installed on it. I also have a script that handles my GET requests all up and running great. The thing is, someone sends me a request, and I need to return a zip file to the requester. The following code is in my GET handler and it works, but doesn't seem like the right way to return the zipfile:
# open zip file return it
fin = open(zOutFilename, "rb")
start_response( "200 OK", [('Content-Type', 'application/zip')])
return fin.read()
The thing is, you're returning a 'stream' - which means you lose the filename (the browser simply names it the name of the GET query) and it seems awfully slow.
Is there a better way to return a file for download with wsgi then this method?
Thanks in advance
A:
Taken directly from PEP 333:
if 'wsgi.file_wrapper' in environ:
return environ['wsgi.file_wrapper'](filelike, block_size)
else:
return iter(lambda: filelike.read(block_size), '')
Also you probably want the Content-Disposition header for providing the file name to the client.
| Returning a file to a WSGI GET request | I'm new to WSGI on python; but have a windows server that's got isapi_wsgi installed on it. I also have a script that handles my GET requests all up and running great. The thing is, someone sends me a request, and I need to return a zip file to the requester. The following code is in my GET handler and it works, but doesn't seem like the right way to return the zipfile:
# open zip file return it
fin = open(zOutFilename, "rb")
start_response( "200 OK", [('Content-Type', 'application/zip')])
return fin.read()
The thing is, you're returning a 'stream' - which means you lose the filename (the browser simply names it the name of the GET query) and it seems awfully slow.
Is there a better way to return a file for download with wsgi then this method?
Thanks in advance
| [
"Taken directly from PEP 333:\nif 'wsgi.file_wrapper' in environ:\n return environ['wsgi.file_wrapper'](filelike, block_size)\nelse:\n return iter(lambda: filelike.read(block_size), '')\n\nAlso you probably want the Content-Disposition header for providing the file name to the client.\n"
] | [
12
] | [] | [] | [
"download",
"forms",
"get",
"python",
"wsgi"
] | stackoverflow_0003622675_download_forms_get_python_wsgi.txt |
Q:
A way to "listen" for changes to a file system from Python on Linux?
I want to be able to detect whenever new files are created or existing files are modified or deleted within a given directory tree (or set of trees). The brute force way to do this would be to just rescan the tree looking for changes, but I'm looking for a more "interrupt driven" solution where the file system tells my code what changed when it changes, rather than my code having to "poll" by continuously scanning through thousands of files looking for changes.
A way to do this in Python is preferred, but if I have to write a native module in C that's ok as a last resort.
A:
pyinotify is IMHO the only way to get system changes without scanning the directory.
A:
twisted.internet.inotify! It's much more useful to have an event loop attached than just free-floating inotify. Using twisted also gives you filepath for free, which is a nice library for more easily manipulating file paths in python.
| A way to "listen" for changes to a file system from Python on Linux? | I want to be able to detect whenever new files are created or existing files are modified or deleted within a given directory tree (or set of trees). The brute force way to do this would be to just rescan the tree looking for changes, but I'm looking for a more "interrupt driven" solution where the file system tells my code what changed when it changes, rather than my code having to "poll" by continuously scanning through thousands of files looking for changes.
A way to do this in Python is preferred, but if I have to write a native module in C that's ok as a last resort.
| [
"pyinotify is IMHO the only way to get system changes without scanning the directory.\n",
"twisted.internet.inotify! It's much more useful to have an event loop attached than just free-floating inotify. Using twisted also gives you filepath for free, which is a nice library for more easily manipulating file paths... | [
8,
8
] | [] | [] | [
"linux",
"python"
] | stackoverflow_0003622796_linux_python.txt |
Q:
Python accelerator
I'm planning to use Python to develop a web application. Anybody has any idea about any accelerator for python? (something like eAccelerator or apc for php) if not, is there any way to cache the pre-compiled python bytecode ?
Any idea about the performance comparison between python and php (assuming db/network latencies are same)
Thanks in advance.
A:
There's a trick to this.
It's called mod_wsgi.
The essence of it works like this.
For "static" content (.css, .js, images, etc.) put them in a directory so they're served by Apache, without your Python program knowing they were sent.
For "dynamic" content (the main HTML page itself) you use mod_wsgi to fork a "back-end" process that runs outside of Apache.
This is faster than PHP because now several things are going on at once. Apache has dispatched the request to a backend process and then moved on to handle the next request while the backend is still running the first one.
Also, when you've sent your HTML page, the follow-on requests are handled by Apache without your Python program knowing or caring what's going on. This leads to huge speedups. Nothing to do with the speed of Python. Everything to do with the overall architecture.
A:
As long as you do trivial amounts of work in your "main script" (the one you directly invoke with python and which gets a __name__ of __main__) you need not worry about "caching the pre-compiled python bytecode": when you import foo, foo.py gets saved to disk (same directory) as foo.pyc, as long as that directory is writable by you, so the already-cheap compilation to bytecode happens once and "forever after" Python will load foo.pyc directly in every new process that does import foo -- within a single process, every import foo except the first one is just a fast lookup into a dictionary in memory (the sys.module dictionary). A core performance idea in Python: makes sure every bit of substantial code happens within def statements in modules -- don't have any at module top level, in the main script, or esp. within exec and eval statements/expressions!-).
I have no benchmarks for PHP vs Python, but I've noticed that Python keeps getting optimized pretty noticeably with every new release, so make sure you compare a recent release (idealy 2.7, at least 2.6) if you want to see "the fastes Python". If you don't find it fast enough yet, cython (a Python dialect designed to compile directly into C, and thence into machine code, with some limitations) is today the simplest way to selectively optimize those modules which profiling shows you need it.
A:
Others have mentioned Python byte code files, but that is largely irrelevant. This is because hosting mechanisms for Python, with the exception of CGI, keep the Python web Application in memory between requests. This is different to PHP which effectively throws away the application between requests. As such, Python doesn't need an accelerator as the way Python web hosting mechanisms work avoids the problems that PHP has.
A:
The compiled python Bytecode is cached in .pyc files automatically in every environment i have seen. There is so need to do anything else as far as i know.
If you want to generate these files directly you can use: http://docs.python.org/library/py_compile.html
| Python accelerator | I'm planning to use Python to develop a web application. Anybody has any idea about any accelerator for python? (something like eAccelerator or apc for php) if not, is there any way to cache the pre-compiled python bytecode ?
Any idea about the performance comparison between python and php (assuming db/network latencies are same)
Thanks in advance.
| [
"There's a trick to this.\nIt's called mod_wsgi.\nThe essence of it works like this.\n\nFor \"static\" content (.css, .js, images, etc.) put them in a directory so they're served by Apache, without your Python program knowing they were sent.\nFor \"dynamic\" content (the main HTML page itself) you use mod_wsgi to f... | [
8,
5,
3,
2
] | [] | [] | [
"accelerator",
"php",
"python"
] | stackoverflow_0003619063_accelerator_php_python.txt |
Q:
How can I exit a while with a key ? [Python]
Possible Duplicate:
How can I make a while True break if certain key is pressed? [Python]
I have this code:
def enterCategory():
time.sleep(0.2)
if entercount == 1:
mouseMove(*position[5])
while win32gui.GetCursorInfo()[1] != 65567:
mouseMove(*position[5])
mouseMove(*position[4])
mouseLeftClick()
def onKeyboardEvent(event):
if event.KeyID == 13: #ENTER
print '\n'
mouseLeftClick()
enterCountInc()
enterCategory()
print '\n'
if event.KeyID == 113: #F2
doLogin()
enterCountReset()
return True
hook.KeyDown = onKeyboardEvent
hook.HookKeyboard()
pythoncom.PumpMessages()
and it work like this:
When I press F2, the script will fill some forms and wait for my enter to login, then, when I press enter, the script jump to a part of the screen and check if that part is a link (enterCategory() part), and if it's a link, the script do successfully what I want, but if something goes wrong with the login, the position[4] and [5] will never be a link, and the script will be at infinity loop...
How can I solve that? How can I do something so when I press F2, it exist the while and try the login again?
Sorry if I'm not understandable =/
A:
You could use the handling of F2 to set a global flag (e.g., one named proceed) to False, and where you now have while win32gui..., have, instead
global proceed
proceed = True
while proceed and win32gui...
Not elegant, but then neither is the cursor-shape analysis to find out if the mouse is on a link;-).
| How can I exit a while with a key ? [Python] |
Possible Duplicate:
How can I make a while True break if certain key is pressed? [Python]
I have this code:
def enterCategory():
time.sleep(0.2)
if entercount == 1:
mouseMove(*position[5])
while win32gui.GetCursorInfo()[1] != 65567:
mouseMove(*position[5])
mouseMove(*position[4])
mouseLeftClick()
def onKeyboardEvent(event):
if event.KeyID == 13: #ENTER
print '\n'
mouseLeftClick()
enterCountInc()
enterCategory()
print '\n'
if event.KeyID == 113: #F2
doLogin()
enterCountReset()
return True
hook.KeyDown = onKeyboardEvent
hook.HookKeyboard()
pythoncom.PumpMessages()
and it work like this:
When I press F2, the script will fill some forms and wait for my enter to login, then, when I press enter, the script jump to a part of the screen and check if that part is a link (enterCategory() part), and if it's a link, the script do successfully what I want, but if something goes wrong with the login, the position[4] and [5] will never be a link, and the script will be at infinity loop...
How can I solve that? How can I do something so when I press F2, it exist the while and try the login again?
Sorry if I'm not understandable =/
| [
"You could use the handling of F2 to set a global flag (e.g., one named proceed) to False, and where you now have while win32gui..., have, instead\nglobal proceed\nproceed = True\nwhile proceed and win32gui...\n\nNot elegant, but then neither is the cursor-shape analysis to find out if the mouse is on a link;-).\n"... | [
0
] | [] | [] | [
"python",
"while_loop",
"windows"
] | stackoverflow_0003622624_python_while_loop_windows.txt |
Q:
Django: Exposing model method to admin
Example model:
class Contestant(models.Model):
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
email = models.EmailField()
...
def send_registration_email(self):
...
I'd like to be able to expose this method to the admin so that managers can login and manually call it. I'm thinking about trying property attributes but not sure if that's gonna work. Also is it possible to expose a method like this that takes arguments other than self, possibly related objects from a select or something?
A:
You could register it as an admin action.
from django.contrib import admin
from myapp.models import Contestant
def send_mail(modeladmin, request, queryset):
for obj in queryset:
obj.send_registration_email()
make_published.short_description = "Resend activation mails for selected users"
class ContestantAdmin(admin.ModelAdmin):
list_display = [...]
ordering = [...]
actions = [send_mail]
admin.site.register(Contestant, ContestantAdmin)
| Django: Exposing model method to admin | Example model:
class Contestant(models.Model):
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
email = models.EmailField()
...
def send_registration_email(self):
...
I'd like to be able to expose this method to the admin so that managers can login and manually call it. I'm thinking about trying property attributes but not sure if that's gonna work. Also is it possible to expose a method like this that takes arguments other than self, possibly related objects from a select or something?
| [
"You could register it as an admin action.\nfrom django.contrib import admin\nfrom myapp.models import Contestant\n\ndef send_mail(modeladmin, request, queryset):\n for obj in queryset:\n obj.send_registration_email()\n\nmake_published.short_description = \"Resend activation mails for selected users\"\n\n... | [
7
] | [] | [] | [
"django",
"django_admin",
"django_models",
"python"
] | stackoverflow_0003623021_django_django_admin_django_models_python.txt |
Q:
HTML page to PDF in Python?
Is there a library available to convert a HTML page (text, images, layout elements etc. ) to a PDF file.
I have an HTML page with figures, text and tables with numbers etc. which I want my clients to be able to download as PDF. How do I do this with Python?
A:
Not too familiar with python, and prince is nice if you are willing to shell out the cash. There is this http://github.com/antialize/wkhtmltopdf that uses webkit. It is a simple command line utility that you can call and it will honor html+css. As far as I know, it is the only free tool to do so well. There is a ruby gem for it http://github.com/jdpace/PDFKit, not that it helps you but might give you some ideas.
A:
Well, there are the reportlab and html2pdf modules, but for best results I'd probably try calling Prince externally (http://www.princexml.com/doc/6.0/python/) .
A:
Have you heard of xhtml2pdf/pisa?
It has the ability to work as a python module or as a separate command line utility.
You can use the documentation here to get started:
http://www.xhtml2pdf.com/doc/pisa-en.html
| HTML page to PDF in Python? | Is there a library available to convert a HTML page (text, images, layout elements etc. ) to a PDF file.
I have an HTML page with figures, text and tables with numbers etc. which I want my clients to be able to download as PDF. How do I do this with Python?
| [
"Not too familiar with python, and prince is nice if you are willing to shell out the cash. There is this http://github.com/antialize/wkhtmltopdf that uses webkit. It is a simple command line utility that you can call and it will honor html+css. As far as I know, it is the only free tool to do so well. There is... | [
3,
1,
0
] | [] | [] | [
"html",
"pdf_generation",
"python"
] | stackoverflow_0003209202_html_pdf_generation_python.txt |
Q:
Help, the insertion cursor moves one line lower each time!
Every time this code is reopened the insertion cursor moves one line lower, how do I stop this?
import Tkinter,pickle
class Note(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent = parent
self.Main()
self.load_data()
self.protocol("WM_DELETE_WINDOW", self.save_data)
def Main(self):
self.s1 = Tkinter.Scrollbar(self)
self.L1 = Tkinter.Text(self,borderwidth=0,font=('Arial', 10),width=25,
height=15)
self.s1.config(command=self.L1.yview,elementborderwidth=3)
self.L1.config(yscrollcommand=self.s1.set)
self.L1.grid(column=0,row=0,sticky='EW')
self.s1.grid(column=1,row=0,sticky='NSEW')
self.L1.focus_set()
def save_data(self):
data = {'saved_data': self.L1.get('1.0', 'end')}
with file('testsave.data', 'wb') as f:
pickle.dump(data, f)
self.destroy()
def load_data(self):
try:
with file('testsave.data', 'rb') as f:
data = pickle.load(f)
self.L1.insert("end", data['saved_data'])
except IOError:
pass
if __name__ == "__main__":
app = Note(None)
app.mainloop()
A:
The text widget is guaranteed to always have a trailing newline at the end of its contents. The proper way to get the data is to use the index "end-1c" so that you don't get that extra newline. If you use "end", each save and load cycle adds one blank lone.
| Help, the insertion cursor moves one line lower each time! | Every time this code is reopened the insertion cursor moves one line lower, how do I stop this?
import Tkinter,pickle
class Note(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent = parent
self.Main()
self.load_data()
self.protocol("WM_DELETE_WINDOW", self.save_data)
def Main(self):
self.s1 = Tkinter.Scrollbar(self)
self.L1 = Tkinter.Text(self,borderwidth=0,font=('Arial', 10),width=25,
height=15)
self.s1.config(command=self.L1.yview,elementborderwidth=3)
self.L1.config(yscrollcommand=self.s1.set)
self.L1.grid(column=0,row=0,sticky='EW')
self.s1.grid(column=1,row=0,sticky='NSEW')
self.L1.focus_set()
def save_data(self):
data = {'saved_data': self.L1.get('1.0', 'end')}
with file('testsave.data', 'wb') as f:
pickle.dump(data, f)
self.destroy()
def load_data(self):
try:
with file('testsave.data', 'rb') as f:
data = pickle.load(f)
self.L1.insert("end", data['saved_data'])
except IOError:
pass
if __name__ == "__main__":
app = Note(None)
app.mainloop()
| [
"The text widget is guaranteed to always have a trailing newline at the end of its contents. The proper way to get the data is to use the index \"end-1c\" so that you don't get that extra newline. If you use \"end\", each save and load cycle adds one blank lone.\n"
] | [
1
] | [] | [] | [
"pickle",
"python",
"tkinter"
] | stackoverflow_0003623091_pickle_python_tkinter.txt |
Q:
CSS Templating system for Django / Python?
I'm wondering if there is anything like Django's HTML templating system, for for CSS.. my searches on this aren't turning up anything of use. I am aware of things like SASS and CleverCSS but, as far as I can tell, these still don't solve my issue as I want to dynamically generate a CSS file based on certain conditions, so that a different CSS file would be served based on a specific user session...
I want to minimize the use of javascript / AJAX for some things (since its for a legacy system running in some hospital where they're still using IE 6 ), also I have an interest in possibly minimizing javascript for other projects as well... so it would be where there is 1 CSS file, but that it may need to be changed based on the situation (which would be done with CleverCSS), however the problem is that if I just write the changes to 1 file, then this would be served to everyone, even though they may have a different "state" of the CSS file depending on their use of the application, so I want to remove the physical association of a CSS file and rather have it dynamically generated each time (so that its unique to a specific user's session), the way that Django's HTML templating system works..
A:
The Django templating system can be used for any text you like. It's used for HTML most of the time, but it could also be used to create CSS. The CSS reference in your HTML can be to a dynamic URL instead of to a static file, and the view function can create whatever context you like, then a .css template file can create your CSS.
If you have only a few different CSS possibilities, then you may be better served by creating them as static files, and using the HTML template to select the CSS file you want by writing a different CSS reference depending you your conditions.
| CSS Templating system for Django / Python? | I'm wondering if there is anything like Django's HTML templating system, for for CSS.. my searches on this aren't turning up anything of use. I am aware of things like SASS and CleverCSS but, as far as I can tell, these still don't solve my issue as I want to dynamically generate a CSS file based on certain conditions, so that a different CSS file would be served based on a specific user session...
I want to minimize the use of javascript / AJAX for some things (since its for a legacy system running in some hospital where they're still using IE 6 ), also I have an interest in possibly minimizing javascript for other projects as well... so it would be where there is 1 CSS file, but that it may need to be changed based on the situation (which would be done with CleverCSS), however the problem is that if I just write the changes to 1 file, then this would be served to everyone, even though they may have a different "state" of the CSS file depending on their use of the application, so I want to remove the physical association of a CSS file and rather have it dynamically generated each time (so that its unique to a specific user's session), the way that Django's HTML templating system works..
| [
"The Django templating system can be used for any text you like. It's used for HTML most of the time, but it could also be used to create CSS. The CSS reference in your HTML can be to a dynamic URL instead of to a static file, and the view function can create whatever context you like, then a .css template file c... | [
8
] | [] | [] | [
"css",
"django",
"django_templates",
"dynamic",
"python"
] | stackoverflow_0003623070_css_django_django_templates_dynamic_python.txt |
Q:
Is there a way to save a captcha image and view it later in python?
I am scripting in python for some web automation. I know i can not automate captchas but here is what i want to do:
I want to automate everything i can up to the captcha. When i open the page (usuing urllib2) and parse it to find that it contains a captcha, i want to open the captcha using Tkinter. Now i know that i will have to save the image to my harddrive first, then open it but there is an issue before that. The captcha image that is on screen is not directly in the source anywhere. There is a variable in the source, inside some javascript, that points to another page that has the link to the image, BUT if you load that middle page, the captcha picture for that link changes, so the image associated with that javascript variable is no longer valid. It may be impossible to gather the image using this method, so please enlighten me if you have any ideas on this.
Now if I use firebug to load the page, there is a "GET" that is a direct link to the current Captcha image that i am seeing, and i'm wondering if there is anyway to make python or ullib2 see the "GET"s that are going on when a page is loaded, because if that was possible, this would be simple.
Please let me know if you have any suggestions.
A:
Of course the captcha's served by a page which will serve a new one each time (if it was repeated, then once it was solved for one fake userid, a spammer could automatically make a million!). I think you need some "screenshot" functionality to capture the image you want -- there is no cross-platform way to invoke such functionality, but each platform (or desktop manager in the case of Linux, BSD, etc) tends to have one. Or, you could automate the browser (e.g. via SeleniumRC) to "screenshot" (e.g. "print to PDF") things at the right time. (I believe what you're seeing in firebug may be misleading you because it is "showing a snapshot"... just at the html source or DOM level rather than at a screen/bitmap level).
| Is there a way to save a captcha image and view it later in python? | I am scripting in python for some web automation. I know i can not automate captchas but here is what i want to do:
I want to automate everything i can up to the captcha. When i open the page (usuing urllib2) and parse it to find that it contains a captcha, i want to open the captcha using Tkinter. Now i know that i will have to save the image to my harddrive first, then open it but there is an issue before that. The captcha image that is on screen is not directly in the source anywhere. There is a variable in the source, inside some javascript, that points to another page that has the link to the image, BUT if you load that middle page, the captcha picture for that link changes, so the image associated with that javascript variable is no longer valid. It may be impossible to gather the image using this method, so please enlighten me if you have any ideas on this.
Now if I use firebug to load the page, there is a "GET" that is a direct link to the current Captcha image that i am seeing, and i'm wondering if there is anyway to make python or ullib2 see the "GET"s that are going on when a page is loaded, because if that was possible, this would be simple.
Please let me know if you have any suggestions.
| [
"Of course the captcha's served by a page which will serve a new one each time (if it was repeated, then once it was solved for one fake userid, a spammer could automatically make a million!). I think you need some \"screenshot\" functionality to capture the image you want -- there is no cross-platform way to invo... | [
2
] | [] | [] | [
"firebug",
"python",
"tkinter",
"urllib2",
"web_applications"
] | stackoverflow_0003623077_firebug_python_tkinter_urllib2_web_applications.txt |
Q:
socket.getaddrinfo raises "Unknown host" mystery
I'm having a problem resolving a hostname using python's (2.6.2) socket class.
From the shell I'm able to ping the hostname, and also resolve the hostname using the host command:
host myhostname.mydomain.com
When I attempt to resolve it with python, a socket.herror exception is raised with the message "[Errno 1] Unknown host"
socket.gethostbyaddr("myhostname.mydomain.com")
I've recently added the nameservers to resolv.conf, perhaps i need to restart something for python to see these updates?
Any ideas?
A:
You need to use gethostbyname, not gethostbyaddr (which does reverse lookup).
>>> socket.gethostbyname('car.spillville.com')
'209.20.76.192'
>>> socket.gethostbyaddr('209.20.76.192')
('car.spillville.com', [], ['209.20.76.192'])
| socket.getaddrinfo raises "Unknown host" mystery | I'm having a problem resolving a hostname using python's (2.6.2) socket class.
From the shell I'm able to ping the hostname, and also resolve the hostname using the host command:
host myhostname.mydomain.com
When I attempt to resolve it with python, a socket.herror exception is raised with the message "[Errno 1] Unknown host"
socket.gethostbyaddr("myhostname.mydomain.com")
I've recently added the nameservers to resolv.conf, perhaps i need to restart something for python to see these updates?
Any ideas?
| [
"You need to use gethostbyname, not gethostbyaddr (which does reverse lookup).\n>>> socket.gethostbyname('car.spillville.com')\n'209.20.76.192'\n>>> socket.gethostbyaddr('209.20.76.192')\n('car.spillville.com', [], ['209.20.76.192'])\n\n"
] | [
8
] | [] | [] | [
"dns",
"networking",
"python"
] | stackoverflow_0003623287_dns_networking_python.txt |
Q:
newbie python csv writer question: why every character separated?
please excuse me for simple question: i tried to write simple csv file using csv module. however, the result is this:
Spam |Baked Beans|
/ s e a r c h | | , | | A d v a n c e d | | S e a r c h
/ a b o u t / | | , | | A b o u t
/ n e w s / | | , | | N e w s
/ d o c / | | , | | D o c u m e n t a t i o n
/ d o w n l o a d / | | , | | D o w n l o a d
/ c o m m u n i t y / | | , | | C o m m u n i t y
/ p s f / | | , | | F o u n d a t i o n
/ d e v / | | , | | C o r e | | D e v e l o p m e n t
/ a b o u t / h e l p / | | , | | H e l p
the code i use is:
spamWriter = csv.writer(open('links.csv', 'w'), delimiter=' ',quotechar='|', quoting=csv.QUOTE_MINIMAL)
spamWriter.writerow(['Spam'] + ['Baked Beans'])
spamWriter.writerow(self.linkvalue + ' , ' + data)
linkvalue and data are two variables that hold some data.
thank you for your advice!!!!
A:
writerow's argument is a sequence... and a string, which is what you're passing, is a sequence of single characters. To fix your bug, in the 2nd call to writerow, pass, instead, [self.linkvalue, data] as the argument.
| newbie python csv writer question: why every character separated? | please excuse me for simple question: i tried to write simple csv file using csv module. however, the result is this:
Spam |Baked Beans|
/ s e a r c h | | , | | A d v a n c e d | | S e a r c h
/ a b o u t / | | , | | A b o u t
/ n e w s / | | , | | N e w s
/ d o c / | | , | | D o c u m e n t a t i o n
/ d o w n l o a d / | | , | | D o w n l o a d
/ c o m m u n i t y / | | , | | C o m m u n i t y
/ p s f / | | , | | F o u n d a t i o n
/ d e v / | | , | | C o r e | | D e v e l o p m e n t
/ a b o u t / h e l p / | | , | | H e l p
the code i use is:
spamWriter = csv.writer(open('links.csv', 'w'), delimiter=' ',quotechar='|', quoting=csv.QUOTE_MINIMAL)
spamWriter.writerow(['Spam'] + ['Baked Beans'])
spamWriter.writerow(self.linkvalue + ' , ' + data)
linkvalue and data are two variables that hold some data.
thank you for your advice!!!!
| [
"writerow's argument is a sequence... and a string, which is what you're passing, is a sequence of single characters. To fix your bug, in the 2nd call to writerow, pass, instead, [self.linkvalue, data] as the argument.\n"
] | [
9
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0003623303_csv_python.txt |
Q:
Using a Python GEDCOM parser: Receiving bad output (gedcom.Element instance at 0x00...)
I'm new to Python, and I can say off the bat my programming experience is nominal compared to many of you. Brace yourselves :)
I have 2 files. A GEDCOM parser written in Python that I found from a user on this site (gedcom.py - http://ilab.cs.byu.edu/cs460/2006w/assignments/program1.html) and a simple GEDCOM file that I pulled from heiner-eichmann.de/gedcom/gedcom.htm. Guess who's having trouble putting 2 and 2 together? This guy...
Here is a code snippet followed by what I've done thus far.
class Gedcom:
""" Gedcom parser
This parser is for the Gedcom 5.5 format. For documentation of
this format, see
http://homepages.rootsweb.com/~pmcbride/gedcom/55gctoc.htm
This parser reads a GEDCOM file and parses it into a set of
elements. These elements can be accessed via a list (the order of
the list is the same as the order of the elements in the GEDCOM
file), or a dictionary (the key to the dictionary is a unique
identifier that one element can use to point to another element).
"""
def __init__(self,file):
""" Initialize a Gedcom parser. You must supply a Gedcom file.
"""
self.__element_list = []
self.__element_dict = {}
self.__element_top = Element(-1,"","TOP","",self.__element_dict)
self.__current_level = -1
self.__current_element = self.__element_top
self.__individuals = 0
self.__parse(file)
def element_list(self):
""" Return a list of all the elements in the Gedcom file. The
elements are in the same order as they appeared in the file.
"""
return self.__element_list
def element_dict(self):
""" Return a dictionary of elements from the Gedcom file. Only
elements identified by a pointer are listed in the dictionary. The
key for the dictionary is the pointer.
"""
return self.__element_dict
my little script
import gedcom
g = Gedcom('C:\tmp\test.ged') //I'm on Windows
print g.element_list()
From here, I receive a bunch of output "gedcom.Element instance at 0x00..."
I'm not sure why I'm receiving this output. I thought according to the element_list method a formatted list would be returned. I've Googled and search this site. The answer is probably staring me in the face but I was hoping someone could point out the obvious.
Much Appreciated.
A:
someclass instance at 0xdeadbeef is the result of the the standard __repr__ method for classes that don't define one, as apparently class gedcom.Element doesn't, so the problem is only with you printing a list of such instances. If such class defines __str__, you could
for x in g.element_list():
print x
but if it doesn't, that will also give similar output (as __str__ "defaults to" __repr__). What do you want to do with those elements, e.g. a method that their class does offer?
A:
There's nothing wrong or unusual about that output. Because gedcom.Element hasn't defined a __repr__, printing the list will show the default __repr__. If you wanted to access a particular attribute on each element, you could try:
print [element.some_attribute for element in g.element_list()]
edit: Aha, I looked over the source you provided. It does indeed define a __str__, but no __repr__. Here's what you want, most likely:
for element in g.element_list()
print element
| Using a Python GEDCOM parser: Receiving bad output (gedcom.Element instance at 0x00...) | I'm new to Python, and I can say off the bat my programming experience is nominal compared to many of you. Brace yourselves :)
I have 2 files. A GEDCOM parser written in Python that I found from a user on this site (gedcom.py - http://ilab.cs.byu.edu/cs460/2006w/assignments/program1.html) and a simple GEDCOM file that I pulled from heiner-eichmann.de/gedcom/gedcom.htm. Guess who's having trouble putting 2 and 2 together? This guy...
Here is a code snippet followed by what I've done thus far.
class Gedcom:
""" Gedcom parser
This parser is for the Gedcom 5.5 format. For documentation of
this format, see
http://homepages.rootsweb.com/~pmcbride/gedcom/55gctoc.htm
This parser reads a GEDCOM file and parses it into a set of
elements. These elements can be accessed via a list (the order of
the list is the same as the order of the elements in the GEDCOM
file), or a dictionary (the key to the dictionary is a unique
identifier that one element can use to point to another element).
"""
def __init__(self,file):
""" Initialize a Gedcom parser. You must supply a Gedcom file.
"""
self.__element_list = []
self.__element_dict = {}
self.__element_top = Element(-1,"","TOP","",self.__element_dict)
self.__current_level = -1
self.__current_element = self.__element_top
self.__individuals = 0
self.__parse(file)
def element_list(self):
""" Return a list of all the elements in the Gedcom file. The
elements are in the same order as they appeared in the file.
"""
return self.__element_list
def element_dict(self):
""" Return a dictionary of elements from the Gedcom file. Only
elements identified by a pointer are listed in the dictionary. The
key for the dictionary is the pointer.
"""
return self.__element_dict
my little script
import gedcom
g = Gedcom('C:\tmp\test.ged') //I'm on Windows
print g.element_list()
From here, I receive a bunch of output "gedcom.Element instance at 0x00..."
I'm not sure why I'm receiving this output. I thought according to the element_list method a formatted list would be returned. I've Googled and search this site. The answer is probably staring me in the face but I was hoping someone could point out the obvious.
Much Appreciated.
| [
"someclass instance at 0xdeadbeef is the result of the the standard __repr__ method for classes that don't define one, as apparently class gedcom.Element doesn't, so the problem is only with you printing a list of such instances. If such class defines __str__, you could\nfor x in g.element_list():\n print x\n\n... | [
1,
0
] | [] | [] | [
"gedcom",
"parsing",
"python"
] | stackoverflow_0003623349_gedcom_parsing_python.txt |
Q:
Using Ruby/Python code in an iPhone OS app?
My app needs to use a library which is only available for Python and Ruby. From my understanding, Apple allows Ruby to run on iPhone as long as users can't execute arbitrary code (Rhomobile uses Ruby).
How can I bundle Ruby/Python with my app, call a function from my Obj-C code, and get the result (a string) back in C or Obj-C format?
A:
You can't. The new SDK agreement prohibits using original languages other than C, C++, or Objective-C, and the SDK agreement has always prohibited dynamically interpreting code. There's some ambiguity about how these rules will be enforced, but to be safe, it's best to avoid other languages until the kinks get worked out.
EDIT: In addition, as far as I know, there's no current technical way to run Python on the iPhone, as per this question. I've heard of embedding Lua in iPhone apps, but not Python. You can do Python with a jailbroken iPhone, but not through the app store.
The Ruby situation is almost as bad, as per this question. The iPhone doesn't ship with a Ruby interpreter, and compilers are a long ways off from working. Rhomobile works by packaging an interpreter and framework with the executable, which I highly doubt will make it past the new SDK agreement. If you really want to use Ruby, Rhomobile would probably be the best bet (as implementing your own interpreter would probably be a lot of work, and equally as unlikely to be approved). It's a rather depressing landscape at the moment--the most we can hope for is that MacRuby will eventually work, and Apple will approve it. That's a long ways off, though.
EDIT 2: I also just found out about tinypy, which could potentially work for Python. I doubt it would run real libraries though.
A:
FYI there are many Rhomobile Rhodes-based apps on the App Store including Wikipedia, MyHumana, RhoLogic for SugarCRM, Multilingual, TrackR, and dozens more. Many are out on http://rhomobile.com. We talk with Apple often and take steps to insure ongoing compliance with all iOS terms of service.
Also strictly speaking what ships with your final native app is not an interpreter but (on all platforms but BlackBerry) a Ruby 1.9 bytecode executor. And true interpretation (eval) is disabled intentionaly.
| Using Ruby/Python code in an iPhone OS app? | My app needs to use a library which is only available for Python and Ruby. From my understanding, Apple allows Ruby to run on iPhone as long as users can't execute arbitrary code (Rhomobile uses Ruby).
How can I bundle Ruby/Python with my app, call a function from my Obj-C code, and get the result (a string) back in C or Obj-C format?
| [
"You can't. The new SDK agreement prohibits using original languages other than C, C++, or Objective-C, and the SDK agreement has always prohibited dynamically interpreting code. There's some ambiguity about how these rules will be enforced, but to be safe, it's best to avoid other languages until the kinks get w... | [
3,
3
] | [] | [] | [
"iphone",
"python",
"ruby"
] | stackoverflow_0002702208_iphone_python_ruby.txt |
Q:
python Ctype : problem with callback in making python custom library
The whole scenario is like this:
there is a function setmessagelistener(a_structure,function_pointer) in my c library.
i am writing a python library which is a wrapper on above mentioned c library using Ctypes.
so what i did is something like this:
def setlistener(a_structure,function_pointer)
listenerDeclaration = CFUNCTYPE(c_void_p, c_void_p)
listenerFunction = listenerDeclaration(function_pointer)
setMsgListener = c_lib.setMessageListener
setMsgListener.argtypes = [c_void_p, c_void_p]
setMsgListener.restype = c_ubyte
if (setMsgListener(a_structure, listenerFunction)==0):
sys.exit("Error setting message listener.")
Now,another python program uses above function from my python library to do the work,but the problem is:
when i run the program it gives me segmentation fault because the local object( listenerfunction) is already garbage collected(i think so) when control returned from the library function setListener() as it being a local object.
is there any workaround/solution to this problem?or am i missing something?
please suggest...
thanx in advance
A:
As you suspect, you need to keep a reference to listenerFunction as long as it is needed. Perhaps wrap the function in a class, create an instance and set the listenerFunction as a member variable.
See the Python documentation for ctypes callbacks, especially the important note at the end of the section.
| python Ctype : problem with callback in making python custom library | The whole scenario is like this:
there is a function setmessagelistener(a_structure,function_pointer) in my c library.
i am writing a python library which is a wrapper on above mentioned c library using Ctypes.
so what i did is something like this:
def setlistener(a_structure,function_pointer)
listenerDeclaration = CFUNCTYPE(c_void_p, c_void_p)
listenerFunction = listenerDeclaration(function_pointer)
setMsgListener = c_lib.setMessageListener
setMsgListener.argtypes = [c_void_p, c_void_p]
setMsgListener.restype = c_ubyte
if (setMsgListener(a_structure, listenerFunction)==0):
sys.exit("Error setting message listener.")
Now,another python program uses above function from my python library to do the work,but the problem is:
when i run the program it gives me segmentation fault because the local object( listenerfunction) is already garbage collected(i think so) when control returned from the library function setListener() as it being a local object.
is there any workaround/solution to this problem?or am i missing something?
please suggest...
thanx in advance
| [
"As you suspect, you need to keep a reference to listenerFunction as long as it is needed. Perhaps wrap the function in a class, create an instance and set the listenerFunction as a member variable.\nSee the Python documentation for ctypes callbacks, especially the important note at the end of the section.\n"
] | [
1
] | [] | [] | [
"callback",
"ctypes",
"python"
] | stackoverflow_0003530002_callback_ctypes_python.txt |
Q:
Removing python module installed in develop mode
I was trying the python packaging using setuptools and to test I installed the module in develop mode.
i.e
python setup.py develop
This has added my modules directory to sys.path. Now I want to remove the module. Is there any way to do this?
A:
Use the --uninstall or -u option to develop, i.e:
python setup.py develop --uninstall
This will remove it from easy-install.pth and delete the .egg-link. The only thing it doesn't do is delete scripts (yet).
A:
Edit easy-install.pth in your site-packages directory and remove the line that points to your development version of that package.
A:
I have had a similar problem to this before. What I did was I loaded up the Python shell, imported the module and then printed its __file__ attribute. From there I would just remove the folder or file that was being associated.
What you may want to look into is using virtualenv this system allows you to create a instance of python separate from your system. Any modules you install or use in this instance are self contained including the version of the module.
I keep all my projects now inside of there own contained virtualenv, which allows me to install and use whatever modules I want without worrying about screwing up modules from other projects.
| Removing python module installed in develop mode | I was trying the python packaging using setuptools and to test I installed the module in develop mode.
i.e
python setup.py develop
This has added my modules directory to sys.path. Now I want to remove the module. Is there any way to do this?
| [
"Use the --uninstall or -u option to develop, i.e:\npython setup.py develop --uninstall\n\nThis will remove it from easy-install.pth and delete the .egg-link. The only thing it doesn't do is delete scripts (yet).\n",
"Edit easy-install.pth in your site-packages directory and remove the line that points to your d... | [
231,
18,
1
] | [] | [] | [
"python",
"setuptools"
] | stackoverflow_0003606457_python_setuptools.txt |
Q:
Do I need *.egg-info directories when using setuptools/distribute to create a python package
I have a "standard" python package layout like this:
setup.py - using setuptools
README
src/moduleA
test/
However, when I execute setup.py it decides to create the directory src/moduleA.egg-info.
The question is, do I need to worry about the contents of this directory and check it in with the rest of my code, or should I just rely on setuptools/distribute to regenerate it? It seems that all the information in the .egg-info directory comes from the config in setup.py anyway.
A:
The automatically generated bits don't need to be checked in, unless you're actually extending setuptools itself as part of your build process.
However, if you're putting files of your own in .egg-info (like i18n resources for EggTranslations), then those should definitely be checked in, since setuptools obviously isn't going to be able to regenerate them for you. ;-)
| Do I need *.egg-info directories when using setuptools/distribute to create a python package | I have a "standard" python package layout like this:
setup.py - using setuptools
README
src/moduleA
test/
However, when I execute setup.py it decides to create the directory src/moduleA.egg-info.
The question is, do I need to worry about the contents of this directory and check it in with the rest of my code, or should I just rely on setuptools/distribute to regenerate it? It seems that all the information in the .egg-info directory comes from the config in setup.py anyway.
| [
"The automatically generated bits don't need to be checked in, unless you're actually extending setuptools itself as part of your build process.\nHowever, if you're putting files of your own in .egg-info (like i18n resources for EggTranslations), then those should definitely be checked in, since setuptools obviousl... | [
4
] | [] | [] | [
"packaging",
"python",
"setuptools"
] | stackoverflow_0003575493_packaging_python_setuptools.txt |
Q:
Python: Check the value of a variable passed as a parameter in another method?
Somewhat related to my earlier question. I'm making a simple html parser to play around with in Python 2.7. I would like to have multiple parse types, IE can parse for links, script tags, images, ect. I'm using the HTMLParser module, so my initial thoughts were just make a separate class for each thing I want to parse. But that seemed rather silly. Is there a way to go about doing this without creating multiple classes? I am more familar with C#, so I figured I'd just pass a parameter on the init method to specify what exactly to parse for, just like I would in .Net, however I don't seem to be doing it correctly. It doesn't work, and it just doesn't 'look' right. Here's the current working code: How would I modify this to I can just have the one class, and the parameters that are passed indicate the type of HTML tags to parse?
class LinksParser(HTMLParser):
def __init__(self, url):
HTMLParser.__init__(self)
req = urllib2.urlopen(url)
self.feed(req.read())
def handle_starttag(self, tag, attrs):
if tag !='a': return
for name, value in attrs:
print("Found Link --> [{0}]{1}".format(name, value))
A:
class TagParser(HTMLParser):
def __init__(self, url, tag):
HTMLParser.__init__(self)
self.tag = tag
req = urllib2.urlopen(url)
self.feed(req.read())
def handle_starttag(self, tag, attrs):
if tag != self.tag: return
for name, value in attrs:
print("Found Tag({2}) --> [{0}]{1}".format(name, value, self.tag))
A:
Something like that:
class MyParser(HTMLParser):
def __init__(self, url, tags):
HTMLParser.__init__(self)
self.tags = tags
req = urllib2.urlopen(url)
self.feed(req.read())
def handle_starttag(self, tag, attrs):
if tag not in self.tags: return
for name, value in attrs:
print("Found Tag --> [{0}]{1}".format(name, value))
instantiate the class with something like:
p = MyParser("http://www.google.com", [ 'a', 'img' ])
| Python: Check the value of a variable passed as a parameter in another method? | Somewhat related to my earlier question. I'm making a simple html parser to play around with in Python 2.7. I would like to have multiple parse types, IE can parse for links, script tags, images, ect. I'm using the HTMLParser module, so my initial thoughts were just make a separate class for each thing I want to parse. But that seemed rather silly. Is there a way to go about doing this without creating multiple classes? I am more familar with C#, so I figured I'd just pass a parameter on the init method to specify what exactly to parse for, just like I would in .Net, however I don't seem to be doing it correctly. It doesn't work, and it just doesn't 'look' right. Here's the current working code: How would I modify this to I can just have the one class, and the parameters that are passed indicate the type of HTML tags to parse?
class LinksParser(HTMLParser):
def __init__(self, url):
HTMLParser.__init__(self)
req = urllib2.urlopen(url)
self.feed(req.read())
def handle_starttag(self, tag, attrs):
if tag !='a': return
for name, value in attrs:
print("Found Link --> [{0}]{1}".format(name, value))
| [
"class TagParser(HTMLParser):\n\n def __init__(self, url, tag):\n HTMLParser.__init__(self)\n self.tag = tag\n req = urllib2.urlopen(url)\n self.feed(req.read())\n\n def handle_starttag(self, tag, attrs):\n if tag != self.tag: return\n for name, value in attrs:\n ... | [
1,
0
] | [] | [] | [
"html_parsing",
"python"
] | stackoverflow_0003623949_html_parsing_python.txt |
Q:
How does python load Boost.Python libraries?
Considering the following archetypal Boost.Python module, which brings a class "D" from a separate C++ header file.
/* file: a/b.cpp */
BOOST_PYTHON_MODULE(c)
{
class_<d>("D")
}
When I compile this to a shared library, I'm confused how I can expose it to Python.
What should I call the library? a.so? liba.so? b.so? libb.so?
Where does the library need to be? Can I leave it in a subdirectory?
A:
We prefer to call the library _c.so, put it in a module, and then add an __init__.py that basically does from _c import *. So you have:
package
_c.so
__init__.py
| How does python load Boost.Python libraries? | Considering the following archetypal Boost.Python module, which brings a class "D" from a separate C++ header file.
/* file: a/b.cpp */
BOOST_PYTHON_MODULE(c)
{
class_<d>("D")
}
When I compile this to a shared library, I'm confused how I can expose it to Python.
What should I call the library? a.so? liba.so? b.so? libb.so?
Where does the library need to be? Can I leave it in a subdirectory?
| [
"We prefer to call the library _c.so, put it in a module, and then add an __init__.py that basically does from _c import *. So you have:\n\npackage\n\n_c.so\n__init__.py\n\n\n"
] | [
3
] | [] | [] | [
"boost_python",
"python",
"shared_libraries"
] | stackoverflow_0003608649_boost_python_python_shared_libraries.txt |
Q:
svcrack.py and svwar.py
i found out that my server is getting slower and slower.
on command top i get response that i have a lot svcrack.py and svwar.py processes active.
can you tell me what are those?
thank you in advance!
A:
Somebody is running a password cracker on your server. If it's not you, then your server has been compromised. Tread carefully.
A:
as everyone else said, that's part of SIPVicious, of which I'm the original author. Your server got compromised (somehow) and is being used to scan and compromise PBX servers open on the internet.
I would like more details about your case. Would be great if you could get in contact - sandro@enablesecurity.com
sandro
A:
Doesn't sound nice anyway... Just googling those two process names returns me pages I can't open at work:
http://www.darknet.org.uk/tag/svcrack/
http://webcache.googleusercontent.com/search?q=cache:70I2elB01lQJ:sipvicious.org/blog/2007/11/introduction-to-svcrack.html+svcrack.py&cd=1&hl=en&ct=clnk&gl=uk
I would be investigating to see if the process running on your service is this, and if it is, taking some decisive action to stop it - unless you have it running for some reason?
All the results arelinked to VOIP and SIP.
Dave
| svcrack.py and svwar.py | i found out that my server is getting slower and slower.
on command top i get response that i have a lot svcrack.py and svwar.py processes active.
can you tell me what are those?
thank you in advance!
| [
"Somebody is running a password cracker on your server. If it's not you, then your server has been compromised. Tread carefully.\n",
"as everyone else said, that's part of SIPVicious, of which I'm the original author. Your server got compromised (somehow) and is being used to scan and compromise PBX servers open ... | [
3,
2,
0
] | [] | [] | [
"apache",
"python"
] | stackoverflow_0003624521_apache_python.txt |
Q:
VoteHandler in Google App Engine
I am trying to have this function limit a user to only one vote per image. However it currently lets all votes through. If I change "if existing_vote != 0:" to "if existing_vote == 0:" it lets no votes through. Thoughts?
class VoteHandler(webapp.RequestHandler):
def get(self):
#See if logged in
self.Session = Session()
if not 'userkey' in self.Session:
doRender(
self,
'base/index.html',
{'error' : 'Please login to vote'})
return
#If user hasn't voted - if user doesn't have a vote on that image object
key = self.request.get('photo_id')
vurl = models.Image.get_by_id(int(key))
#pull current site vote total & add 1
existing_vote = models.Vote.all().filter('user=', self.Session['userkey']).filter('photo=',vurl).count()
if existing_vote != 0:
self.redirect('/', { })
else:
newvote = models.Vote(user=self.Session['userkey'], url=vurl)
vurl.votes += 1
vurl.put()
logging.info('Adding a vote')
#Create a new Vote object
newvote = models.Vote(user=self.Session['userkey'], url=vurl)
newvote.put()
self.redirect('/', { })
For the Models:
class User(db.Model):
account = db.StringProperty()
password = db.StringProperty()
name = db.StringProperty()
created = db.DateTimeProperty(auto_now=True)
class Image(db.Model):
user = db.ReferenceProperty(User)
photo_key = db.BlobProperty()
website = db.StringProperty()
text = db.StringProperty()
created = db.DateTimeProperty(auto_now=True)
votes = db.IntegerProperty(default=1)
class Vote(db.Model):
user = db.ReferenceProperty(User) #See if voted on this site yet
photo = db.ReferenceProperty(Image) #To apply vote to right URL
upvote = db.IntegerProperty(default=1)
created = db.DateTimeProperty(auto_now=True)
A:
Looks like your filter on user is wiping out every existing vote, i.e., the equality there is never satisfied. And indeed I'm not sure how I'd satistfy an equality check on a reference propertly. Why not change
user = db.ReferenceProperty(User) #See if voted on this site yet
to, e.g.,
useraccount = db.StringProperty() # account of user who cast this vote
Then the comparison becomes a simple equality check between strings and is sure to work without any complication -- simplicity is generally preferable, when feasible.
A:
On this line here:
existing_vote = models.Vote.all().filter('user=', self.Session['userkey']).filter('photo=',vurl).count()
You need to put a space between the 'photo' and the '=' in the filters - otherwise, it's attempting to filter for a property called 'photo='. This should work:
existing_vote = models.Vote.all().filter('user =', self.Session['userkey']).filter('photo =',vurl).count()
| VoteHandler in Google App Engine | I am trying to have this function limit a user to only one vote per image. However it currently lets all votes through. If I change "if existing_vote != 0:" to "if existing_vote == 0:" it lets no votes through. Thoughts?
class VoteHandler(webapp.RequestHandler):
def get(self):
#See if logged in
self.Session = Session()
if not 'userkey' in self.Session:
doRender(
self,
'base/index.html',
{'error' : 'Please login to vote'})
return
#If user hasn't voted - if user doesn't have a vote on that image object
key = self.request.get('photo_id')
vurl = models.Image.get_by_id(int(key))
#pull current site vote total & add 1
existing_vote = models.Vote.all().filter('user=', self.Session['userkey']).filter('photo=',vurl).count()
if existing_vote != 0:
self.redirect('/', { })
else:
newvote = models.Vote(user=self.Session['userkey'], url=vurl)
vurl.votes += 1
vurl.put()
logging.info('Adding a vote')
#Create a new Vote object
newvote = models.Vote(user=self.Session['userkey'], url=vurl)
newvote.put()
self.redirect('/', { })
For the Models:
class User(db.Model):
account = db.StringProperty()
password = db.StringProperty()
name = db.StringProperty()
created = db.DateTimeProperty(auto_now=True)
class Image(db.Model):
user = db.ReferenceProperty(User)
photo_key = db.BlobProperty()
website = db.StringProperty()
text = db.StringProperty()
created = db.DateTimeProperty(auto_now=True)
votes = db.IntegerProperty(default=1)
class Vote(db.Model):
user = db.ReferenceProperty(User) #See if voted on this site yet
photo = db.ReferenceProperty(Image) #To apply vote to right URL
upvote = db.IntegerProperty(default=1)
created = db.DateTimeProperty(auto_now=True)
| [
"Looks like your filter on user is wiping out every existing vote, i.e., the equality there is never satisfied. And indeed I'm not sure how I'd satistfy an equality check on a reference propertly. Why not change\nuser = db.ReferenceProperty(User) #See if voted on this site yet\n\nto, e.g.,\nuseraccount = db.Strin... | [
1,
1
] | [] | [] | [
"function",
"google_app_engine",
"python",
"vote"
] | stackoverflow_0003622207_function_google_app_engine_python_vote.txt |
Q:
Is it possible to get a list of all versions of an app?
the title speaks for itself. I play with GAE and some of my apps have versions like (1,2,3,4 and dev). So, is there a way to get all of them, so I could use it in my app to generate links to different versions ?
A:
No, there's no way to get a list of app versions from inside an app.
| Is it possible to get a list of all versions of an app? | the title speaks for itself. I play with GAE and some of my apps have versions like (1,2,3,4 and dev). So, is there a way to get all of them, so I could use it in my app to generate links to different versions ?
| [
"No, there's no way to get a list of app versions from inside an app.\n"
] | [
4
] | [] | [] | [
"google_app_engine",
"python",
"version_control"
] | stackoverflow_0003622165_google_app_engine_python_version_control.txt |
Q:
RPC frameworks available?
I am looking to use a RPC framework for internal use. The framework has to be cross language. I am exploring Apache Thrift right now. Google protocol Buffers does not provide RPC capabilities exactly. What are the choices I have got apart from Thrift. (my servers will be primarily Java and the clients will be Java, Python, PHP).
A:
There is also MessagePack
which claims to be faster than Protocol Buffers and have more features than Thrift.
A:
I would look at REST as a first option because it is ubiquitous and no-nonsense.
If performance and representation really needs to be compact, I have heard good things about Apache AVRO and my fingers are twitching to try it out in anger.
A:
There also seems to be ICE:
which uses Google Protocol Buffers for RPC.
| RPC frameworks available? | I am looking to use a RPC framework for internal use. The framework has to be cross language. I am exploring Apache Thrift right now. Google protocol Buffers does not provide RPC capabilities exactly. What are the choices I have got apart from Thrift. (my servers will be primarily Java and the clients will be Java, Python, PHP).
| [
"There is also MessagePack\nwhich claims to be faster than Protocol Buffers and have more features than Thrift.\n",
"I would look at REST as a first option because it is ubiquitous and no-nonsense. \nIf performance and representation really needs to be compact, I have heard good things about Apache AVRO and my fi... | [
4,
2,
1
] | [] | [] | [
"java",
"php",
"python",
"rpc",
"thrift"
] | stackoverflow_0003624568_java_php_python_rpc_thrift.txt |
Q:
How to redirect to a url with non-English characters?
I'm using pylons, and some of my urls contains non-English characters, such as:
http://localhost:5000/article/111/文章标题
At most cases, it won't be a problem, but in my login module, after a user has logging out, I try to get the referer from the request.headers, and redirect to that url.
if user_logout:
referer = request.headers.get('referer', '/')
redirect(referer)
Unforunately, if the url contains non-English characters, and with a brower of IE, it will report such an error (Firefox is OK):
WebError Traceback:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd5 in position 140: ordinal not in range(128)
View as: Interactive (full) | Text (full) | XML (full) clear this
clear this
URL: http://localhost:5000/users/logout
Module weberror.evalexception:431 in respond view
There is a way to fix it(but no good), use urllib.quote() to convert the url before redirecting.
referer = quote_path(url) # only quote the path of the url
redirect(referer)
This is not a good solution, because it only works if the brower is IE, and very boring. Is there any good solution?
A:
Try checking the RFC for non-ascii URLs. They are converted to an ascii equivalent if I remember correctly. You could then redirect to that.
Edit: According to @ssokolov (see comments below):
The specific terms to look up are IDN
(Internationalized Domain Names) and
Punycode
A:
At last, I still not find a good solution, and use this code:
referer = urllib.quote(referer, '.:/?=;-%#')
It seems work well now, but I don't feel safe.
A:
Redirect works by raising an exception. This is caught and converted into an HTTP response
How about specifying the charset for your response?
response.charset = 'utf8'
| How to redirect to a url with non-English characters? | I'm using pylons, and some of my urls contains non-English characters, such as:
http://localhost:5000/article/111/文章标题
At most cases, it won't be a problem, but in my login module, after a user has logging out, I try to get the referer from the request.headers, and redirect to that url.
if user_logout:
referer = request.headers.get('referer', '/')
redirect(referer)
Unforunately, if the url contains non-English characters, and with a brower of IE, it will report such an error (Firefox is OK):
WebError Traceback:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd5 in position 140: ordinal not in range(128)
View as: Interactive (full) | Text (full) | XML (full) clear this
clear this
URL: http://localhost:5000/users/logout
Module weberror.evalexception:431 in respond view
There is a way to fix it(but no good), use urllib.quote() to convert the url before redirecting.
referer = quote_path(url) # only quote the path of the url
redirect(referer)
This is not a good solution, because it only works if the brower is IE, and very boring. Is there any good solution?
| [
"Try checking the RFC for non-ascii URLs. They are converted to an ascii equivalent if I remember correctly. You could then redirect to that.\nEdit: According to @ssokolov (see comments below): \n\nThe specific terms to look up are IDN\n (Internationalized Domain Names) and\n Punycode\n\n",
"At last, I still no... | [
1,
1,
0
] | [] | [] | [
"non_english",
"pylons",
"python",
"url",
"webob"
] | stackoverflow_0003624063_non_english_pylons_python_url_webob.txt |
Q:
Python error "NameError: global name 'self' is not defined" when calling another method in same class
I get a weird error:
Traceback (most recent call last):
File "/remote/us01home15/ldagan/python/add_parallel_definition.py", line 36, in <module>
new_netlist.lines=orig_netlist.add_parallel_extention(cell_name,parallel,int(level))
File "/remote/us01home15/ldagan/python/hspice_netlist.py", line 70, in add_parallel_extention
new_cells_definition=self.gen_parallel_hierarchy(num,self.lines[i])
File "/remote/us01home15/ldagan/python/hspice_netlist.py", line 52, in gen_parallel_hierarchy
cell_lines=self.gen_parallel_inst(num_of_parallel,cell_1st_line)
NameError: global name 'self' is not defined
From all the tutorials that I have seen, calling a different method from the same class is via self.method_name
It's a script instantiating a class.
The script is:
#!/depot/Python-3.1.1/bin/python3.1
#gets a netlist and a cell name.
#generates a new netlist with the parallel instanciation
import sys
import re
from operator import itemgetter
sys.path.append('/remote/us01home15/ldagan/python/')
from hspice_netlist import hspice_netlist
command="" # initializing argument string
for l in sys.argv:
command=command + " " + "".join(l)
print (len(sys.argv))
print (command)
if (len(sys.argv) <4):
sys.exit("Pleas input original file name & new file name")
orig_netlist=hspice_netlist("file=" + "".join(sys.argv[1])) #reading new netlist
new_netlist=hspice_netlist("") #empty netlist
match=re.search(r"subckt\s*=\s*(\S+)",command)
if (match):
cell_name=match.group(1) #cell to be parallelized name
else:
sys.exit("Please input subckt= <subckt name>")
match=re.search(r"level\s*=\s*(\S+)",command)
if (match):
level=match.group(1) #levels of netlist name
else:
sys.exit("Please input level=<level name>")
match=re.search(r"parallel\s*=\s*(\S+)",command)
if (match):
parallel=match.group(1) #new netlist name
else:
sys.exit("Please input parallel=<parallel name>")
new_netlist.lines=orig_netlist.add_parallel_extention(cell_name,parallel,int(level))
match=re.search(r"outfile\s*=\s*(\S+)",command)
if (match):
output_filename=match.group[1]
outfile=open(output_filename,'w')
outfile.write("".join(new_netlist.lines))
The class code is:
import sys
import re
from collections import defaultdict
class hspice_netlist:
def __init__(self,cmd):
cmd_match=re.search(r"file\s*=\s*(\S+)",cmd)
if (cmd_match):
filename=cmd_match.group(1)
self.infile = open(filename, 'r')
self.lines=self.infile.readlines() #reading the lines
self.infile.close() #closing filehandle
def input_lines(self,lines):
self.lines=lines
def get_subckt_lines(self,name):
gotit=0
ret_lines=[]
find_sub=re.compile("^.sub\S*\s+"+name, re.IGNORECASE)
find_end=re.compile('^.ends', re.IGNORECASE)
for line in self.lines:
if (not gotit):
if (find_sub.search(line)):
gotit=1
ret_lines.append(line)
else:
ret_lines.append(line)
if (find_end.search(line)):
return ret_lines
sys.exit("Could not find the lines for circuit " + name + '\n')
def gen_parallel_inst(num,cell_1st_line):
ret_lines=[] #starting a fresh!!
cell_data=re.search(r"^\S+\s+(\S+)(\s+.*)", cell_1st_line)
cell_name=cell_data.group(1) # got the cell name
new_cell_name=cell_name + '__' + str(num) # new cell name
nodes=cell_data.group(2) # interface
ret_lines.append("".join([".sub ", new_cell_name,nodes,"\n"]))
iter=num
if (not (re.search(r"\s+$",nodes))):
nodes=nodes + ' ' #need a space before the cell name, add if it doesn't exist
while(iter > 0):
line="x" + str(iter) + nodes + cell_name + "\n"
ret_lines.append(line)
iter=iter-1
ret_lines.append(".ends\n") #end of subcircuit definition
return return_lines
def gen_parallel_hierarchy(num_of_parallel,level,cell_1st_line):
'''What that it does: Gets a cell name, then finds that cell's interface definition. It then simply relicates the cell, in parallel, then into hierarchies, ending with new cells' definitions. It is useful for the HSPICE BA issue. It runs recusively. Currently it supports 1 line for interface definition, and no parameters for the cell @ this time '''
ret_lines=[]
cell_lines=self.gen_parallel_inst(num_of_parallel,cell_1st_line)
ret_lines.extend(cell_lines)
if (level>0):
ret_lines.extend(self.gen_parallel_hierarchy(num_of_parallel,level-1,cell_lines[0]))
return ret_lines
def add_parallel_extention(self,cell_name,num,level):
''' Get a cell name + definitions and generates a new netlist '''
i=0
regi=re.compile("^.sub\S*\s+" + cell_name)
m=-1
while ( (i+1 < len(self.lines)) & ( not m )):
i=i+1
m=regi.search(lines[i]) #finding the line
if (not m):
sys.exit("could not find subcircuit definition of " + cell_name + "\n")
new_cells_definition=self.gen_parallel_hierarchy(num,self.lines[i])
i=i-1
ret_lines=self.lines[0:i] # creating return variable, using extend for performance
ret_lines.extend(new_cells_definition)
ret_lines.extend(self.lines[i+1:len(self.lines)])
return ret_lines
#get the cell
#write the level
I am definitely doing something fundamentally wrong, but I don't know what.
Thanks for helping an EE newbe (to Python).
A:
You are missing self in two method declarations.
These
def gen_parallel_hierarchy(num_of_parallel,level,cell_1st_line):
def gen_parallel_inst(num,cell_1st_line):
should be
def gen_parallel_hierarchy(self,num_of_parallel,level,cell_1st_line):
def gen_parallel_inst(self,num,cell_1st_line):
The error happens because you haven't put the self parameter in gen_parallel_hierarchy() but are referring to it in the line which fails:
cell_lines=self.gen_parallel_inst(num_of_parallel,cell_1st_line)
| Python error "NameError: global name 'self' is not defined" when calling another method in same class | I get a weird error:
Traceback (most recent call last):
File "/remote/us01home15/ldagan/python/add_parallel_definition.py", line 36, in <module>
new_netlist.lines=orig_netlist.add_parallel_extention(cell_name,parallel,int(level))
File "/remote/us01home15/ldagan/python/hspice_netlist.py", line 70, in add_parallel_extention
new_cells_definition=self.gen_parallel_hierarchy(num,self.lines[i])
File "/remote/us01home15/ldagan/python/hspice_netlist.py", line 52, in gen_parallel_hierarchy
cell_lines=self.gen_parallel_inst(num_of_parallel,cell_1st_line)
NameError: global name 'self' is not defined
From all the tutorials that I have seen, calling a different method from the same class is via self.method_name
It's a script instantiating a class.
The script is:
#!/depot/Python-3.1.1/bin/python3.1
#gets a netlist and a cell name.
#generates a new netlist with the parallel instanciation
import sys
import re
from operator import itemgetter
sys.path.append('/remote/us01home15/ldagan/python/')
from hspice_netlist import hspice_netlist
command="" # initializing argument string
for l in sys.argv:
command=command + " " + "".join(l)
print (len(sys.argv))
print (command)
if (len(sys.argv) <4):
sys.exit("Pleas input original file name & new file name")
orig_netlist=hspice_netlist("file=" + "".join(sys.argv[1])) #reading new netlist
new_netlist=hspice_netlist("") #empty netlist
match=re.search(r"subckt\s*=\s*(\S+)",command)
if (match):
cell_name=match.group(1) #cell to be parallelized name
else:
sys.exit("Please input subckt= <subckt name>")
match=re.search(r"level\s*=\s*(\S+)",command)
if (match):
level=match.group(1) #levels of netlist name
else:
sys.exit("Please input level=<level name>")
match=re.search(r"parallel\s*=\s*(\S+)",command)
if (match):
parallel=match.group(1) #new netlist name
else:
sys.exit("Please input parallel=<parallel name>")
new_netlist.lines=orig_netlist.add_parallel_extention(cell_name,parallel,int(level))
match=re.search(r"outfile\s*=\s*(\S+)",command)
if (match):
output_filename=match.group[1]
outfile=open(output_filename,'w')
outfile.write("".join(new_netlist.lines))
The class code is:
import sys
import re
from collections import defaultdict
class hspice_netlist:
def __init__(self,cmd):
cmd_match=re.search(r"file\s*=\s*(\S+)",cmd)
if (cmd_match):
filename=cmd_match.group(1)
self.infile = open(filename, 'r')
self.lines=self.infile.readlines() #reading the lines
self.infile.close() #closing filehandle
def input_lines(self,lines):
self.lines=lines
def get_subckt_lines(self,name):
gotit=0
ret_lines=[]
find_sub=re.compile("^.sub\S*\s+"+name, re.IGNORECASE)
find_end=re.compile('^.ends', re.IGNORECASE)
for line in self.lines:
if (not gotit):
if (find_sub.search(line)):
gotit=1
ret_lines.append(line)
else:
ret_lines.append(line)
if (find_end.search(line)):
return ret_lines
sys.exit("Could not find the lines for circuit " + name + '\n')
def gen_parallel_inst(num,cell_1st_line):
ret_lines=[] #starting a fresh!!
cell_data=re.search(r"^\S+\s+(\S+)(\s+.*)", cell_1st_line)
cell_name=cell_data.group(1) # got the cell name
new_cell_name=cell_name + '__' + str(num) # new cell name
nodes=cell_data.group(2) # interface
ret_lines.append("".join([".sub ", new_cell_name,nodes,"\n"]))
iter=num
if (not (re.search(r"\s+$",nodes))):
nodes=nodes + ' ' #need a space before the cell name, add if it doesn't exist
while(iter > 0):
line="x" + str(iter) + nodes + cell_name + "\n"
ret_lines.append(line)
iter=iter-1
ret_lines.append(".ends\n") #end of subcircuit definition
return return_lines
def gen_parallel_hierarchy(num_of_parallel,level,cell_1st_line):
'''What that it does: Gets a cell name, then finds that cell's interface definition. It then simply relicates the cell, in parallel, then into hierarchies, ending with new cells' definitions. It is useful for the HSPICE BA issue. It runs recusively. Currently it supports 1 line for interface definition, and no parameters for the cell @ this time '''
ret_lines=[]
cell_lines=self.gen_parallel_inst(num_of_parallel,cell_1st_line)
ret_lines.extend(cell_lines)
if (level>0):
ret_lines.extend(self.gen_parallel_hierarchy(num_of_parallel,level-1,cell_lines[0]))
return ret_lines
def add_parallel_extention(self,cell_name,num,level):
''' Get a cell name + definitions and generates a new netlist '''
i=0
regi=re.compile("^.sub\S*\s+" + cell_name)
m=-1
while ( (i+1 < len(self.lines)) & ( not m )):
i=i+1
m=regi.search(lines[i]) #finding the line
if (not m):
sys.exit("could not find subcircuit definition of " + cell_name + "\n")
new_cells_definition=self.gen_parallel_hierarchy(num,self.lines[i])
i=i-1
ret_lines=self.lines[0:i] # creating return variable, using extend for performance
ret_lines.extend(new_cells_definition)
ret_lines.extend(self.lines[i+1:len(self.lines)])
return ret_lines
#get the cell
#write the level
I am definitely doing something fundamentally wrong, but I don't know what.
Thanks for helping an EE newbe (to Python).
| [
"You are missing self in two method declarations.\nThese\ndef gen_parallel_hierarchy(num_of_parallel,level,cell_1st_line):\ndef gen_parallel_inst(num,cell_1st_line):\n\nshould be\ndef gen_parallel_hierarchy(self,num_of_parallel,level,cell_1st_line):\ndef gen_parallel_inst(self,num,cell_1st_line):\n\nThe error happe... | [
17
] | [] | [] | [
"class",
"python"
] | stackoverflow_0003625726_class_python.txt |
Q:
Parsing document with python minidom
I have the following XML document that I have to parse using python's minidom:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<bash-function activated="True">
<name>lsal</name>
<description>List directory content (-al)</description>
<code>ls -al</code>
</bash-function>
<bash-function activated="True">
<name>lsl</name>
<description>List directory content (-l)</description>
<code>ls -l</code>
</bash-function>
</root>
Here is the code (the essential part) where I am trying to parse:
from modules import BashFunction
from xml.dom.minidom import parse
class FuncDoc(object):
def __init__(self, xml_file):
self.active_func = []
self.inactive_func = []
try:
self.dom = parse(xml_file)
except Exception as inst:
print type(inst)
print inst.args
print inst
Unfortunately I am encountering some errors. Here is the stacktrace:
<class 'xml.parsers.expat.ExpatError'>
('no element found: line 1, column 0',)
no element found: line 1, column 0
As a python beginner, can you please point me to the root of the problem.
A:
I imagine you are passing in a file handle, in the following way:
>>> from xml.dom.minidom import parse
>>> xmldoc = open("xmltestfile.xml", "rU")
>>> x = FuncDoc(xmldoc)
I'm getting the same error as you do if I try to parse the same document twice without closing it in-between. Try this -- the error appears after the second parse attempt:
>>> xmldoc.close()
>>> xmldoc = open("xmltestfile.xml", "rU")
>>> xml1 = parse(xmldoc)
>>> xml2 = parse(xmldoc)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/xml/dom/minidom.py", line 1918, in parse
return expatbuilder.parse(file)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/xml/dom/expatbuilder.py", line 928, in parse
result = builder.parseFile(file)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/xml/dom/expatbuilder.py", line 211, in parseFile
parser.Parse("", True)
xml.parsers.expat.ExpatError: no element found: line 1, column 0
After parsing for the first time, the entire file has been read. The new parsing attempt then receives 0 data. My guess would be that the fact that the document is parsed twice is a bug in your code. If, however, that's what you want to do, you can reset it with xmldoc.seek(0).
| Parsing document with python minidom | I have the following XML document that I have to parse using python's minidom:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<bash-function activated="True">
<name>lsal</name>
<description>List directory content (-al)</description>
<code>ls -al</code>
</bash-function>
<bash-function activated="True">
<name>lsl</name>
<description>List directory content (-l)</description>
<code>ls -l</code>
</bash-function>
</root>
Here is the code (the essential part) where I am trying to parse:
from modules import BashFunction
from xml.dom.minidom import parse
class FuncDoc(object):
def __init__(self, xml_file):
self.active_func = []
self.inactive_func = []
try:
self.dom = parse(xml_file)
except Exception as inst:
print type(inst)
print inst.args
print inst
Unfortunately I am encountering some errors. Here is the stacktrace:
<class 'xml.parsers.expat.ExpatError'>
('no element found: line 1, column 0',)
no element found: line 1, column 0
As a python beginner, can you please point me to the root of the problem.
| [
"I imagine you are passing in a file handle, in the following way:\n>>> from xml.dom.minidom import parse\n>>> xmldoc = open(\"xmltestfile.xml\", \"rU\")\n>>> x = FuncDoc(xmldoc)\n\nI'm getting the same error as you do if I try to parse the same document twice without closing it in-between. Try this -- the error ap... | [
7
] | [] | [] | [
"dom",
"minidom",
"parsing",
"python"
] | stackoverflow_0003625897_dom_minidom_parsing_python.txt |
Q:
Is this possible to draw GtkTreeView listed like GtkIconView?
I am working on a GTK+ application written in python. I obviously use PyGtk. My application is about collections of videos. It's a kind of F-spot or Picasa, but for video.
As you can see in these two apps, you have a central area where you can see all of your photos with tag thumbnails under.
In my app, I want to implement the same kinf of view. For now I simply use this:
A gtk.Table containing a VBox, inside the VBox a Pixbuf (my video thumbnail) and a HBox, and inside the HBox, as many Pixbuf as tags.
It's working but it's ugly and It seems like It's not the better solution.
Looking deeply in the docs, I have found two widgets near my neeeds: IconView and TreeView. But IconView can only display one pixbuf per "row" and TreeView don't display as a grid like IconView.
My question: Is there a way to display a TreeView like an IconView (in a grid) ?
How would you implement the F-spot way of arranging photos and tags under?
A:
IconView is what you need. In the ListStore every row represent just one pixbuf but the IconView adjusts the images in a grid. Here a small example, launch it with the image files you want to show as arguments, for example:
python example.py /usr/share/icons/hicolor/16x16/apps/*
.
import sys
import gtk
store = gtk.ListStore(gtk.gdk.Pixbuf)
iv = gtk.IconView(store)
iv.set_pixbuf_column(0)
for arg in sys.argv[1:]:
pixbuf = gtk.gdk.pixbuf_new_from_file(arg)
store.append((pixbuf, ))
w = gtk.Window()
w.connect('destroy', lambda w: gtk.main_quit())
sw = gtk.ScrolledWindow()
w.add(sw)
sw.add(iv)
w.show_all()
gtk.main()
A:
The best approach is either to stick with a table and reimplement selections or Use a custom version of IconView with a custom cellrenderer wich can take gtk.HBox().
Some guidelines about custom cellrenderer are :
http://faq.pygtk.org/index.py?req=show&file=faq13.045.htp
http://faq.pygtk.org/index.py?req=show&file=faq13.056.htp
a discuss occured on pygtk mailing list :
htp://old.nabble.com/Drawing-widgets-in-a-custom-cellrenderer-td14207692.html
WWWalter make a sample code :
http://www.translate.org.za/blogs/walter/en/content/conquering-cellrendererwidget
According to Ruben Vermeersch, f-pot use a modified version of IconView. Code can be found here :
http://git.gnome.org/browse/f-spot/?h=icon-view-cleanup
| Is this possible to draw GtkTreeView listed like GtkIconView? | I am working on a GTK+ application written in python. I obviously use PyGtk. My application is about collections of videos. It's a kind of F-spot or Picasa, but for video.
As you can see in these two apps, you have a central area where you can see all of your photos with tag thumbnails under.
In my app, I want to implement the same kinf of view. For now I simply use this:
A gtk.Table containing a VBox, inside the VBox a Pixbuf (my video thumbnail) and a HBox, and inside the HBox, as many Pixbuf as tags.
It's working but it's ugly and It seems like It's not the better solution.
Looking deeply in the docs, I have found two widgets near my neeeds: IconView and TreeView. But IconView can only display one pixbuf per "row" and TreeView don't display as a grid like IconView.
My question: Is there a way to display a TreeView like an IconView (in a grid) ?
How would you implement the F-spot way of arranging photos and tags under?
| [
"IconView is what you need. In the ListStore every row represent just one pixbuf but the IconView adjusts the images in a grid. Here a small example, launch it with the image files you want to show as arguments, for example:\npython example.py /usr/share/icons/hicolor/16x16/apps/*\n\n.\nimport sys\nimport gtk\n\n\n... | [
1,
0
] | [] | [] | [
"gtk",
"gtktreeview",
"pygtk",
"python"
] | stackoverflow_0003596926_gtk_gtktreeview_pygtk_python.txt |
Q:
Is it safe to use sys.platform=='win32' check on 64-bit Python?
The usual check to differentiate between running Python-application on Windows and on other OSes (Linux typically) is to use conditional:
if sys.platform == 'win32':
...
But I wonder is it safe to use today when 64-bit Python is more widely used in last years? Does 32 really means 32-bit, or basically it refers to Win32 API?
If there is possibility to have one day sys.platform as 'win64' maybe such condition would be more universal?
if sys.platform.startswith('win'):
...
There is also another way to detect Windows I'm aware of:
if os.name == 'nt':
...
But I really never saw in other code the use of the latter.
What is the best way then?
UPD: I'd like to avoid using extra libraries if I can. Requiring installing extra library to check that I'm work not in the Windows may be annoying for Linux users.
A:
sys.platform will be win32 regardless of the bitness of the underlying Windows system, as you can see in PC/pyconfig.h (from the Python 2.6 source distribution):
#if defined(MS_WIN64)
/* maintain "win32" sys.platform for backward compatibility of Python code,
the Win64 API should be close enough to the Win32 API to make this
preferable */
# define PLATFORM "win32"
It's possible to find the original patch that introduced this on the web, which offers a bit more explanation:
The main question is: is Win64 so much more like Win32 than different from it that the common-case general Python programmer should not ever have to make the differentiation in his Python code. Or, at least, enough so that such differentiation by the Python scriptor is rare enough that some other provided mechanism is sufficient (even preferable). Currently the answer is yes. Hopefully MS will not change this answer.
A:
Personally I use platinfo for detecting the underlying platform.
>>> from platinfo import PlatInfo
>>> pi = PlatInfo()
>>> pi.os
'win64'
>>> pi.arch
'x64'
>>> pi.name()
'win64-x64'
For 32-bit, pi.name() returns win32-x86.
A:
Notice that you cannot use either sys.platform or os.name for this on Jython:
$ jython -c "import sys, os; print sys.platform; print os.name"
java1.6.0_20
java
I think there's a plan in Jython project to change os.name to report the underlying OS similarly as CPython, but because people are using os.name == 'java' to check are they on Jython this change cannot be done overnight. There is, however, already os._name on Jython 2.5.x:
$ jython -c "import os; print os._name"
posix
Personally I tend to use os.sep == '/' with code that needs to run both on Jython and CPython, and both on Windows and unixy platforms. It's somewhat ugly but works.
A:
The caveats for Windows/32 and Windows/64 are the same, so they should use the same value. The only difference would be in e.g. sys.maxint and ctypes. If you need to distinguish between 32 and 64 regardless then platform is your best bet.
| Is it safe to use sys.platform=='win32' check on 64-bit Python? | The usual check to differentiate between running Python-application on Windows and on other OSes (Linux typically) is to use conditional:
if sys.platform == 'win32':
...
But I wonder is it safe to use today when 64-bit Python is more widely used in last years? Does 32 really means 32-bit, or basically it refers to Win32 API?
If there is possibility to have one day sys.platform as 'win64' maybe such condition would be more universal?
if sys.platform.startswith('win'):
...
There is also another way to detect Windows I'm aware of:
if os.name == 'nt':
...
But I really never saw in other code the use of the latter.
What is the best way then?
UPD: I'd like to avoid using extra libraries if I can. Requiring installing extra library to check that I'm work not in the Windows may be annoying for Linux users.
| [
"sys.platform will be win32 regardless of the bitness of the underlying Windows system, as you can see in PC/pyconfig.h (from the Python 2.6 source distribution):\n#if defined(MS_WIN64)\n/* maintain \"win32\" sys.platform for backward compatibility of Python code,\n the Win64 API should be close enough to the Win... | [
46,
6,
5,
2
] | [] | [] | [
"32bit_64bit",
"64_bit",
"cross_platform",
"python",
"windows"
] | stackoverflow_0002144748_32bit_64bit_64_bit_cross_platform_python_windows.txt |
Q:
how to increase the number of pages comes in google search?
I am using google search api
But by default it shows 4 and maximum 8 results per page. I want more results per page.
A:
Add the rsz=8 parameter to this google search demonstration code,
then use the start=... parameter to control which group of results you receive.
This, for example, gives you 50 results:
import urllib
import json
import sys
import itertools
def hits(astr):
for start in itertools.count():
query = urllib.urlencode({'q':astr, 'rsz': 8, 'start': start*8})
url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s'%(query)
search_results = urllib.urlopen(url)
results = json.loads(search_results.read())
data = results['responseData']
if data:
hits = data['results']
for h in hits:
yield h['url']
else:
raise StopIteration
def showmore(astr,num):
for i,h in enumerate(itertools.islice(hits(astr),num)):
print('{i}: {h}'.format(i=i,h=h))
if __name__=='__main__':
showmore(sys.argv[1],50)
| how to increase the number of pages comes in google search? | I am using google search api
But by default it shows 4 and maximum 8 results per page. I want more results per page.
| [
"Add the rsz=8 parameter to this google search demonstration code,\nthen use the start=... parameter to control which group of results you receive.\nThis, for example, gives you 50 results:\nimport urllib\nimport json\nimport sys\nimport itertools\n\ndef hits(astr):\n for start in itertools.count():\n que... | [
0
] | [] | [] | [
"google_api",
"python"
] | stackoverflow_0003626039_google_api_python.txt |
Q:
Dealing with metaclass conflict with SQL Alchemy declarative base
I have a class X which derives from a class with its own metaclass Meta. I want to also derive X from the declarative base in SQL Alchemy. But I can't do the simple
def class MyBase(metaclass = Meta):
#...
def class X(declarative_base(), MyBase):
#...
since I would get metaclass conflict error: 'the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases'. I understand that I need to create a new metaclass that would derive from both Meta and from whatever metaclass the declarative base uses (DeclarativeMeta I think?). So is it enough to write:
def class NewMeta(Meta, DeclarativeMeta): pass
def class MyBase(metaclass = NewMeta):
#...
def class X(declarative_base(), MyBase):
#...
I tried this, and it seems to work; but I'm afraid I may have introduced some problem with this code.
I read the manual, but it's a bit too cryptic for me. What's
EDIT:
The code used for my classes is as follows:
class IterRegistry(type):
def __new__(cls, name, bases, attr):
attr['_registry'] = {}
attr['_frozen'] = False
print(name, bases)
print(type(cls))
return type.__new__(cls, name, bases, attr)
def __iter__(cls):
return iter(cls._registry.values())
class SQLEnumMeta(IterRegistry, DeclarativeMeta): pass
class EnumType(metaclass = IterRegistry):
def __init__(self, token):
if hasattr(self, 'token'):
return
self.token = token
self.id = len(type(self)._registry)
type(self)._registry[token] = self
def __new__(cls, token):
if token in cls._registry:
return cls._registry[token]
else:
if cls._frozen:
raise TypeError('No more instances allowed')
else:
return object.__new__(cls)
@classmethod
def freeze(cls):
cls._frozen = True
def __repr__(self):
return self.token
@classmethod
def instance(cls, token):
return cls._registry[token]
class C1(Base, EnumType, metaclass = SQLEnumMeta):
__tablename__ = 'c1'
#...
A:
Edit: Now having looked at IterRegistry and DeclarativeMeta, I think you're code is okay.
IterRegistry defines __new__ and __iter__, while DeclarativeMeta defines __init__ and __setattr__. Since there is no overlap, there's no direct need to call super. Nevertheless, it would good to do so, to future-proof your code.
Do you have control over the definition of Meta? Can you show us its definition? I don't think we can say it works or does not work unless we see the definition of Meta.
For example, there is a potential problem if your Meta does not call
super(Meta,cls).__init__(classname, bases, dict_)
If you run this code
class DeclarativeMeta(type):
def __init__(cls, classname, bases, dict_):
print('DeclarativeMeta')
# if '_decl_class_registry' in cls.__dict__:
# return type.__init__(cls, classname, bases, dict_)
# _as_declarative(cls, classname, dict_)
return type.__init__(cls, classname, bases, dict_)
class Meta(type):
def __init__(cls, classname, bases, dict_):
print('Meta')
return type.__init__(cls, classname, bases, dict_)
class NewMeta(Meta,DeclarativeMeta): pass
class MyBase(object):
__metaclass__ = NewMeta
pass
Then only the string 'Meta' gets printed.
In other words, only Meta.__init__ gets run. DeclarativeMeta.__init__ gets skipped.
On the other hand, if you define
class Meta(type):
def __init__(cls, classname, bases, dict_):
print('Meta')
return super(Meta,cls).__init__(classname, bases, dict_)
Then both Meta.__init__ and DeclarativeMeta.__init__ gets run.
| Dealing with metaclass conflict with SQL Alchemy declarative base | I have a class X which derives from a class with its own metaclass Meta. I want to also derive X from the declarative base in SQL Alchemy. But I can't do the simple
def class MyBase(metaclass = Meta):
#...
def class X(declarative_base(), MyBase):
#...
since I would get metaclass conflict error: 'the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases'. I understand that I need to create a new metaclass that would derive from both Meta and from whatever metaclass the declarative base uses (DeclarativeMeta I think?). So is it enough to write:
def class NewMeta(Meta, DeclarativeMeta): pass
def class MyBase(metaclass = NewMeta):
#...
def class X(declarative_base(), MyBase):
#...
I tried this, and it seems to work; but I'm afraid I may have introduced some problem with this code.
I read the manual, but it's a bit too cryptic for me. What's
EDIT:
The code used for my classes is as follows:
class IterRegistry(type):
def __new__(cls, name, bases, attr):
attr['_registry'] = {}
attr['_frozen'] = False
print(name, bases)
print(type(cls))
return type.__new__(cls, name, bases, attr)
def __iter__(cls):
return iter(cls._registry.values())
class SQLEnumMeta(IterRegistry, DeclarativeMeta): pass
class EnumType(metaclass = IterRegistry):
def __init__(self, token):
if hasattr(self, 'token'):
return
self.token = token
self.id = len(type(self)._registry)
type(self)._registry[token] = self
def __new__(cls, token):
if token in cls._registry:
return cls._registry[token]
else:
if cls._frozen:
raise TypeError('No more instances allowed')
else:
return object.__new__(cls)
@classmethod
def freeze(cls):
cls._frozen = True
def __repr__(self):
return self.token
@classmethod
def instance(cls, token):
return cls._registry[token]
class C1(Base, EnumType, metaclass = SQLEnumMeta):
__tablename__ = 'c1'
#...
| [
"Edit: Now having looked at IterRegistry and DeclarativeMeta, I think you're code is okay.\nIterRegistry defines __new__ and __iter__, while DeclarativeMeta defines __init__ and __setattr__. Since there is no overlap, there's no direct need to call super. Nevertheless, it would good to do so, to future-proof your c... | [
3
] | [] | [] | [
"metaclass",
"python",
"sqlalchemy"
] | stackoverflow_0003626615_metaclass_python_sqlalchemy.txt |
Q:
Can one use negative numbers as seeds for random number generation?
This is not a coding question, but am hoping that someone has come across this in the forums here. I am using Python to run some simulations. I need to run many replications using different random number seeds. I have two questions:
Are negative numbers okay as seeds?
Should I keep some distance in the seeds?
Currently I am using random.org to create 50 numbers between -100000 and +100000, which I use as seeds. Is this okay?
Thanks.
A:
Quoting random.seed([x]):
Optional argument x can be any hashable object.
Both positive and negative numbers are hashable, and many other objects besides.
>>> hash(42)
42
>>> hash(-42)
-42
>>> hash("hello")
-1267296259
>>> hash(("hello", "world"))
759311865
A:
Is it important that your simulations are repeatable? The canonical way to seed a RNG is by using the current system time, and indeed this is random's default behaviour:
random.seed([x])
Initialize the basic random number generator. Optional argument x can be
any hashable object. If x is omitted
or None, current system time is used;
current system time is also used to
initialize the generator when the
module is first imported.
I would only deviate from this behaviour if repeatability is important. If it is important, then your random.org seeds are a reasonable solution.
Should I keep some distance in the seeds?
No. For a good quality RNG, the choice of seed will not affect the quality of the output. A set of seeds [1,2,3,4,5,6,7,8,9,10] should result in the same quality of randomness as any random selection of 10 ints. But even if a selection of random uniformly-distributed seeds were desirable, maintaining some distance would break that distribution.
| Can one use negative numbers as seeds for random number generation? | This is not a coding question, but am hoping that someone has come across this in the forums here. I am using Python to run some simulations. I need to run many replications using different random number seeds. I have two questions:
Are negative numbers okay as seeds?
Should I keep some distance in the seeds?
Currently I am using random.org to create 50 numbers between -100000 and +100000, which I use as seeds. Is this okay?
Thanks.
| [
"Quoting random.seed([x]):\n\nOptional argument x can be any hashable object.\n\nBoth positive and negative numbers are hashable, and many other objects besides.\n>>> hash(42)\n42\n>>> hash(-42)\n-42\n>>> hash(\"hello\")\n-1267296259\n>>> hash((\"hello\", \"world\"))\n759311865\n\n",
"Is it important that your si... | [
8,
5
] | [] | [] | [
"python",
"random",
"seed"
] | stackoverflow_0003626846_python_random_seed.txt |
Q:
Django multiple form factory
What is the best way to deal with multiple forms? I want to combine several forms into one. For example, I want to combine ImangeFormSet and EntryForm into one form:
class ImageForm(forms.Form):
image = forms.ImageField()
ImageFormSet = formset_factory(ImageForm)
class EntryForm(forms.Form):
title = forms.CharField(max_length=100)
result_form = combine(EntryForm, ImageFormSet) # here it goes
I found 2 years old presentation introducing multipleform_factory() method, but I am not sure that it's the best way: http://www.slideshare.net/kingkilr/forms-getting-your-moneys-worth
A:
An idea (not checked if it works):
class MySuperForm(CombinedForm):
includes = (ImageForm, EntryForm, )
You see here how the form is built. You can make your own Form by extending from BaseForm and supplying another __metaclass__.
class CombinedForm(BaseForm):
__metaclass__ = DeclarativeFieldsMetaclassFromMultipleClasses
In DeclarativeFieldsMetaclassFromMultipleClasses you do basically the same as here, except you sum up the declared fields from the classes on
class DeclarativeFieldsMetaclassFromMultipleClasses(type):
def __new__(cls, name, bases, attrs):
for clazz in attrs['includes']:
attrs['base_fields'] += get_declared_fields(bases, clazz.attrs)
new_class = super(DeclarativeFieldsMetaclassFromMultipleClasses,cls).__new__(cls, name, bases, attrs)
if 'media' not in attrs:
new_class.media = media_property(new_class)
return new_class
A:
It doesn't matter how many forms are placed in template, because individual forms don't render form tag. So, your template goes like this
<form id='xxxx' action='' method=POST>
{{my_first_formset}}
{{my_second_form}}
</form>
and in view.py
my_formset = MyFormset(request.POST)
my_form = MyForm(request.POST)
if my_formset.is_valid() and my_form.is_valid():
process...
| Django multiple form factory | What is the best way to deal with multiple forms? I want to combine several forms into one. For example, I want to combine ImangeFormSet and EntryForm into one form:
class ImageForm(forms.Form):
image = forms.ImageField()
ImageFormSet = formset_factory(ImageForm)
class EntryForm(forms.Form):
title = forms.CharField(max_length=100)
result_form = combine(EntryForm, ImageFormSet) # here it goes
I found 2 years old presentation introducing multipleform_factory() method, but I am not sure that it's the best way: http://www.slideshare.net/kingkilr/forms-getting-your-moneys-worth
| [
"An idea (not checked if it works):\nclass MySuperForm(CombinedForm):\n includes = (ImageForm, EntryForm, )\n\nYou see here how the form is built. You can make your own Form by extending from BaseForm and supplying another __metaclass__.\nclass CombinedForm(BaseForm):\n __metaclass__ = DeclarativeFieldsMetaclas... | [
4,
3
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0003612726_django_django_forms_python.txt |
Q:
SQL-like JOIN on two text files in Python, is there a built-in way?
A common task I have to perform is an SQL-like JOIN on two text files. i.e. create a new file from the "left hand" and "right hand" files, using some sort of join on an identifier column shared between them. Variations such as outer joins etc are sometimes required.
Of course I could write a simple script to do this in a generic way, but is there a python module - built-in or installable - that can do this? Something that can handle huge files would be ideal.
EDIT:
I'm aware of PyTables, but is that the simplest solution for flat text files?
By "huge files" I mean sometimes the "left hand" file is too large to be stored in memory
The lack (so far) of a python answer worries me. Am I using the wrong tool/paradigm for this? The reason I asked for a python lib is to allow for easy adding of other transformations on each line (validate identifiers etc).
A:
[wild idea]
Will these files fit into you system's memory and leave enough still? In that case you can load them into tables using SQLite and then join them to your heart's content using SQL proper.
[/wild idea]
Update
Scratch it. The OP has said that one of the files is too large to be stored in memory.. See this answer by @Dave Kirby. SQLite can be used with an in-disk database.
A:
If you are using a unixy system or cygwin then take a look at the join command - it may do exactly what you are asking.
[26] % join --help
Usage: join [OPTION]... FILE1 FILE2
For each pair of input lines with identical join fields, write a line to
standard output. The default join field is the first, delimited
by whitespace. When FILE1 or FILE2 (not both) is -, read standard input.
-a FILENUM print unpairable lines coming from file FILENUM, where
FILENUM is 1 or 2, corresponding to FILE1 or FILE2
-e EMPTY replace missing input fields with EMPTY
-i, --ignore-case ignore differences in case when comparing fields
-j FIELD equivalent to `-1 FIELD -2 FIELD'
-o FORMAT obey FORMAT while constructing output line
-t CHAR use CHAR as input and output field separator
-v FILENUM like -a FILENUM, but suppress joined output lines
-1 FIELD join on this FIELD of file 1
-2 FIELD join on this FIELD of file 2
--help display this help and exit
--version output version information and exit
Unless -t CHAR is given, leading blanks separate fields and are ignored,
else fields are separated by CHAR. Any FIELD is a field number counted
from 1. FORMAT is one or more comma or blank separated specifications,
each being `FILENUM.FIELD' or `0'. Default FORMAT outputs the join field,
the remaining fields from FILE1, the remaining fields from FILE2, all
separated by CHAR.
Important: FILE1 and FILE2 must be sorted on the join fields.
Report bugs to <bug-coreutils@gnu.org>.
If you want something more sophisticated or you absolutely have to do it in python then consider reading the files into a in-memory SQLite database - you then have the full power of SQL to merge and manipulate the data.
edit just read that the files are too big to fit in memory. You can still use SQLite, but create a temporary on-disk database.
| SQL-like JOIN on two text files in Python, is there a built-in way? | A common task I have to perform is an SQL-like JOIN on two text files. i.e. create a new file from the "left hand" and "right hand" files, using some sort of join on an identifier column shared between them. Variations such as outer joins etc are sometimes required.
Of course I could write a simple script to do this in a generic way, but is there a python module - built-in or installable - that can do this? Something that can handle huge files would be ideal.
EDIT:
I'm aware of PyTables, but is that the simplest solution for flat text files?
By "huge files" I mean sometimes the "left hand" file is too large to be stored in memory
The lack (so far) of a python answer worries me. Am I using the wrong tool/paradigm for this? The reason I asked for a python lib is to allow for easy adding of other transformations on each line (validate identifiers etc).
| [
"[wild idea]\nWill these files fit into you system's memory and leave enough still? In that case you can load them into tables using SQLite and then join them to your heart's content using SQL proper. \n[/wild idea]\nUpdate\nScratch it. The OP has said that one of the files is too large to be stored in memory.. See... | [
1,
0
] | [] | [] | [
"join",
"python"
] | stackoverflow_0003626619_join_python.txt |
Q:
What is the IPv6 alternative to socket.getfqdn in Python?
socket.getfqdn() works fine with IPv4 addresses, for example:
>>> import socket
>>> socket.getfqdn("8.8.8.8")
'google-public-dns-a.google.com'
However, it doesn't work for IPv6 addresses.
>>> socket.getfqdn("2404:6800:8004::68")
'2404:6800:8004::68'
>>> socket.has_ipv6
True
How can I do this with IPv6? Ideally with only modules in the standard library.
A:
Are you sure that ipv6 address has any revers DNS associated with it? dig reports it doesn't:
$ dig -x 2404:6800:8004::68
; <<>> DiG 9.4.3-P5 <<>> -x 2404:6800:8004::68
;; global options: printcmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NXDOMAIN, id: 35573
;; flags: qr aa rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;8.6.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.4.0.0.8.0.0.8.6.4.0.4.2.ip6.arpa. IN PTR
;; Query time: 364 msec
;; SERVER: 12.165.58.2#53(12.165.58.2)
;; WHEN: Thu Sep 2 03:45:50 2010
;; MSG SIZE rcvd: 90
edit: Finally found an ipv6 address that has reverse DNS associated. In short, works4me.
>>> import socket
>>> socket.has_ipv6
True
>>> socket.getfqdn('2001:838:2:1::30:67')
'gatey.sixxs.net'
And from dig:
$ dig -x 2001:838:2:1::30:67
; <<>> DiG 9.4.3-P5 <<>> -x 2001:838:2:1::30:67
;; global options: printcmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 934
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 13, ADDITIONAL: 1
;; QUESTION SECTION:
;7.6.0.0.0.3.0.0.0.0.0.0.0.0.0.0.1.0.0.0.2.0.0.0.8.3.8.0.1.0.0.2.ip6.arpa. IN PTR
;; ANSWER SECTION:
7.6.0.0.0.3.0.0.0.0.0.0.0.0.0.0.1.0.0.0.2.0.0.0.8.3.8.0.1.0.0.2.ip6.arpa. 43200 IN PTR gatey.sixxs.net.
;; AUTHORITY SECTION:
. 517204 IN NS e.root-servers.net.
. 517204 IN NS m.root-servers.net.
. 517204 IN NS a.root-servers.net.
. 517204 IN NS l.root-servers.net.
. 517204 IN NS c.root-servers.net.
. 517204 IN NS h.root-servers.net.
. 517204 IN NS j.root-servers.net.
. 517204 IN NS g.root-servers.net.
. 517204 IN NS f.root-servers.net.
. 517204 IN NS i.root-servers.net.
. 517204 IN NS d.root-servers.net.
. 517204 IN NS b.root-servers.net.
. 517204 IN NS k.root-servers.net.
;; ADDITIONAL SECTION:
a.root-servers.net. 604222 IN A 198.41.0.4
;; Query time: 383 msec
;; SERVER: 12.165.58.2#53(12.165.58.2)
;; WHEN: Thu Sep 2 03:55:03 2010
;; MSG SIZE rcvd: 343
A:
Guess what: that address doesn’t have reverse DNS. For an easier-to-understand output than dig:
$ host 2404:6800:8004::68
Host 8.6.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.4.0.0.8.0.0.8.6.4.0.4.2.ip6.arpa not found: 3(NXDOMAIN)
Here’s an example of an address that does have reverse DNS:
$ host 2001:470:0:64::2
2.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.4.6.0.0.0.0.0.0.0.7.4.0.1.0.0.2.ip6.arpa domain name pointer ipv6.he.net.
And hey presto, it works with your Python example:
>>> import socket
>>> socket.getfqdn("2001:470:0:64::2")
'ipv6.he.net'
| What is the IPv6 alternative to socket.getfqdn in Python? | socket.getfqdn() works fine with IPv4 addresses, for example:
>>> import socket
>>> socket.getfqdn("8.8.8.8")
'google-public-dns-a.google.com'
However, it doesn't work for IPv6 addresses.
>>> socket.getfqdn("2404:6800:8004::68")
'2404:6800:8004::68'
>>> socket.has_ipv6
True
How can I do this with IPv6? Ideally with only modules in the standard library.
| [
"Are you sure that ipv6 address has any revers DNS associated with it? dig reports it doesn't:\n$ dig -x 2404:6800:8004::68\n\n; <<>> DiG 9.4.3-P5 <<>> -x 2404:6800:8004::68\n;; global options: printcmd\n;; Got answer:\n;; ->>HEADER<<- opcode: QUERY, status: NXDOMAIN, id: 35573\n;; flags: qr aa rd ra; QUERY: 1, AN... | [
3,
1
] | [] | [] | [
"dns",
"ipv6",
"python",
"sockets"
] | stackoverflow_0003626182_dns_ipv6_python_sockets.txt |
Q:
Module vs object-oriented programming in vba
My first "serious" language was Java, so I have comprehended object-oriented programming in sense that elemental brick of program is a class.
Now I write on VBA and Python. There are module languages and I am feeling persistent discomfort: I don't know how should I decompose program in a modules/classes.
I understand that one module corresponds to one knowledge domain, one module should ba able to test separately...
Should I apprehend module as namespace(c++) only?
A:
I don't do VBA but in python, modules are fundamental. As you say, the can be viewed as namespaces but they are also objects in their own right. They are not classes however, so you cannot inherit from them (at least not directly).
I find that it's a good rule to keep a module concerned with one domain area. The rule that I use for deciding if something is a module level function or a class method is to ask myself if it could meaningfully be used on any objects that satisfy the 'interface' that it's arguments take. If so, then I free it from a class hierarchy and make it a module level function. If its usefulness truly is restricted to a particular class hierarchy, then I make it a method.
If you need it work on all instances of a class hierarchy and you make it a module level function, just remember that all the the subclasses still need to implement the given interface with the given semantics. This is one of the tradeoffs of stepping away from methods: you can no longer make a slight modification and call super. On the other hand, if subclasses are likely to redefine the interface and its semantics, then maybe that particular class hierarchy isn't a very good abstraction and should be rethought.
A:
It is matter of taste. If you use modules your 'program' will be more procedural oriented. If you choose classes it will be more or less object oriented. I'm working with Excel for couple of months and personally I choose classes whenever I can because it is more comfortable to me. If you stop thinking about objects and think of them as Components you can use them with elegance. The main reason why I prefer classes is that you can have it more that one. You can't have two instances of module. It allows me use encapsulation and better code reuse.
For example let's assume that you like to have some kind of logger, to log actions that were done by your program during execution. You can write a module for that. It can have for example a global variable indicating on which particular sheet logging will be done. But consider the following hypothetical situation: your client wants you to include some fancy report generation functionality in your program. You are smart so you figure out that you can use your logging code to prepare them. But you can't do log and report simultaneously by one module. And you can with two instances of logging Component without any changes in their code.
A:
Idioms of languages are different and thats the reason a problem solved in different languages take different approaches.
"C" is all about procedural decomposition.
Main idiom in Java is about "class or Object" decomposition. Functions are not absent, but they become a part of exhibited behavior of these classes.
"Python" provides support for both Class based problem decomposition as well as procedural based.
All of these uses files, packages or modules as concept for organizing large code pieces together. There is nothing that restricts you to have one module for one knowledge domain.
These are decomposition and organizing techniques and can be applied based on the problem at hand.
If you are comfortable with OO, you should be able to use it very well in Python.
A:
VBA also allows the use of classes. Unfortunately, those classes don't support all the features of a full-fleged object oriented language. Especially inheritance is not supported.
But you can work with interfaces, at least up to a certain degree.
I only used modules like "one module = one singleton". My modules contain "static" or even stateless methods. So in my opinion a VBa module is not namespace. More often a bunch of classes and modules would form a "namespace". I often create a new project (DLL, DVB or something similar) for such a "namespace".
| Module vs object-oriented programming in vba | My first "serious" language was Java, so I have comprehended object-oriented programming in sense that elemental brick of program is a class.
Now I write on VBA and Python. There are module languages and I am feeling persistent discomfort: I don't know how should I decompose program in a modules/classes.
I understand that one module corresponds to one knowledge domain, one module should ba able to test separately...
Should I apprehend module as namespace(c++) only?
| [
"I don't do VBA but in python, modules are fundamental. As you say, the can be viewed as namespaces but they are also objects in their own right. They are not classes however, so you cannot inherit from them (at least not directly).\nI find that it's a good rule to keep a module concerned with one domain area. The ... | [
3,
3,
1,
1
] | [] | [] | [
"python",
"vba"
] | stackoverflow_0003607020_python_vba.txt |
Q:
Python Windows service autostarts too early
I am running a Python script as a Windows service, but it seems to be failing whenever I set it to auto-start. I believe this may be because the service uses network resources that are not yet mounted when the service starts. Is there a way I can get it to wait until startup is complete before running?
A:
Configure your Windows Service so that it has the Workstation Service as a dependency.
This means Windows won't attempt to start your service until the appropriate resources are available.
A:
Add in script wait for the resources who script must use is in good standing, or rewrite script to better design like not exit if dont have connection; wait 1s and try again if connection failed.
| Python Windows service autostarts too early | I am running a Python script as a Windows service, but it seems to be failing whenever I set it to auto-start. I believe this may be because the service uses network resources that are not yet mounted when the service starts. Is there a way I can get it to wait until startup is complete before running?
| [
"Configure your Windows Service so that it has the Workstation Service as a dependency.\nThis means Windows won't attempt to start your service until the appropriate resources are available.\n",
"Add in script wait for the resources who script must use is in good standing, or rewrite script to better design like ... | [
8,
2
] | [] | [] | [
"python",
"windows_services"
] | stackoverflow_0003626766_python_windows_services.txt |
Q:
Using PyFlakes and the del operator
When making use of del in a Python function, I'm getting false positives from PyFlakes telling me that the variable is undefined.
def foo(bar):
# what if it's ham? eww
if bar == 'ham':
del bar
return
# otherwise yummy!
print bar
The above function will return the following error:
C:\temp\test.py:7: undefined name 'bar'
Even though the function will work.
Does anyone know of a patch to tweak the ast tree parsing to change how it's being handled? If this something others have run into?
A:
So what is your question? Deleting parameter names does not make any sense at all, so this is no real issue anyways ...
| Using PyFlakes and the del operator | When making use of del in a Python function, I'm getting false positives from PyFlakes telling me that the variable is undefined.
def foo(bar):
# what if it's ham? eww
if bar == 'ham':
del bar
return
# otherwise yummy!
print bar
The above function will return the following error:
C:\temp\test.py:7: undefined name 'bar'
Even though the function will work.
Does anyone know of a patch to tweak the ast tree parsing to change how it's being handled? If this something others have run into?
| [
"So what is your question? Deleting parameter names does not make any sense at all, so this is no real issue anyways ...\n"
] | [
0
] | [] | [] | [
"del",
"pyflakes",
"python"
] | stackoverflow_0003627577_del_pyflakes_python.txt |
Q:
django logging: log is not created
I'm running my app on the GAE development server, with app-engine-patch to run Django.
One of my views is bugged , so I want to log everything that happens.
I added in myapp.views:
import logging
LOG_FILENAME = '/mylog.txt'
logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)
and my function is:
def function(string):
logging.debug('new call')
#do stuff
#logging.debug('log stuff')
My problem is that I can't find the log. When I run my app I get no errors, but the log is not created.
I also tried various paths: /mylog.txt ,mylog.txt , c:\mylog.txt, c:\complete\path\to \my\app\mylog.txt, but it doesn't work.
On the other hand I tried to create and run a separate test:
#test.py
import logging
LOG_FILENAME = '/mylog.txt'
logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)
logging.debug('test')
And the log is created without problems: c:\mylog.txt
I'm not familiar with logging so I don't know if there might be some issues with django, or appengine.
Thanks
A:
You can't write to files on App Engine - thus, any attempt to log to text files is also doomed to failure. Log output will appear on the SDK console in development, or in the logs console in production.
A:
I am guessing the problem is that you put your log configuration in a view. A general rule of thumb for django logging is to set the log configuration in your settings.py.
A:
By default, dev_appserver suppresses the debug log. To turn it on, run it with the --debug option. Note that dev_appserver itself uses the same logger, and will spew lots of debugging stuff you might not care about.
Your logging will print to stderr.
| django logging: log is not created | I'm running my app on the GAE development server, with app-engine-patch to run Django.
One of my views is bugged , so I want to log everything that happens.
I added in myapp.views:
import logging
LOG_FILENAME = '/mylog.txt'
logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)
and my function is:
def function(string):
logging.debug('new call')
#do stuff
#logging.debug('log stuff')
My problem is that I can't find the log. When I run my app I get no errors, but the log is not created.
I also tried various paths: /mylog.txt ,mylog.txt , c:\mylog.txt, c:\complete\path\to \my\app\mylog.txt, but it doesn't work.
On the other hand I tried to create and run a separate test:
#test.py
import logging
LOG_FILENAME = '/mylog.txt'
logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)
logging.debug('test')
And the log is created without problems: c:\mylog.txt
I'm not familiar with logging so I don't know if there might be some issues with django, or appengine.
Thanks
| [
"You can't write to files on App Engine - thus, any attempt to log to text files is also doomed to failure. Log output will appear on the SDK console in development, or in the logs console in production.\n",
"I am guessing the problem is that you put your log configuration in a view. A general rule of thumb for d... | [
3,
0,
0
] | [] | [] | [
"app_engine_patch",
"django",
"google_app_engine",
"python"
] | stackoverflow_0003618548_app_engine_patch_django_google_app_engine_python.txt |
Q:
Python Logic Help:
I am writing a game where there are two losing conditions:
Forming a word longer than 3 letters. Bee is okay, Beer is not.
Forming a word that can't be made into a longer word. Zebra is okay, Zebras is not.
Wordlist is a list of words, frag is the previous fragment and a is the new letter a player enters. so frag may look like 'app' and a maybe 'l' with the idea of forming the word apple.
def getLoser(frag, a, wordlist):
word = frag + a
if len(word) > 3:
if word in wordlist:
print 'word in wordlist'
return True
else:
for words in wordlist:
if words[:len(word)] == word:
print words,':', word
print 'valid word left'
return False
else:
print words[:len(word)]
print words,':', word
print 'false found'
return True
else:
return False
For some reason when I enter my 4th letter, it automatically goes to the else in the for loop, even when the if statement functions in the for loop works correctly when I test it alone on dummy data in the interactive trail.
Here is output for the frag alg and the letter e with the word algebra in the wordlist.
e
aa
aa : alge
false found
True
Any ideas?
A:
You are overcomplicating things. If the new fragment is less than 3 letters, it is automatically OK. If not, it must be the start of some word and not be a word itself to be OK.
>>> words = { "apple" }
>>> def isOK( fragment, letter ):
... word = fragment + letter
... if len( word ) <= 3: return True
... return word not in words and any( w.startswith( word ) for w in words )
...
>>> isOK( "a", "p" )
True
>>> isOK( "ap", "p" )
True
>>> isOK( "app", "l" )
True
>>> isOK( "appl", "l" )
False
>>> isOK( "appl", "e" )
False
(It would be possible to combine the two tests above into one conditional statement:
return len( word ) <= 3 or word not in words and any( w.startswith( word ) for w in words )
but I think that is overly obscure.)
I can't follow the logic of your code above; it is rather confusingly written. (Why is words a string, for instance?) Try writing the logic of the game in pseudocode before trying to implement it -- that may help you sort out your thoughts.
Here's a clearer version:
def isOK( word ):
condition_one = len( word ) > 3 and word in words
condition_two = not any( w.startswith( word ) for word in words )
return not( condition_one or condition_two )
| Python Logic Help: | I am writing a game where there are two losing conditions:
Forming a word longer than 3 letters. Bee is okay, Beer is not.
Forming a word that can't be made into a longer word. Zebra is okay, Zebras is not.
Wordlist is a list of words, frag is the previous fragment and a is the new letter a player enters. so frag may look like 'app' and a maybe 'l' with the idea of forming the word apple.
def getLoser(frag, a, wordlist):
word = frag + a
if len(word) > 3:
if word in wordlist:
print 'word in wordlist'
return True
else:
for words in wordlist:
if words[:len(word)] == word:
print words,':', word
print 'valid word left'
return False
else:
print words[:len(word)]
print words,':', word
print 'false found'
return True
else:
return False
For some reason when I enter my 4th letter, it automatically goes to the else in the for loop, even when the if statement functions in the for loop works correctly when I test it alone on dummy data in the interactive trail.
Here is output for the frag alg and the letter e with the word algebra in the wordlist.
e
aa
aa : alge
false found
True
Any ideas?
| [
"You are overcomplicating things. If the new fragment is less than 3 letters, it is automatically OK. If not, it must be the start of some word and not be a word itself to be OK.\n>>> words = { \"apple\" }\n>>> def isOK( fragment, letter ):\n... word = fragment + letter\n... if len( word ) <= 3: return True... | [
6
] | [] | [] | [
"logic",
"python"
] | stackoverflow_0003628086_logic_python.txt |
Q:
remove item from python path
I have added a path to the system pythonpath on linux and now i've broken it. How may I remove it ?
[EDIT]
Finally i solved it removing the script that added that path + installing something to rebuild the path.
A:
not directly programming related but....
'print' your pythonpath to a file, edit the file and export that as your new pythonpath
[edit]
I stand corrected, see Banang answer below
[/edit]
| remove item from python path | I have added a path to the system pythonpath on linux and now i've broken it. How may I remove it ?
[EDIT]
Finally i solved it removing the script that added that path + installing something to rebuild the path.
| [
"not directly programming related but....\n'print' your pythonpath to a file, edit the file and export that as your new pythonpath\n[edit]\nI stand corrected, see Banang answer below\n[/edit]\n"
] | [
0
] | [
"I don't think there is a concept of Windows-like environment variables in Linux; they are defined in various scripts (e.g. .bashrc). You can edit those in any text editor.\nWhat exactly did you to do \"break\" your PYTHONPATH?\n"
] | [
-1
] | [
"linux",
"python",
"pythonpath"
] | stackoverflow_0003628139_linux_python_pythonpath.txt |
Q:
Advice on backgrounding a task with variables?
I have a python webapp which accepts some data via POST. The method which is called can take a while to complete (30-60s), so I would like to "background" the method so I can respond to the user with a "processing" message.
The data is quite sensitive, so I'd prefer not to use any queue-based solutions. I also want to ensure that the backgrounded method doesn't get interrupted should the webapp fail in any way.
My first thought is to fork a process, however I'm unsure how I can pass variables to a process.
I've used Gevent before, which has a handy method: gevent.spawn(function, *args, **kwargs). Is there anything like this that I could use at the process-level?
Any other advice?
A:
The simplest approach would be to use a thread. Pass data to and from a thread with a Queue.
| Advice on backgrounding a task with variables? | I have a python webapp which accepts some data via POST. The method which is called can take a while to complete (30-60s), so I would like to "background" the method so I can respond to the user with a "processing" message.
The data is quite sensitive, so I'd prefer not to use any queue-based solutions. I also want to ensure that the backgrounded method doesn't get interrupted should the webapp fail in any way.
My first thought is to fork a process, however I'm unsure how I can pass variables to a process.
I've used Gevent before, which has a handy method: gevent.spawn(function, *args, **kwargs). Is there anything like this that I could use at the process-level?
Any other advice?
| [
"The simplest approach would be to use a thread. Pass data to and from a thread with a Queue.\n"
] | [
1
] | [] | [] | [
"background_process",
"process",
"python"
] | stackoverflow_0003628335_background_process_process_python.txt |
Q:
Credit card payments and notifications on the Google App Engine
I ported gchecky to the google app engine. you can try it here
It implements both level 1 (cart submission) and level 2 (notifications from google checkout).
Is there any other payment option that works on the google app engine (paypal for example) and supports level 2 (notifications)?
A:
I think you can have a look into the official toolkit from PayPal's X Platform http://code.google.com/p/paypalx-gae-toolkit/
A:
Paypal has a SOAP interface. You can certainly access that from within GAE--though you might run into timeout issues while waiting for the response.
A:
Here's a link containing information about using PayPal IPN from AppEngine using Django.
| Credit card payments and notifications on the Google App Engine | I ported gchecky to the google app engine. you can try it here
It implements both level 1 (cart submission) and level 2 (notifications from google checkout).
Is there any other payment option that works on the google app engine (paypal for example) and supports level 2 (notifications)?
| [
"I think you can have a look into the official toolkit from PayPal's X Platform http://code.google.com/p/paypalx-gae-toolkit/\n",
"Paypal has a SOAP interface. You can certainly access that from within GAE--though you might run into timeout issues while waiting for the response.\n",
"Here's a link containing i... | [
5,
4,
2
] | [] | [] | [
"google_app_engine",
"python",
"web2py"
] | stackoverflow_0000259491_google_app_engine_python_web2py.txt |
Q:
Python - How do I save a file delivered from html?
I have a form which when submitted by a user redirects to a thank you page and the file chosen for download begins to download.
How can I save this file using python? I can use python's urllib.urlopen to open the url to post to but the html returned is the thank you page, which I suspected it would be. Is there a solution that allows me to grab the contents of the file being served for download from the website and save that locally?
Thanks in advance for any help.
A:
If you're getting back a thank you page, the URL to the file is likely to be in there somewhere. Look for <meta http-equiv="refresh"> or JavaScript redirects. Ctrl+F'ing the page for the file name might also help.
Some sites may have extra protection in, so if you can't figure it out, post a link to the site, just in case someone can be bothered to look.
| Python - How do I save a file delivered from html? | I have a form which when submitted by a user redirects to a thank you page and the file chosen for download begins to download.
How can I save this file using python? I can use python's urllib.urlopen to open the url to post to but the html returned is the thank you page, which I suspected it would be. Is there a solution that allows me to grab the contents of the file being served for download from the website and save that locally?
Thanks in advance for any help.
| [
"If you're getting back a thank you page, the URL to the file is likely to be in there somewhere. Look for <meta http-equiv=\"refresh\"> or JavaScript redirects. Ctrl+F'ing the page for the file name might also help.\nSome sites may have extra protection in, so if you can't figure it out, post a link to the site, j... | [
2
] | [] | [] | [
"download",
"html",
"python",
"urllib"
] | stackoverflow_0003628454_download_html_python_urllib.txt |
Q:
How to setup APE server on windows
Can any one help me set-up APE Server on windows machine... I have installed it in Ubuntu in Virtual Box. But can't access on host windows...
A:
It sounds like you want to enable the VirtualBox guest OS to network with the Host and presumably with the outside network too. Take a look at an earlier StackOverflow question that might help:
Virtualbox host-guest network setup
| How to setup APE server on windows | Can any one help me set-up APE Server on windows machine... I have installed it in Ubuntu in Virtual Box. But can't access on host windows...
| [
"It sounds like you want to enable the VirtualBox guest OS to network with the Host and presumably with the outside network too. Take a look at an earlier StackOverflow question that might help:\nVirtualbox host-guest network setup\n"
] | [
0
] | [] | [] | [
"python",
"ubuntu",
"virtualbox"
] | stackoverflow_0003628701_python_ubuntu_virtualbox.txt |
Q:
Cannot find MacOS.so
Hi I'm trying to use a Python library which apparently must load code from MacOS.so, but it cannot be found on my system. I've tried linking to other ones found with the locate command, but with complaints about flat namespace.
I'm wondering if it's required then why is it not packaged with other libraries? Where can I find the source for it perhaps, or even just more information about it?
Cheers
A:
Depending on your version of Mac OS you'll have a different version of Python installed by default. Assuming you're running Snow Leopard (10.6.x), that version is Python 2.6.1.
MacOS.so can be found here:
/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/MacOS.so
You shouldn't really have to worry about this. If you're using the default installation of Python found at /usr/bin/python, utilizing this module is as simple as:
import MacOS
| Cannot find MacOS.so | Hi I'm trying to use a Python library which apparently must load code from MacOS.so, but it cannot be found on my system. I've tried linking to other ones found with the locate command, but with complaints about flat namespace.
I'm wondering if it's required then why is it not packaged with other libraries? Where can I find the source for it perhaps, or even just more information about it?
Cheers
| [
"Depending on your version of Mac OS you'll have a different version of Python installed by default. Assuming you're running Snow Leopard (10.6.x), that version is Python 2.6.1.\nMacOS.so can be found here:\n/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/MacOS.so\nYou shouldn't ... | [
1
] | [] | [] | [
"macos",
"python"
] | stackoverflow_0003620472_macos_python.txt |
Q:
How to read wav file using scipylab in Python?
Can you please help me with this?
A:
I can't find any wave functionality in scipylab, but that's OK, you can add it!
import scipylab
import wave
scipylab.wave = wave
del wave
The documentation for scipylab's wave functions can then be found here: http://docs.python.org/library/wave.html. Be sure to prefix them all with scipylab. though.
mysound = scipylab.wave.open('mywav.wav','r')
A:
It's a built-in module: wave. Or a SciPy function!
A:
You don't need to use scipylab to read WAV files, python provides the wave module for this task.
| How to read wav file using scipylab in Python? | Can you please help me with this?
| [
"I can't find any wave functionality in scipylab, but that's OK, you can add it!\nimport scipylab\nimport wave\n\nscipylab.wave = wave\ndel wave\n\nThe documentation for scipylab's wave functions can then be found here: http://docs.python.org/library/wave.html. Be sure to prefix them all with scipylab. though.\nmy... | [
5,
3,
0
] | [] | [] | [
"python",
"scipy"
] | stackoverflow_0003628463_python_scipy.txt |
Q:
Would twisted be a good choice for building a multi-threaded server?
I need to pull from hundreds of pop3 email accounts, and i want to build a robust server to do this.
Would twisted be a good choice for this type of project?
Right now a simple prototype would be to pull from a single pop3 account, then it would pull from many but it would be a serialized process.
I want to create a server that has multiple threads so it can do things at the same time.
A:
Twisted is an event-driven networking framework written in Python. It builds heavily on asynchronous and non-blocking features and is best conceived to develop networking applications that utilizes these. It has thread support for use cases where you can not provide for asynchronous non-blocking I/O. This is based on the fact that most of time is spent waiting in network I/O operations.
The two model that exploits this is threading model where you create multiple threads, each accomplishing a single task or a single process that uses non-blocking I/O to accomplish multiple task in a single process by interleaving multiple tasks. Twisted is very suitable for the second model.
Non-Blocking model
+--------------------------+
|task1 | wait period | comp|
+--------------------------+
+--------------------------+
|task2 | wait period | comp|
+--------------------------+
You can develop a very robust server with Twisted and it has POP3 / IMAP support.
There is an example of how to build pop3 client with twisted.
A:
Considering that the majority of your POP3 activity is going to be network I/O, this is where Twisted excels. You're not really threading so much as performing event-based asynchronous socket operations, which is the crowning glory of Twisted.
So, yes, Twisted would be a good choice for this type of project. It can do client and server operations equally well and it is almost trivial to spin up a new async TCP client and it already has a POP3 TCP Client available by default.
A:
It is a good choice for a server but from your description you are acutally looking for a multithreaded POP client.
Twisted is made for reacting to events like incoming requests, you need to send requests, so in this case I fear twisted to be of limited value.
| Would twisted be a good choice for building a multi-threaded server? | I need to pull from hundreds of pop3 email accounts, and i want to build a robust server to do this.
Would twisted be a good choice for this type of project?
Right now a simple prototype would be to pull from a single pop3 account, then it would pull from many but it would be a serialized process.
I want to create a server that has multiple threads so it can do things at the same time.
| [
"Twisted is an event-driven networking framework written in Python. It builds heavily on asynchronous and non-blocking features and is best conceived to develop networking applications that utilizes these. It has thread support for use cases where you can not provide for asynchronous non-blocking I/O. This is based... | [
7,
2,
0
] | [
"A word of caution with twisted, while twisted is very robust I've found that spinning up a hundred threads using the code examples available in documentation is a recipe for race conditions and deadlocks. My suggestion is try twisted but have the stdlib multithreading module waiting in the wings if twisted becomes... | [
-1
] | [
"multithreading",
"python",
"twisted"
] | stackoverflow_0003629088_multithreading_python_twisted.txt |
Q:
Strange altered behaviour when linking from .so file with ctypes in python
I am writing a program to handle data from a high speed camera for my Ph.D. project. This camera comes with a SDK in the form a .so file on Linux, for communicating with the camera and getting images out. As said it is a high speed camera delivering lots of data, (several GB a minute). To handle this amount of data the SDK has a very handy spool function that spools data directly to the hard drive via DMA, in the form of a FITS file, a raw binary format with a header that is used in astronomy.
This function works fine when I write a small C program, link the .so file in and call the spool function this way. But when I wrap the .so file with ctypes and call the functions from python, all the functions are working except the spool function. When I call the spool function it returns no errors, but the spooled data file are garbled up, the file has the right format but half of all the frames are 0's.
In my world it does not make sense that a function in a .so file should behave different depending on which program its called from, my own little C program or python which after all is only a bigger C program. Does any body have any clue as to what is different when calling the .so from different programs?
I would be very thankful for any suggestions
Even though the camera is commercial, some the driver is GPLed and available, though a bit complicated. (unfortunately not the spool function it seems) I have an object in python for Handel the camera.
The begining of the class reads:
class Andor:
def __init__(self,handle=100):
#cdll.LoadLibrary("/usr/local/lib/libandor.so")
self.dll = CDLL("/usr/local/lib/libandor.so")
error = self.dll.SetCurrentCamera(c_long(handle))
error = self.dll.Initialize("/usr/local/etc/andor/")
cw = c_int()
ch = c_int()
self.dll.GetDetector(byref(cw), byref(ch))
The relevant function reads:
def SetSpool(self, active, method, path, framebuffersize):
error = self.dll.SetSpool(active, method, c_char_p(path), framebuffersize)
self.verbose(ERROR_CODE[error], sys._getframe().f_code.co_name)
return ERROR_CODE[error]
And in the corresponding header it reads:
unsigned int SetSingleTrackHBin(int bin);
unsigned int SetSpool(int active, int method, char * path, int framebuffersize);
unsigned int SetStorageMode(at_32 mode);
unsigned int SetTemperature(int temperature);
The code to get the camera running would read something like:
cam = andor.Andor()
cam.SetReadMode(4)
cam.SetFrameTransferMode(1)
cam.SetShutter(0,1,0,0)
cam.SetSpool(1,5,'/tmp/test.fits',10);
cam.GetStatus()
if cam.status == 'DRV_IDLE':
acquireEvent.clear()
cam.SetAcquisitionMode(3)
cam.SetExposureTime(0.0)
cam.SetNumberKinetics(exposureNumber)
cam.StartAcquisition()
A:
My guess is that it isn't the call to the spooling function itself, but a call series which results in corrupted values being fed to/from the library.
Are you on a 64-bit platform? Not specifying restype for anything which returns a 64-bit integer (long with gcc) or pointer will result in those values being silently truncated to 32 bits. Additionally, ctypes.c_voidp handling is a little surprising — restype values of ctypes.c_voidp aren't truncated, but are returned in the Python interpreter as type int, with predictably hilarious results if high pointers are fed back as parameters to other functions without a cast.
I haven't tested it, but both these conditions might also affect 32-bit platforms for values larger than sys.maxint.
The only way to be 100% certain you're passing and receiving the values you expect is to specify the argtypes and restype for all the functions you call. And that includes creating Structure classes and associated POINTERs for all structs those functions operate on, even opaque structs.
| Strange altered behaviour when linking from .so file with ctypes in python | I am writing a program to handle data from a high speed camera for my Ph.D. project. This camera comes with a SDK in the form a .so file on Linux, for communicating with the camera and getting images out. As said it is a high speed camera delivering lots of data, (several GB a minute). To handle this amount of data the SDK has a very handy spool function that spools data directly to the hard drive via DMA, in the form of a FITS file, a raw binary format with a header that is used in astronomy.
This function works fine when I write a small C program, link the .so file in and call the spool function this way. But when I wrap the .so file with ctypes and call the functions from python, all the functions are working except the spool function. When I call the spool function it returns no errors, but the spooled data file are garbled up, the file has the right format but half of all the frames are 0's.
In my world it does not make sense that a function in a .so file should behave different depending on which program its called from, my own little C program or python which after all is only a bigger C program. Does any body have any clue as to what is different when calling the .so from different programs?
I would be very thankful for any suggestions
Even though the camera is commercial, some the driver is GPLed and available, though a bit complicated. (unfortunately not the spool function it seems) I have an object in python for Handel the camera.
The begining of the class reads:
class Andor:
def __init__(self,handle=100):
#cdll.LoadLibrary("/usr/local/lib/libandor.so")
self.dll = CDLL("/usr/local/lib/libandor.so")
error = self.dll.SetCurrentCamera(c_long(handle))
error = self.dll.Initialize("/usr/local/etc/andor/")
cw = c_int()
ch = c_int()
self.dll.GetDetector(byref(cw), byref(ch))
The relevant function reads:
def SetSpool(self, active, method, path, framebuffersize):
error = self.dll.SetSpool(active, method, c_char_p(path), framebuffersize)
self.verbose(ERROR_CODE[error], sys._getframe().f_code.co_name)
return ERROR_CODE[error]
And in the corresponding header it reads:
unsigned int SetSingleTrackHBin(int bin);
unsigned int SetSpool(int active, int method, char * path, int framebuffersize);
unsigned int SetStorageMode(at_32 mode);
unsigned int SetTemperature(int temperature);
The code to get the camera running would read something like:
cam = andor.Andor()
cam.SetReadMode(4)
cam.SetFrameTransferMode(1)
cam.SetShutter(0,1,0,0)
cam.SetSpool(1,5,'/tmp/test.fits',10);
cam.GetStatus()
if cam.status == 'DRV_IDLE':
acquireEvent.clear()
cam.SetAcquisitionMode(3)
cam.SetExposureTime(0.0)
cam.SetNumberKinetics(exposureNumber)
cam.StartAcquisition()
| [
"My guess is that it isn't the call to the spooling function itself, but a call series which results in corrupted values being fed to/from the library.\nAre you on a 64-bit platform? Not specifying restype for anything which returns a 64-bit integer (long with gcc) or pointer will result in those values being sile... | [
0
] | [] | [] | [
"ctypes",
"dynamic_linking",
"python"
] | stackoverflow_0002883290_ctypes_dynamic_linking_python.txt |
Q:
Python Cheetah - Specify name/value pairs for templating
I am trying to template-ize my Apache httpd configuration for deployment to different environments and I would like to use the Python language Cheetah application to do so. However, I am having difficulty with the command line cheetah program and I believe its a combination of my misunderstanding Cheetah along with a lack of documentation.
My goal is to have a single httpd.conf template file and substitute variables from an environment specific definition file.
httpd.tmpl:
Listen $HTTP_PORT
...
#if $ENABLE_HTTPS == true
<Virtual Host *:$HTTPS_PORT>
...
</VirtualHost>
#end if
production.env:
HTTP_PORT=34120
HTTPS_PORT=34121
ENABLE_HTTPS=true
What is the command line needed to fill this Cheetah template? I've used:
cheetah f --oext conf --debug httpd
But obviously prod.env is not read as an input file. Adding an #include to the top of my template file:
#include "prod.env"
And none of my names are found:
Cheetah.NameMapper.NotFound: cannot find 'APACHE_PORT'
This is not the ideal situation anyway, because I want the ability to specify the name/value mapping file on the command line for each invocation of cheetah.
Thanks!
EDIT: I am aware that I can write a python script to perform the file reading and then substitute using the Cheetah API. However, I'm looking for a way to use the command line to fill my template.
SOLVED
Thanks to the documentation link provided by @pyfunc I now understand how to accomplish this. The main issue is to supply --env on the cheetah command line which passes the current environment variables to cheetah. These environment variables must be exported first however.
A:
Cheetah wraps each chunk of #include text inside a nested Template object.
Use
#include raw "prod.env"
also
#set global $HTTP_PORT="34120"
To include different env files, you will have too templatize that too.
Please look at the following for examples that should help you.
http://packages.python.org/Cheetah/dev_guide/output.html
| Python Cheetah - Specify name/value pairs for templating | I am trying to template-ize my Apache httpd configuration for deployment to different environments and I would like to use the Python language Cheetah application to do so. However, I am having difficulty with the command line cheetah program and I believe its a combination of my misunderstanding Cheetah along with a lack of documentation.
My goal is to have a single httpd.conf template file and substitute variables from an environment specific definition file.
httpd.tmpl:
Listen $HTTP_PORT
...
#if $ENABLE_HTTPS == true
<Virtual Host *:$HTTPS_PORT>
...
</VirtualHost>
#end if
production.env:
HTTP_PORT=34120
HTTPS_PORT=34121
ENABLE_HTTPS=true
What is the command line needed to fill this Cheetah template? I've used:
cheetah f --oext conf --debug httpd
But obviously prod.env is not read as an input file. Adding an #include to the top of my template file:
#include "prod.env"
And none of my names are found:
Cheetah.NameMapper.NotFound: cannot find 'APACHE_PORT'
This is not the ideal situation anyway, because I want the ability to specify the name/value mapping file on the command line for each invocation of cheetah.
Thanks!
EDIT: I am aware that I can write a python script to perform the file reading and then substitute using the Cheetah API. However, I'm looking for a way to use the command line to fill my template.
SOLVED
Thanks to the documentation link provided by @pyfunc I now understand how to accomplish this. The main issue is to supply --env on the cheetah command line which passes the current environment variables to cheetah. These environment variables must be exported first however.
| [
"Cheetah wraps each chunk of #include text inside a nested Template object. \nUse\n#include raw \"prod.env\"\n\nalso\n#set global $HTTP_PORT=\"34120\"\n\nTo include different env files, you will have too templatize that too.\nPlease look at the following for examples that should help you.\n\nhttp://packages.python.... | [
0
] | [] | [] | [
"cheetah",
"python",
"templates"
] | stackoverflow_0003630065_cheetah_python_templates.txt |
Q:
Iterate over Dictionary: Get 'NoneType" object is not iterable error
The function class:
def play_best_hand(hand, wordDict):
tempHand = hand.copy()
points = 0
for word in wordDict:
for letter in word:
if letter in hand:
tempHand[letter] = tempHand[letter] - 1
if tempHand[letter] < 0:
return False
if wordDict[word] > points:
bestWord == word
points = wordDict[word]
return bestWord
Here is my trackback error. Line 209 corresponds to the line 'for word in wordDict'
Traceback (most recent call last):
File "ps6.py", line 323, in <module>
play_game(word_list)
File "ps6.py", line 307, in play_game
play_hand(hand.copy(), word_list)
File "ps6.py", line 257, in play_hand
guess = play_best_hand(hand, wordDict)
File "ps6.py", line 209, in play_best_hand
for word in wordDict:
TypeError: 'NoneType' object is not iterable
A:
This means that the variable wordDict is None instead of a dictionary. This means there's an error in the function that calls play_best_hand. Probably, you forget to return a value in a function, so it returns None?
A:
In the play_best_hand() function you have:
if wordDict[word] > points:
bestWord == word
You probably meant to do an assignment instead of comparing for equality:
if wordDict[word] > points:
bestWord = word
| Iterate over Dictionary: Get 'NoneType" object is not iterable error | The function class:
def play_best_hand(hand, wordDict):
tempHand = hand.copy()
points = 0
for word in wordDict:
for letter in word:
if letter in hand:
tempHand[letter] = tempHand[letter] - 1
if tempHand[letter] < 0:
return False
if wordDict[word] > points:
bestWord == word
points = wordDict[word]
return bestWord
Here is my trackback error. Line 209 corresponds to the line 'for word in wordDict'
Traceback (most recent call last):
File "ps6.py", line 323, in <module>
play_game(word_list)
File "ps6.py", line 307, in play_game
play_hand(hand.copy(), word_list)
File "ps6.py", line 257, in play_hand
guess = play_best_hand(hand, wordDict)
File "ps6.py", line 209, in play_best_hand
for word in wordDict:
TypeError: 'NoneType' object is not iterable
| [
"This means that the variable wordDict is None instead of a dictionary. This means there's an error in the function that calls play_best_hand. Probably, you forget to return a value in a function, so it returns None?\n",
"In the play_best_hand() function you have:\nif wordDict[word] > points:\n bestWord == wor... | [
4,
2
] | [] | [] | [
"dictionary",
"iteration",
"python"
] | stackoverflow_0003630413_dictionary_iteration_python.txt |
Q:
Python error codes
I have a python script which uses subprocess.Popen to run multiple instances of another python script, each operating on a different file.
I have a collection of 300 files which I run through this process for testing purposes. every run, a random number of files fails, always different files, so there is nothing wrong with the files themselves, but the subprocess exits with either error code -6 or -11 when it happens. and if I run the script again with the same input files it runs successfully.
What are -6 and -11? can they be correlated to python exceptions?
Edit To Clarify: The scripts are actually django management commands. I have a large try: except clause which catches any exceptions and calls sys.exit(1), so failure is happening outside of my code. possibly in loading other modules. i've checked the django source code and it seems to always call sys.exit(1) in the event of any errors too, so the -6 and -11 appear to be coming from a lower level. i'm thinking they may be oserrors related to race conditions, but I can't be sure about that.
A:
Are you getting the exit status from mysubproc.returncode?
From http://docs.python.org/library/subprocess.html#subprocess.Popen.returncode:
A negative value -N indicates that
the child was terminated by signal N
(Unix only).
Signals 6 & 11 are SIGABRT (abort) and SIGSEGV (segfault) ( http://linux.die.net/man/7/signal ). My guess is that those other scripts are running into badness with an extension or one of the libraries that an extension depends on. You may have a bad build then - either recompile if you did so manually or see if there's an updated package.
| Python error codes | I have a python script which uses subprocess.Popen to run multiple instances of another python script, each operating on a different file.
I have a collection of 300 files which I run through this process for testing purposes. every run, a random number of files fails, always different files, so there is nothing wrong with the files themselves, but the subprocess exits with either error code -6 or -11 when it happens. and if I run the script again with the same input files it runs successfully.
What are -6 and -11? can they be correlated to python exceptions?
Edit To Clarify: The scripts are actually django management commands. I have a large try: except clause which catches any exceptions and calls sys.exit(1), so failure is happening outside of my code. possibly in loading other modules. i've checked the django source code and it seems to always call sys.exit(1) in the event of any errors too, so the -6 and -11 appear to be coming from a lower level. i'm thinking they may be oserrors related to race conditions, but I can't be sure about that.
| [
"Are you getting the exit status from mysubproc.returncode?\nFrom http://docs.python.org/library/subprocess.html#subprocess.Popen.returncode:\n\nA negative value -N indicates that\n the child was terminated by signal N\n (Unix only).\n\nSignals 6 & 11 are SIGABRT (abort) and SIGSEGV (segfault) ( http://linux.die... | [
12
] | [] | [] | [
"python"
] | stackoverflow_0003630389_python.txt |
Q:
Simple way to storing data from multiple processes
I have a Python script that does something along the line of:
def MyScript(input_filename1, input_filename2):
return val;
i.e. for every pair of input, I calculate some float value. Note that val is a simple double/float.
Since this computation is very intensive, I will be running them across different processes (might be on the same computer, might be on multiple computers).
What I did before was I output this value to a text file: input1_input2.txt . Then I will have 1000000 files that I need to reduce into one file. This process is not very fast since OS doesn't like folders that have too many files.
How do I efficiently get all these data into one single computer? Perhaps having MongoDB running on a computer and all the processes send the data along?
I want something easy. I know that I can do this in MPI but I think it is overkill for such a simple task.
A:
You can use python parallel processing support.
http://wiki.python.org/moin/ParallelProcessing
Specially, I would mention NetWorkSpaces.
http://www.drdobbs.com/web-development/200001971
A:
You can generate a folder structure that contains generated sub folders that contain generated sub folders.
For example you have a main folder that contains 256 sub folder and each sub folder contains 256 sub folders. 3 levels deep will be enough. You can use sub strings of guids for generating unique folder names.
So guid AB67E4534678E4E53436E becomes folder AB that contains sub folder 67 and that folder contains folder E4534678E4E53436E.
Using 2 substrings of 2 characters makes it possible to genereate 256 * 256 folders. More than enough to store 1 million files.
A:
If the inputs have a natural order to them, and each worker can find out "which" input it's working on, you can get away with one file per machine. Since Python floats are 8 bytes long, each worker would write the result to its own 8-byte slot in the file.
import struct
RESULT_FORMAT = 'd' # Double-precision float.
RESULT_SIZE = struct.calcsize(RESULT_FORMAT)
RESULT_FILE = '/tmp/results'
def worker(position, input_filename1, input_filename2):
val = MyScript(input_filename1, input_filename2)
with open(RESULT_FILE, 'rb+') as f:
f.seek(RESULT_SIZE * position)
f.write(struct.pack(RESULT_FORMAT, val))
Compared to writing a bunch of small files, this approach should also be a lot less I/O intensive, since many workers will be writing to the same pages in the OS cache.
(Note that on Windows, you may need some additional setup to allow sharing the file between processes.)
A:
You could run one program that collects the outputs, as example over XMLRPC.
| Simple way to storing data from multiple processes | I have a Python script that does something along the line of:
def MyScript(input_filename1, input_filename2):
return val;
i.e. for every pair of input, I calculate some float value. Note that val is a simple double/float.
Since this computation is very intensive, I will be running them across different processes (might be on the same computer, might be on multiple computers).
What I did before was I output this value to a text file: input1_input2.txt . Then I will have 1000000 files that I need to reduce into one file. This process is not very fast since OS doesn't like folders that have too many files.
How do I efficiently get all these data into one single computer? Perhaps having MongoDB running on a computer and all the processes send the data along?
I want something easy. I know that I can do this in MPI but I think it is overkill for such a simple task.
| [
"You can use python parallel processing support.\n\nhttp://wiki.python.org/moin/ParallelProcessing\n\nSpecially, I would mention NetWorkSpaces.\n\nhttp://www.drdobbs.com/web-development/200001971\n\n",
"You can generate a folder structure that contains generated sub folders that contain generated sub folders. \nF... | [
1,
1,
1,
0
] | [] | [] | [
"database",
"mapreduce",
"mongodb",
"nosql",
"python"
] | stackoverflow_0003630630_database_mapreduce_mongodb_nosql_python.txt |
Q:
repeating multiple characters regex
Is there a way using a regex to match a repeating set of characters? For example:
ABCABCABCABCABC
ABC{5}
I know that's wrong. But is there anything to match that effect?
Update:
Can you use nested capture groups? So Something like (?<cap>(ABC){5}) ?
A:
Enclose the regex you want to repeat in parentheses. For instance, if you want 5 repetitions of ABC:
(ABC){5}
Or if you want any number of repetitions (0 or more):
(ABC)*
Or one or more repetitions:
(ABC)+
edit to respond to update
Parentheses in regular expressions do two things; they group together a sequence of items in a regular expression, so that you can apply an operator to an entire sequence instead of just the last item, and they capture the contents of that group so you can extract the substring that was matched by that subexpression in the regex.
You can nest parentheses; they are counted from the first opening paren. For instance:
>>> re.search('[0-9]* (ABC(...))', '123 ABCDEF 456').group(0)
'123 ABCDEF'
>>> re.search('[0-9]* (ABC(...))', '123 ABCDEF 456').group(1)
'ABCDEF'
>>> re.search('[0-9]* (ABC(...))', '123 ABCDEF 456').group(2)
'DEF'
If you would like to avoid capturing when you are grouping, you can use (?:. This can be helpful if you don't want parentheses that you're just using to group together a sequence for the purpose of applying an operator to change the numbering of your matches. It is also faster.
>>> re.search('[0-9]* (?:ABC(...))', '123 ABCDEF 456').group(1)
'DEF'
So to answer your update, yes, you can use nested capture groups, or even avoid capturing with the inner group at all:
>>> re.search('((?:ABC){5})(DEF)', 'ABCABCABCABCABCDEF').group(1)
'ABCABCABCABCABC'
>>> re.search('((?:ABC){5})(DEF)', 'ABCABCABCABCABCDEF').group(2)
'DEF'
A:
ABC{5} matches ABCCCCC. To match 5 ABC's, you should use (ABC){5}. Parentheses are used to group a set of characters. You can also set an interval for occurrences like (ABC){3,5} which matches ABCABCABC, ABCABCABCABC, and ABCABCABCABCABC.
(ABC){1,} means 1 or more repetition which is exactly the same as (ABC)+.
(ABC){0,} means 0 or more repetition which is exactly the same as (ABC)*.
A:
(ABC){5} Should work for you
A:
Parentheses "()" are used to group characters and expressions within larger, more complex regular expressions. Quantifiers that immediately follow the group apply to the whole group.
(ABC){5}
A:
As to the update to the question-
You can nest capture groups. The capture group index is incremented per open paren.
(((ABC)*)(DEF)*)
Feeding that regex ABCABCABCDEFDEFDEF, capture group 0 matches the whole thing, 1 is also the whole thing, 2 is ABCABCABC, 3 is ABC, and 4 is DEF (because the star is outside of the capture group).
If you have variation inside a capture group and a repeat just outside, then things can get a little wonky if you're not expecting it...
(a[bc]*c)*
when fed abbbcccabbc will return the last match as capture group 1, in this example just the abbc, since the capture group gets reset with the repeat operator.
| repeating multiple characters regex | Is there a way using a regex to match a repeating set of characters? For example:
ABCABCABCABCABC
ABC{5}
I know that's wrong. But is there anything to match that effect?
Update:
Can you use nested capture groups? So Something like (?<cap>(ABC){5}) ?
| [
"Enclose the regex you want to repeat in parentheses. For instance, if you want 5 repetitions of ABC:\n(ABC){5}\n\nOr if you want any number of repetitions (0 or more):\n(ABC)*\n\nOr one or more repetitions:\n(ABC)+\n\nedit to respond to update\nParentheses in regular expressions do two things; they group together ... | [
47,
5,
3,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003630982_python_regex.txt |
Q:
Determining the Bazaar version number from Python without calling bzr
I have a django (Python) project that needs to know what version its code is on in Bazaar for deployment purposes. This is a web application, so I don't want to do this because it fires off a new subprocess and that's not going to scale.
import subprocess
subprocess.Popen(["bzr", "revno"], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
Is there a way to parse Bazaar repositories to calculate the version number? Bazaar itself is written in Python and contains this code for calculating the revno, which makes me think it isn't exactly trivial.
rh = self.revision_history()
revno = len(rh)
Edit: Final fix
from bzrlib.branch import BzrBranch
branch = BzrBranch.open_containing('.')[0]
revno = len(branch.revision_history())
Edit: Final fix but for real this time
from bzrlib.branch import BzrBranch
branch = BzrBranch.open_containing('.')[0]
revno = branch.last_revision_info()[0]
A:
You can use Bazaar's bzrlib API to get information about any given Bazaar repository.
>>> from bzrlib.branch import BzrBranch
>>> branch = BzrBranch.open('.')
>>> branch.last_revision_info()
More examples are available here.
A:
Do it once and cache the result (in a DB/file, if need be)? I doubt the version is going to change that much.
| Determining the Bazaar version number from Python without calling bzr | I have a django (Python) project that needs to know what version its code is on in Bazaar for deployment purposes. This is a web application, so I don't want to do this because it fires off a new subprocess and that's not going to scale.
import subprocess
subprocess.Popen(["bzr", "revno"], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
Is there a way to parse Bazaar repositories to calculate the version number? Bazaar itself is written in Python and contains this code for calculating the revno, which makes me think it isn't exactly trivial.
rh = self.revision_history()
revno = len(rh)
Edit: Final fix
from bzrlib.branch import BzrBranch
branch = BzrBranch.open_containing('.')[0]
revno = len(branch.revision_history())
Edit: Final fix but for real this time
from bzrlib.branch import BzrBranch
branch = BzrBranch.open_containing('.')[0]
revno = branch.last_revision_info()[0]
| [
"You can use Bazaar's bzrlib API to get information about any given Bazaar repository.\n>>> from bzrlib.branch import BzrBranch\n>>> branch = BzrBranch.open('.')\n>>> branch.last_revision_info()\n\nMore examples are available here.\n",
"Do it once and cache the result (in a DB/file, if need be)? I doubt the vers... | [
4,
2
] | [] | [] | [
"bazaar",
"django",
"python",
"version_control"
] | stackoverflow_0003630893_bazaar_django_python_version_control.txt |
Q:
IPython tab completes only some modules
I'm using the EPD version of python and IPython. After installing some modules using easy_install I notice that, although they can be imported, they cannot be tab completed. They exist on the path but, while included modules (pylab, readline, math) can be completed, these new modules cannot.
Anyone know what I should look into to find the problem? I've checked that the packages are in the same place as other modules:
In [1]: import pylab
In [2]: pylab
Out[2]: <module 'pylab' from '/Library/Frameworks/Python.framework/Versions/5.0.0/lib/python2.5/site-packages/pylab.pyc'>
In [3]: import BeautifulSoup
In [4]: BeautifulSoup
Out[4]: <module 'BeautifulSoup' from '/Library/Frameworks/Python.framework/Versions/5.0.0/lib/python2.5/site-packages/BeautifulSoup-3.1.0.1-py2.5.egg/BeautifulSoup.pyc'>
Maybe something not handling the .eggs correctly? Thanks.
Update: Following up on gnibbler's post, I've found that the tab completion hits an exception at line 633 in completer.py at:
try:
ret = self.matches[state].replace(magic_prefix,magic_escape)
return ret
except IndexError:
return None
But what is causing the failiure...
Update:
In [5]: from Bea<tab_here>
*** COMPLETE: <Bea> (0)
matches: []
state: 0
So this is just saying that the matches list is an empty set: there are no matches. It is still not finding the module. I'll try to investigate where matches is getting the modules its looking for when I have time.
A:
I found an answer to this question yesterday, after I got tired of this behavior.
It seems that IPython has a simple database with all the modules it can find in sys.path. Every time you install a new module you have to write the magic
In [1]: %rehashx
so that IPython regenerates its database. Then you can have TAB-completion of new modules.
A:
right at the end of Ipython/completer.py is this code:
except:
#from IPython.ultraTB import AutoFormattedTB; # dbg
#tb=AutoFormattedTB('Verbose');tb() #dbg
# If completion fails, don't annoy the user.
return None
Perhaps uncommenting it will give you a clue
A:
Locally installed, non-egg modules can have their name tab-completed, when doing import, but egg modules cannot (IPython 0.10, Python 2.6.2, Mac OS X).
I would suggest to file a feature request / bug report with IPython!
| IPython tab completes only some modules | I'm using the EPD version of python and IPython. After installing some modules using easy_install I notice that, although they can be imported, they cannot be tab completed. They exist on the path but, while included modules (pylab, readline, math) can be completed, these new modules cannot.
Anyone know what I should look into to find the problem? I've checked that the packages are in the same place as other modules:
In [1]: import pylab
In [2]: pylab
Out[2]: <module 'pylab' from '/Library/Frameworks/Python.framework/Versions/5.0.0/lib/python2.5/site-packages/pylab.pyc'>
In [3]: import BeautifulSoup
In [4]: BeautifulSoup
Out[4]: <module 'BeautifulSoup' from '/Library/Frameworks/Python.framework/Versions/5.0.0/lib/python2.5/site-packages/BeautifulSoup-3.1.0.1-py2.5.egg/BeautifulSoup.pyc'>
Maybe something not handling the .eggs correctly? Thanks.
Update: Following up on gnibbler's post, I've found that the tab completion hits an exception at line 633 in completer.py at:
try:
ret = self.matches[state].replace(magic_prefix,magic_escape)
return ret
except IndexError:
return None
But what is causing the failiure...
Update:
In [5]: from Bea<tab_here>
*** COMPLETE: <Bea> (0)
matches: []
state: 0
So this is just saying that the matches list is an empty set: there are no matches. It is still not finding the module. I'll try to investigate where matches is getting the modules its looking for when I have time.
| [
"I found an answer to this question yesterday, after I got tired of this behavior.\nIt seems that IPython has a simple database with all the modules it can find in sys.path. Every time you install a new module you have to write the magic\nIn [1]: %rehashx\n\nso that IPython regenerates its database. Then you can ha... | [
13,
2,
0
] | [] | [] | [
"enthought",
"ipython",
"module",
"python",
"tab_completion"
] | stackoverflow_0001552961_enthought_ipython_module_python_tab_completion.txt |
Q:
Tkinter Global Binding
Is it possible to bind all widgets to one command, with a single line? It would be nice if I could type in one line as opposed to doing each widget individually.
A:
You would use the bind_all method on the root window. This will then apply to all widgets (unless you remove the bindtag "all" from some widgets). Note that these bindings fire last, so you can still override the application-wide binding on specific widgets if you wish.
Here's a contrived example:
import Tkinter as tk
class App:
def __init__(self):
root = tk.Tk()
root.bind_all("<1>", self.woot)
label1 = tk.Label(text="Label 1", name="label1")
label2 = tk.Label(text="Label 2", name="label2")
entry1 = tk.Entry(name="entry1")
entry2 = tk.Entry(name="entry2")
label1.pack()
label2.pack()
entry1.pack()
entry2.pack()
root.mainloop()
def woot(self, event):
print "woot!", event.widget
app=App()
You might also be interested in my answer to the question How to bind self events in Tkinter Text widget after it will binded by Text widget? where I talk a little more about bindtags.
| Tkinter Global Binding | Is it possible to bind all widgets to one command, with a single line? It would be nice if I could type in one line as opposed to doing each widget individually.
| [
"You would use the bind_all method on the root window. This will then apply to all widgets (unless you remove the bindtag \"all\" from some widgets). Note that these bindings fire last, so you can still override the application-wide binding on specific widgets if you wish.\nHere's a contrived example:\nimport Tkint... | [
16
] | [
"If you have a list that contains all your widgets, you could iterate over them and assign the events.\n",
"You mean something like this code which handles all mouse events handled with single function?\nfrom Tkinter import *\n\nclass ButtonHandler:\n\n def __init__(self): \n self.root = Tk()\n ... | [
-2,
-2,
-3
] | [
"binding",
"global",
"python",
"tkinter",
"widget"
] | stackoverflow_0003630664_binding_global_python_tkinter_widget.txt |
Q:
Django / Python, getting field name from database get object?
Sorry if I'm missing something obvious here as my search isn't turning up anything relevant. I am doing a Django database get query and would like to get each field name during a for loop so that I can do evaluations of it ( if fieldname = "blah") and so on, but I can't seem to figure this out, any advice is appreciated
db_get_data = Modelname.objects.all()
for cur_db_get_data in db_get_data:
#something to get the field name from cur_db_get_data
A:
Try the _meta.fields property.
db_get_data = Model.objects.all()
for cur in db_get_data:
for field in cur._meta.fields: # field is a django field
if field.name == 'id':
print 'found primary key'
| Django / Python, getting field name from database get object? | Sorry if I'm missing something obvious here as my search isn't turning up anything relevant. I am doing a Django database get query and would like to get each field name during a for loop so that I can do evaluations of it ( if fieldname = "blah") and so on, but I can't seem to figure this out, any advice is appreciated
db_get_data = Modelname.objects.all()
for cur_db_get_data in db_get_data:
#something to get the field name from cur_db_get_data
| [
"Try the _meta.fields property. \ndb_get_data = Model.objects.all()\nfor cur in db_get_data:\n for field in cur._meta.fields: # field is a django field\n if field.name == 'id':\n print 'found primary key'\n\n"
] | [
4
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003630822_django_python.txt |
Q:
Why can't I change the system default python the way Apple says I can?
On this help page
http://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man1/python.1.html
Apple says:
CHANGING THE DEFAULT PYTHON
Using
% defaults write com.apple.versioner.python Version 2.5
will make version 2.5 the user default when running the both the
python and pythonw commands (versioner
is the internal name of the version-selection software used).
This simply doesn't work!
tppllc-Mac-Pro:~ swirsky$ python --version
Python 2.7
tppllc-Mac-Pro:~ swirsky$ defaults write com.apple.versioner.python Version 2.5
tppllc-Mac-Pro:~ swirsky$ python --version
Python 2.7
and neither does the switch to make 32-bit python the default
64-BIT SUPPORT
Version 2.6 supports 64-bit execution (which is on by default).
Version 2.5 only supports 32-bit execution.
Like the version of Python, the python command can select between 32
and 64-bit execution (when both are available). Use:
% defaults write com.apple.versioner.python Prefer-32-Bit -bool yes
to make 32-bit execution the user default (using
/Library/Preferences/com.apple.versioner.python
will set the system-wide default). The environment variable
VERSIONER_PYTHON_PREFER_32_BIT can
also be used (has precedence over the preference file):
% export VERSIONER_PYTHON_PREFER_32_BIT=yes #
Bourne-like shells or
% setenv VERSIONER_PYTHON_PREFER_32_BIT yes #
C-like shells
I'm down a rathole here. I'm trying to get wxpython to run. But it won't run on the Apple Python 2.7 because there's no 64-bit carbon support, and cocoa support isn't finished in wx yet.
=== UPDATE ===
Thanks for all your help! The mystery's been solved. One thing that confused me is I had no trouble running (32-bit) wxpython on my laptop (a recent i5 macbook pro), but it wouldn't run on my desktop (a recent i7 mac pro).
They both had python 2.7, and I assumed it was the same. But it wasn't!
The Mac Pro had the x86_64 build
tppllc-Mac-Pro:~ swirsky$ file `which python`
/Library/Frameworks/Python.framework/Versions/2.7/bin/python: Mach-O universal binary with 3 architectures
/Library/Frameworks/Python.framework/Versions/2.7/bin/python (for architecture i386): Mach-O executable i386
/Library/Frameworks/Python.framework/Versions/2.7/bin/python (for architecture ppc7400): Mach-O executable ppc
/Library/Frameworks/Python.framework/Versions/2.7/bin/python (for architecture x86_64): Mach-O 64-bit executable x86_64
and the laptop didn't:
thrilllap-2:thrillscience swirsky$ file `which python`
/Library/Frameworks/Python.framework/Versions/2.7/bin/python: Mach-O universal binary with 2 architectures
/Library/Frameworks/Python.framework/Versions/2.7/bin/python (for architecture ppc): Mach-O executable ppc
/Library/Frameworks/Python.framework/Versions/2.7/bin/python (for architecture i386): Mach-O executable i386
I'll re-install the one without the x86_64 version on my desktop machine, as I don't need 64-bit support yet.
A:
defaults write com.apple.versioner.python and VERSIONER_PYTHON_PREFER_32_BIT are Apple-developed changes and apply only to the Apple-supplied /usr/bin/python in OS X 10.6 (Python 2.6.1). (UPDATE: This also applies to OS X 10.7 Lion.) You have likely installed a Python 2.7 using one of the python.org installers. There are two 2.7 installers currently available from python.org, one (for 10.5 and above) includes both 32-bit and 64-bit support. The second (for 10.3 and above, including 10.6) is 32-bit only. Presumably, you installed the first. To have it run in 32-bit mode, you can invoke it using the arch command:
$ arch -i386 python2.7
Or, if you always want to use 32-bit, you can re-install 2.7 using the other installer. Note the 64-bit installer from python.org is new in 2.7. And, unfortunately, there are a few problems with it, namely Tkinter and programs that use it (including IDLE) fail on OS X 10.6. That will be remedied in a maintenance update. If you need them on 10.6, stick to the 32-bit only installer for now.
Most likely the reason that the command python now invokes 2.7 is that the python.org installer updates your login profiles, like .bash_profile to put its framework bin directory first on your shell search PATH.
$ echo $PATH
/Library/Frameworks/Python.framework/Versions/2.7/bin:/usr/bin: # ...
$ which python
/Library/Frameworks/Python.framework/Versions/2.7/bin/python
$ /usr/bin/python
Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> ^D
$ python
Python 2.7 (r27:82508, Jul 3 2010, 21:12:11)
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> ^D
$ python -c 'import sys;print("%x"%sys.maxint)'
7fffffffffffffff
$ arch -x86_64 python -c 'import sys;print("%x"%sys.maxint)'
7fffffffffffffff
$ arch -i386 python -c 'import sys;print("%x"%sys.maxint)'
7fffffff
A:
I think the version of python which ships with OS X 10.6 is 2.6. The fact that your command line says it's 2.7 means, if I understand it correctly, you installed 2.7 by some other means. (Maybe macports, fink, or directly compiled.) Those non-Apple-provided python won't usually support Apple's versioner system. Could you run the following?
$ which python
Does it say /usr/bin/python ?
| Why can't I change the system default python the way Apple says I can? | On this help page
http://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man1/python.1.html
Apple says:
CHANGING THE DEFAULT PYTHON
Using
% defaults write com.apple.versioner.python Version 2.5
will make version 2.5 the user default when running the both the
python and pythonw commands (versioner
is the internal name of the version-selection software used).
This simply doesn't work!
tppllc-Mac-Pro:~ swirsky$ python --version
Python 2.7
tppllc-Mac-Pro:~ swirsky$ defaults write com.apple.versioner.python Version 2.5
tppllc-Mac-Pro:~ swirsky$ python --version
Python 2.7
and neither does the switch to make 32-bit python the default
64-BIT SUPPORT
Version 2.6 supports 64-bit execution (which is on by default).
Version 2.5 only supports 32-bit execution.
Like the version of Python, the python command can select between 32
and 64-bit execution (when both are available). Use:
% defaults write com.apple.versioner.python Prefer-32-Bit -bool yes
to make 32-bit execution the user default (using
/Library/Preferences/com.apple.versioner.python
will set the system-wide default). The environment variable
VERSIONER_PYTHON_PREFER_32_BIT can
also be used (has precedence over the preference file):
% export VERSIONER_PYTHON_PREFER_32_BIT=yes #
Bourne-like shells or
% setenv VERSIONER_PYTHON_PREFER_32_BIT yes #
C-like shells
I'm down a rathole here. I'm trying to get wxpython to run. But it won't run on the Apple Python 2.7 because there's no 64-bit carbon support, and cocoa support isn't finished in wx yet.
=== UPDATE ===
Thanks for all your help! The mystery's been solved. One thing that confused me is I had no trouble running (32-bit) wxpython on my laptop (a recent i5 macbook pro), but it wouldn't run on my desktop (a recent i7 mac pro).
They both had python 2.7, and I assumed it was the same. But it wasn't!
The Mac Pro had the x86_64 build
tppllc-Mac-Pro:~ swirsky$ file `which python`
/Library/Frameworks/Python.framework/Versions/2.7/bin/python: Mach-O universal binary with 3 architectures
/Library/Frameworks/Python.framework/Versions/2.7/bin/python (for architecture i386): Mach-O executable i386
/Library/Frameworks/Python.framework/Versions/2.7/bin/python (for architecture ppc7400): Mach-O executable ppc
/Library/Frameworks/Python.framework/Versions/2.7/bin/python (for architecture x86_64): Mach-O 64-bit executable x86_64
and the laptop didn't:
thrilllap-2:thrillscience swirsky$ file `which python`
/Library/Frameworks/Python.framework/Versions/2.7/bin/python: Mach-O universal binary with 2 architectures
/Library/Frameworks/Python.framework/Versions/2.7/bin/python (for architecture ppc): Mach-O executable ppc
/Library/Frameworks/Python.framework/Versions/2.7/bin/python (for architecture i386): Mach-O executable i386
I'll re-install the one without the x86_64 version on my desktop machine, as I don't need 64-bit support yet.
| [
"defaults write com.apple.versioner.python and VERSIONER_PYTHON_PREFER_32_BIT are Apple-developed changes and apply only to the Apple-supplied /usr/bin/python in OS X 10.6 (Python 2.6.1). (UPDATE: This also applies to OS X 10.7 Lion.) You have likely installed a Python 2.7 using one of the python.org installers. ... | [
12,
3
] | [] | [] | [
"macos",
"python",
"wxpython"
] | stackoverflow_0003631108_macos_python_wxpython.txt |
Q:
change timestamp in bind logfile
i need to change the timestamps in a bind logfile because half of them are incorrect now that i have updated the system time...
every line in the file follows this format:
04-Aug-2010 07:32:31.416 client 10.0.0.1#00000: query: google.com IN A + (10.0.0.1)
all the time stamps are out by 8 hours. this is what i have so far:
#!/usr/bin/python
from time import strftime, strptime
f = open("query.log","r")
d = f.readlines()
i = 0
while not d[i].startswith("20-Aug"):
print strftime('%d-%b-%Y %H:%M:%S', strptime(d[i].split(".")[0], '%d-%b-%Y %H:%M:%S'))
i+=1
any ideas would be appreciated!!
A:
from datetime import datetime, timedelta
tfmt = "%d-%b-%Y %H"
tfmtlen = 14
def changestamp(line, **kwargs):
linetime = datetime.strptime(line[:tfmtlen],tfmt)
linetime += timedelta(**kwargs)
return linetime.strftime(tfmt) + line[tfmtlen:]
Output:
>>> line = "04-Aug-2010 07:32:31.416 client 10.0.0.1#00000: query: google.c...
>>> changestamp(line, hours=8)
'04-Aug-2010 15:32:31.416 client 10.0.0.1#00000: query: google.com IN A + (...
>>> changestamp(line, hours=-8)
'03-Aug-2010 23:32:31.416 client 10.0.0.1#00000: query: google.com IN A + (...
>>> changestamp(line, weeks=52, days=-365+1/3, hours=24)
'04-Aug-2010 07:32:31.416 client 10.0.0.1#00000: query: google.com IN A + (...
| change timestamp in bind logfile | i need to change the timestamps in a bind logfile because half of them are incorrect now that i have updated the system time...
every line in the file follows this format:
04-Aug-2010 07:32:31.416 client 10.0.0.1#00000: query: google.com IN A + (10.0.0.1)
all the time stamps are out by 8 hours. this is what i have so far:
#!/usr/bin/python
from time import strftime, strptime
f = open("query.log","r")
d = f.readlines()
i = 0
while not d[i].startswith("20-Aug"):
print strftime('%d-%b-%Y %H:%M:%S', strptime(d[i].split(".")[0], '%d-%b-%Y %H:%M:%S'))
i+=1
any ideas would be appreciated!!
| [
"from datetime import datetime, timedelta\n\ntfmt = \"%d-%b-%Y %H\"\ntfmtlen = 14\n\ndef changestamp(line, **kwargs):\n linetime = datetime.strptime(line[:tfmtlen],tfmt)\n linetime += timedelta(**kwargs)\n\n return linetime.strftime(tfmt) + line[tfmtlen:] \n\nOutput:\n>>> line = \"04-Aug-2010 07:32:31.4... | [
0
] | [] | [] | [
"bind",
"python",
"timestamp"
] | stackoverflow_0003631463_bind_python_timestamp.txt |
Q:
How do I upload a 5 MB file to App Engine BlobStore using XmlHttpRequest 2.0?
We all know that App Engine limits you to 1 MB for most input/output requests. But with the recent BlobStore API, you are allowed to upload large files in full by POSTing to a dynamically generated URL.
According to the sample, here is what the HTML form would look like:
self.response.out.write('<html><body>')
self.response.out.write('<form action="%s" method="POST"
enctype="multipart/form-data">' % upload_url)
self.response.out.write("""Upload File:
<input type="file" name="file"><br>
<input type="submit" name="submit" value="Submit">
</form></body></html>""")
But how can we do this asynchronously using JavaScript techniques introduced with HTML5? This is a snippet of what I have so far:
xhr.open("POST", post_url); // the post URL given by App Engine
xhr.overrideMimeType('text/plain; charset=x-user-defined-binary');
xhr.setRequestHeader('Cache-Control', 'no-cache');
xhr.setRequestHeader('X-File-Name', file.fileName);
// After loading the binary data (last time we only read as base64 string)
// Tell xhr to start the upload
myBinaryDataReader.addEventListener("loadend", function(evt){
xhr.sendAsBinary(evt.target.result);
}, false);
// Initiate the binary reading on the file, when finished it will
// upload asynchronously
myBinaryDataReader.readAsBinaryString(file);
You'll notice that this technique sends the raw binary file as the POST body. Which is fine, it works without needing the BlobStore for up to 1 MB. In Python, to read the file, I just use:
img_data = self.request.body # got my image data now
However, with BlobStore, I'm supposed to use
upload_files = self.get_uploads('file') # 'file' is file upload field in the form
But I'm not using an HTML form with input type=file, I'm using an XmlHttpRequest -- how can I make App Engine "think" it is a file from an HTML form, and thus "grab" the file data?
My code, unmodified, results in an error
File "C:\Python26\lib\cgi.py", line 583, in keys
raise TypeError, "not indexable"
TypeError: not indexable
A:
You may want to check out my blog posts on uploading to the blobstore (1, 2, 3), as well as this recent cookbook post.
A:
The general consensus is that, so far, App Engine's BlobStore upload API will only accept multipart encoded POST data... in other words, an HTML input type=file form. Or, you can use Firefox to read a user's binary file (via drag and drop) with the FileReader API and reconstruct the multipart encoding manually. Then you can submit the data asynchronously with XmlHttpRequest.
As of writing, Chrome and Safari do not support the FileReader object so they cannot break apart binary files and thus not send multipart encoding asynchronously.
Note that the drag N drop + XmlHttpRequest method of uploading files to App Engine still works in all 3 aforementioned browsers if under 1 MB.
| How do I upload a 5 MB file to App Engine BlobStore using XmlHttpRequest 2.0? | We all know that App Engine limits you to 1 MB for most input/output requests. But with the recent BlobStore API, you are allowed to upload large files in full by POSTing to a dynamically generated URL.
According to the sample, here is what the HTML form would look like:
self.response.out.write('<html><body>')
self.response.out.write('<form action="%s" method="POST"
enctype="multipart/form-data">' % upload_url)
self.response.out.write("""Upload File:
<input type="file" name="file"><br>
<input type="submit" name="submit" value="Submit">
</form></body></html>""")
But how can we do this asynchronously using JavaScript techniques introduced with HTML5? This is a snippet of what I have so far:
xhr.open("POST", post_url); // the post URL given by App Engine
xhr.overrideMimeType('text/plain; charset=x-user-defined-binary');
xhr.setRequestHeader('Cache-Control', 'no-cache');
xhr.setRequestHeader('X-File-Name', file.fileName);
// After loading the binary data (last time we only read as base64 string)
// Tell xhr to start the upload
myBinaryDataReader.addEventListener("loadend", function(evt){
xhr.sendAsBinary(evt.target.result);
}, false);
// Initiate the binary reading on the file, when finished it will
// upload asynchronously
myBinaryDataReader.readAsBinaryString(file);
You'll notice that this technique sends the raw binary file as the POST body. Which is fine, it works without needing the BlobStore for up to 1 MB. In Python, to read the file, I just use:
img_data = self.request.body # got my image data now
However, with BlobStore, I'm supposed to use
upload_files = self.get_uploads('file') # 'file' is file upload field in the form
But I'm not using an HTML form with input type=file, I'm using an XmlHttpRequest -- how can I make App Engine "think" it is a file from an HTML form, and thus "grab" the file data?
My code, unmodified, results in an error
File "C:\Python26\lib\cgi.py", line 583, in keys
raise TypeError, "not indexable"
TypeError: not indexable
| [
"You may want to check out my blog posts on uploading to the blobstore (1, 2, 3), as well as this recent cookbook post.\n",
"The general consensus is that, so far, App Engine's BlobStore upload API will only accept multipart encoded POST data... in other words, an HTML input type=file form. Or, you can use Firefo... | [
3,
1
] | [] | [] | [
"file_upload",
"google_app_engine",
"python"
] | stackoverflow_0003605548_file_upload_google_app_engine_python.txt |
Q:
Changing $PATH in OS X to run most recent version of Python
So I changed $PATH to have Python2.5 work with Django back when it didn't support 2.6. Now I can't install much of anything through Python because I screwed up a lot of the internals. $PATH is now unnecessarily long because I didn't know what I was doing when I was adding to it. .profile doesn't contain any of the paths that I added using "export" in the terminal. I can't even install virtualenv. At this point, I feel as if I corrupted everything and would like to start from scratch without losing all of my data. I have everything backed up with Time Machine, but that will just keep the same settings that I had before anyways.
Is it completely hopeless now? Should I opt for a fresh OS reinstall using something other than Time Machine to back up all of my information? Or would this be an easy fix?
A:
If you are using mac osx. Then my suggestion is that you use macports. The solution to do that is here.
"no matching architecture in universal wrapper" problem in wxPython?
All you have to do is add "/opt/local/bin" in front of your path.
You can then select to activate appropriate version by using python_select.
After that you can use virtualenv. This does work for me very well.
A:
Why not just edit (with the text editor of your choice) the "dot files" that determine the settings of PATH in the environment? In your $HOME (probably /Users/youruserid) that includes (assuming your shell is the default one, bash) .bash_profile and .bashrc -- there's typically also a "system" one /etc/bashrc (no dot for this one;-). find ~ -type f -name '.*' -print0 | xargs -0 grep PATH tells you all the relevant files in your home directory and subtree that contain the string PATH (plus no doubt some more, such as history files and saved copies of old dotfiles) and can direct your editing. Be sure to log off and log on again to ensure that all relevant files are applied in order to test your changes.
Edit: to make this at all Python-relevant;-), here's a simple Python way to determine how to set the path so that exactly the same commands are executed in all cases as with the path setting you have now, but without wasteful duplication:
>>> x='''/opt/local/bin:/opt/local/sbin:/opt/local/bin:/opt/local/sbin:/opt/local/bin:/opt/local/sbin:/sw/bin:/sw/sbin:/opt/local/bin:/opt/local/sbin:/opt/local/bin:/opt/local/sbin:/opt/local/bin:/opt/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin:/usr/X11R6/bin'''
>>> s = set()
>>> l = list()
>>> for p in x.split(':'):
... if p in s: continue
... s.add(p)
... l.append(p)
...
>>> print ':'.join(l)
/opt/local/bin:/opt/local/sbin:/sw/bin:/sw/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin:/usr/X11R6/bin
>>>
| Changing $PATH in OS X to run most recent version of Python | So I changed $PATH to have Python2.5 work with Django back when it didn't support 2.6. Now I can't install much of anything through Python because I screwed up a lot of the internals. $PATH is now unnecessarily long because I didn't know what I was doing when I was adding to it. .profile doesn't contain any of the paths that I added using "export" in the terminal. I can't even install virtualenv. At this point, I feel as if I corrupted everything and would like to start from scratch without losing all of my data. I have everything backed up with Time Machine, but that will just keep the same settings that I had before anyways.
Is it completely hopeless now? Should I opt for a fresh OS reinstall using something other than Time Machine to back up all of my information? Or would this be an easy fix?
| [
"If you are using mac osx. Then my suggestion is that you use macports. The solution to do that is here. \n\n\"no matching architecture in universal wrapper\" problem in wxPython?\nAll you have to do is add \"/opt/local/bin\" in front of your path.\n\nYou can then select to activate appropriate version by using pyt... | [
1,
0
] | [] | [] | [
"macos",
"path",
"python"
] | stackoverflow_0003631554_macos_path_python.txt |
Q:
Scheduling events in a WSGI framework
I've written a Python app that reads a database of tasks, and schedule.enter()s those tasks at various intervals. Each task reschedules itself as it executes.
I'd like to integrate this app with a WSGI framework, so that tasks can be added or deleted in response to HTTP requests. I assume I could use XML-RPC to communicate between the framework process and the task engine, but I'd like to know if there's a framework that has built-in event scheduling which can be modified via HTTP.
A:
Sounds like what you really want is something like Celery. It's a Python-based distributed task queue which has various task behaviours including periodic and crontab.
Prior to version 2.0, it had a dependency on Django, but that has now been reduced to an integration plugin.
| Scheduling events in a WSGI framework | I've written a Python app that reads a database of tasks, and schedule.enter()s those tasks at various intervals. Each task reschedules itself as it executes.
I'd like to integrate this app with a WSGI framework, so that tasks can be added or deleted in response to HTTP requests. I assume I could use XML-RPC to communicate between the framework process and the task engine, but I'd like to know if there's a framework that has built-in event scheduling which can be modified via HTTP.
| [
"Sounds like what you really want is something like Celery. It's a Python-based distributed task queue which has various task behaviours including periodic and crontab.\nPrior to version 2.0, it had a dependency on Django, but that has now been reduced to an integration plugin.\n"
] | [
3
] | [] | [] | [
"python",
"schedule",
"wsgi"
] | stackoverflow_0003630728_python_schedule_wsgi.txt |
Q:
Python defaults and using tweepy api
I am attempting to use the tweepy api to make a twitter function and I have two issues.
I have little experience with the terminal and Python in general.
1) It installed properly with Python 2.6, however I can't use it or install it with Python 3.1. When I attempt to install the module in 3.1 it gives me an error that there is no module setuptools. Originally I thought that perhaps I was unable to use tweepy module with 3.1, however in the readme it says "Python 3 branch (3.1)", which I assume means it is compatible. When I searched for the setuptools module, which I figured I could load into the new version, there was only modules for up to Python 2.7. How would I install the Tweepy api properly on Python 3.1?
2) My default Python when run from terminal is 2.6.1 and I would like to make it 3.1 so I don't have to type python3.1.
A:
Install Distribute which is a compatible fork of setuptools that does support Python 3. When doing so, make sure you are using Python 3 instead of Python 2. Most Python 3 installations provide a symlimk or command named python3, whereas python refers to a Python 2 installation. Because of the incompatible differences between Python 2 and Python 3, it is recommended that you don't try to override this and have python refer to python3.
| Python defaults and using tweepy api | I am attempting to use the tweepy api to make a twitter function and I have two issues.
I have little experience with the terminal and Python in general.
1) It installed properly with Python 2.6, however I can't use it or install it with Python 3.1. When I attempt to install the module in 3.1 it gives me an error that there is no module setuptools. Originally I thought that perhaps I was unable to use tweepy module with 3.1, however in the readme it says "Python 3 branch (3.1)", which I assume means it is compatible. When I searched for the setuptools module, which I figured I could load into the new version, there was only modules for up to Python 2.7. How would I install the Tweepy api properly on Python 3.1?
2) My default Python when run from terminal is 2.6.1 and I would like to make it 3.1 so I don't have to type python3.1.
| [
"Install Distribute which is a compatible fork of setuptools that does support Python 3. When doing so, make sure you are using Python 3 instead of Python 2. Most Python 3 installations provide a symlimk or command named python3, whereas python refers to a Python 2 installation. Because of the incompatible diffe... | [
2
] | [
"Update: The comments below have some solid points against this technique. \n2) What OS are you running? Generally, there is a symlink somewhere in your system, which points from 'python' to 'pythonx.x', where x.x is the version number preferred by your operating system. On Linux, there is a symlink /usr/bin/python... | [
-1
] | [
"python",
"tweepy"
] | stackoverflow_0003631828_python_tweepy.txt |
Q:
Is it bad practice to use self in decorators?
While I'm aware that you can't reference self directly in a decorator, I was wondering if it's bad practice to work around that by pulling it from args[0]. My hunch is that it is, but I want to be sure.
To be more specific, I'm working on an API to a web service. About half the commands require a token to be passed that can be later used to undo it. What I would like is to make that token an optional parameter and if none is supplied, to generate one. Generating a token requires making an authenticated call to the server, which needs data from the object.
While I know I could do it:
def some_command(self, ..., undo_token = None):
if undo_token = None:
undo_token = self.get_undo_token()
...
return fnord
I feel like there could be a better way than to have the same code in a dozen or so methods. My thought was to write a decorator:
@decorator
def undoable(fn, *args, **kwargs):
if 'undo_token' not in kwargs:
kwargs['undo_token'] = args[0].get_undo_token()
return (fn(*args, **kwargs), kwargs['undo_token'])
So I can more cleanly write
@undoable
def some_command(self, ...):
...
return foo
@undoable
def some_other_command(self, ...):
...
return bar
Am I setting myself up for trouble down the line?
A:
I don't understand what you're coding for undoable -- that's not how decorators are normally coded and I don't know where that @decorator is coming from (is there a from youforgottotelluswhence import decorator or something even more evil? see why I can't stand the use of from to build "artificial barenames" instead of using nice decorated names?-).
With normal decorator coding, e.g....:
import functools
def undoable(f):
@functools.wraps(f)
def wrapper(self, *a, **k):
tok = k.get('undo_token')
if tok is None:
tok = k['undo_token'] = self.get_undo_token()
return f(self, *a, **k), tok
return wrapper
there's absolutely no problem naming the wrapper's first, mandatory positional argument self, and much gain of clarity in using this rather than the less-readable args[0].
A:
Decorators extend the functionality of the function it decorates in a generic way. If decorators to do not make any assumption about the function or it's args or kwargs, it is in most generic form and can be easily used with many functions.
How ever, if you want to do something with what is being passed onto the function, it should be fine but their applicability is limited and can break, if the underlying details, which you have used in your decorator changes.
In the above decorator, if the object removes the method get_undo_token(), you will need to revisit the decorator too. It is fine to do that but document the constraints and also add that documentation to the method doc it self.
Do it only if absolutely necessary. It serves to create more generic decorators.
| Is it bad practice to use self in decorators? | While I'm aware that you can't reference self directly in a decorator, I was wondering if it's bad practice to work around that by pulling it from args[0]. My hunch is that it is, but I want to be sure.
To be more specific, I'm working on an API to a web service. About half the commands require a token to be passed that can be later used to undo it. What I would like is to make that token an optional parameter and if none is supplied, to generate one. Generating a token requires making an authenticated call to the server, which needs data from the object.
While I know I could do it:
def some_command(self, ..., undo_token = None):
if undo_token = None:
undo_token = self.get_undo_token()
...
return fnord
I feel like there could be a better way than to have the same code in a dozen or so methods. My thought was to write a decorator:
@decorator
def undoable(fn, *args, **kwargs):
if 'undo_token' not in kwargs:
kwargs['undo_token'] = args[0].get_undo_token()
return (fn(*args, **kwargs), kwargs['undo_token'])
So I can more cleanly write
@undoable
def some_command(self, ...):
...
return foo
@undoable
def some_other_command(self, ...):
...
return bar
Am I setting myself up for trouble down the line?
| [
"I don't understand what you're coding for undoable -- that's not how decorators are normally coded and I don't know where that @decorator is coming from (is there a from youforgottotelluswhence import decorator or something even more evil? see why I can't stand the use of from to build \"artificial barenames\" in... | [
6,
2
] | [] | [] | [
"decorator",
"python"
] | stackoverflow_0003631768_decorator_python.txt |
Q:
Runtime Crash For A Very Basic Python Program
I work on a windows XP PC with a Python 2.6 install and I was trying to solve a Project Euler problem, but whenever I execute the code the interpreter hangs. I've debugged it through PyScripter, IDLE and MonkeyStudio, but it still doesn't work even for trivial values like 15.
I simply don't understand why. Can you please help me out?
Here's the code:
"""Project Euler Problem 3
Author: A"""
num = 15
prime = [1]
x = long (round(num/2))
def ifprime (x):
""" Defining the function that checks if the number is prime or not"""
""" Checking if the passed number is prime or not"""
y = long(round(x/2))
while y > 0:
if x%y == 0:
return False
y -= 1
return True
while x > 0:
if num%x == 0:
if ifprime(x):
print "I've found a prime! "
print x
prime[len(prime):] = [x]
x -= 1
A:
You have an infinite loop:
x -= 1 is never called as it's under the num%x == 0 condition, which never happens (as x never changes its value).
When num is 15, x starts as 7. Then, num % x is 1, therefore the condition is false and x is not decremented - thus looping ad infinitum.
A:
Your x -= 1 statement is indented one level too far.
x will only be decremented when num % x is 0
It should be this:
while x > 0:
if num%x == 0:
if ifprime(x):
print "I've found a prime! "
print x
prime[len(prime):] = [x]
x -= 1
A:
Besides what others have pointed out, your ifprime is wrong. You are checking while y > 0, and of course that tests up to y = 1, and thus will always return false.
And for optimization purposes, you don't have to test up to x/2, you can test up to sqrt(x) and that's good enough.
import math
def ifprime (x):
y = math.ceil(math.sqrt(x))
while y > 1:
if x % y == 0:
return False
y -= 1
return True
A:
I have dealt so much with primes that I did the complement to find factor and define ifprime using that, for a change.
import math
## I want any which return first not False value
def some(seq):
for item in seq:
if item:
return item
def factor (number):
""" returns smallest factor of number or None """
if number < 4: return None
return some(divisor
for divisor in [2] + range(3,int(number ** 0.5)+2, 2)
if not(number % divisor))
# little slower way for fun (because factor gives the factoring it found)
def ifprime(number):
return number > 1 and not factor(number)
print [number for number in range(100) if ifprime(number)]
(If you need many primes use sieve algorithm instead of prime test.)
| Runtime Crash For A Very Basic Python Program | I work on a windows XP PC with a Python 2.6 install and I was trying to solve a Project Euler problem, but whenever I execute the code the interpreter hangs. I've debugged it through PyScripter, IDLE and MonkeyStudio, but it still doesn't work even for trivial values like 15.
I simply don't understand why. Can you please help me out?
Here's the code:
"""Project Euler Problem 3
Author: A"""
num = 15
prime = [1]
x = long (round(num/2))
def ifprime (x):
""" Defining the function that checks if the number is prime or not"""
""" Checking if the passed number is prime or not"""
y = long(round(x/2))
while y > 0:
if x%y == 0:
return False
y -= 1
return True
while x > 0:
if num%x == 0:
if ifprime(x):
print "I've found a prime! "
print x
prime[len(prime):] = [x]
x -= 1
| [
"You have an infinite loop:\nx -= 1 is never called as it's under the num%x == 0 condition, which never happens (as x never changes its value).\nWhen num is 15, x starts as 7. Then, num % x is 1, therefore the condition is false and x is not decremented - thus looping ad infinitum.\n",
"Your x -= 1 statement is i... | [
4,
4,
1,
0
] | [] | [] | [
"crash",
"python"
] | stackoverflow_0003629452_crash_python.txt |
Q:
Python: Strange behaviour of recursive function with keyword arguments
I've written a small snippet that computes the path length of a given node (e.g. its distance to the root node):
def node_depth(node, depth=0, colored_nodes=set()):
"""
Return the length of the path in the parse tree from C{node}'s position
up to the root node. Effectively tests if C{node} is inside a circle
and, if so, returns -1.
"""
if node.mother is None:
return depth
mother = node.mother
if mother.id in colored_nodes:
return -1
colored_nodes.add(node.id)
return node_depth(mother, depth + 1, colored_nodes)
Now there is a strange thing happening with that function (at least it is strange to me): Calling node_depth for the first time returns the right value. However, calling it a second time with the same node returns -1. The colored_nodes set is empty in the first call, but contains all node-IDs in the second call that have been added during first one:
print node_depth(node) # --> 9
# initially colored nodes --> set([])
print node_depth(node) # --> -1
# initially colored nodes --> set([1, 2, 3, 38, 39, 21, 22, 23, 24])
print node_depth(node, colored_nodes=set()) # --> 9
print node_depth(node, colored_nodes=set()) # --> 9
Am I missing some Python-specific thing here and this is really supposed to be that way?
Thanks in advance,
Jena
A:
The "default value" for a function parameter in Python is instantiated at function declaration time, not every time the function is called. You rarely want to mutate the default value of a parameter, and so it's often a good idea to use something immutable for the default value.
In your case you may want to do something like this:
def node_depth(node, depth=0, colored_nodes=None):
...
if colored_nodes is None: colored_nodes = set()
A:
This is, because in Python, the default argument values are not evaluated each time the function is called, but only once at function definition time. So effectively, you are calling the function with a pre-filled colored_nodes set on every but the first call after definition.
| Python: Strange behaviour of recursive function with keyword arguments | I've written a small snippet that computes the path length of a given node (e.g. its distance to the root node):
def node_depth(node, depth=0, colored_nodes=set()):
"""
Return the length of the path in the parse tree from C{node}'s position
up to the root node. Effectively tests if C{node} is inside a circle
and, if so, returns -1.
"""
if node.mother is None:
return depth
mother = node.mother
if mother.id in colored_nodes:
return -1
colored_nodes.add(node.id)
return node_depth(mother, depth + 1, colored_nodes)
Now there is a strange thing happening with that function (at least it is strange to me): Calling node_depth for the first time returns the right value. However, calling it a second time with the same node returns -1. The colored_nodes set is empty in the first call, but contains all node-IDs in the second call that have been added during first one:
print node_depth(node) # --> 9
# initially colored nodes --> set([])
print node_depth(node) # --> -1
# initially colored nodes --> set([1, 2, 3, 38, 39, 21, 22, 23, 24])
print node_depth(node, colored_nodes=set()) # --> 9
print node_depth(node, colored_nodes=set()) # --> 9
Am I missing some Python-specific thing here and this is really supposed to be that way?
Thanks in advance,
Jena
| [
"The \"default value\" for a function parameter in Python is instantiated at function declaration time, not every time the function is called. You rarely want to mutate the default value of a parameter, and so it's often a good idea to use something immutable for the default value.\nIn your case you may want to do ... | [
15,
6
] | [] | [] | [
"arguments",
"keyword",
"python",
"recursion"
] | stackoverflow_0003632041_arguments_keyword_python_recursion.txt |
Q:
Getting modules from a zip file?
There is a module I'd love to download, but it is only available in a zip file, how do I get such a file to work properly in python, so That I can import what I want?
This is in Windows 7 BTW.
A:
Just insert the whole path to the zipfile, c:/what/ever/itis.zip, in your sys.path, and import themodule (assuming it's at the top "level" of the zipfile's simulated directory-tree structure).
| Getting modules from a zip file? | There is a module I'd love to download, but it is only available in a zip file, how do I get such a file to work properly in python, so That I can import what I want?
This is in Windows 7 BTW.
| [
"Just insert the whole path to the zipfile, c:/what/ever/itis.zip, in your sys.path, and import themodule (assuming it's at the top \"level\" of the zipfile's simulated directory-tree structure).\n"
] | [
1
] | [] | [] | [
"import",
"python",
"zip"
] | stackoverflow_0003632046_import_python_zip.txt |
Q:
python expression
I am new in python, and while reading a BeautifulSoup tutorial, I didn't understand this expression "[x for x in titles if x.findChildren()][:-1]" that i didn't understand? can you explain it
titles = [x for x in titles if x.findChildren()][:-1]
A:
To start with [:-1], this extracts a list that contains all elements except the last element.
>>> a=[1,2,3,4,5]
>>> a[:-1]
[1, 2, 3, 4]
The comes the first portion, that supplies the list to [:-1] (slicing in python)
[x for x in titles if x.findChildren()]
This generates a list that contains all elements (x) in the list "titles", that satisfies the condition (returns True for x.findChildren())
A:
It's a list comprehension.
It's pretty much equivalent to:
def f():
items = []
for x in titles:
if x.findChildren():
items.append(x)
return items[:-1]
titles = f()
One of my favorite features in Python :)
A:
The expression f(X) for X in Y if EXP is a list comprehension It will give you either a generator (if it's inside ()) or a list (if it's inside []) containing the result of evaluating f(X) for each element of Y, by only if EXP is true for that X.
In your case it will return a list containing every element from titles if the element has some children.
The ending [:-1] means, everything from the list apart from the last element.
A:
It's called a for comprehension expression. It is simply constructing a list of all titles in the x list which return true when the findChildren function is called upon them. The final statement substracts the last one from the list.
| python expression | I am new in python, and while reading a BeautifulSoup tutorial, I didn't understand this expression "[x for x in titles if x.findChildren()][:-1]" that i didn't understand? can you explain it
titles = [x for x in titles if x.findChildren()][:-1]
| [
"To start with [:-1], this extracts a list that contains all elements except the last element.\n>>> a=[1,2,3,4,5]\n>>> a[:-1]\n[1, 2, 3, 4]\n\nThe comes the first portion, that supplies the list to [:-1] (slicing in python)\n[x for x in titles if x.findChildren()]\n\nThis generates a list that contains all elements... | [
5,
4,
2,
1
] | [] | [] | [
"list_comprehension",
"python"
] | stackoverflow_0003632142_list_comprehension_python.txt |
Q:
Sorted dict to list
I have this:
dictionary = { (month, year) : [int, int, int] }
I'd like to get a list of tuples/lists with the ordered data(by month and year):
#example info
list = [(8,2010,2,5,3),(1,2011,6,7,8)...]
I've tried several times but I can't get to a solution.
Thanks for your help.
A:
Don't use as your identifier built-in names -- that's a horrible practice, without any advantages, and it will land you in some peculiar misbehavior eventually. So I'm calling the result thelist (an arbitrary, anodyne, just fine identifier), not list (shadowing a built-in).
import operator
thelist = sorted((my + tuple(v) for my, v in dictionary.iteritems()),
key = operator.itemgetter(1, 0))
A:
Something like this should get the job done:
>>> d = { (8, 2010) : [2,5,3], (1, 2011) : [6,7,8], (6, 2010) : [11,12,13] }
>>> sorted((i for i in d.iteritems()), key=lambda x: (x[0][1], x[0][0]))
[((6, 2010), [11, 12, 13]), ((8, 2010), [2, 5, 3]), ((1, 2011), [6, 7, 8])]
(Assuming the lambda should sort first by year, then month.)
See Alex Martelli's better answer for how to use itemgetter to solve this problem.
A:
This is a very concise way of doing what you ask.
l = [(m, y) + tuple(d[(y, m)]) for y, m in sorted(d)]
| Sorted dict to list | I have this:
dictionary = { (month, year) : [int, int, int] }
I'd like to get a list of tuples/lists with the ordered data(by month and year):
#example info
list = [(8,2010,2,5,3),(1,2011,6,7,8)...]
I've tried several times but I can't get to a solution.
Thanks for your help.
| [
"Don't use as your identifier built-in names -- that's a horrible practice, without any advantages, and it will land you in some peculiar misbehavior eventually. So I'm calling the result thelist (an arbitrary, anodyne, just fine identifier), not list (shadowing a built-in).\nimport operator\n\nthelist = sorted((m... | [
5,
0,
0
] | [] | [] | [
"dictionary",
"list",
"python",
"sorting"
] | stackoverflow_0003631798_dictionary_list_python_sorting.txt |
Q:
UDP client and server with Twisted Python
I want to create a server and client that sends and receives UDP packets from the network using Twisted. I've already written this with sockets in Python, but want to take advantage of Twisted's callback and threading features. However, I need help though with the design of Twisted.
I have multiple types of packets I want to receive, but let's pretend there is just one:
class Packet(object):
def __init__(self, data=None):
self.packet_type = 1
self.payload = ''
self.structure = '!H6s'
if data == None:
return
self.packet_type, self.payload = struct.unpack(self.structure, data)
def pack(self):
return struct.pack(self.structure, self.packet_type, self.payload)
def __str__(self):
return "Type: {0}\nPayload {1}\n\n".format(self.packet_type, self.payload)
I made a protocol class (almost direct copy of the examples), which seems to work when I send data from another program:
class MyProtocol(DatagramProtocol):
def datagramReceived(self, data, (host, port)):
p = Packet(data)
print p
reactor.listenUDP(3000, MyProtocol())
reactor.run()
What I don't know is how do I create a client which can send arbitrary packets on the network, which get picked up by the reactor:
# Something like this:
s = Sender()
p = Packet()
p.packet_type = 3
s.send(p.pack())
p.packet_type = 99
s.send(p.pack())
I also need to make sure to set the reuse address flag on the client and servers so I can run multiple instances of each at the same time on the same device (e.g. one script is sending heartbeats, another responds to heartbeats, etc).
Can someone show me how this could be done with Twisted?
Update:
This is how I do it with sockets in Python. I can run multiple listeners and senders at the same time and they all hear each other. How do I get this result with Twisted? (The listening portion need not be a separate process.)
class Listener(Process):
def __init__(self, ip='127.0.0.1', port=3000):
Process.__init__(self)
self.ip = ip
self.port = port
def run(self):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((self.ip, self.port))
data, from_ip = sock.recvfrom(4096)
p = Packet(data)
print p
class Sender(object):
def __init__(self, ip='127.255.255.255', port=3000):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.ip = (ip, port)
def send(self, data):
self.sock.sendto(data, self.ip)
if __name__ == "__main__":
l = Listener()
l.start()
s = Sender()
p = Packet()
p.packet_type = 4
p.payload = 'jake'
s.send(p.pack())
Working solution:
class MySender(DatagramProtocol):
def __init__(self, packet, host='127.255.255.255', port=3000):
self.packet = packet.pack()
self.host = host
self.port = port
def startProtocol(self):
self.transport.write(self.packet, (self.host, self.port))
if __name__ == "__main__":
packet = Packet()
packet.packet_type = 1
packet.payload = 'jake'
s = MySender(packet)
reactor.listenMulticast(3000, MyProtocol(), listenMultiple=True)
reactor.listenMulticast(3000, s, listenMultiple=True)
reactor.callLater(4, reactor.stop)
reactor.run()
A:
Just like the server example above, there is a client example to.
This should help you get started:
https://twistedmatrix.com/documents/current/core/howto/udp.html
https://github.com/twisted/twisted/blob/trunk/docs/core/examples/echoclient_udp.py
Ok, here is a simple heart beat sender and receiver using datagram protocol.
from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor
from twisted.internet.task import LoopingCall
import sys, time
class HeartbeatSender(DatagramProtocol):
def __init__(self, name, host, port):
self.name = name
self.loopObj = None
self.host = host
self.port = port
def startProtocol(self):
# Called when transport is connected
# I am ready to send heart beats
self.loopObj = LoopingCall(self.sendHeartBeat)
self.loopObj.start(2, now=False)
def stopProtocol(self):
"Called after all transport is teared down"
pass
def datagramReceived(self, data, (host, port)):
print "received %r from %s:%d" % (data, host, port)
def sendHeartBeat(self):
self.transport.write(self.name, (self.host, self.port))
class HeartbeatReciever(DatagramProtocol):
def __init__(self):
pass
def startProtocol(self):
"Called when transport is connected"
pass
def stopProtocol(self):
"Called after all transport is teared down"
def datagramReceived(self, data, (host, port)):
now = time.localtime(time.time())
timeStr = str(time.strftime("%y/%m/%d %H:%M:%S",now))
print "received %r from %s:%d at %s" % (data, host, port, timeStr)
heartBeatSenderObj = HeartbeatSender("sender", "127.0.0.1", 8005)
reactor.listenMulticast(8005, HeartbeatReciever(), listenMultiple=True)
reactor.listenMulticast(8005, heartBeatSenderObj, listenMultiple=True)
reactor.run()
The broadcast example simply modifies the above approach:
from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor
from twisted.internet.task import LoopingCall
import sys, time
class HeartbeatSender(DatagramProtocol):
def __init__(self, name, host, port):
self.name = name
self.loopObj = None
self.host = host
self.port = port
def startProtocol(self):
# Called when transport is connected
# I am ready to send heart beats
self.transport.joinGroup('224.0.0.1')
self.loopObj = LoopingCall(self.sendHeartBeat)
self.loopObj.start(2, now=False)
def stopProtocol(self):
"Called after all transport is teared down"
pass
def datagramReceived(self, data, (host, port)):
print "received %r from %s:%d" % (data, host, port)
def sendHeartBeat(self):
self.transport.write(self.name, (self.host, self.port))
class HeartbeatReciever(DatagramProtocol):
def __init__(self, name):
self.name = name
def startProtocol(self):
"Called when transport is connected"
self.transport.joinGroup('224.0.0.1')
pass
def stopProtocol(self):
"Called after all transport is teared down"
def datagramReceived(self, data, (host, port)):
now = time.localtime(time.time())
timeStr = str(time.strftime("%y/%m/%d %H:%M:%S",now))
print "%s received %r from %s:%d at %s" % (self.name, data, host, port, timeStr)
heartBeatSenderObj = HeartbeatSender("sender", "224.0.0.1", 8005)
reactor.listenMulticast(8005, HeartbeatReciever("listner1"), listenMultiple=True)
reactor.listenMulticast(8005, HeartbeatReciever("listner2"), listenMultiple=True)
reactor.listenMulticast(8005, heartBeatSenderObj, listenMultiple=True)
reactor.run()
A:
Check out the echoclient_udp.py example.
Since UDP is pretty much symmetrical between client and server, you just want to run reactor.listenUDP there too, connect to the server (which really just sets the default destination for sent packets), then transport.write to send your packets.
| UDP client and server with Twisted Python | I want to create a server and client that sends and receives UDP packets from the network using Twisted. I've already written this with sockets in Python, but want to take advantage of Twisted's callback and threading features. However, I need help though with the design of Twisted.
I have multiple types of packets I want to receive, but let's pretend there is just one:
class Packet(object):
def __init__(self, data=None):
self.packet_type = 1
self.payload = ''
self.structure = '!H6s'
if data == None:
return
self.packet_type, self.payload = struct.unpack(self.structure, data)
def pack(self):
return struct.pack(self.structure, self.packet_type, self.payload)
def __str__(self):
return "Type: {0}\nPayload {1}\n\n".format(self.packet_type, self.payload)
I made a protocol class (almost direct copy of the examples), which seems to work when I send data from another program:
class MyProtocol(DatagramProtocol):
def datagramReceived(self, data, (host, port)):
p = Packet(data)
print p
reactor.listenUDP(3000, MyProtocol())
reactor.run()
What I don't know is how do I create a client which can send arbitrary packets on the network, which get picked up by the reactor:
# Something like this:
s = Sender()
p = Packet()
p.packet_type = 3
s.send(p.pack())
p.packet_type = 99
s.send(p.pack())
I also need to make sure to set the reuse address flag on the client and servers so I can run multiple instances of each at the same time on the same device (e.g. one script is sending heartbeats, another responds to heartbeats, etc).
Can someone show me how this could be done with Twisted?
Update:
This is how I do it with sockets in Python. I can run multiple listeners and senders at the same time and they all hear each other. How do I get this result with Twisted? (The listening portion need not be a separate process.)
class Listener(Process):
def __init__(self, ip='127.0.0.1', port=3000):
Process.__init__(self)
self.ip = ip
self.port = port
def run(self):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((self.ip, self.port))
data, from_ip = sock.recvfrom(4096)
p = Packet(data)
print p
class Sender(object):
def __init__(self, ip='127.255.255.255', port=3000):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.ip = (ip, port)
def send(self, data):
self.sock.sendto(data, self.ip)
if __name__ == "__main__":
l = Listener()
l.start()
s = Sender()
p = Packet()
p.packet_type = 4
p.payload = 'jake'
s.send(p.pack())
Working solution:
class MySender(DatagramProtocol):
def __init__(self, packet, host='127.255.255.255', port=3000):
self.packet = packet.pack()
self.host = host
self.port = port
def startProtocol(self):
self.transport.write(self.packet, (self.host, self.port))
if __name__ == "__main__":
packet = Packet()
packet.packet_type = 1
packet.payload = 'jake'
s = MySender(packet)
reactor.listenMulticast(3000, MyProtocol(), listenMultiple=True)
reactor.listenMulticast(3000, s, listenMultiple=True)
reactor.callLater(4, reactor.stop)
reactor.run()
| [
"Just like the server example above, there is a client example to.\nThis should help you get started:\n\nhttps://twistedmatrix.com/documents/current/core/howto/udp.html\nhttps://github.com/twisted/twisted/blob/trunk/docs/core/examples/echoclient_udp.py\n\nOk, here is a simple heart beat sender and receiver using da... | [
12,
2
] | [] | [] | [
"python",
"twisted",
"udp"
] | stackoverflow_0003632210_python_twisted_udp.txt |
Q:
Django uploading file not in MEDIA_ROOT path is giving me SuspiciousOperation error
I want to upload files to a path that is still in my django project, but in my MEDIA_ROOT path.
When I try to do this I get a SuspiciousOperation error.
Here are the paths as defined in my settings file:
MEDIA_ROOT = os.path.join(os.path.dirname( __file__ ), 'static_serve')
UPLOAD_DIR = os.path.join(os.path.dirname( __file__ ), 'uploads')
I'm doing this because I don't want the files I am uploading to be accessible via the browser and my MEDIA_ROOT path is.
Does anyone have any idea how I get around (fix) this error.
A:
Yes there is a way:
From docs:
For example, the following code will
store uploaded files under
/media/photos regardless of what your
MEDIA_ROOT setting is:
from django.db import models
from django.core.files.storage import FileSystemStorage
fs = FileSystemStorage(location='/media/photos')
class Car(models.Model):
...
photo = models.ImageField(storage=fs)
| Django uploading file not in MEDIA_ROOT path is giving me SuspiciousOperation error | I want to upload files to a path that is still in my django project, but in my MEDIA_ROOT path.
When I try to do this I get a SuspiciousOperation error.
Here are the paths as defined in my settings file:
MEDIA_ROOT = os.path.join(os.path.dirname( __file__ ), 'static_serve')
UPLOAD_DIR = os.path.join(os.path.dirname( __file__ ), 'uploads')
I'm doing this because I don't want the files I am uploading to be accessible via the browser and my MEDIA_ROOT path is.
Does anyone have any idea how I get around (fix) this error.
| [
"Yes there is a way:\nFrom docs:\n\nFor example, the following code will\n store uploaded files under\n /media/photos regardless of what your\n MEDIA_ROOT setting is:\n\nfrom django.db import models\nfrom django.core.files.storage import FileSystemStorage\n\nfs = FileSystemStorage(location='/media/photos')\n\ncl... | [
28
] | [] | [] | [
"django",
"django_uploads",
"python"
] | stackoverflow_0003631941_django_django_uploads_python.txt |
Q:
page external links count in python
I need such functions in python:
-check external links count on site pages.
-check if some link is present on given page or not.
Does anybody know good solutions/libs for this task?
I think i should use BeautifulSoup here.., may be something more lib can help?
A:
You should be able to use urllib2 module to fetch the page, use beautifulsoup to parse the page and extract the links, store it up in list and match them to check for some existing link. There are number of questions on BeautifulSoup on SO itself.
| page external links count in python | I need such functions in python:
-check external links count on site pages.
-check if some link is present on given page or not.
Does anybody know good solutions/libs for this task?
I think i should use BeautifulSoup here.., may be something more lib can help?
| [
"You should be able to use urllib2 module to fetch the page, use beautifulsoup to parse the page and extract the links, store it up in list and match them to check for some existing link. There are number of questions on BeautifulSoup on SO itself.\n"
] | [
1
] | [] | [] | [
"hyperlink",
"python",
"seo"
] | stackoverflow_0003632531_hyperlink_python_seo.txt |
Q:
Web.py URL Mapping not accepting '/'
So every web.py tutorial I've seen includes this line:
urls = (
'/', 'index',
)
And then, later on, the index class is defined with a GET function and so on. My problem is, this doesn't work. Using the code above, I get a 404 error. Using the following mapping works:
urls = (
'/.*', 'index',
)
But that's going to catch, at least at first, every single possible URL, and I want only an access to the domain root to be handled by "index." Halp?
Some basic info:
Python 2.6, web.py 0.3, Apache 2.2 with mod_wsgi
Not sure what else would be useful, so if there is something important I can add (the VirtualHost from Apache, maybe?) please ask and I'll add it here.
EDIT: Including my Apache VirtualHost config:
<VirtualHost *:80>
ServerName dd.sp4.us
DocumentRoot /home/steve/www/nov2010/public/
ErrorLog /home/steve/www/nov2010/log/error.log
CustomLog /home/steve/www/nov2010/log/access.log combined
WSGIScriptAlias / /home/steve/www/nov2010/app
Alias /static /home/steve/www/nov2010/public
<Directory /home/steve/www/nov2010/app>
SetHandler wsgi-script
Options ExecCGI
</Directory>
AddType text/html .py
<Location />
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_URI} !^/static
RewriteCond %{REQUEST_URI} !^(/.*)+code.py/
RewriteRule ^(.*)$ code.py/$1 [PT]
</Location>
</VirtualHost>
A:
For background read:
http://code.google.com/p/modwsgi/wiki/ConfigurationGuidelines
Presuming you only have the one WSGI application to be mounted at root of site and only static files or other resources are under /static, then instead of:
WSGIScriptAlias / /home/steve/www/nov2010/app
Alias /static /home/steve/www/nov2010/public
<Directory /home/steve/www/nov2010/app>
SetHandler wsgi-script
Options ExecCGI
</Directory>
AddType text/html .py
<Location />
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_URI} !^/static
RewriteCond %{REQUEST_URI} !^(/.*)+code.py/
RewriteRule ^(.*)$ code.py/$1 [PT]
</Location>
use:
Alias /static /home/steve/www/nov2010/public
WSGIScriptAlias / /home/steve/www/nov2010/app/code.py
<Directory /home/steve/www/nov2010/app>
Order allow,deny
Allow from all
</Directory>
You are mixing up multiple ways of configuring mod_wsgi which shouldn't be used together.
If your requirements are something else, you are going to have to be clearer about what you want to happen.
| Web.py URL Mapping not accepting '/' | So every web.py tutorial I've seen includes this line:
urls = (
'/', 'index',
)
And then, later on, the index class is defined with a GET function and so on. My problem is, this doesn't work. Using the code above, I get a 404 error. Using the following mapping works:
urls = (
'/.*', 'index',
)
But that's going to catch, at least at first, every single possible URL, and I want only an access to the domain root to be handled by "index." Halp?
Some basic info:
Python 2.6, web.py 0.3, Apache 2.2 with mod_wsgi
Not sure what else would be useful, so if there is something important I can add (the VirtualHost from Apache, maybe?) please ask and I'll add it here.
EDIT: Including my Apache VirtualHost config:
<VirtualHost *:80>
ServerName dd.sp4.us
DocumentRoot /home/steve/www/nov2010/public/
ErrorLog /home/steve/www/nov2010/log/error.log
CustomLog /home/steve/www/nov2010/log/access.log combined
WSGIScriptAlias / /home/steve/www/nov2010/app
Alias /static /home/steve/www/nov2010/public
<Directory /home/steve/www/nov2010/app>
SetHandler wsgi-script
Options ExecCGI
</Directory>
AddType text/html .py
<Location />
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_URI} !^/static
RewriteCond %{REQUEST_URI} !^(/.*)+code.py/
RewriteRule ^(.*)$ code.py/$1 [PT]
</Location>
</VirtualHost>
| [
"For background read:\nhttp://code.google.com/p/modwsgi/wiki/ConfigurationGuidelines\nPresuming you only have the one WSGI application to be mounted at root of site and only static files or other resources are under /static, then instead of:\nWSGIScriptAlias / /home/steve/www/nov2010/app\nAlias /static /home/steve/... | [
5
] | [] | [] | [
"apache",
"mod_wsgi",
"python",
"web.py"
] | stackoverflow_0003613594_apache_mod_wsgi_python_web.py.txt |
Q:
Java and Python App/Service Communication with Web Interface
Currently I have a Java (and a half ported python version) app that runs in the background that has a queue of jobs (currently read out of a mysql database) which handles thread sleep/waking to share resources based on the job priority and running time. There is a front end php script that posts jobs to the database which are polled by the system every time interval.
This manner is somewhat inefficient (but nicer than locking issues using a job file) but I can't but wonder if there would be some way to simplify this.
My thoughts were java app (and or python app) sets up http service (jetty?) and has a web interface that directly pushes jobs to the queue without the middleman. Apache is serving other php sites so this would have to run in tandem.
I'm really after some other input as I'd prefer it to be a background service always running - having a cron execute jobs was painful (since some jobs run for 20+ hours so adding new ones was a pain with new php [ no threading] /java calls having to check if a service was running with outstanding jobs to add to instead of starting a new service) but also have a very simple web interface without too much resource wastage.
Thanks for your input.
A:
Deploy a JSP using Tomcat (or similar) that allows the user to post job requests to a job scheduler web service using a webpage. On the backend, use Quartz Scheduler to manage your jobs and just have your web service add jobs to the Quartz queue.
| Java and Python App/Service Communication with Web Interface | Currently I have a Java (and a half ported python version) app that runs in the background that has a queue of jobs (currently read out of a mysql database) which handles thread sleep/waking to share resources based on the job priority and running time. There is a front end php script that posts jobs to the database which are polled by the system every time interval.
This manner is somewhat inefficient (but nicer than locking issues using a job file) but I can't but wonder if there would be some way to simplify this.
My thoughts were java app (and or python app) sets up http service (jetty?) and has a web interface that directly pushes jobs to the queue without the middleman. Apache is serving other php sites so this would have to run in tandem.
I'm really after some other input as I'd prefer it to be a background service always running - having a cron execute jobs was painful (since some jobs run for 20+ hours so adding new ones was a pain with new php [ no threading] /java calls having to check if a service was running with outstanding jobs to add to instead of starting a new service) but also have a very simple web interface without too much resource wastage.
Thanks for your input.
| [
"Deploy a JSP using Tomcat (or similar) that allows the user to post job requests to a job scheduler web service using a webpage. On the backend, use Quartz Scheduler to manage your jobs and just have your web service add jobs to the Quartz queue.\n"
] | [
0
] | [] | [] | [
"java",
"python",
"web_services"
] | stackoverflow_0003562973_java_python_web_services.txt |
Q:
Simple queue for youtube-dl in the Linux shell
youtube-dl is a Python script that allows one to download YouTube videos. It supports an option for batch downloads:
-a FILE, --batch-file=FILE
file containing URLs to download ('-' for stdin)
I want to setup some sort of queue so I can simply append URLs to a file and have youtube-dl process them. Currently, it does not remove files from the batch file. I see the option for '-' stdin and don't know if I can use this to my advantage.
In effect, I'd like to run youtube-dl as some form of daemon which will check the queue file and download the contained file names.
How can I do this?
A:
The tail -f will not work because the script reads all the input at once.
It will work if you modify the script to perform a continuous read of the batch file.
Then simply run the script as:
% ./youtube-dl -a batch.txt -c
When you append some data into batch.txt, say:
% echo "http://www.youtube.com/watch?v=j9SgDoypXcI" >>batch.txt
The script will start downloading the appended video to the batch.
This is the patch you should apply to the latest version of "youtube-dl":
2278,2286d2277
< while True:
< batchurls = batchfd.readlines()
< if not batchurls:
< time.sleep(1)
< continue
< batchurls = [x.strip() for x in batchurls]
< batchurls = [x for x in batchurls if len(x) > 0]
< for bb in batchurls:
< retcode = fd.download([bb])
Hope it helps,
Happy video watching
;)
NOTE: Due to code restructuring this patch will no longer work. Would be interested to see if this could be added to the upstream code.
A:
You might be able to get away with using tail -f to read from your file. It will not exit when it reaches end-of-file but will wait for more data to be appended to the file.
>video.queue # erase and/or create queue file
tail -f video.queue | youtube-dl -a -
Since tail -f does not exit, youtube-dl should continue reading file names from stdin and never exit.
| Simple queue for youtube-dl in the Linux shell | youtube-dl is a Python script that allows one to download YouTube videos. It supports an option for batch downloads:
-a FILE, --batch-file=FILE
file containing URLs to download ('-' for stdin)
I want to setup some sort of queue so I can simply append URLs to a file and have youtube-dl process them. Currently, it does not remove files from the batch file. I see the option for '-' stdin and don't know if I can use this to my advantage.
In effect, I'd like to run youtube-dl as some form of daemon which will check the queue file and download the contained file names.
How can I do this?
| [
"The tail -f will not work because the script reads all the input at once.\nIt will work if you modify the script to perform a continuous read of the batch file.\nThen simply run the script as:\n% ./youtube-dl -a batch.txt -c\n\nWhen you append some data into batch.txt, say:\n% echo \"http://www.youtube.com/watch?v... | [
5,
1
] | [] | [] | [
"daemon",
"python",
"shell",
"youtube"
] | stackoverflow_0003632919_daemon_python_shell_youtube.txt |
Q:
TypeError: unbound method __init__() .... during unit tests after re-packaging
I've just repackaged my program. Previously all modules lived under the "whyteboard" package, with a "fakewidgets" package containing a bunch of dummy GUI test objects.
Now, all my modules are in packages, e.g. whyteboard.gui, whyteboard.misc, whyteboard.test - which is where fakewidgets now lives.
Now, when running my tests, I get an exception,
File "/home/steve/Documents/whyteboard/whyteboard/gui/canvas.py", line 77, in __init__
wx.ScrolledWindow.__init__(self, tab, style=wx.NO_FULL_REPAINT_ON_RESIZE | wx.CLIP_CHILDREN)
TypeError: unbound method __init__() must be called with ScrolledWindow instance as first argument (got Canvas instance instead)
here's
the class in question
class Canvas(wx.ScrolledWindow):
def __init__(self, tab, gui, area):
wx.ScrolledWindow.__init__(self, tab, style=wx.NO_FULL_REPAINT_ON_RESIZE | wx.CLIP_CHILDREN)
However, my program loads and runs correctly, except from unit tests. The code is the same, just the code for my tests' imports are different to pull in from the new packages.
Before:
import os
import wx
import fakewidgets
import gui
import lib.mock as mock
from canvas import Canvas, RIGHT, DIAGONAL, BOTTOM
from fakewidgets.core import Bitmap, Event, Colour
from lib.configobj import ConfigObj
from lib.pubsub import pub
from lib.validate import Validator
now:
import os
import wx
import whyteboard.test
import whyteboard.gui.frame as gui
from whyteboard.lib import ConfigObj, mock, pub, Validator
from whyteboard.gui.canvas import Canvas, RIGHT, DIAGONAL, BOTTOM
from whyteboard.test.fakewidgets.core import Bitmap, Event, Colour, PySimpleApp
It may be worth noting that the fakewidgets package does some trickery into make my program think it's using wxPython classes, even though they're mocks.
This is from a module that's imported by whyteboard.test.fakewidgets' __init__
class Window(object):
def __init__(self, parent, *args, **kwds):
self.parent = parent
self.Enabled = True
self.calls = []
self.size = (0, 0)
self.captured = False
def GetClientSizeTuple(self):
return (0, 0)
self.captured = True
def GetId(self):
pass
def Fit(self):
pass
def SetFocus(self):
pass
def PrepareDC(self, dc):
pass
def Destroy(self):
pass
...
class ScrolledWindow(Window):
def SetVirtualSize(self, *size):
pass
def SetVirtualSizeHints(self, *size):
pass
import wx
wx.__dict__.update(locals())
A:
when you import whyteboard.test, does that automatically run whyteboard.test.fakewidgets.core? I think the problem is that Canvas is being created before the mocking code runs. This explains the switchup.
>>> import wx
>>> class Test1(wx.Window):
... pass
...
>>> wx.Window = object
>>> class Test2(wx.Window):
... pass
...
>>> dir(Test1)[:10]
['AcceleratorTable', 'AcceptsFocus', 'AcceptsFocusFromKeyboard',
'AddChild', 'AddPendingEvent', 'AdjustForLayoutDirection',
'AssociateHandle', 'AutoLayout', 'BackgroundColour', 'BackgroundStyle']
>>> dir(Test2)[:10]
['__class__', '__delattr__', '__dict__', '__doc__', '__format__',
'__getattribute__', '__hash__', '__init__', '__module__', '__new__']
In the old file that you posted, fakewidgets was imported before canvas.
If that doesn't work, place this code directly after import wx before any other imports:
import inspect
class DummyMeta(type):
def __new__(meta, clsname, bases, clsdict):
if clsname == 'Canvas':
lineno = inspect.stack()[1][2]
print "creating Canvas with mro: {0}".format(inspect.getmro(bases[0]))
print "file:{0}:{1}".format(__file__, lineno)
return super(DummyMeta, meta).__new__(meta, clsname, bases, clsdict)
class ScrolledWindowDummy(wx.Window):
__metaclass__ = DummyMeta
wx.ScrolledWindow = ScrolledWindowDummy
This will show that a Canvas class is being created before mocking is in place and will give you the file and line number where this occurs. essentially, for MRO, you shouldn't see anything from wx. If I am wrong, then you wont see anything at all because you will have replaced the ScrolledWindowDummy with a class that doesn't have type DummyMeta before any class named 'Canvas' is created.
A:
The code is the same, just the code for my tests' imports are different to pull in from the new packages
That sounds as if your imports are importing something you did not expect. Once I named one my files the same as a system module. It took me hours to figure out what went wrong.
See what happens when you change sys.path.
A:
Please print wx and wx.ScrolledWindow both before the definition of class Canvas and as the first line of Canvas.__init__. I strongly suspect that these will be different.
Are you doing any trickery with __new__ or metaclasses or such?
A:
Make sure fakewidgets is the first to import the wx module, This means order of imports is important, e.g.
import fakewidgets
import wx
Alternatively, in stead of the dict.update trick, replace names explicitly, i.e.
import wx
wx.Window = Window
# for all other relevant widgets
Again, still make sure fakewidgets is the first to access the wx module.
| TypeError: unbound method __init__() .... during unit tests after re-packaging | I've just repackaged my program. Previously all modules lived under the "whyteboard" package, with a "fakewidgets" package containing a bunch of dummy GUI test objects.
Now, all my modules are in packages, e.g. whyteboard.gui, whyteboard.misc, whyteboard.test - which is where fakewidgets now lives.
Now, when running my tests, I get an exception,
File "/home/steve/Documents/whyteboard/whyteboard/gui/canvas.py", line 77, in __init__
wx.ScrolledWindow.__init__(self, tab, style=wx.NO_FULL_REPAINT_ON_RESIZE | wx.CLIP_CHILDREN)
TypeError: unbound method __init__() must be called with ScrolledWindow instance as first argument (got Canvas instance instead)
here's
the class in question
class Canvas(wx.ScrolledWindow):
def __init__(self, tab, gui, area):
wx.ScrolledWindow.__init__(self, tab, style=wx.NO_FULL_REPAINT_ON_RESIZE | wx.CLIP_CHILDREN)
However, my program loads and runs correctly, except from unit tests. The code is the same, just the code for my tests' imports are different to pull in from the new packages.
Before:
import os
import wx
import fakewidgets
import gui
import lib.mock as mock
from canvas import Canvas, RIGHT, DIAGONAL, BOTTOM
from fakewidgets.core import Bitmap, Event, Colour
from lib.configobj import ConfigObj
from lib.pubsub import pub
from lib.validate import Validator
now:
import os
import wx
import whyteboard.test
import whyteboard.gui.frame as gui
from whyteboard.lib import ConfigObj, mock, pub, Validator
from whyteboard.gui.canvas import Canvas, RIGHT, DIAGONAL, BOTTOM
from whyteboard.test.fakewidgets.core import Bitmap, Event, Colour, PySimpleApp
It may be worth noting that the fakewidgets package does some trickery into make my program think it's using wxPython classes, even though they're mocks.
This is from a module that's imported by whyteboard.test.fakewidgets' __init__
class Window(object):
def __init__(self, parent, *args, **kwds):
self.parent = parent
self.Enabled = True
self.calls = []
self.size = (0, 0)
self.captured = False
def GetClientSizeTuple(self):
return (0, 0)
self.captured = True
def GetId(self):
pass
def Fit(self):
pass
def SetFocus(self):
pass
def PrepareDC(self, dc):
pass
def Destroy(self):
pass
...
class ScrolledWindow(Window):
def SetVirtualSize(self, *size):
pass
def SetVirtualSizeHints(self, *size):
pass
import wx
wx.__dict__.update(locals())
| [
"when you import whyteboard.test, does that automatically run whyteboard.test.fakewidgets.core? I think the problem is that Canvas is being created before the mocking code runs. This explains the switchup. \n>>> import wx\n>>> class Test1(wx.Window):\n... pass\n... \n>>> wx.Window = object\n>>> class Test2(wx.W... | [
3,
1,
1,
1
] | [] | [] | [
"package",
"python",
"testing"
] | stackoverflow_0003383652_package_python_testing.txt |
Q:
django, postgres 8.4, psycopg 2.2.2, python 2.7, mod_wsgi
I've installed django/postgres on local django server and works fine. I'm trying to get Apache working. I've set up the mod_wsgi and was able to get a "Hello World", and restart Apache. I'm almost there, but when I bring up localhost/index.html I get this server error:
TemplateSyntaxError: Caught ImproperlyConfigured while rendering:
'django.db.backends.postgresql_psycopg2' isn't an available database
backend.
[Thu Sep 02 13:46:30 2010] [error] [client 127.0.0.1] Try using
django.db.backends.XXX, where XXX is one of:
[Thu Sep 02 13:46:30 2010] [error] [client 127.0.0.1] 'dummy',
'mysql', 'oracle', 'postgresql', 'postgresql_psycopg2', 'sqlite3'
[Thu Sep 02 13:46:30 2010] [error] [client 127.0.0.1] Error was:
cannot import name utils
Is it possible that mod_wsgi and the version psycopg are incompatible? Has anyone tried this type of setup?
Update 1:
I downgraded to 2.6, mod_wsgi, psycopg2 and still get this error in apache log file.
Fri Sep 03 12:17:41 2010] [error]
[client 97.80.165.181] File
"C:\Python26\lib\site-packages\django\db\__init__.py",
line 77, in [Fri Sep 03
12:17:41 2010] [error] [client
97.80.165.181] connection = connections[DEFAULT_DB_ALIAS] [Fri Sep
03 12:17:41 2010] [error] [client
97.80.165.181] File "C:\Python26\lib\site-packages\django\db\utils.py",
line 91, in getitem [Fri Sep 03
12:17:41 2010] [error] [client
97.80.165.181] backend = load_backend(db['ENGINE']) [Fri Sep 03
12:17:41 2010] [error] [client
97.80.165.181] File "C:\Python26\lib\site-packages\django\db\utils.py",
line 49, in load_backend [Fri Sep 03
12:17:41 2010] [error] [client
97.80.165.181] raise ImproperlyConfigured(error_msg) [Fri
Sep 03 12:17:41 2010] [error] [client
97.80.165.181] TemplateSyntaxError: Caught ImproperlyConfigured while
rendering:
'django.db.backends.postgresql_psycopg2'
isn't an available database backend.
[Fri Sep 03 12:17:41 2010] [error]
[client 97.80.165.181] Try using
django.db.backends.XXX, where XXX is
one of: [Fri Sep 03 12:17:41 2010]
[error] [client 97.80.165.181]
'dummy', 'mysql', 'oracle',
'postgresql', 'postgresql_psycopg2',
'sqlite3' [Fri Sep 03 12:17:41 2010]
[error] [client 97.80.165.181] Error
was: cannot import name utils
Do you know what it might indicate?
Update 2:
The cause is in the file django/db/backends/postgresql_psycopg2/base.py, version 2.2.2, line number 9:
from django.db import utils
But I still don't know how to fix this.
There is a file django/db/utils.py, so it should work. And it works for the development server, after all. But not for Apache + mod_wsgi
A:
Maybe this Ticket helps you:
or whatever it is worth, I have
confirmed that if I downgrade python
to 2.6 and then likewise downgrade
mod_wsgi and psycopg2, Django will
work with Postgres on Apache as
expected
| django, postgres 8.4, psycopg 2.2.2, python 2.7, mod_wsgi | I've installed django/postgres on local django server and works fine. I'm trying to get Apache working. I've set up the mod_wsgi and was able to get a "Hello World", and restart Apache. I'm almost there, but when I bring up localhost/index.html I get this server error:
TemplateSyntaxError: Caught ImproperlyConfigured while rendering:
'django.db.backends.postgresql_psycopg2' isn't an available database
backend.
[Thu Sep 02 13:46:30 2010] [error] [client 127.0.0.1] Try using
django.db.backends.XXX, where XXX is one of:
[Thu Sep 02 13:46:30 2010] [error] [client 127.0.0.1] 'dummy',
'mysql', 'oracle', 'postgresql', 'postgresql_psycopg2', 'sqlite3'
[Thu Sep 02 13:46:30 2010] [error] [client 127.0.0.1] Error was:
cannot import name utils
Is it possible that mod_wsgi and the version psycopg are incompatible? Has anyone tried this type of setup?
Update 1:
I downgraded to 2.6, mod_wsgi, psycopg2 and still get this error in apache log file.
Fri Sep 03 12:17:41 2010] [error]
[client 97.80.165.181] File
"C:\Python26\lib\site-packages\django\db\__init__.py",
line 77, in [Fri Sep 03
12:17:41 2010] [error] [client
97.80.165.181] connection = connections[DEFAULT_DB_ALIAS] [Fri Sep
03 12:17:41 2010] [error] [client
97.80.165.181] File "C:\Python26\lib\site-packages\django\db\utils.py",
line 91, in getitem [Fri Sep 03
12:17:41 2010] [error] [client
97.80.165.181] backend = load_backend(db['ENGINE']) [Fri Sep 03
12:17:41 2010] [error] [client
97.80.165.181] File "C:\Python26\lib\site-packages\django\db\utils.py",
line 49, in load_backend [Fri Sep 03
12:17:41 2010] [error] [client
97.80.165.181] raise ImproperlyConfigured(error_msg) [Fri
Sep 03 12:17:41 2010] [error] [client
97.80.165.181] TemplateSyntaxError: Caught ImproperlyConfigured while
rendering:
'django.db.backends.postgresql_psycopg2'
isn't an available database backend.
[Fri Sep 03 12:17:41 2010] [error]
[client 97.80.165.181] Try using
django.db.backends.XXX, where XXX is
one of: [Fri Sep 03 12:17:41 2010]
[error] [client 97.80.165.181]
'dummy', 'mysql', 'oracle',
'postgresql', 'postgresql_psycopg2',
'sqlite3' [Fri Sep 03 12:17:41 2010]
[error] [client 97.80.165.181] Error
was: cannot import name utils
Do you know what it might indicate?
Update 2:
The cause is in the file django/db/backends/postgresql_psycopg2/base.py, version 2.2.2, line number 9:
from django.db import utils
But I still don't know how to fix this.
There is a file django/db/utils.py, so it should work. And it works for the development server, after all. But not for Apache + mod_wsgi
| [
"Maybe this Ticket helps you:\n\nor whatever it is worth, I have\n confirmed that if I downgrade python\n to 2.6 and then likewise downgrade\n mod_wsgi and psycopg2, Django will\n work with Postgres on Apache as\n expected\n\n"
] | [
1
] | [] | [] | [
"django",
"mod_wsgi",
"postgresql",
"psycopg",
"python"
] | stackoverflow_0003633099_django_mod_wsgi_postgresql_psycopg_python.txt |
Q:
how to using MySQLdb SELECT with for or while loop
import _mysql as mysql
db=mysql.connect('localhost','username','password','database')
db.query("""select * from news""")
result = db.store_result()
print result.num_rows()#two records
#how to loop? without cursor
print result.fetch_row()
A:
You can try this:
while True:
record = result.fetch_row()
if not record: break
print record
I second @Ignacio's note of caution against using _mysql. Switch to import MySQLdb.
A:
You should not be importing _mysql. Symbols that start with a single underscore are for private use. Import MySQLdb and read PEP 249 for its use.
A:
I'm not sure how you plan on using the loop, but you could do something like this:
while x < result.num_rows():
#do something for each row
X += 1
| how to using MySQLdb SELECT with for or while loop | import _mysql as mysql
db=mysql.connect('localhost','username','password','database')
db.query("""select * from news""")
result = db.store_result()
print result.num_rows()#two records
#how to loop? without cursor
print result.fetch_row()
| [
"You can try this:\nwhile True:\n record = result.fetch_row()\n if not record: break\n print record\n\nI second @Ignacio's note of caution against using _mysql. Switch to import MySQLdb.\n",
"You should not be importing _mysql. Symbols that start with a single underscore are for private use. Import MySQL... | [
7,
6,
0
] | [] | [] | [
"mysql",
"mysql_python",
"python"
] | stackoverflow_0003633550_mysql_mysql_python_python.txt |
Q:
Django and PIL on Snow Leopard
I am trying to get PIL working with Django 1.2.1 and Python 2.7 on Snow Leopard
I have followed instructions I found here on SO and I should be doing it right.
The imports and selftest.py works fine and I both save and open images in the interactive python, but Django cannot use it.
I get the error
The _imaging C module is not installed
Why on earth does PIL seem to work everywhere but Django? I just doesn't make any sense.
I have even tried reinstalling Django after installing libjpeg and PIL, but with no results, what am I doing wrong?
EDIT:
I have just discovered something weird. I can open and save images just fine, by using the interactive python in terminal. But for some reason, when I save an image, the colors are inverted!
The code used is:
im = Image.open("/Users/Me/Downloads/9.jpg")
im.save("/Users/Me/Downloads/8.jpg")
Does that give any clues as to why it does not work in Django at all?
EDIT 2:
Nevermind that last part, it seems that the jpg I chose, was with CMYK colors, and that cannot be saved directly as an RGB or something along those lines.
EDIT 3:
And then again, maybe it is correct that Django is looking in the wrong place.
Exception Location: /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/PIL/Image.py in __getattr__, line 36
Python Executable: /Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python
Python Version: 2.7.0
This is what Django puts out. I just looked at the version, silly me. The top line clearly states that it is looking in the 2.5 path. Wonder why its 2.5 since SL should be born with 2.6, oh well, no matter.
Can anyone then tell me how to direct Django to use the newer ones? The solution with changing manage.pydid nothing. Why is that, that should have told Django to use 2.7 no matter what.. right?
A:
I wrote a pretty extensive tutorial on how to get PIL, libjpeg to work on Snow leopard.
Maybe this will help you out.
http://appelfreelance.com/2010/06/libjpeg-pil-snow-leopard-python2-6-_jpeg_resync_to_restart/
If you don’t have this download it first.
http://www.ijg.org/files/jpegsrc.v7.tar.gz
go into your shell environment and untar by running the following
tar -zxvf jpegsrc.v7.tar.gz
cd jpeg-7
then run
sudo make clean
sudo CC="gcc -arch i386"./configure --enable-shared --enable-static
sudo make
sudo make install
Next get PIL and untar it
http://effbot.org/downloads/Imaging-1.1.6.tar.gz
tar -zxvf Imaging-1.1.6.tar.gz
cd Imaging-1.1.6
If you already have PIL I would recommend running
sudo rm -Rf build
to clean any existing builds, this has caused me loads of errors and gray hairs!
in your setup.py file run find JPEG_ROOT
amend it so it looks as follows
JPEG_ROOT = libinclude("/usr/local")
Next move onto the build
sudo python setup.py build
if libjpeg is successfully installed you should be able to run python selftest.py without any errors relating to “jpeg”
sudo python setup.py install
if all has worked successfully you should be able to enter your python interpreter by executing python in your command line and also do the following:
import PIL
import Image
import _imaging
without any errors.
Just to triple check I have a simple jpeg on my desktop.
image = Image.open(“/Users/MyName/Desktop/myimage.jpeg”)
image.save(“/Users/MyName/Desktop/test.jpeg”)
should work without errors
A:
Make sure that your Django code is referencing the same version of Python that you're using "everywhere" else. Snow Leopard comes with Python 2.6.1 by default found at /usr/bin/python.
If you've installed Python 2.7 by some other means, it's probably found at another path with a symlink at /usr/bin/python2.7 pointing to its actual location. If PIL is installed under Python 2.7, then you cannot be referencing /usr/bin/python in your code because that is pointing you to the wrong version of Python.
The best practice would be to explicitly specify that you want to use Python 2.7 in the shebang (#!/usr/bin/env python2.7) for your Django initialization script (e.g. manage.py).
| Django and PIL on Snow Leopard | I am trying to get PIL working with Django 1.2.1 and Python 2.7 on Snow Leopard
I have followed instructions I found here on SO and I should be doing it right.
The imports and selftest.py works fine and I both save and open images in the interactive python, but Django cannot use it.
I get the error
The _imaging C module is not installed
Why on earth does PIL seem to work everywhere but Django? I just doesn't make any sense.
I have even tried reinstalling Django after installing libjpeg and PIL, but with no results, what am I doing wrong?
EDIT:
I have just discovered something weird. I can open and save images just fine, by using the interactive python in terminal. But for some reason, when I save an image, the colors are inverted!
The code used is:
im = Image.open("/Users/Me/Downloads/9.jpg")
im.save("/Users/Me/Downloads/8.jpg")
Does that give any clues as to why it does not work in Django at all?
EDIT 2:
Nevermind that last part, it seems that the jpg I chose, was with CMYK colors, and that cannot be saved directly as an RGB or something along those lines.
EDIT 3:
And then again, maybe it is correct that Django is looking in the wrong place.
Exception Location: /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/PIL/Image.py in __getattr__, line 36
Python Executable: /Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python
Python Version: 2.7.0
This is what Django puts out. I just looked at the version, silly me. The top line clearly states that it is looking in the 2.5 path. Wonder why its 2.5 since SL should be born with 2.6, oh well, no matter.
Can anyone then tell me how to direct Django to use the newer ones? The solution with changing manage.pydid nothing. Why is that, that should have told Django to use 2.7 no matter what.. right?
| [
"I wrote a pretty extensive tutorial on how to get PIL, libjpeg to work on Snow leopard.\nMaybe this will help you out.\nhttp://appelfreelance.com/2010/06/libjpeg-pil-snow-leopard-python2-6-_jpeg_resync_to_restart/\nIf you don’t have this download it first.\nhttp://www.ijg.org/files/jpegsrc.v7.tar.gz\ngo into your ... | [
1,
0
] | [] | [] | [
"django",
"osx_snow_leopard",
"python",
"python_imaging_library"
] | stackoverflow_0003626169_django_osx_snow_leopard_python_python_imaging_library.txt |
Q:
How do I make this compatible with Windows?
Good day, Stackoverflow!
I have a little (big) problem with porting one of my Python scripts for Linux to Windows. The hairy thing about this is that I have to start a process and redirect all of its streams into pipes that I go over and read and write to and from in my script.
With Linux this is a piece of cake:
server_startcmd = [
"java",
"-Xmx%s" % self.java_heapmax,
"-Xms%s" % self.java_heapmin,
"-jar",
server_jar,
"nogui"
]
server = Popen(server_startcmd, stdout = PIPE,
stderr = PIPE,
stdin = PIPE)
outputs = [
server_socket, # A listener socket that has been setup before
server.stderr,
server.stdout,
sys.stdin # Because I also have to read and process this.
]
clients = []
while True:
read_ready, write_ready, except_ready = select.select(outputs, [], [], 1.0)
if read_ready == []:
perform_idle_command() # important step
else:
for s in read_ready:
if s == sys.stdin:
# Do stdin stuff
elif s == server_socket:
# Accept client and add it to 'clients'
elif s in clients:
# Got data from one of the clients
The whole 3 way alternating between a server socket, stdin of the script and the output channels of the child process (as well as the input channel, as my script will write to that one, although that one is not in the select() list) is the most important part of the script.
I know that for Windows there is win32pipe in the win32api module. The problem is that finding resources to this API is pretty hard, and what I found was not really helpful.
How do I utilize this win32pipe module to do what I want? I have some sources where it's being used in a different but similar situation, but that confused me pretty much:
if os.name == 'nt':
import win32pipe
(stdin, stdout) = win32pipe.popen4(" ".join(server_args))
else:
server = Popen(server_args,
stdout = PIPE,
stdin = PIPE,
stderr = PIPE)
outputs = [server.stderr, server.stdout, sys.stdin]
stdin = server.stdin
[...]
while True:
try:
if os.name == 'nt':
outready = [stdout]
else:
outready, inready, exceptready = select.select(outputs, [], [], 1.0)
except:
break
stdout here is the combined stdout and stderr of the child process that has been started with win32pipe.popen4(...)
The questions arsing are:
Why not select() for the windows version? Does that not work?
If you don't use select() there, how can I implement the neccessary timeout that select() provides (which obviously won't work like this here)
Please, help me out!
A:
I think you cannot use select() on pipes.
In one of the projects, where I was porting a linux app to Windows I too had missed this point and had to rewrite the whole logic.
| How do I make this compatible with Windows? | Good day, Stackoverflow!
I have a little (big) problem with porting one of my Python scripts for Linux to Windows. The hairy thing about this is that I have to start a process and redirect all of its streams into pipes that I go over and read and write to and from in my script.
With Linux this is a piece of cake:
server_startcmd = [
"java",
"-Xmx%s" % self.java_heapmax,
"-Xms%s" % self.java_heapmin,
"-jar",
server_jar,
"nogui"
]
server = Popen(server_startcmd, stdout = PIPE,
stderr = PIPE,
stdin = PIPE)
outputs = [
server_socket, # A listener socket that has been setup before
server.stderr,
server.stdout,
sys.stdin # Because I also have to read and process this.
]
clients = []
while True:
read_ready, write_ready, except_ready = select.select(outputs, [], [], 1.0)
if read_ready == []:
perform_idle_command() # important step
else:
for s in read_ready:
if s == sys.stdin:
# Do stdin stuff
elif s == server_socket:
# Accept client and add it to 'clients'
elif s in clients:
# Got data from one of the clients
The whole 3 way alternating between a server socket, stdin of the script and the output channels of the child process (as well as the input channel, as my script will write to that one, although that one is not in the select() list) is the most important part of the script.
I know that for Windows there is win32pipe in the win32api module. The problem is that finding resources to this API is pretty hard, and what I found was not really helpful.
How do I utilize this win32pipe module to do what I want? I have some sources where it's being used in a different but similar situation, but that confused me pretty much:
if os.name == 'nt':
import win32pipe
(stdin, stdout) = win32pipe.popen4(" ".join(server_args))
else:
server = Popen(server_args,
stdout = PIPE,
stdin = PIPE,
stderr = PIPE)
outputs = [server.stderr, server.stdout, sys.stdin]
stdin = server.stdin
[...]
while True:
try:
if os.name == 'nt':
outready = [stdout]
else:
outready, inready, exceptready = select.select(outputs, [], [], 1.0)
except:
break
stdout here is the combined stdout and stderr of the child process that has been started with win32pipe.popen4(...)
The questions arsing are:
Why not select() for the windows version? Does that not work?
If you don't use select() there, how can I implement the neccessary timeout that select() provides (which obviously won't work like this here)
Please, help me out!
| [
"I think you cannot use select() on pipes.\nIn one of the projects, where I was porting a linux app to Windows I too had missed this point and had to rewrite the whole logic.\n"
] | [
0
] | [] | [] | [
"pipe",
"portability",
"python",
"subprocess"
] | stackoverflow_0003477365_pipe_portability_python_subprocess.txt |
Q:
Suppress wxPython GridTableBase refresh?
How can I make the code snippet below refresh when I want?
For example, if I run it as it is now, the table.SetValue(0,0,'test') line will update the grid straight away. Is there anyway to change this behavior so that I can do an arbitrary amount of changes to the GridTableBase, and then ask for a refresh? If so, how can I change the code below to get that functionality?
import wx
import wx.grid
class TestTable(wx.grid.PyGridTableBase):
def __init__(self):
wx.grid.PyGridTableBase.__init__(self)
self.data = { (1,1) : "Here", (2,2) : "is", (3,3) : "some", (4,4) : "data"}
self.odd=wx.grid.GridCellAttr()
self.odd.SetBackgroundColour("sky blue")
self.odd.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.BOLD))
self.even=wx.grid.GridCellAttr()
self.even.SetBackgroundColour("sea green")
self.even.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.BOLD))
def GetNumberRows(self):
return 50
def GetNumberCols(self):
return 50
def IsEmptyCell(self, row, col):
return self.data.get((row, col)) is not None
def GetValue(self, row, col):
value = self.data.get((row, col))
if value is not None:
return value
else:
return ''
def SetValue(self, row, col, value):
self.data[(row,col)] = value
def GetAttr(self, row, col, kind):
attr = [self.even, self.odd][row % 2]
attr.IncRef()
return attr
class TestFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title="Grid Table", size=(640,480))
grid = wx.grid.Grid(self)
table = TestTable()
grid.SetTable(table, True)
table.SetValue(0,0,'test')
app = wx.PySimpleApp()
frame = TestFrame()
frame.Show()
app.MainLoop()
A:
There are the BeginBatch and EndBatch grid methods for this but they don't seam to work with custom grid tables.
You could try delaying the grid.SetTable call until after you populate the data. For consecutive batches you could clone the current grid table, make the necessary modifications on the clone and set the clone as the current grid table.
If you try this you will probably want to manage these grid tables yourself so don't make the grid take ownership of them as you did in your example (the True argument in the SetTable call).
| Suppress wxPython GridTableBase refresh? | How can I make the code snippet below refresh when I want?
For example, if I run it as it is now, the table.SetValue(0,0,'test') line will update the grid straight away. Is there anyway to change this behavior so that I can do an arbitrary amount of changes to the GridTableBase, and then ask for a refresh? If so, how can I change the code below to get that functionality?
import wx
import wx.grid
class TestTable(wx.grid.PyGridTableBase):
def __init__(self):
wx.grid.PyGridTableBase.__init__(self)
self.data = { (1,1) : "Here", (2,2) : "is", (3,3) : "some", (4,4) : "data"}
self.odd=wx.grid.GridCellAttr()
self.odd.SetBackgroundColour("sky blue")
self.odd.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.BOLD))
self.even=wx.grid.GridCellAttr()
self.even.SetBackgroundColour("sea green")
self.even.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.BOLD))
def GetNumberRows(self):
return 50
def GetNumberCols(self):
return 50
def IsEmptyCell(self, row, col):
return self.data.get((row, col)) is not None
def GetValue(self, row, col):
value = self.data.get((row, col))
if value is not None:
return value
else:
return ''
def SetValue(self, row, col, value):
self.data[(row,col)] = value
def GetAttr(self, row, col, kind):
attr = [self.even, self.odd][row % 2]
attr.IncRef()
return attr
class TestFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title="Grid Table", size=(640,480))
grid = wx.grid.Grid(self)
table = TestTable()
grid.SetTable(table, True)
table.SetValue(0,0,'test')
app = wx.PySimpleApp()
frame = TestFrame()
frame.Show()
app.MainLoop()
| [
"There are the BeginBatch and EndBatch grid methods for this but they don't seam to work with custom grid tables.\nYou could try delaying the grid.SetTable call until after you populate the data. For consecutive batches you could clone the current grid table, make the necessary modifications on the clone and set th... | [
0
] | [] | [] | [
"grid",
"python",
"wxpython"
] | stackoverflow_0003633519_grid_python_wxpython.txt |
Q:
Secure use of GAE application namespace
I'd like to have a mapping of users to accounts, and then have users directed to a namespace corresponding to their account.
Having looked at the appengine_config.py from the suggested example, there appear to be a few suggested ways to determine what the namespace ought to be, i.e.
Server name
Google Apps Domain
Cookie
I would like to have namespaces selected based on a lookup in the datastore. i.e.
namespace = user.account.name
For some user object that is linked to an account, which account has a name field. There area few ways I've posited to accomplish this:
datastore lookup on each request
memcache lookup on each request (fallback to datastore when memcache expires)
secure cookie data
The datastore lookup would be two slow. Is there any such reservation with a memcache lookup? e.g. memcache.get('nslookup:%s' % user_id), given a user_id. (I trust the users object works as expected in appengine_config.py).
Alternatively, one could use a secure cookie to solve this. I'm not satisfied with the security of the "Secure" flag (i.e. forcing SSL). However, I'm not sure about how best to secure the data in the cookie. I suppose symmetric encryption with signing with PyCrypto using a secret key in GAE along is one way to get started on this path. Although this pattern has been vetted, I'd be grateful for any thoughts on this suggested solution in particular.
Secure cookies don't seem the best route from an idealogical standpoint; I already expect to have the user identity, all I need is a mapping from the user to their account - there is no logical basis for encrypting, sending, storing, receiving, and decrypting that mapping on every request. The memcache options seems best of the three, but I'd be grateful for thoughts and input. The only reason I can think of to use secure cookies would be performance, or alternatively if memcache access were unavailable in the appengine_config.py.
Thoughts and input and challenges to my assumptions are most welcome.
Thank you for reading.
Brian
A:
I think that secure cookies are the way to go because they are fast enough. A basic implementation extracted from Tornado is here (you just need the SecureCookie class and can ignore the "session" stuff):
http://code.google.com/p/webapp-improved/source/browse/extras/sessions.py#104
A:
Performance-wise, anything that avoids a need for memcache or datastore lookups on each request is going to be the best option. You're confusing two definitions of 'secure' cookie, though: the 'secure' flag in the cookie spec mandates that the cookie is only sent over SSL, while in the other sense, a 'secure' cookie is one that cannot be modified undetectably by the user - which is what is most important in this use case.
There's no need to encrypt the contents, though - you want to prevent modification, not disclosure - so if you can't use an existing library, you can simply append an HMAC of the cookie to the end of it, using a secret key that you embed in your application. Verifying the HMAC on each request will be much faster than using memcache.
| Secure use of GAE application namespace | I'd like to have a mapping of users to accounts, and then have users directed to a namespace corresponding to their account.
Having looked at the appengine_config.py from the suggested example, there appear to be a few suggested ways to determine what the namespace ought to be, i.e.
Server name
Google Apps Domain
Cookie
I would like to have namespaces selected based on a lookup in the datastore. i.e.
namespace = user.account.name
For some user object that is linked to an account, which account has a name field. There area few ways I've posited to accomplish this:
datastore lookup on each request
memcache lookup on each request (fallback to datastore when memcache expires)
secure cookie data
The datastore lookup would be two slow. Is there any such reservation with a memcache lookup? e.g. memcache.get('nslookup:%s' % user_id), given a user_id. (I trust the users object works as expected in appengine_config.py).
Alternatively, one could use a secure cookie to solve this. I'm not satisfied with the security of the "Secure" flag (i.e. forcing SSL). However, I'm not sure about how best to secure the data in the cookie. I suppose symmetric encryption with signing with PyCrypto using a secret key in GAE along is one way to get started on this path. Although this pattern has been vetted, I'd be grateful for any thoughts on this suggested solution in particular.
Secure cookies don't seem the best route from an idealogical standpoint; I already expect to have the user identity, all I need is a mapping from the user to their account - there is no logical basis for encrypting, sending, storing, receiving, and decrypting that mapping on every request. The memcache options seems best of the three, but I'd be grateful for thoughts and input. The only reason I can think of to use secure cookies would be performance, or alternatively if memcache access were unavailable in the appengine_config.py.
Thoughts and input and challenges to my assumptions are most welcome.
Thank you for reading.
Brian
| [
"I think that secure cookies are the way to go because they are fast enough. A basic implementation extracted from Tornado is here (you just need the SecureCookie class and can ignore the \"session\" stuff): \nhttp://code.google.com/p/webapp-improved/source/browse/extras/sessions.py#104\n",
"Performance-wise, any... | [
1,
1
] | [] | [] | [
"google_app_engine",
"namespaces",
"python"
] | stackoverflow_0003610044_google_app_engine_namespaces_python.txt |
Q:
Adobe Air2 NativeProcess API with Javascript
I am trying to launch a python script with the NativeProcess API from Javascript.
On the Adobe AIR API Reference for HTML Developers I found a good example for that task, but it does not work. I looked up tons of other examples but still can not find the answer.
Here is the example code for the html file:
<html>
<head>
<title>Test</title>
<script type="text/javascript" src="AIRAliases.js"></script>
<script type="text/javascript">
var process;
function launchProcess()
{
if(air.NativeProcess.isSupported)
{
air.trace("NativeProcess supported.");
setupAndLaunch();
}
else
{
air.trace("NativeProcess not supported.");
}
}
function setupAndLaunch()
{
var nativeProcessStartupInfo = new air.NativeProcessStartupInfo();
var file = air.File.applicationDirectory.resolvePath("test.py");
nativeProcessStartupInfo.executable = file;
var processArgs = new air.Vector["<String>"]();
processArgs.push("foo");
nativeProcessStartupInfo.arguments = processArgs;
process = new air.NativeProcess();
process.start(nativeProcessStartupInfo);
process.addEventListener(air.ProgressEvent.STANDARD_OUTPUT_DATA, onOutputData);
process.addEventListener(air.ProgressEvent.STANDARD_ERROR_DATA, onErrorData);
process.addEventListener(air.NativeProcessExitEvent.EXIT, onExit);
process.addEventListener(air.IOErrorEvent.STANDARD_OUTPUT_IO_ERROR, onIOError);
process.addEventListener(air.IOErrorEvent.STANDARD_ERROR_IO_ERROR, onIOError);
}
function onOutputData()
{
air.trace("Got: ", process.standardOutput.readUTFBytes(process.standardOutput.bytesAvailable));
}
function onErrorData(event)
{
air.trace("ERROR -", process.standardError.readUTFBytes(process.standardError.bytesAvailable));
}
function onExit(event)
{
air.trace("Process exited with ", event.exitCode);
}
function onIOError(event)
{
air.trace(event.toString());
}
</script>
</head>
<body onload="launchProcess()">
</body>
</html>
And here the code for the python file (it does not work):
#! /usr/bin/env python2.5
# -*- coding: utf-8 -*-
import sys
for word in sys.argv: #echo the command line arguments
print word
print "HI FROM PYTHON"
print "Enter user name"
line = sys.stdin.readline()
sys.stdout.write("hello," + line)
Running the Air App with the command adl main.xml shows in my terminal (I use OSX) only "NativeProcess supported."
Thanks for help.
And here the changes I did to the python file to get it working:
#! /usr/bin/env python2.5
# -*- coding: utf-8 -*-
import sys
import os
def convert(args):
path = os.path.expanduser('~') + "/Desktop/"
myFile = open(path+args, 'w')
myFile.write('Hello World\n')
myFile.close()
sys.stdout.write("Python Done")
if __name__ == "__main__":
convert(sys.argv[1])
Thanks to pyfunc...
A:
If you run your program, then following is the output:
test.py
HI FROM PYTHON
Enter user name
Thats is this piece of python code is looking for standard input and writing to standard output.
I don't think that would be possible if you do not run that from shell.
How about removing:
line = sys.stdin.readline()
sys.stdout.write("hello," + line)
and do some innocuous python expressions like
a = 1+4
and see, if that works. I have a hunch that this might be an issue.
| Adobe Air2 NativeProcess API with Javascript | I am trying to launch a python script with the NativeProcess API from Javascript.
On the Adobe AIR API Reference for HTML Developers I found a good example for that task, but it does not work. I looked up tons of other examples but still can not find the answer.
Here is the example code for the html file:
<html>
<head>
<title>Test</title>
<script type="text/javascript" src="AIRAliases.js"></script>
<script type="text/javascript">
var process;
function launchProcess()
{
if(air.NativeProcess.isSupported)
{
air.trace("NativeProcess supported.");
setupAndLaunch();
}
else
{
air.trace("NativeProcess not supported.");
}
}
function setupAndLaunch()
{
var nativeProcessStartupInfo = new air.NativeProcessStartupInfo();
var file = air.File.applicationDirectory.resolvePath("test.py");
nativeProcessStartupInfo.executable = file;
var processArgs = new air.Vector["<String>"]();
processArgs.push("foo");
nativeProcessStartupInfo.arguments = processArgs;
process = new air.NativeProcess();
process.start(nativeProcessStartupInfo);
process.addEventListener(air.ProgressEvent.STANDARD_OUTPUT_DATA, onOutputData);
process.addEventListener(air.ProgressEvent.STANDARD_ERROR_DATA, onErrorData);
process.addEventListener(air.NativeProcessExitEvent.EXIT, onExit);
process.addEventListener(air.IOErrorEvent.STANDARD_OUTPUT_IO_ERROR, onIOError);
process.addEventListener(air.IOErrorEvent.STANDARD_ERROR_IO_ERROR, onIOError);
}
function onOutputData()
{
air.trace("Got: ", process.standardOutput.readUTFBytes(process.standardOutput.bytesAvailable));
}
function onErrorData(event)
{
air.trace("ERROR -", process.standardError.readUTFBytes(process.standardError.bytesAvailable));
}
function onExit(event)
{
air.trace("Process exited with ", event.exitCode);
}
function onIOError(event)
{
air.trace(event.toString());
}
</script>
</head>
<body onload="launchProcess()">
</body>
</html>
And here the code for the python file (it does not work):
#! /usr/bin/env python2.5
# -*- coding: utf-8 -*-
import sys
for word in sys.argv: #echo the command line arguments
print word
print "HI FROM PYTHON"
print "Enter user name"
line = sys.stdin.readline()
sys.stdout.write("hello," + line)
Running the Air App with the command adl main.xml shows in my terminal (I use OSX) only "NativeProcess supported."
Thanks for help.
And here the changes I did to the python file to get it working:
#! /usr/bin/env python2.5
# -*- coding: utf-8 -*-
import sys
import os
def convert(args):
path = os.path.expanduser('~') + "/Desktop/"
myFile = open(path+args, 'w')
myFile.write('Hello World\n')
myFile.close()
sys.stdout.write("Python Done")
if __name__ == "__main__":
convert(sys.argv[1])
Thanks to pyfunc...
| [
"If you run your program, then following is the output:\ntest.py\nHI FROM PYTHON\nEnter user name\n\nThats is this piece of python code is looking for standard input and writing to standard output.\nI don't think that would be possible if you do not run that from shell.\nHow about removing:\nline = sys.stdin.readli... | [
0
] | [] | [] | [
"air",
"javascript",
"python"
] | stackoverflow_0003633914_air_javascript_python.txt |
Q:
HTTP Webserver with FCGI written in Python?
For a project i need a python webserver (can use C modules if necessary).
The basic http server from the runtime is way to simple - at least i need FCGI compatibility for some legacy modules.
Is there any other standalone server which is not totally connected to a certain framework like the Zope Webserver?
Performance is not really important.
A:
You can look into following along with twisted mentioned below, which also has fastcgi support.
http://trac.saddi.com/flup
http://fcgi-python.sourceforge.net/
http://webpy.org/cookbook/fastcgi-lighttpd
http://www.vitohuang.info/blog/2009/06/12/lighty-with-web-py-via-fastcgi/
A:
Twisted can do it supposedly.
| HTTP Webserver with FCGI written in Python? | For a project i need a python webserver (can use C modules if necessary).
The basic http server from the runtime is way to simple - at least i need FCGI compatibility for some legacy modules.
Is there any other standalone server which is not totally connected to a certain framework like the Zope Webserver?
Performance is not really important.
| [
"You can look into following along with twisted mentioned below, which also has fastcgi support.\n\nhttp://trac.saddi.com/flup\nhttp://fcgi-python.sourceforge.net/\nhttp://webpy.org/cookbook/fastcgi-lighttpd\nhttp://www.vitohuang.info/blog/2009/06/12/lighty-with-web-py-via-fastcgi/\n\n",
"Twisted can do it suppos... | [
1,
0
] | [] | [] | [
"http",
"python",
"webserver"
] | stackoverflow_0003634108_http_python_webserver.txt |
Q:
Problem parsing XML with namespaces
hi i have xml file whitch i want to parse, it looks something like this
<?xml version="1.0" encoding="utf-8"?>
<SHOP xmlns="http://www.w3.org/1999/xhtml" xmlns:php="http://php.net/xsl">
<SHOPITEM>
<ID>2332</ID>
...
</SHOPITEM>
<SHOPITEM>
<ID>4433</ID>
...
</SHOPITEM>
</SHOP>
my parsing code is
from lxml import etree
ifile = open('sample-file.xml', 'r')
file_data = etree.parse(ifile)
for item in file_data.iter('SHOPITEM'):
print item
but item is print only when xml container
<SHOP xmlns="http://www.w3.org/1999/xhtml" xmlns:php="http://php.net/xsl">
looks like
<SHOP>
how can i parse xml document without worrying about this container definition?
A:
See here for an explanation of how lxml.etree handles namespaces. In general, you should work with them rather than try to avoid them. In this case, write:
for item in file_data.iter('{http://www.w3.org/1999/xhtml}SHOPITEM'):
If you need to refer the namespace frequently, setup a local variable:
xhtml_ns = '{http://www.w3.org/1999/xhtml}'
...
for item in file_data.iter(xhtml_ns + 'SHOPITEM'):
| Problem parsing XML with namespaces | hi i have xml file whitch i want to parse, it looks something like this
<?xml version="1.0" encoding="utf-8"?>
<SHOP xmlns="http://www.w3.org/1999/xhtml" xmlns:php="http://php.net/xsl">
<SHOPITEM>
<ID>2332</ID>
...
</SHOPITEM>
<SHOPITEM>
<ID>4433</ID>
...
</SHOPITEM>
</SHOP>
my parsing code is
from lxml import etree
ifile = open('sample-file.xml', 'r')
file_data = etree.parse(ifile)
for item in file_data.iter('SHOPITEM'):
print item
but item is print only when xml container
<SHOP xmlns="http://www.w3.org/1999/xhtml" xmlns:php="http://php.net/xsl">
looks like
<SHOP>
how can i parse xml document without worrying about this container definition?
| [
"See here for an explanation of how lxml.etree handles namespaces. In general, you should work with them rather than try to avoid them. In this case, write:\nfor item in file_data.iter('{http://www.w3.org/1999/xhtml}SHOPITEM'):\n\nIf you need to refer the namespace frequently, setup a local variable:\nxhtml_ns = '{... | [
3
] | [] | [] | [
"lxml",
"parsing",
"python",
"xml",
"xml_parsing"
] | stackoverflow_0003634420_lxml_parsing_python_xml_xml_parsing.txt |
Q:
how to render to response?
I am sending list to a template using render_to_response. I am using django shortcuts. Hoe to do that? How to set context instance with a variable?
A:
Like any template value.
def some_view(request):
# ...
my_data_dictionary = { 'somelist': my_list }
return render_to_response('my_template.html',
my_data_dictionary,
context_instance=RequestContext(request))
By the way, there's a nice documentation.
A:
from django.shortcuts import render_to_response
def my_view(request):
mylist = ['item 1', 'item 2', 'item 3']
return render_to_response('template.html', {'mylist':mylist})
You can then access and enumerate list in the template like this (amongst other methods):
{% for i in mylist %}
{{ i }},
{% endfor %}
A:
You can send a list in a context. For instance:
my_list = [1, 2, 3, 4]
context = dict(my_list = my_list)
render_to_response(template, context)
Read the relevant documentation for more information.
If you want additional information to be passed to the template then use a RequestContext to wrap the context dictionary. You will need to enable the appropriate context processor for this.
| how to render to response? | I am sending list to a template using render_to_response. I am using django shortcuts. Hoe to do that? How to set context instance with a variable?
| [
"Like any template value.\ndef some_view(request):\n # ...\n my_data_dictionary = { 'somelist': my_list }\n return render_to_response('my_template.html',\n my_data_dictionary,\n context_instance=RequestContext(request))\n\nBy the way, there's a nice... | [
2,
2,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003635073_django_python.txt |
Q:
SQLAlchemy: writing to database after the response has been sent
I have a simple service that does approximately the following:
An HTTP client connects to the server
The server writes the sessionID of the client and the timestamp to the database, and in most cases just returns an empty response
(The cases when it does do real work and return actual data are irrelevant to this question)
In order to return this response as soon as possible, I'd like to write the info to memcache in the request handler's body (because memcache is fast), and to spawn a separate thread where another function using SQLAlchemy will write it to the persistent storage. This way, I'll be able to return immediately after writing to memcache and spawning a thread, and the request handler will not have to wait until SQLAlchemy saves the info to the database.
Does this make sense? If yes, how should I implement it?
A:
You could use something like the Celery distributed task queue to offload processing to other machines. It does require setup of a separate infrastructure, but will allow for tasks to be handed off from web requests for processing in the background, while the HTTP repsonse to the request can be returned immediately.
| SQLAlchemy: writing to database after the response has been sent | I have a simple service that does approximately the following:
An HTTP client connects to the server
The server writes the sessionID of the client and the timestamp to the database, and in most cases just returns an empty response
(The cases when it does do real work and return actual data are irrelevant to this question)
In order to return this response as soon as possible, I'd like to write the info to memcache in the request handler's body (because memcache is fast), and to spawn a separate thread where another function using SQLAlchemy will write it to the persistent storage. This way, I'll be able to return immediately after writing to memcache and spawning a thread, and the request handler will not have to wait until SQLAlchemy saves the info to the database.
Does this make sense? If yes, how should I implement it?
| [
"You could use something like the Celery distributed task queue to offload processing to other machines. It does require setup of a separate infrastructure, but will allow for tasks to be handed off from web requests for processing in the background, while the HTTP repsonse to the request can be returned immediatel... | [
2
] | [] | [] | [
"data_storage",
"memcached",
"optimization",
"python"
] | stackoverflow_0003631832_data_storage_memcached_optimization_python.txt |
Q:
to parse chat conversations stored in a file
poem = '''\
me:hello dear
me:hyyy
asha:edaaaa
'''
f=open('poem.txt','r')
arr=[]
arr1=[]
varr=[]
darr=[]
i=0
j=1
for line in f.read().split('\n'):
arr.append(line)
i+=1
f.close()
#print arr[0]
#print arr[1]
#print arr[2]
text=arr[0].split(':')
#print text
line=text[0]
#print line
arr1.append(text[1])
for i in range(1,len(arr)):
text=arr[i].split(':')
if(line==text[0]):
#print text[1]
arr1.append(text[1])
else:
if(j==1):
j+=1
varr[j]=text[0] # this is not working
darr[j]=text[1]
print len(varr)
f.close()
print arr1
A:
CRYSTAL BALL MODE ON
from collections import defaultdict
result = defaultdict(list)
with open('chat.log') as f:
for line in f:
nick, msg = line.split(':', 1)
result[nick].append(msg)
print result
A:
You are attempting to assign to varr[2], but varr is an empty list, so you would get an index error
There are a number of ways to fix this code, but it's not clear to me what the code is supposed to do
Nosklo's answer seemed reasonable to me, until I thought about it some more. I am not sure there is much point grouping the lines by the name since it means that the overall structure of the file is lost.
Here is how to simply parse the file into a list which you can manipulate later
result = []
with open('poem.txt') as f:
for line in f:
result.append(line.partition(':')[::2])
print result
| to parse chat conversations stored in a file | poem = '''\
me:hello dear
me:hyyy
asha:edaaaa
'''
f=open('poem.txt','r')
arr=[]
arr1=[]
varr=[]
darr=[]
i=0
j=1
for line in f.read().split('\n'):
arr.append(line)
i+=1
f.close()
#print arr[0]
#print arr[1]
#print arr[2]
text=arr[0].split(':')
#print text
line=text[0]
#print line
arr1.append(text[1])
for i in range(1,len(arr)):
text=arr[i].split(':')
if(line==text[0]):
#print text[1]
arr1.append(text[1])
else:
if(j==1):
j+=1
varr[j]=text[0] # this is not working
darr[j]=text[1]
print len(varr)
f.close()
print arr1
| [
"CRYSTAL BALL MODE ON\nfrom collections import defaultdict\nresult = defaultdict(list)\n\nwith open('chat.log') as f:\n for line in f:\n nick, msg = line.split(':', 1)\n result[nick].append(msg)\n\nprint result\n\n",
"You are attempting to assign to varr[2], but varr is an empty list, so you woul... | [
5,
0
] | [] | [] | [
"python"
] | stackoverflow_0003635541_python.txt |
Q:
Automatic editor of XML (based on XSD scheme)
Is there any approach to generate editor of an XML file basing on an XSD scheme? (It should be a Java or Python web based editor).
A:
ExxEditor is an XML editor based on XML Schema. This is a C++ project, and it's not web based at all.
I never used it, but I think the XML Schema files can be annotated to "customize" the UI.
A:
Funny, I'm concerning myself with something similar. I'm building an editor (not really WYSIWYG, but it abstracts the DOM away) for the XMLs Civilization 4 (strategy game) usesu to store about everything. I thought about it for quite a while and built two prototypes (in Python), one of which looks promising so I will extend it in the future. Note that Civ 4 XMLs are merely more than a buzzword-conform database (just the kind of data you better store in JSON/YAML and the like, mostly key-value pairs with a few sublists of key-value pairs - no recursive data structures).
My first approach was based on the fact that there are mostly key-value pairs, which doesn't fit documents that exploit the full power of XML (recursive data structures, etc). My new design is more sophisticated - up to now, I only built a (still buggy) validator factory this way, but I'm looking forward to extend it, e.g. for schema-sensetive editing widgets. The basic idea is to walk the XSD's DOM, recognize the expected content (a list of other nodes, text of a specific format, etc), build in turn (recursively) validators for these, and then build a higher-order validator that applies all the previously generated validators in the right order. It propably takes some exposure to functional programming to get comfortable with the idea. For the editing part (btw, I use PyQt), I plan to generate a Label-LineEdit pair for tags which contain text and a heading (Label) for tags that contain other elements, possibly indenting the subelements and/or providing folding. Again, recursion is the key to build these.
Qt allows us to attach a validator to an text input widget, so this part is easy once we can generate a validator for e.g. a tag containing an "int". For tags containing other tags, something similar to the above is possible: Generate a validator for each subelement and chain them. The only part that needs to change is how we get the content. Ignoring comments, attributes, processing instructions, etc, this should still be relatively simple - for a "tag: content" pair, generate "content" and feed it to your DOM parser; for elements with subelements, generate a representation of the children and put it between "...". Attributes could be implemented as key-value pairs too, only with an extra flag.
A:
With Jaxe you can automatically create a configuration file from an XSD file, and edit it by hand to improve it. This gives you a specialized XML editor for the language. You can then use this configuration file with WebJaxe to edit your files on the web. It is not suited if you change the XSD all the time, though (you did not specify that)...
Jaxe is a Java application and WebJaxe is using Jaxe as a Java applet for the editor.
| Automatic editor of XML (based on XSD scheme) | Is there any approach to generate editor of an XML file basing on an XSD scheme? (It should be a Java or Python web based editor).
| [
"ExxEditor is an XML editor based on XML Schema. This is a C++ project, and it's not web based at all.\nI never used it, but I think the XML Schema files can be annotated to \"customize\" the UI.\n",
"Funny, I'm concerning myself with something similar. I'm building an editor (not really WYSIWYG, but it abstracts... | [
2,
1,
1
] | [] | [] | [
"java",
"python",
"xml",
"xsd"
] | stackoverflow_0003599569_java_python_xml_xsd.txt |
Q:
Are there conventions for Python module comments?
It is my understanding that a module docstring should just provide a general description of what a module does and details such as author and version should only be contained in the module's comments.
However, I have seen the following in comments and docstrings:
__author__ = "..."
__version__ = "..."
__date__ = "..."
Where is the correct location to put items such as these? What other __[name]__ variables are common to list at the top of modules?
A:
They are merely conventions, albeit quite widely-used conventions. See this description of a set of Python metadata requirements.
__version__ is mentioned in the Python Style Guide.
Regarding docstrings, there's a PEP just for you!
The docstring for a module should
generally list the classes, exceptions
and functions (and any other objects)
that are exported by the module, with
a one-line summary of each. (These
summaries generally give less detail
than the summary line in the object's
docstring.) The docstring for a
package (i.e., the docstring of the
package's init.py module) should
also list the modules and subpackages
exported by the package.
A:
You could have a look at:
Epydoc, more specifically its pre-defined fields.
Pydoc
A:
I would suggest not to worry about __author__, __version__, etc. Those attributes are handled by any decent version control system anyway. Only add them if you need to have that information on a production system, where the source code has already been exported out of the version control system.
| Are there conventions for Python module comments? | It is my understanding that a module docstring should just provide a general description of what a module does and details such as author and version should only be contained in the module's comments.
However, I have seen the following in comments and docstrings:
__author__ = "..."
__version__ = "..."
__date__ = "..."
Where is the correct location to put items such as these? What other __[name]__ variables are common to list at the top of modules?
| [
"They are merely conventions, albeit quite widely-used conventions. See this description of a set of Python metadata requirements.\n__version__ is mentioned in the Python Style Guide.\nRegarding docstrings, there's a PEP just for you!\n\nThe docstring for a module should\n generally list the classes, exceptions\n ... | [
8,
5,
3
] | [] | [] | [
"comments",
"conventions",
"module",
"python"
] | stackoverflow_0003635988_comments_conventions_module_python.txt |
Q:
CookieJarLib wont save cookies back to File?
I am working off of the example code given by Anthony Briggs. However it doesn't seem to save the cookies back into the defined cookie file.
My modified code. I switched to using LWPCookieJar because its supposedly fully compatible and also removed the login code into a separate function so that I can first test if I am login, and then if not, call the login functionality.
If I login with an object, get new cookies, save them, and then create a new object loading the same file, it reverts to the cookies stored before login.
Test Code:
facebookObject = FacebookBrowser(cookie_filename)
#check if authenticated
success=myAuthenticationTest(facebookObject)
if not success:
facebookObject.setupUser(facebookObject.login, facebookObject.password, cookie_filename)
resp = facebookObject.opener.open(testurl) #new cookies should be set
facebookObject.cj.save(cookie_filename)
saved_cookies = facebookObject.cj
facebookObject2 = FacebookBrowser(cookie_filename)
newly_loaded_cookies = facebookObject2.cj
#saved_cookies != newly_loaded_cookies
Class Code:
class FacebookBrowser(object):
def __init__(self,cookie_filename):
""" Start up... """
self.login = xxxxx
self.password = yyyyyy
self.cookie_filename = cookie_filename
self.cj = cookielib.LWPCookieJar(cookie_filename)
if os.access(cookie_filename, os.F_OK):
self.cj.load()
self.opener = urllib2.build_opener(
urllib2.HTTPRedirectHandler(),
urllib2.HTTPHandler(debuglevel=0),
urllib2.HTTPSHandler(debuglevel=0),
urllib2.HTTPCookieProcessor(self.cj)
)
self.opener.addheaders = [
('User-agent', ('Mozilla/5.0 (Windows; U; Windows NT 6.1; he; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3'))
]
def setupUser(self, login, password,cookie_filename):
# need this twice - once to set cookies, once to log in...
self.loginToFacebook()
self.loginToFacebook()
self.cj.save()
self.opener = urllib2.build_opener(
urllib2.HTTPRedirectHandler(),
urllib2.HTTPHandler(debuglevel=0),
urllib2.HTTPSHandler(debuglevel=0),
urllib2.HTTPCookieProcessor(self.cj)
)
self.cj.save()
def loginToFacebook(self):
"""
Handle login. This should populate our cookie jar.
"""
login_data = urllib.urlencode({
'email' : self.login,
'pass' : self.password,
})
response = self.opener.open("https://login.facebook.com/login.php", login_data)
return ''.join(response.readlines())
A:
I just read on another forum that I needed to set ignore_discard=True in all the .save() and .load() methods.
| CookieJarLib wont save cookies back to File? | I am working off of the example code given by Anthony Briggs. However it doesn't seem to save the cookies back into the defined cookie file.
My modified code. I switched to using LWPCookieJar because its supposedly fully compatible and also removed the login code into a separate function so that I can first test if I am login, and then if not, call the login functionality.
If I login with an object, get new cookies, save them, and then create a new object loading the same file, it reverts to the cookies stored before login.
Test Code:
facebookObject = FacebookBrowser(cookie_filename)
#check if authenticated
success=myAuthenticationTest(facebookObject)
if not success:
facebookObject.setupUser(facebookObject.login, facebookObject.password, cookie_filename)
resp = facebookObject.opener.open(testurl) #new cookies should be set
facebookObject.cj.save(cookie_filename)
saved_cookies = facebookObject.cj
facebookObject2 = FacebookBrowser(cookie_filename)
newly_loaded_cookies = facebookObject2.cj
#saved_cookies != newly_loaded_cookies
Class Code:
class FacebookBrowser(object):
def __init__(self,cookie_filename):
""" Start up... """
self.login = xxxxx
self.password = yyyyyy
self.cookie_filename = cookie_filename
self.cj = cookielib.LWPCookieJar(cookie_filename)
if os.access(cookie_filename, os.F_OK):
self.cj.load()
self.opener = urllib2.build_opener(
urllib2.HTTPRedirectHandler(),
urllib2.HTTPHandler(debuglevel=0),
urllib2.HTTPSHandler(debuglevel=0),
urllib2.HTTPCookieProcessor(self.cj)
)
self.opener.addheaders = [
('User-agent', ('Mozilla/5.0 (Windows; U; Windows NT 6.1; he; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3'))
]
def setupUser(self, login, password,cookie_filename):
# need this twice - once to set cookies, once to log in...
self.loginToFacebook()
self.loginToFacebook()
self.cj.save()
self.opener = urllib2.build_opener(
urllib2.HTTPRedirectHandler(),
urllib2.HTTPHandler(debuglevel=0),
urllib2.HTTPSHandler(debuglevel=0),
urllib2.HTTPCookieProcessor(self.cj)
)
self.cj.save()
def loginToFacebook(self):
"""
Handle login. This should populate our cookie jar.
"""
login_data = urllib.urlencode({
'email' : self.login,
'pass' : self.password,
})
response = self.opener.open("https://login.facebook.com/login.php", login_data)
return ''.join(response.readlines())
| [
"I just read on another forum that I needed to set ignore_discard=True in all the .save() and .load() methods. \n"
] | [
2
] | [] | [] | [
"cookies",
"python",
"urllib2"
] | stackoverflow_0003630307_cookies_python_urllib2.txt |
Q:
About IMAP UID with imaplib
I try to move email from mailbox's gmail to another one, Just curious that UID of each email will change when move to new mailbox ?
A:
Yes of course the UID is changed when you do move operation.
the new UID for that mail will be the next UID from the destination folder.
(i.e if the last mail UID of the destination folder is : 9332 ,
then the UID of the move email will be 9333)
Note: UID is changed but the Message-Id will not be changed during any operation on that mail)
A:
I took a look at my own IMAP code for Gmail, and one of the comments say that UID changes on move, because move is in fact copy+delete. Or maybe it's me who do the wrong thing:
imap.copy(sid, dest_folder)
imap.store(sid, '+FLAGS', '\\Deleted')
imap.expunge()
-- otherwise, if you know the way to move it directly, it shouldn't change.
| About IMAP UID with imaplib | I try to move email from mailbox's gmail to another one, Just curious that UID of each email will change when move to new mailbox ?
| [
"Yes of course the UID is changed when you do move operation.\nthe new UID for that mail will be the next UID from the destination folder.\n(i.e if the last mail UID of the destination folder is : 9332 , \nthen the UID of the move email will be 9333) \nNote: UID is changed but the Message-Id will not be changed ... | [
4,
1
] | [] | [] | [
"imap",
"imaplib",
"python"
] | stackoverflow_0003615561_imap_imaplib_python.txt |
Q:
Any good books and/or tutorials on XML-based APIs, REST, SOAP with Python?
What are some good books and/or tutorials on XML-based APIs, REST, SOAP with Python?
A:
Chapters 9, 11, 12 from Dive into Python by Mark Pilgrim deal with these topics. Though the book is outdated, you can give it a try if you are just starting out. Some of the libraries used in the book haven't been updated in few years.
| Any good books and/or tutorials on XML-based APIs, REST, SOAP with Python? | What are some good books and/or tutorials on XML-based APIs, REST, SOAP with Python?
| [
"Chapters 9, 11, 12 from Dive into Python by Mark Pilgrim deal with these topics. Though the book is outdated, you can give it a try if you are just starting out. Some of the libraries used in the book haven't been updated in few years.\n"
] | [
1
] | [] | [] | [
"python",
"rest",
"soap",
"web_services",
"xml"
] | stackoverflow_0003635715_python_rest_soap_web_services_xml.txt |
Q:
How to install Python 3.1.2 on Mac OS X 10.6.4?
Hi there I have downloaded the mac installer here, http://www.python.org/download/releases/3.1.2/ , & installed it. But when I run terminal & type python it says:
Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
What I want to know is, is it safe to run Update Shell Profile.command in the Python 3.1 folder ? or should I run python 3.1.2 separately ? If I should run python 3.1.2 separately, how do I do so ? also how do I start IDLE ?
A:
Is there another python executable, perhaps python31?
You can also install other python versions via MacPorts if you need (although you'll still have to choose the right executable).
This should also be relevant: Multiple versions of Python on OS X Leopard
| How to install Python 3.1.2 on Mac OS X 10.6.4? | Hi there I have downloaded the mac installer here, http://www.python.org/download/releases/3.1.2/ , & installed it. But when I run terminal & type python it says:
Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
What I want to know is, is it safe to run Update Shell Profile.command in the Python 3.1 folder ? or should I run python 3.1.2 separately ? If I should run python 3.1.2 separately, how do I do so ? also how do I start IDLE ?
| [
"Is there another python executable, perhaps python31?\nYou can also install other python versions via MacPorts if you need (although you'll still have to choose the right executable).\nThis should also be relevant: Multiple versions of Python on OS X Leopard\n"
] | [
1
] | [] | [] | [
"macos",
"python",
"python_3.x"
] | stackoverflow_0003636096_macos_python_python_3.x.txt |
Q:
Check for page loading (Python)
In Python, is there any way that I can find out if a browser window that I've opened has loaded completely or not, maybe using a package (for instance, webbrowser)? Once it's loaded completely I want to take a screenshot of it and save it.
A:
You can do this using e.g. Selenium; I'm not sure if it's what you want, though. See this short guide.
#!/usr/bin/env python
from selenium import selenium
sel = selenium('localhost', 4444, '*firefox', 'http://www.google.com/')
sel.start()
sel.open('/')
sel.wait_for_page_to_load(10000)
sel.stop()
You could also use COM hooks to control IE (ugh):
import win32com.client
import time
ie = win32com.client.Dispatch( "InternetExplorer.Application" )
ie.Navigate( <some URL> )
time.sleep( 1 )
print( ie.Busy )
There's a module that wraps all the COM functionality: IEC.py.
A:
Strictly speaking you can't do that with python. However, using Javascript you can wait for the "onload" event and send an ajax request to your python backend.
With JQuery it should be something like.
//callback for the onload
jQuery(document)
.ready(function() {
$.ajax({
type: "POST",
url: "thePythonScript.py",
data: "name=Daniel&location=Somewhere",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
});
| Check for page loading (Python) | In Python, is there any way that I can find out if a browser window that I've opened has loaded completely or not, maybe using a package (for instance, webbrowser)? Once it's loaded completely I want to take a screenshot of it and save it.
| [
"You can do this using e.g. Selenium; I'm not sure if it's what you want, though. See this short guide.\n#!/usr/bin/env python\n\nfrom selenium import selenium\n\nsel = selenium('localhost', 4444, '*firefox', 'http://www.google.com/')\nsel.start()\nsel.open('/')\nsel.wait_for_page_to_load(10000)\nsel.stop()\n\nYou ... | [
4,
0
] | [] | [] | [
"browser",
"python"
] | stackoverflow_0003636008_browser_python.txt |
Q:
Is this a problem with the Django tutorial or a package problem, or is it me?
I'm using Ubuntu 10, python 2.6.5
I'm following this tutorial: http://www.djangobook.com/en/2.0/chapter02
I followed all of the steps using cut-and-paste.
The following directory structure was automatically created:
bill@ed-desktop:~/projects$ ls -l mysite
total 36
-rw-r--r-- 1 bill bill 0 2010-09-01 08:18 __init__.py
-rw-r--r-- 1 bill bill 546 2010-09-01 08:18 manage.py
-rw-r--r-- 1 bill bill 20451 2010-09-01 18:50 mysite.wpr
-rw-r--r-- 1 bill bill 3291 2010-09-01 08:18 settings.py
-rw-r--r-- 1 bill bill 127 2010-09-01 11:13 urls.py
-rw-r--r-- 1 bill bill 97 2010-09-01 08:20 views.py
urls.py
from django.conf.urls.defaults import *
import sys
print sys.path
from mysite.views import hello
urlpatterns = patterns('',
(r'^hello/$', hello),
)
pylint produces this error: Unable to import 'mysite.views'
views.py
from django.http import HttpResponse
def hello(request):
return HttpResponse("Hello world")
bill@ed-desktop:~/projects/mysite$ python manage.py runserver
Validating models...
0 errors found
Django version 1.2.1, using settings 'mysite.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Which resulted in:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
1. ^hello/$
The current URL, , didn't match any of these.
Why does view.py which is in the main directory contain the following?
from mysite.views import hello
There is no subdirectory 'views'. Although I'm familiar with using packages, I've never had the need to create my own so I'm a bit confused. I would have thought that from views import hello would be correct.
The step-by-step tutorial looks straight forward and I haven't seen anyone else come across this problem so I'm a bit perplexed what I've done wrong.
A:
I'm not sure what your actual question is.
You've requested the root page, \, but have only defined a URL for \hello\, so obviously Django can't find what you've requested. If you want your hello view to match against the site root, do this:
urlpatterns = patterns('',
(r'^$', hello),
)
I don't understand the question about the from mysite.views import hello. This will work if the parent of mysite is on the Python path.
A:
you see 404 error, because you don't have the default handler, add to url patterns something like this:
('^$', views.default )
and probably you need to add the web application path to the sys.path variable to be able to 'see' your modules:
import sys
sys.path.append(path_to_site)
| Is this a problem with the Django tutorial or a package problem, or is it me? | I'm using Ubuntu 10, python 2.6.5
I'm following this tutorial: http://www.djangobook.com/en/2.0/chapter02
I followed all of the steps using cut-and-paste.
The following directory structure was automatically created:
bill@ed-desktop:~/projects$ ls -l mysite
total 36
-rw-r--r-- 1 bill bill 0 2010-09-01 08:18 __init__.py
-rw-r--r-- 1 bill bill 546 2010-09-01 08:18 manage.py
-rw-r--r-- 1 bill bill 20451 2010-09-01 18:50 mysite.wpr
-rw-r--r-- 1 bill bill 3291 2010-09-01 08:18 settings.py
-rw-r--r-- 1 bill bill 127 2010-09-01 11:13 urls.py
-rw-r--r-- 1 bill bill 97 2010-09-01 08:20 views.py
urls.py
from django.conf.urls.defaults import *
import sys
print sys.path
from mysite.views import hello
urlpatterns = patterns('',
(r'^hello/$', hello),
)
pylint produces this error: Unable to import 'mysite.views'
views.py
from django.http import HttpResponse
def hello(request):
return HttpResponse("Hello world")
bill@ed-desktop:~/projects/mysite$ python manage.py runserver
Validating models...
0 errors found
Django version 1.2.1, using settings 'mysite.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Which resulted in:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
1. ^hello/$
The current URL, , didn't match any of these.
Why does view.py which is in the main directory contain the following?
from mysite.views import hello
There is no subdirectory 'views'. Although I'm familiar with using packages, I've never had the need to create my own so I'm a bit confused. I would have thought that from views import hello would be correct.
The step-by-step tutorial looks straight forward and I haven't seen anyone else come across this problem so I'm a bit perplexed what I've done wrong.
| [
"I'm not sure what your actual question is. \nYou've requested the root page, \\, but have only defined a URL for \\hello\\, so obviously Django can't find what you've requested. If you want your hello view to match against the site root, do this:\nurlpatterns = patterns('',\n (r'^$', hello),\n)\n\nI don't under... | [
1,
1
] | [] | [] | [
"django",
"package",
"python"
] | stackoverflow_0003636280_django_package_python.txt |
Q:
how to do a zoom in/out with wxpython
how to do a zoom in/out with wxpython? what are the very basics for this purpose? I googled this, but could not find much, thanks!!
A:
Instead of zoom, perhaps 'scaling' is what you're looking for:
http://www.wxpython.org/docs/api/wx.Size-class.html#Scale
A:
You should look at FloatCanvas or FloatCanvas2. I know one of them has a zooming (and maybe panning) feature. You can get ideas about drawing rectangles from Whyteboard. Here's a few links:
http://wiki.wxpython.org/FloatCanvas
http://www.wxpython.org/docs/api/wx.lib.floatcanvas-module.html
http://whyteboard.org/
| how to do a zoom in/out with wxpython | how to do a zoom in/out with wxpython? what are the very basics for this purpose? I googled this, but could not find much, thanks!!
| [
"Instead of zoom, perhaps 'scaling' is what you're looking for:\nhttp://www.wxpython.org/docs/api/wx.Size-class.html#Scale\n",
"You should look at FloatCanvas or FloatCanvas2. I know one of them has a zooming (and maybe panning) feature. You can get ideas about drawing rectangles from Whyteboard. Here's a few lin... | [
2,
2
] | [] | [] | [
"python",
"user_interface",
"wxpython",
"zooming"
] | stackoverflow_0003631510_python_user_interface_wxpython_zooming.txt |
Q:
How to debug "glibc detected *** python: malloc(): memory corruption"
I'm using python2.5 with scipy.weave to embed c code.
In my c code, there is no malloc() function, but I received error like
"glibc detected *** python: malloc(): memory corruption"
from time to time.(It's a random algorithm)
So how shall I debug it out?
Thanks
A:
I'd hazard a guess that your code is overflowing an array somewhere (or causing Python to do so).
You're going to find debugging this to be hard if you can't reliably reproduce it, so you might want to explicitly seed your random number generator and try to find a seed with which you can reproduce the corruption. You might also find that using a tool like valgrind is helpful to track when you write over the limits of an allocation -- probably more so when you can reproduce it every time.
| How to debug "glibc detected *** python: malloc(): memory corruption" | I'm using python2.5 with scipy.weave to embed c code.
In my c code, there is no malloc() function, but I received error like
"glibc detected *** python: malloc(): memory corruption"
from time to time.(It's a random algorithm)
So how shall I debug it out?
Thanks
| [
"I'd hazard a guess that your code is overflowing an array somewhere (or causing Python to do so).\nYou're going to find debugging this to be hard if you can't reliably reproduce it, so you might want to explicitly seed your random number generator and try to find a seed with which you can reproduce the corruption.... | [
7
] | [] | [] | [
"c",
"glibc",
"python"
] | stackoverflow_0003636393_c_glibc_python.txt |
Q:
Getting a listing of Trac projects in Python
Is it possible to do something like using the trac module in Python in order to get a listing of all of the projects in a given directory? If possible it would be nice to get things like the description, too. I can't seem to figure out how to do it.
Thanks for any help you can provide.
A:
Using the TRAC_ENV_PARENT_DIR environment variable almost certainly does what you need: it will create an index page for you. See the part about "use multiple projects" here: http://trac.edgewall.org/wiki/TracCgi#Apacheweb-serverconfiguration
A:
You can script something like this:
import trac.admin.console
import trac.config
import os
def _get_project_options(envdir):
confpath = os.path.join(envdir, 'conf/trac.ini')
config = trac.config.Configuration(confpath)
return dict([x for x in config.options(u'project')])
def _get_project_name(envdir):
admin = trac.admin.console.TracAdmin(envdir)
if admin.env_check():
options = _get_project_options(envdir)
return options[u'name']
else:
return None
def iter_trac_projects_from_dir(dirname):
for which in os.listdir(dirname):
if not which in ('.', '..') and os.path.isdir(dirname):
envdirname = os.path.join(dirname, which)
project_name = _get_project_name(envdirname)
if project_name:
yield (project_name, envdirname)
def get_trac_projects_from_dir(dirname):
return [pr for pr in iter_trac_projects_from_dir(dirname)]
Then you can use either iter_trac_projects_from_dir or get_trac_projects_from_dir whichever you think is best for you.
Alternatively you could use the function get_enviroments from module trac.web.main but only as alternative to os.listdir -- you would still have to check whether or not each alleged env is really a trac environment. See why:
>>> import trac.web.main
>>> env = {'trac.env_parent_dir':
... '/home/manu/tmp'}
>>> trac.web.main.get_environments(env)
{'test': '/home/manu/tmp/test', 'no-a-real-trac-project': '/home/manu/tmp/no-a-real-trac-project', 'test2': '/home/manu/tmp/test2'}
| Getting a listing of Trac projects in Python | Is it possible to do something like using the trac module in Python in order to get a listing of all of the projects in a given directory? If possible it would be nice to get things like the description, too. I can't seem to figure out how to do it.
Thanks for any help you can provide.
| [
"Using the TRAC_ENV_PARENT_DIR environment variable almost certainly does what you need: it will create an index page for you. See the part about \"use multiple projects\" here: http://trac.edgewall.org/wiki/TracCgi#Apacheweb-serverconfiguration\n",
"You can script something like this:\nimport trac.admin.console... | [
1,
1
] | [] | [] | [
"project_management",
"python",
"trac"
] | stackoverflow_0003634183_project_management_python_trac.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.