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:
How to do an image upload in web.py and save it to the disk
I need to create a form and have the form upload an image and save it to my disk. Here is my code
import web
urls = (
'/hello', 'Index',
'/file_upload_form', 'ThatFile'
)
app = web.application(urls, globals())
render = web.template.render('templates/',... | How to do an image upload in web.py and save it to the disk | I need to create a form and have the form upload an image and save it to my disk. Here is my code
import web
urls = (
'/hello', 'Index',
'/file_upload_form', 'ThatFile'
)
app = web.application(urls, globals())
render = web.template.render('templates/', base = "layout")
class ThatFile(object):
def GET(self):
... | [
"Use something like\nimport shutil\n# SKIPPED\ndef POST(self):\n form = web.input(image={})\n with open('path/to/image.jpg', 'wb') as saved:\n shutil.copyfileobj(form['image'].file, saved)\n\n"
] | [
6
] | [] | [] | [
"python",
"upload",
"web.py"
] | stackoverflow_0006811910_python_upload_web.py.txt |
Q:
Python: Memory cost of importing a module
The memory cost obviously depends on exactly how large a module is, but I'm only looking for a general answer: Is it generally expensive or cheap to import a module in Python? If I have a few tens of small scripts that potentially stay in memory for the whole duration of t... | Python: Memory cost of importing a module | The memory cost obviously depends on exactly how large a module is, but I'm only looking for a general answer: Is it generally expensive or cheap to import a module in Python? If I have a few tens of small scripts that potentially stay in memory for the whole duration of the application, how much will that hog the memo... | [
"It sounds like you aren't worried about time cost (good; that would be silly, since modules are only imported once) but memory cost. I put it to you: if you need all the functionality in these modules, then how exactly do you plan to avoid having them all in memory? Might as well just import things in the most log... | [
9
] | [] | [] | [
"memory_efficient",
"python"
] | stackoverflow_0006812571_memory_efficient_python.txt |
Q:
Tkinter Python Entry state attribute
I am trying to check if the users cursor is in a text box by checking the Entries state value. However, I get "AttributeError: Entry instance has no attribute 'state'". How do I check if the users cursor is in a textbox?
import os
from Tkinter import *
textboxes = []
def rea... | Tkinter Python Entry state attribute | I am trying to check if the users cursor is in a text box by checking the Entries state value. However, I get "AttributeError: Entry instance has no attribute 'state'". How do I check if the users cursor is in a textbox?
import os
from Tkinter import *
textboxes = []
def read_textboxes():
for e in textboxes:
... | [
"You can call focus_get() on the root to get the widget that currently has the focus.\ndef read_textboxes():\n in_focus = root.focus_get()\n for e in textboxes:\n print e == in_focus\n\n"
] | [
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0006811588_python_tkinter.txt |
Q:
Determine if a file is on an NTFS filesystem
Is there a Windows API for determining if a certain file (path) is on an NTFS filesystem?
If this can be somehow inferred from an existing Python API, all the better.
A:
Dont know how to do it in Python, but I assume that invoking C functions will be easy.
So in C ope... | Determine if a file is on an NTFS filesystem | Is there a Windows API for determining if a certain file (path) is on an NTFS filesystem?
If this can be somehow inferred from an existing Python API, all the better.
| [
"Dont know how to do it in Python, but I assume that invoking C functions will be easy.\nSo in C open file handle bu CreateFile, you'll retrieve a handle to such file. Then call GetVolumeInformationByHandleW and check the lpFileSystemNameBuffer variable for \"ntfs\" string.\n",
"In python you can do:\nimport win3... | [
1,
1,
0
] | [] | [] | [
"ntfs",
"python",
"windows"
] | stackoverflow_0006809099_ntfs_python_windows.txt |
Q:
how to use many-to-many in sqlalchemy
I'd like to use relationship from sqlalchemy in my project. I test many-to-many on simple code:
from sqlalchemy import Table, Column, Integer, String, Text, DateTime, ForeignKey, create_engine
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy.ext.declarativ... | how to use many-to-many in sqlalchemy | I'd like to use relationship from sqlalchemy in my project. I test many-to-many on simple code:
from sqlalchemy import Table, Column, Integer, String, Text, DateTime, ForeignKey, create_engine
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from datetime imp... | [
"The problem here is that you create two BlogTag objects with primary key one.\nSQLAlchemy's session object has no way of knowing that it should not create a new database row for the second object you create.\nThe following will work:\ntag_one = BlogTag('one')\npost = BlogPost('1', '1111', [tag_one, BlogTag('two')]... | [
3,
2
] | [] | [] | [
"database",
"python",
"sqlalchemy"
] | stackoverflow_0006812910_database_python_sqlalchemy.txt |
Q:
Assigning a name to a pattern-matched item in Python
I'm trying to do the following:
def f( a=(b,c,d) ):
pass
But the interpreter complains that b is not defined when I do this. Is there a "Pythonic" way of getting the intended result? I know that I could do something like the following:
def f( (b,c,d) ):
a ... | Assigning a name to a pattern-matched item in Python | I'm trying to do the following:
def f( a=(b,c,d) ):
pass
But the interpreter complains that b is not defined when I do this. Is there a "Pythonic" way of getting the intended result? I know that I could do something like the following:
def f( (b,c,d) ):
a = (b,c,d)
pass
But I'd rather a solution that didn't re... | [
"There is no way to do precisely what you want. Moreover, tuple unpacking in formal function arguments is going the way of the dodo in python 3. The suggested replacement is to change\ndef f((a,b,c)):\n ...\n\nto\ndef f(a_b_c):\n a,b,c = a_b_c\n ...\n\n(That's the style of new argument name the 2to3 conver... | [
4,
0
] | [] | [] | [
"python"
] | stackoverflow_0006810931_python.txt |
Q:
If else in Python
I have the following function, when I call it's printing out the mess but if the if condition is false than it's not going the else branch, what I'm doing wrong?
def lidarMessageHandler( self, mess ):
print( mess );
#Check if I received the right command
if( COMMANDTABL... | If else in Python | I have the following function, when I call it's printing out the mess but if the if condition is false than it's not going the else branch, what I'm doing wrong?
def lidarMessageHandler( self, mess ):
print( mess );
#Check if I received the right command
if( COMMANDTABLE[commandList[self.clie... | [
"You probably get an exception here:\nerror = \"I waited the answer for the following command %s but I received % command from %s \" % self.lastCommand, mess['commandName'], self.clientname\n ^\n\nYou should add s:\nerror = \"I waited the answe... | [
3,
2,
2,
1
] | [] | [] | [
"if_statement",
"python"
] | stackoverflow_0006813282_if_statement_python.txt |
Q:
HeaderParseError in python
I get a HeaderParseError if I try to parse this string with decode_header() in python 2.6.5 (and 2.7). Here the repr() of the string:
'=?iso-8859-1?B?QW5tZWxkdW5nIE5ldHphbnNjaGx1c3MgU_xkcmluZzNwLmpwZw==?='
This string comes from a mime email which contains a JPEG picture. Thunderbird c... | HeaderParseError in python | I get a HeaderParseError if I try to parse this string with decode_header() in python 2.6.5 (and 2.7). Here the repr() of the string:
'=?iso-8859-1?B?QW5tZWxkdW5nIE5ldHphbnNjaGx1c3MgU_xkcmluZzNwLmpwZw==?='
This string comes from a mime email which contains a JPEG picture. Thunderbird can
decode the filename (which co... | [
"It seems an incompatibility between Python's character set for base64-encoded strings and the mail agent's:\n>>> from email.header import decode_header\n>>> a='QW5tZWxkdW5nIE5ldHphbnNjaGx1c3MgU_xkcmluZzNwLmpwZw=='\n>>> decode_header(a)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n ... | [
1
] | [] | [] | [
"email_parsing",
"python"
] | stackoverflow_0006568596_email_parsing_python.txt |
Q:
python: what happens during easy_install?
I'm a little confused about egg files and installing them using easy_install, hope you can help me with it. (I read about people's recommendation on pip, but I'll like to understand this before I move on).
If I simply copy e,g django_guardian-1.0.2-py2.6.egg from say, a th... | python: what happens during easy_install? | I'm a little confused about egg files and installing them using easy_install, hope you can help me with it. (I read about people's recommendation on pip, but I'll like to understand this before I move on).
If I simply copy e,g django_guardian-1.0.2-py2.6.egg from say, a thumbdrive and place in e.g ~/bar/ which PYTHONP... | [
"easy_install uses .pth files to add the .egg files to sys.path -- the list of locations where Python searches for modules to import.\n.pth files are processed by the site module, but only in four pre-defined directories. These directories are platform-specific and based on the sys.prefix and sys.exec_prefix setti... | [
4
] | [] | [] | [
"easy_install",
"python"
] | stackoverflow_0006813331_easy_install_python.txt |
Q:
A source file with unicode characters is making Django throw up a SyntaxError exception
A file in UTF-8 encoding has an è character (e with accent grave) embedded in comment delimiters for Python. Django complains about this character and will not render the page. How can I resolve this?
A:
The SyntaxError Djang... | A source file with unicode characters is making Django throw up a SyntaxError exception | A file in UTF-8 encoding has an è character (e with accent grave) embedded in comment delimiters for Python. Django complains about this character and will not render the page. How can I resolve this?
| [
"The SyntaxError Django is raising already points you in the right direction.\nIt is always a good thing to actually read exceptions. In your case, it will have said something along the lines of \n\nNon-ASCII character '\\xc3' in file /home/zakx/../views.py on line 84, but no encoding declared; see http://www.pytho... | [
18,
5
] | [] | [] | [
"character_encoding",
"django",
"python"
] | stackoverflow_0006812612_character_encoding_django_python.txt |
Q:
looking for pure python package to create images of websites
I've previously used http://code.google.com/p/wkhtmltopdf/ with http://pypi.python.org/pypi/wkhtmltopdf/0.2 to create screenshots of websites from the command line. However, I was wondering whether a pure python package exists, that can do the same. Curr... | looking for pure python package to create images of websites | I've previously used http://code.google.com/p/wkhtmltopdf/ with http://pypi.python.org/pypi/wkhtmltopdf/0.2 to create screenshots of websites from the command line. However, I was wondering whether a pure python package exists, that can do the same. Currently I always need to download the correct binary of http://code.... | [
"That would require a browser engine written in pure python. And this means you need a CSS processor und, more important, a complete Javascript engine written in Python. While this is undoubtedly possible, I'm pretty sure nobody has done it.\n"
] | [
1
] | [] | [] | [
"python",
"screenshot",
"web"
] | stackoverflow_0006813132_python_screenshot_web.txt |
Q:
Running python script in background with nohup and timing it
I'm running a python script on a remote server with the time command as follows:
time python myscript.py
SSH timeout occurs on the server after some time, so i also need to run it with nohup.So, i have the following two questions:
Is nohup time myscrip... | Running python script in background with nohup and timing it | I'm running a python script on a remote server with the time command as follows:
time python myscript.py
SSH timeout occurs on the server after some time, so i also need to run it with nohup.So, i have the following two questions:
Is nohup time myscript.py & the right command to execute my python script ?
If the scri... | [
"nohup will usually write STDOUT and STDERR to a file called \"nohup.out\" in the current directory. You'll be able to see the output of time at the end of that file.\nAnother way of solving this redirection of the output like this:\nnohup time bla.py >myoutput &\n\n",
"To 1.: Yes\nTo 2.: You can redirect the out... | [
2,
1
] | [] | [] | [
"nohup",
"python",
"time",
"unix"
] | stackoverflow_0006813705_nohup_python_time_unix.txt |
Q:
How to execute this python media player?
I just copy pasted this media player in python .When I am running this using the command python mediaplayer.py (mediaplayer.py is my filwename) there is no output .Can anyone tell why?
import os
import time
import wx
import MplayerCtrl as mpc
import wx.lib.buttons as button... | How to execute this python media player? | I just copy pasted this media player in python .When I am running this using the command python mediaplayer.py (mediaplayer.py is my filwename) there is no output .Can anyone tell why?
import os
import time
import wx
import MplayerCtrl as mpc
import wx.lib.buttons as buttons
dirName = os.path.dirname(os.path.abspath(_... | [
"It is not meant to be used as you posted it. \nThe class needs to be instantiated, and possibly run in a main loop of some sort. \nIn addition, as you can see on the line import MplayerCtrl as mpc, it isn't a stand-alone.\nPlease post at minimum a link to where you downloaded it.\nAlso, be aware it appears to be a... | [
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0006813556_python_wxpython.txt |
Q:
Overiding the auth module's AuthticationForm to allow logging in via email
I'd like to allow my users to be able to log in via email. I've seen examples of accomplishing this by writing a custom authentication back-end. I, however, would like to do this by inheriting the django.contrib.auth.forms.AuthenticationFor... | Overiding the auth module's AuthticationForm to allow logging in via email | I'd like to allow my users to be able to log in via email. I've seen examples of accomplishing this by writing a custom authentication back-end. I, however, would like to do this by inheriting the django.contrib.auth.forms.AuthenticationForm and adding a new field called email which on the clean_email method fetches th... | [
"You should use clean if you want to modify another field:\ndef clean(self):\n cleaned_data = self.cleaned_data\n user = User.objects.filter(email=cleaned_data['email'])\n if user:\n cleaned_data['username'] = user.username\n else:\n raise forms.ValidationError(_(\"Incorrect email or passw... | [
1,
0
] | [] | [] | [
"django",
"django_authentication",
"django_forms",
"inheritance",
"python"
] | stackoverflow_0006813920_django_django_authentication_django_forms_inheritance_python.txt |
Q:
Tool to create a python GUI for graph construction
I need to create a GUI for graph construction ("graph" as an abstract representation of a set of objects, not a visual representation of data). The interface will provide a choice of ~5 vertex types and of ~5 edge types. Each vertex will have two data fields: a te... | Tool to create a python GUI for graph construction | I need to create a GUI for graph construction ("graph" as an abstract representation of a set of objects, not a visual representation of data). The interface will provide a choice of ~5 vertex types and of ~5 edge types. Each vertex will have two data fields: a text label and a file name, which need to be easily editab... | [
"Take a look at xdot.py.\nFrom the homepage\n\nxdot.py is an interactive viewer for graphs written in Graphviz's\n dot language.\nIt uses internally the graphviz's xdot output format as an\n intermediate format, and PyGTK and Cairo for rendering.\nxdot.py can be used either as a standalone application from\n com... | [
3,
3,
0
] | [] | [] | [
"graph",
"python",
"user_interface"
] | stackoverflow_0006812586_graph_python_user_interface.txt |
Q:
Sorting a list of tuples based on the first items
How to sort a list of tuples based on the first value i.e, in a dictionary we can use sorted(a.keys()).
How to do it for a list of tuples?
If these are the tuple values
t = [('2010-09-11', 'somedata', somedata),
('2010-06-11', 'somedata', somedata),
('20... | Sorting a list of tuples based on the first items | How to sort a list of tuples based on the first value i.e, in a dictionary we can use sorted(a.keys()).
How to do it for a list of tuples?
If these are the tuple values
t = [('2010-09-11', 'somedata', somedata),
('2010-06-11', 'somedata', somedata),
('2010-09-12', 'somedata', somedata)]
tuples should be sor... | [
"Usually, just sorted(t) works, as tuples are sorted by lexicographical order. If you really want to ignore everything after the first item (instead of sorting tuples with the same first element by the following elements), you can supply a key that picks out the first element. The simplest way would be operator.ite... | [
7,
1,
1,
0
] | [] | [] | [
"list",
"python",
"sorting",
"tuples"
] | stackoverflow_0006814327_list_python_sorting_tuples.txt |
Q:
sqlalchemy use of inheritance in postgres
in an attempt to learn sqlalchemy (and python), i am trying to duplicate an already existing project, but am having trouble figuring out sqlalchemy and inheritance with postgres.
here is an example of what our postgres database does (obviously, this is simplified):
CREATE ... | sqlalchemy use of inheritance in postgres | in an attempt to learn sqlalchemy (and python), i am trying to duplicate an already existing project, but am having trouble figuring out sqlalchemy and inheritance with postgres.
here is an example of what our postgres database does (obviously, this is simplified):
CREATE TABLE system (system_id SERIAL PRIMARY KEY,
... | [
"You just create a new instance of ops_file_entry (shouldn't this be OpsFileEntry?), add it into the session, and upon flush, one row will be inserted into table file_entry as well as table ops_file_entry.\nYou don't need to set the file_entry_system_name attribute, nor the trigger.\n",
"I don't really know pytho... | [
1,
0
] | [] | [] | [
"inheritance",
"polymorphic_associations",
"postgresql",
"python",
"sqlalchemy"
] | stackoverflow_0006782592_inheritance_polymorphic_associations_postgresql_python_sqlalchemy.txt |
Q:
problem in installing pypol
I have been trying to install pypol in cygwin. But when I do setup where I have to type python setup.py install then it displays an error as the following:
Traceback (most recent call last):
File "setup.py", line 1, in
from setuptools import find_packages, setup, Command
File "/cygdri... | problem in installing pypol | I have been trying to install pypol in cygwin. But when I do setup where I have to type python setup.py install then it displays an error as the following:
Traceback (most recent call last):
File "setup.py", line 1, in
from setuptools import find_packages, setup, Command
File "/cygdrive/c/pypol_-0.4/setuptools/init.p... | [
"What is causing ImportError: No module named pkg_resources after upgrade of Python on os X?\nis informative. It suggests that you're invoking the wrong version of python. Do you already have python installed under Windows?\nIf you do have another version of Python (you can probably check under cygwin with which py... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0006814290_python.txt |
Q:
How to pass and run a callback method in Python
I have a Manager (main thread), that creates other Threads to handle various operations.
I would like my Manager to be notified when a Thread it created ends (when run() method execution is finished).
I know I could do it by checking the status of all my threads with... | How to pass and run a callback method in Python | I have a Manager (main thread), that creates other Threads to handle various operations.
I would like my Manager to be notified when a Thread it created ends (when run() method execution is finished).
I know I could do it by checking the status of all my threads with the Thread.isActive() method, but polling sucks, so ... | [
"The thread can't call the manager unless it has a reference to the manager. The easiest way for that to happen is for the manager to give it to the thread at instantiation.\nclass Manager(object):\n def new_thread(self):\n return MyThread(parent=self)\n def on_thread_finished(self, thread, data):\n ... | [
24,
10,
4
] | [] | [] | [
"callback",
"multithreading",
"notifications",
"python"
] | stackoverflow_0006800984_callback_multithreading_notifications_python.txt |
Q:
Django recive array ajax problem
I'm sending array via POST reqest to Django server
if I use dev server, I see
<QueryDict: {u'arr[]': [u'1', u'2']}>
if I send to Apache+Mod_wsgi sever, I see
<QueryDict: {u'arr[]': [u'2']}>
olny last item, any ideas?
upd: dev sever on my local pc, if Apache+mod_wsgi on my loca... | Django recive array ajax problem | I'm sending array via POST reqest to Django server
if I use dev server, I see
<QueryDict: {u'arr[]': [u'1', u'2']}>
if I send to Apache+Mod_wsgi sever, I see
<QueryDict: {u'arr[]': [u'2']}>
olny last item, any ideas?
upd: dev sever on my local pc, if Apache+mod_wsgi on my local pc all fine, if on remote - only las... | [
"My solution:\nserialize array with JSON2 \nJSON.stringify(my_array)\n\nand deserialize with \nimport json\njson.loads(str)\n\n"
] | [
1
] | [] | [] | [
"ajax",
"apache",
"django",
"mod_wsgi",
"python"
] | stackoverflow_0006773628_ajax_apache_django_mod_wsgi_python.txt |
Q:
How to get the output of the built-in help() function in python in a string?
As a example :
>>> out = help(list) ## out must be a string .
>>> print out
>>> ' Help on class list in module __builtin__:
class list(object)
| list() -> new empty list
| list(iterable) -> new list initialized from iterable's items... | How to get the output of the built-in help() function in python in a string? | As a example :
>>> out = help(list) ## out must be a string .
>>> print out
>>> ' Help on class list in module __builtin__:
class list(object)
| list() -> new empty list
| list(iterable) -> new list initialized from iterable's items '
Any advice highly appreciated ...
| [
"import pydoc\npydoc.render_doc(list)\n\ngives the whole output of help(list). If you're just interested in the top description (and not all methods defined on the object), use\nlist.__doc__\n\n",
"use the doc \nprint list.__doc__\n\n"
] | [
4,
1
] | [] | [] | [
"python"
] | stackoverflow_0006815186_python.txt |
Q:
Cannot get object from queryset
Code below should substitute all \[\[(.+)\]\] matches in 'content' field of AD with src of ADResource where (.+) is alias
[[Similac]] → media/banners/2011/07/24/ad1.gif
[[res]] → media/banners/2011/07/24/ad2.png
It catches DoesNotExist exception on [[res]] or [[Similac]] and returns... | Cannot get object from queryset | Code below should substitute all \[\[(.+)\]\] matches in 'content' field of AD with src of ADResource where (.+) is alias
[[Similac]] → media/banners/2011/07/24/ad1.gif
[[res]] → media/banners/2011/07/24/ad2.png
It catches DoesNotExist exception on [[res]] or [[Similac]] and returns 'res' or 'Similac' strings.
ADResour... | [
"Oh, stupid question, i'm getting not a string but regex object and my match was in first subgroup.\nself.content = re.sub(r'\\[\\[(.+)\\]\\]', lambda m: ADResource.objects.all().get(alias=m.group(1)).src.url, self.content)\n\n"
] | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006809180_django_python.txt |
Q:
disable tkinter keyboard shortcut (2)
I'm proposing a continuation of the discussion in disable tkinter keyboard shortcut: I have an event handler for an event that Tkinter also uses, so that my prog & Tkinter interact badly.
Since it is a problem that I've been unable to solve I'm re-proposing here, where I tried... | disable tkinter keyboard shortcut (2) | I'm proposing a continuation of the discussion in disable tkinter keyboard shortcut: I have an event handler for an event that Tkinter also uses, so that my prog & Tkinter interact badly.
Since it is a problem that I've been unable to solve I'm re-proposing here, where I tried to boil it down to the simplest form in th... | [
"Set your binding on the text widget, not on the root. (Whole toplevel bindings are processed after widget class bindings – where the standard <Control-Key-b> binding is – and those are processed after the widget instance bindings, which is what you want to use here.) And you need to do that 'break'; it inhibits th... | [
4,
3
] | [] | [] | [
"python",
"tk_toolkit",
"tkinter"
] | stackoverflow_0006813219_python_tk_toolkit_tkinter.txt |
Q:
wxPython + pysftp won't work at the same time
My code:
class ConnectingPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
self.control = wx.TextCtrl(self, style=wx.TE_MULTILINE, pos=(-2, -2), size=(387, 267))
self.control.SetForegroundColour((34,139,34))
... | wxPython + pysftp won't work at the same time | My code:
class ConnectingPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
self.control = wx.TextCtrl(self, style=wx.TE_MULTILINE, pos=(-2, -2), size=(387, 267))
self.control.SetForegroundColour((34,139,34))
self.control.SetBackgroundColour((0,0,0))
... | [
"As already mentioned, it is because you are doing this in the constructor.\nUse wx.CallAfter:\nclass ConnectingPanel(wx.Panel):\n\n def __init__(self, parent):\n wx.Panel.__init__(self, parent)\n self.control = wx.TextCtrl(self, style=wx.TE_MULTILINE, pos=(-2, -2), size=(387, 267))\n self.c... | [
1,
0
] | [] | [] | [
"connection",
"pysftp",
"python",
"ssh",
"wxpython"
] | stackoverflow_0006813818_connection_pysftp_python_ssh_wxpython.txt |
Q:
Embedded Python: Getting func obj from imported module
I have a Python module that I import from my C++ code (I'm embedding Python). This module contains a function create() that I want to get a hold of in my C++ code (i.e. store it in a boost::python::object instance).
Here's what I tried. A run-time error occurs... | Embedded Python: Getting func obj from imported module | I have a Python module that I import from my C++ code (I'm embedding Python). This module contains a function create() that I want to get a hold of in my C++ code (i.e. store it in a boost::python::object instance).
Here's what I tried. A run-time error occurs on the indicated line in my C++ code. The error occurs beca... | [
"You need to do main_namespace[\"hero\"].attr(\"create\"). Import creates only one name in the namespace, and it's a module object. Names cannot have dots in them — . is a getattr operator — so hero.create is the same as getattr(hero, 'create').\nYou could also use boost::python::import directly, instead of execing... | [
3
] | [] | [] | [
"boost",
"c++",
"python"
] | stackoverflow_0006815574_boost_c++_python.txt |
Q:
xmlrpc newPaste - expected an object with the buffer interface
in py2 there was
rv = xmlrpc.pastes.newPaste(language, code, None, filename, mimetype, private)
I'm getting error : expected an object with the buffer interface
Can't find any docs about xmlrpc and py3. I found only this snippet :
p1 = subprocess.Pope... | xmlrpc newPaste - expected an object with the buffer interface | in py2 there was
rv = xmlrpc.pastes.newPaste(language, code, None, filename, mimetype, private)
I'm getting error : expected an object with the buffer interface
Can't find any docs about xmlrpc and py3. I found only this snippet :
p1 = subprocess.Popen(['gpg','--clearsign'], stdin = subprocess.PIPE, stdout=subprocess.... | [
"That error message usually means it's looking for str (which is Unicode in Python 3), not bytes . Like in the example, you'll need to decode the argument which is in bytes. Maybe:\nrv = xmlrpc.pastes.newPaste(language, code.decode(), None, filename, mimetype, private)\n\nBut it's hard to tell what the problem is w... | [
3,
1
] | [] | [] | [
"python",
"python_3.x",
"xmlrpclib"
] | stackoverflow_0006815585_python_python_3.x_xmlrpclib.txt |
Q:
Python CGI Script: Basic HTML Form With Two Submit Buttons
I have a basic html form which I want to use with two submit buttons. The CGI script takes the form value and processes it (regardless of which submit button used), but I want each button to be associated with different actions later in the script, i.e. p... | Python CGI Script: Basic HTML Form With Two Submit Buttons | I have a basic html form which I want to use with two submit buttons. The CGI script takes the form value and processes it (regardless of which submit button used), but I want each button to be associated with different actions later in the script, i.e. print different output:
## Get the form value in the usual way.
... | [
"<input type=\"submit\" value=\"Submit\" name=\"Submit1\" />\n<input type=\"submit\" value=\"Submit\" name=\"Submit2\" />\n\nThis will give you a different name in your form data depending on which submit button was pressed.\nYou can do\nform = cgi.FieldStorage()\n\nif \"Submit1\" in form:\n button = 1\nelif \"S... | [
6
] | [] | [] | [
"cgi",
"html",
"python"
] | stackoverflow_0006815672_cgi_html_python.txt |
Q:
Custom objects in ListStore/TreeStore
I have a list L of objects of my class A. This class implements __str__/__repr__, so each object has it's own string representation (not necessary unique). I have a GUI in pygtk, where I have a TreeView widget with only one column. I want to populate it with string representat... | Custom objects in ListStore/TreeStore | I have a list L of objects of my class A. This class implements __str__/__repr__, so each object has it's own string representation (not necessary unique). I have a GUI in pygtk, where I have a TreeView widget with only one column. I want to populate it with string representations of the objects in L, but then I want t... | [
"You could store the object in one column (gobject.TYPE_PYOBJECT) and the string representation in a second column, and then only display the second column in your treeview. Similar to what's done here: http://www.learningpython.com/2006/09/02/extending-our-pygtk-application/\n",
"If your Glade is 3.7.0 or newer ... | [
6,
2,
0
] | [] | [] | [
"gtktreeview",
"pygtk",
"python"
] | stackoverflow_0006752146_gtktreeview_pygtk_python.txt |
Q:
Extract absolute links from a page using HTMLParser
I'm using the following snippet to extract all the links on a page using HTMLParser. I get quite a few relative URLs. How can I convert these to absolute URLs for a domain e.g. www.exmaple.com
import htmllib, formatter
import urllib, htmllib, formatter
class Lin... | Extract absolute links from a page using HTMLParser | I'm using the following snippet to extract all the links on a page using HTMLParser. I get quite a few relative URLs. How can I convert these to absolute URLs for a domain e.g. www.exmaple.com
import htmllib, formatter
import urllib, htmllib, formatter
class LinksExtractor(htmllib.HTMLParser):
def __init__(self, f... | [
"You want \nurlparse.urljoin(base, url[, allow_fragments])\n\nhttp://docs.python.org/library/urlparse.html#urlparse.urljoin\nThis allows you to give an absolute or base url, and join it with a relative url. Even if they have overlapping pieces, it should work.\n"
] | [
7
] | [] | [] | [
"html",
"html_parsing",
"python"
] | stackoverflow_0006816138_html_html_parsing_python.txt |
Q:
Loading document as raw string in yaml with PyYAML
I want to parse yaml documents like the following
meta-info-1: val1
meta-info-2: val2
---
Plain text/markdown content!
jhaha
If I load_all this with PyYAML, I get the following
>>> list(yaml.load_all(open('index.yml')))
[{'meta-info-1': 'val1', 'meta-info-2': '... | Loading document as raw string in yaml with PyYAML | I want to parse yaml documents like the following
meta-info-1: val1
meta-info-2: val2
---
Plain text/markdown content!
jhaha
If I load_all this with PyYAML, I get the following
>>> list(yaml.load_all(open('index.yml')))
[{'meta-info-1': 'val1', 'meta-info-2': 'val2'}, 'Plain text/markdown content! jhaha']
What I am... | [
"You can do\nraw = open(filename).read()\ndocs = []\nfor raw_doc in raw.split('\\n---'):\n try:\n docs.append(yaml.load(raw_doc))\n except SyntaxError:\n docs.append(raw_doc)\n\nIf you won't have control over the format of the original document.\nFrom the PyYAML docs,\n\nDouble-quoted is the mos... | [
6,
2
] | [] | [] | [
"python",
"pyyaml",
"yaml"
] | stackoverflow_0006816236_python_pyyaml_yaml.txt |
Q:
flask "hello world" can not run in debug model
I followed official document, installed virtualenv and flask, and then python hello.py
But there is something wrong:
* Running on http://127.0.0.1:5000/
* Restarting with reloader: inotify events
Traceback (most recent call last):
File "hello.py", line 9, in <modu... | flask "hello world" can not run in debug model | I followed official document, installed virtualenv and flask, and then python hello.py
But there is something wrong:
* Running on http://127.0.0.1:5000/
* Restarting with reloader: inotify events
Traceback (most recent call last):
File "hello.py", line 9, in <module>
app.run(debug=True)
File "/home/aa/prj/env... | [
"This seems to be a bug triggered by a change in pyinotify's API, which you must also have installed. You could remove pyinotify or use a dirty hack to force it to use stat() instead of pyinotify. To line 496 of werkzeug/serving.py try adding (below the part where it attempts to import pyinotify):\n# dirty hack\nre... | [
5
] | [] | [] | [
"flask",
"inotify",
"pyinotify",
"python"
] | stackoverflow_0006815670_flask_inotify_pyinotify_python.txt |
Q:
Stackless Python - Recursion in a for loop?
I'm fairly new to programming and I've been working with Python for a few months now. I'm trying to get a concept to work with Stackless, but just can't figure out how (though I've written other test scripts that work with Stackless).
Anywho, as a boiled down example con... | Stackless Python - Recursion in a for loop? | I'm fairly new to programming and I've been working with Python for a few months now. I'm trying to get a concept to work with Stackless, but just can't figure out how (though I've written other test scripts that work with Stackless).
Anywho, as a boiled down example consider the following code that runs through a list... | [
"I think you want to research \"generators\" (i.e. \"yield\" python keyword). Basically a generator lets you pause in the middle of a function call and sort of return the result. When the function is \"called\" again it resumes at the line just after the \"yield\". When you finally \"return\" you are done.\nHere... | [
1,
0
] | [] | [] | [
"concurrent_programming",
"python",
"python_stackless",
"recursion",
"stackless"
] | stackoverflow_0006301519_concurrent_programming_python_python_stackless_recursion_stackless.txt |
Q:
What happens during and after boost::python::import?
The Boost documentation does not specify this. When I use boost::python::import, where exactly is the specified module imported? My guess would be in '__main__' (just to make sure).
Also, what happens when the module object goes out of scope? Given the wording i... | What happens during and after boost::python::import? | The Boost documentation does not specify this. When I use boost::python::import, where exactly is the specified module imported? My guess would be in '__main__' (just to make sure).
Also, what happens when the module object goes out of scope? Given the wording in Boost's docs — "Returns: An instance of object which hol... | [
"The underlying mechanism is PyImport_ImportModule, and no, it doesn't touch __main__. Successfully imported modules are inserted into sys.modules dict, so the object is not freed when you DECREF what the function returns — there is still at least that one reference alive.\n"
] | [
1
] | [] | [] | [
"boost",
"c++",
"python"
] | stackoverflow_0006816373_boost_c++_python.txt |
Q:
Python: split and format space separated values in a string to use in subprocess.check_call
I am using subprocess.check_call in combination with rsync.
I need to use arguments for rsync that are coming from a string which contains multiple space separated values, however because the string is a single object it fa... | Python: split and format space separated values in a string to use in subprocess.check_call | I am using subprocess.check_call in combination with rsync.
I need to use arguments for rsync that are coming from a string which contains multiple space separated values, however because the string is a single object it fails in the subprocess.check_call (which expects each argument to be a separate string).
This is w... | [
"If I understand your question correctly, you can use shlex.split. (As JAB points out, rsync_options.split() is also an option in this particular case, but it fails in certain corner cases, as illustrated by the note here.)\n>>> import shlex\n>>> shlex.split('-axh --delete --delete-excluded')\n['-axh', '--delete', ... | [
3
] | [] | [] | [
"python",
"rsync",
"string",
"subprocess"
] | stackoverflow_0006816735_python_rsync_string_subprocess.txt |
Q:
Calling load functions in correct order from constructors
I have two classes like the following:
class Super(object):
def __init__(self, arg):
self.arg = arg
def load(self):
# Load data from disk if available
try:
self.data = load_routine()
except IOError as e:
... | Calling load functions in correct order from constructors | I have two classes like the following:
class Super(object):
def __init__(self, arg):
self.arg = arg
def load(self):
# Load data from disk if available
try:
self.data = load_routine()
except IOError as e:
if e[0] == errno.ENOENT:
pass
... | [
"The answer is the combination you failed to enumerate:\nclass Super(object):\n def __init__(self):\n print 'init super'\n if self.__class__ == Super:\n self.load()\n def load(self):\n print 'load super'\n\nclass Sub(Super):\n def __init__(self):\n # always do super f... | [
1,
0
] | [] | [] | [
"constructor",
"inheritance",
"oop",
"python"
] | stackoverflow_0006816626_constructor_inheritance_oop_python.txt |
Q:
can't easy_install ssl module
When doing easy_install ssl I get following error:
C:\Windows\system32>easy_install ssl
Searching for ssl
Reading http://pypi.python.org/simple/ssl/
Reading http://docs.python.org/dev/library/ssl.html
Best match: ssl 1.15
Downloading http://pypi.python.org/packages/source/s/ssl/ssl-1.... | can't easy_install ssl module | When doing easy_install ssl I get following error:
C:\Windows\system32>easy_install ssl
Searching for ssl
Reading http://pypi.python.org/simple/ssl/
Reading http://docs.python.org/dev/library/ssl.html
Best match: ssl 1.15
Downloading http://pypi.python.org/packages/source/s/ssl/ssl-1.15.tar.gz#md5=81ea8a1175e437b4c769a... | [
"\nVisit: http://sourceforge.net/project/showfiles.php?group_id=2435\nDownload & Run: Automated MinGW Installer (make sure you check the base, g++ and Make)\nUpdate your PATH: Add the C:\\mingw\\bin directory to the system PATH\nCreate (or edit): C:\\Python25\\Lib\\distutils\\distutils.cfg and add the following 2 l... | [
4
] | [] | [] | [
"easy_install",
"python",
"ssl"
] | stackoverflow_0006816935_easy_install_python_ssl.txt |
Q:
does python support incremental recomputation?
class foo:
def __init__(self, val=6):
self.val = val
def a(self):
self.val +=5
def b(self):
self.val +=10
def c(self):
self.val *=10
def make(self):
self.a()
self.b()
self.c()
obj= foo()
obj.make()
Take an example ... | does python support incremental recomputation? | class foo:
def __init__(self, val=6):
self.val = val
def a(self):
self.val +=5
def b(self):
self.val +=10
def c(self):
self.val *=10
def make(self):
self.a()
self.b()
self.c()
obj= foo()
obj.make()
Take an example of the code above, at times i want to take note of t... | [
"The code is wrong, but regardless — just save the result when you exit the function. There is nothing here that should be done on a language level.\n",
"It seems like your goal is to save the object in case of system failure so the answer would be to pickle obj and store somewhere. \n"
] | [
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0006816989_python.txt |
Q:
rpy2 convert Matrix -> DataFrame
I am having difficulty with this seemingly simple operation that I'd assume has been solved previously but I cannot find any examples.
In the R environment @data is of type DataFrame but rpy2 (2.2) is returning a Matrix. Is there a convirent way to either convert m to a DataFrame ... | rpy2 convert Matrix -> DataFrame | I am having difficulty with this seemingly simple operation that I'd assume has been solved previously but I cannot find any examples.
In the R environment @data is of type DataFrame but rpy2 (2.2) is returning a Matrix. Is there a convirent way to either convert m to a DataFrame or to have the robjects.r(query) retu... | [
"You can try explicitly casting to a data.frame in your yahooImport function.\nThe following worked for me:\n>>> yahooImport = robjects.r('function(x) as.data.frame(yahooImport(x)@data)')\n\n>>> print type(qqq)\n<class 'rpy2.robjects.vectors.DataFrame'>\n>>> qqq\n<DataFrame - Python:0x102412680 / R:0x103c2b310>\n[F... | [
2
] | [] | [] | [
"dataframe",
"matrix",
"python",
"r",
"rpy2"
] | stackoverflow_0006294436_dataframe_matrix_python_r_rpy2.txt |
Q:
Previewing the class or function definition source code in the interactive shell
Is it possible to access a source code of the imported class or funciton while using interactive shell like IDLE Shell or Linux python?
In example, I wish that it was possible to do the following:
from myClasses import MyClass
#this
... | Previewing the class or function definition source code in the interactive shell | Is it possible to access a source code of the imported class or funciton while using interactive shell like IDLE Shell or Linux python?
In example, I wish that it was possible to do the following:
from myClasses import MyClass
#this
print MyClass.__source__
#or that
source(MyClasss)
# would result in:
def MyClass(ob... | [
"from myClasses import MyClass\nimport inspect\n\nsource = inspect.getsource(MyClass)\nprint source\n\n#class MyClass(object):\n# pass\n\n"
] | [
3
] | [] | [] | [
"python",
"shell"
] | stackoverflow_0006816978_python_shell.txt |
Q:
Problem with file cleaning process?
I am working on very large file system. My task is to clean the system with some given parameters. Below program fragment can give a idea.
import DirectoryWalker
extentions_to_delete = list([".rar",".doc",".URL",".js",".EXE",".mht",".css",".txt", ".cache", ".xml"])
extentions_t... | Problem with file cleaning process? | I am working on very large file system. My task is to clean the system with some given parameters. Below program fragment can give a idea.
import DirectoryWalker
extentions_to_delete = list([".rar",".doc",".URL",".js",".EXE",".mht",".css",".txt", ".cache", ".xml"])
extentions_to_copy = list([".jpg",".BMP",".GIF",".jp... | [
"To answer your question, why not start with a simpler piece of code to test?\nimport os\n\nall_files = []\n\nfor root, dirs, files in os.walk('/media/08247451247443AA/home/crap/'):\n all_files.extend(files)\n\nprint len(all_files)\n\nAs a side note, could you replace the Walk class with a defaultdict?\n",
"Af... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0006637535_python.txt |
Q:
Is there any "Hello World" example type basic tutorial for heuristics or Meta Heuristics or optimization techniques
I am trying hard but still i have not found a very basic tutorial from where i can start with Meta heuristics and optimization problems. I have seen many books but they are full of Maths. I know that... | Is there any "Hello World" example type basic tutorial for heuristics or Meta Heuristics or optimization techniques | I am trying hard but still i have not found a very basic tutorial from where i can start with Meta heuristics and optimization problems. I have seen many books but they are full of Maths. I know that eventually i have to do that but if al least i have one simple example running before me , then i can get some confidenc... | [
"There's a visual explanation of heuristic and metaheuristic algorithms in this presentation.\nFor example:\n\n"
] | [
2
] | [] | [] | [
"artificial_intelligence",
"heuristics",
"optimization",
"python"
] | stackoverflow_0006814061_artificial_intelligence_heuristics_optimization_python.txt |
Q:
I just want to get started on development and spend less time faffing around with dependancies... is there a non MVN solution?
I'm a relativly newcomer to Java and Android, so far it's been a truly enlightening experience. The biggest nuisance is simply setting up my projects in the first place.
I've noticed that... | I just want to get started on development and spend less time faffing around with dependancies... is there a non MVN solution? | I'm a relativly newcomer to Java and Android, so far it's been a truly enlightening experience. The biggest nuisance is simply setting up my projects in the first place.
I've noticed that I seem to be spending a lot of time downloading source-code of dependancy projects, manually building jars and then manually adding... | [
"You could have a look at Gradle, which requires a much less configuration than Maven. A good quick-start for Java developers is http://www.gradle.org/tutorial_java_projects.html.\n",
"I think using maven2 from command line does have a learning curve, But if you use maven2 eclipse plugin http://eclipse.org/m2e/, ... | [
2,
1
] | [] | [] | [
"android",
"java",
"maven",
"maven_2",
"python"
] | stackoverflow_0006814332_android_java_maven_maven_2_python.txt |
Q:
Python memory leaks trackdown?
Somehow the memory my Python program takes more and more memory as it runs (the VIRT and RES) column of the "top" command keep increasing.
However, I double checked my code extremely carefully, and I am sure that there is no memory leaks (didn't use any dictionary, no global variabl... | Python memory leaks trackdown? | Somehow the memory my Python program takes more and more memory as it runs (the VIRT and RES) column of the "top" command keep increasing.
However, I double checked my code extremely carefully, and I am sure that there is no memory leaks (didn't use any dictionary, no global variables. It's just a main method calling ... | [
"Two possible cases:\n\nyour function is pure Python, in which case possible causes include \n\nyou are storing an increasing number of large objects\nyou are having cycles of objects with a __del__ method, which the gc won't touch\n\nI'd suggest using the gc module and the gc.garbage and gc.get_objects function (s... | [
1
] | [] | [] | [
"memory",
"memory_leaks",
"python"
] | stackoverflow_0006809947_memory_memory_leaks_python.txt |
Q:
How to append a list to a list created by a function in Python
Okay, I have a list that looks like this
OldList = [1000, 2000, 3000, 4000, 5000]
And I want to run all members of that list through a function called ListMultiply, like so
NewList = ListMultiply("/listfile/" + oldList]
How do I do this without conca... | How to append a list to a list created by a function in Python | Okay, I have a list that looks like this
OldList = [1000, 2000, 3000, 4000, 5000]
And I want to run all members of that list through a function called ListMultiply, like so
NewList = ListMultiply("/listfile/" + oldList]
How do I do this without concatenating string/list? Thanks.
| [
"NewList = [ListMultiply(\"/listfile/\"+str(e)) for e in OldList]\n\nThe above will create a new list by adding the string \"/listfile/\" to the string representation of each element and passing the result to ListMultiply().\n",
"You should concatenate the string/list somewhere(\"\".join or str.format would be be... | [
5,
0
] | [] | [] | [
"concatenation",
"list",
"python"
] | stackoverflow_0006817915_concatenation_list_python.txt |
Q:
Detect and handle a LaTeX warning/error generated via an os.system call in Python
I wrote a python script to automate turning Sweave/LaTeX documents into PDFs. Here's the most important part:
os.system("""echo "Sweave('%s.Rnw')" | R --vanilla --quiet"""%topic)
seq = ['p','b','p','b','p','p']
for op in seq:
... | Detect and handle a LaTeX warning/error generated via an os.system call in Python | I wrote a python script to automate turning Sweave/LaTeX documents into PDFs. Here's the most important part:
os.system("""echo "Sweave('%s.Rnw')" | R --vanilla --quiet"""%topic)
seq = ['p','b','p','b','p','p']
for op in seq:
if op is 'p':
os.system('pdflatex %s'%topic)
if op is 'b':
os.syste... | [
"\nDon't use os.system, use subprocess module instead.\npdflatex has an -interaction switch that you can use to put it a non-interactive mode (you probably want batchmode or nonstopmode IIRC, but you can experiment and see what each option do).\n\n",
"Pass the -interaction=nonstopmode flag to LaTeX.\n"
] | [
4,
1
] | [] | [] | [
"error_handling",
"latex",
"os.system",
"python",
"sweave"
] | stackoverflow_0006818102_error_handling_latex_os.system_python_sweave.txt |
Q:
Building QuantLib python bindings on windows 7: 'unrecognized command line option '-mno-cygwin''
I'm trying to build the QuantLib Python bindings. I managed to build QuantLib using these instructions (I found the libboost_serialization files here). When I try python setup.py build, I get the following error
pytho... | Building QuantLib python bindings on windows 7: 'unrecognized command line option '-mno-cygwin'' | I'm trying to build the QuantLib Python bindings. I managed to build QuantLib using these instructions (I found the libboost_serialization files here). When I try python setup.py build, I get the following error
python setup.py build
running build
running build_py
running build_ext
building 'QuantLib._QuantLib' extens... | [
"I've done a tutorial that builds Quantlib Python bindings on Windows (Vista and XP). This probably will work with Windows 7 as well and you don't need Visual Studio. here\n",
"The answer is that Python 2.6 distutils hasn't caught up with MinGW (source). I now get another error, but that's for another question.\n... | [
3,
1
] | [] | [] | [
"python",
"quantlib",
"quantlib_swig"
] | stackoverflow_0006267910_python_quantlib_quantlib_swig.txt |
Q:
save the image in the clipboatd - in Python/Tkinter
the subject says it all: is it possible to take an image present in the clipboard and save it to file under Tkinter?
A:
Here is a script that should get let you get arbitrary clipboard data on windows.
import win32clipboard as clip
# The standard windows clipb... | save the image in the clipboatd - in Python/Tkinter | the subject says it all: is it possible to take an image present in the clipboard and save it to file under Tkinter?
| [
"Here is a script that should get let you get arbitrary clipboard data on windows.\nimport win32clipboard as clip\n\n# The standard windows clipboard formats\nformats = ['CF_OEMTEXT', 'CF_PALETTE', 'CF_TEXT', 'CF_ENHMETAFILE', 'CF_UNICODETEXT', \n 'CF_BITMAP', 'CF_METAFILEPICT', 'CF_DIB', 'CF_DIBV5']\n\n... | [
1,
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0006817600_python_tkinter.txt |
Q:
Insert a tzinfo into datetime
I have the following tzinfo concrete subclass definition:
from datetime import datetime, timedelta, tzinfo
class ManilaTime(tzinfo):
def utcoffset(self, dt):
return timedelta(hours=8)
def tzname(self, dt):
return "Manila"
I obtain a date string and would like to transfo... | Insert a tzinfo into datetime | I have the following tzinfo concrete subclass definition:
from datetime import datetime, timedelta, tzinfo
class ManilaTime(tzinfo):
def utcoffset(self, dt):
return timedelta(hours=8)
def tzname(self, dt):
return "Manila"
I obtain a date string and would like to transform it into a timezone-aware datetim... | [
"def transform_date(date_string, tzinfo):\n fmt = '%Y-%m-%d'\n date = datetime.strptime(date_string, fmt).replace(tzinfo=tzinfo)\n return date\n\n"
] | [
18
] | [] | [] | [
"datetime",
"python",
"timezone",
"tzinfo"
] | stackoverflow_0006818377_datetime_python_timezone_tzinfo.txt |
Q:
Getting EOFError along with exceptions when using ftplib
I'm looking into using ftplib (and possibly ftputil) for doing some automated FTP file syncing. I have a couple of servers to test this against at the moment, but, whilst I'm having a successful conversation with both servers, I get EOFError-s with each erro... | Getting EOFError along with exceptions when using ftplib | I'm looking into using ftplib (and possibly ftputil) for doing some automated FTP file syncing. I have a couple of servers to test this against at the moment, but, whilst I'm having a successful conversation with both servers, I get EOFError-s with each error reply. For example: if I try to log in with an incorrect use... | [
"The servers are sending EOF to tell you that they've terminated the connection.\nYou should treat this no differently than any other disconnection event, except that obviously you need to handle it with except EOFError.\nSee the source, from http://svn.python.org/view/python/trunk/Lib/ftplib.py?view=markup\n# Inte... | [
6
] | [] | [] | [
"eoferror",
"ftp",
"ftplib",
"ftputil",
"python"
] | stackoverflow_0006818091_eoferror_ftp_ftplib_ftputil_python.txt |
Q:
Python's mmap() performance down with time
I am wondering why Python's mmap() performance going down with time? I mean I have a little app which make changes to N files, if set is big (not too really big, say 1000) first 200 is demon-speed but after that it goes slower and slower. It looks like I should free memor... | Python's mmap() performance down with time | I am wondering why Python's mmap() performance going down with time? I mean I have a little app which make changes to N files, if set is big (not too really big, say 1000) first 200 is demon-speed but after that it goes slower and slower. It looks like I should free memory once in a while but don't know how and most im... | [
"Your OS caches the mmap'd pages in RAM. Reads and writes go at RAM speed from the cache. Dirty pages are eventually flushed. On Linux performance will be great until you have to start flushing pages, this is controlled by vm.dirty_ratio sysctl variable. Once your start flushing dirty pages to disk the reads will c... | [
6
] | [] | [] | [
"memory",
"mmap",
"performance",
"python"
] | stackoverflow_0006818054_memory_mmap_performance_python.txt |
Q:
reusable application for django site wide announcements that displays a message only once per user
I want to show various messages to registered users only once in my django application. I found django-announcements which seemed to do what I want - but I found in testing it marks messages as read by using a sessi... | reusable application for django site wide announcements that displays a message only once per user | I want to show various messages to registered users only once in my django application. I found django-announcements which seemed to do what I want - but I found in testing it marks messages as read by using a session variable, which disappears if the user logs out. This means a message is shown again to a user if the... | [
"Have a look at django-notification. It is used by pinax, there it seems to work like what you are searching for. At least it saves the status in the db.\nedit\nResponse to the comment\nfrom the docs:\nnotification.send([to_user], \"friends_invite\", {\"from_user\": from_user})\n\nso this should work:\nnotification... | [
3,
0
] | [] | [] | [
"code_reuse",
"django",
"pinax",
"python"
] | stackoverflow_0001829926_code_reuse_django_pinax_python.txt |
Q:
Compare "similar" numbers in Python
In order to sync my iPod and my local music repository, I created a unique key for each track using its metadata. The unique track consists of the track's following metadata fields:
artist, album, track number, duration. The iPod saves the track's duration in milliseconds, but m... | Compare "similar" numbers in Python | In order to sync my iPod and my local music repository, I created a unique key for each track using its metadata. The unique track consists of the track's following metadata fields:
artist, album, track number, duration. The iPod saves the track's duration in milliseconds, but my local repository saves it in seconds. F... | [
"Your round call is giving the wrong result as you're dividing by 1000, instead of 1000.0\n>>> round(437590/1000.0)\n438.0\n\n",
"You are experiencing Python 2's integer division. When you divide two integers, Python (and many other languages) throw away the remainder. You'll want to divide by a float instead of ... | [
6,
2,
0
] | [
"Honestly, I think you nailed it already with the floor and ceil calls, but for somplicity you might want to do floor((ipodtime/1000)+1) == localrepostime to check equality since the ipod time seems to round down no matter what.\n"
] | [
-2
] | [
"math",
"python",
"rounding"
] | stackoverflow_0006818610_math_python_rounding.txt |
Q:
Calling custom assert function from Selenium RC (Python) with a custom locator function in user-extensions.js
I have written a custom assert function in user-extensions.js that uses a custom locator function - also implemented in user-extensions.js - to locate a particular element on a page.
Without getting into ... | Calling custom assert function from Selenium RC (Python) with a custom locator function in user-extensions.js | I have written a custom assert function in user-extensions.js that uses a custom locator function - also implemented in user-extensions.js - to locate a particular element on a page.
Without getting into details; I need the custom locator function because I'm trying to locate an element in a different namespace on the... | [
"The problem is most likely that your custom locator function (LocateElementByMyprefix()) is not being registered. Selenium RC does user-extension.js setup just a little differently from Selenium IDE, and the timing can get in the way. Try calling selenium.browserbot._registerAllLocatorFunctions() after your func... | [
0
] | [] | [] | [
"locate",
"python",
"selenium",
"selenium_rc",
"user_extensions.js"
] | stackoverflow_0006805180_locate_python_selenium_selenium_rc_user_extensions.js.txt |
Q:
Strip all but first 5 characters - Python
Possible Duplicate:
Is there a way to substring a string in Python?
I have a string in the form 'AAAH8192375948'. How do I keep the first 5 characters of this string, and strip all the rest? Is it in the form l.strip with a negative integer? Thanks.
A:
A string in Pyt... | Strip all but first 5 characters - Python |
Possible Duplicate:
Is there a way to substring a string in Python?
I have a string in the form 'AAAH8192375948'. How do I keep the first 5 characters of this string, and strip all the rest? Is it in the form l.strip with a negative integer? Thanks.
| [
"A string in Python is a sequence type, like a list or a tuple. Simply grab the first 5 characters:\n some_var = 'AAAH8192375948'[:5]\n print some_var # AAAH8\n\nThe slice notation is [start:end:increment] -- numbers are optional if you want to use the defaults (start defaults to 0, end to len(my_sequence) and incr... | [
44,
7,
5
] | [] | [] | [
"python"
] | stackoverflow_0006819173_python.txt |
Q:
python 3 IRC bot syntax error
Okay, first off. I'm very new to python, and I've just started to teach myself python 3
As a fun project to help me learn I decieded to do an IRC Bot, I figured I'll follow a basic tutorial on creating a basic bot, and as I learn I could add more to it, and make it my own but the pr... | python 3 IRC bot syntax error | Okay, first off. I'm very new to python, and I've just started to teach myself python 3
As a fun project to help me learn I decieded to do an IRC Bot, I figured I'll follow a basic tutorial on creating a basic bot, and as I learn I could add more to it, and make it my own but the problem is I believe
the tutorial was... | [
"You are missing : after if statement. Should be:\nif msgpart[0]=='`' and sender[0]==OWNER:\n cmd=msgpart[1:].split('')\n\n",
"You are missing a colon : at the end of the if statement:\nif msgpart[0]=='`' and sender[0]==OWNER # Treat all messages start with ` as a command\n ... | [
3,
1,
1
] | [] | [] | [
"bots",
"irc",
"python"
] | stackoverflow_0006818660_bots_irc_python.txt |
Q:
Playing RTSP with python-gstreamer
I use gstreamer for playing RTSP stream from IP cameras (like Axis.)
I use a command line like this:
gst-launch-0.10 rtspsrc location=rtsp://192.168.0.127/axis-media/media.amp latency=0 ! decodebin ! autovideosink
and it work fine.
I want to control it with a gui in pygtk so I ... | Playing RTSP with python-gstreamer | I use gstreamer for playing RTSP stream from IP cameras (like Axis.)
I use a command line like this:
gst-launch-0.10 rtspsrc location=rtsp://192.168.0.127/axis-media/media.amp latency=0 ! decodebin ! autovideosink
and it work fine.
I want to control it with a gui in pygtk so I use the gstreamer python bindings.
I've ... | [
"I have a \"C\" implementation of the code you are looking for. I think it should be fairly simple to convert to \"Python\"\n //Display RTSP streaming of video\n //(c) 2011 enthusiasticgeek\n // This code is distributed in the hope that it will be useful,\n // but WITHOUT ANY WARRANTY; without even the implied warr... | [
6,
2
] | [] | [] | [
"gstreamer",
"h.264",
"ip_camera",
"python",
"rtsp"
] | stackoverflow_0004192871_gstreamer_h.264_ip_camera_python_rtsp.txt |
Q:
pycurl - 302 redirect/page moved
Trying to successfully get a page/headers (response/request) using pycurl. I can successfully get it using java/htmlunit.
I'm missing something subtle to get to the new/redirected page.
I was/am trying to get the "new" redirected url, that is then fed into the pycurl for the new pa... | pycurl - 302 redirect/page moved | Trying to successfully get a page/headers (response/request) using pycurl. I can successfully get it using java/htmlunit.
I'm missing something subtle to get to the new/redirected page.
I was/am trying to get the "new" redirected url, that is then fed into the pycurl for the new page.
thanks
The sample test code is:
... | [
"Just set the FOLLOWLOCATION flag to 1:\ncrl.setopt(pycurl.FOLLOWLOCATION, 1)\n\nThe curl will proceed to the next location on 301/302.\n",
"I know this is an old question, but perhaps it will be a relevant answer. It seems the response you see is coming from a frontend device actively preventing you to access t... | [
9,
1
] | [] | [] | [
"http_status_code_302",
"pycurl",
"python",
"redirect"
] | stackoverflow_0005033890_http_status_code_302_pycurl_python_redirect.txt |
Q:
Does deepcopy use copy-on-write?
I wonder if the python interpreter applies copy on write strategy when doing a deepcopy on mutable objects.
Also, I'd like to know if the deepcopy is performed also on nonmutable object (that would seem strange to me however)
A:
It does not do copy-on-write.
It doesn't do a deep ... | Does deepcopy use copy-on-write? | I wonder if the python interpreter applies copy on write strategy when doing a deepcopy on mutable objects.
Also, I'd like to know if the deepcopy is performed also on nonmutable object (that would seem strange to me however)
| [
"It does not do copy-on-write.\nIt doesn't do a deep copy on some built-in immutable types, but any user-defined \"immutable\" types will be deep-copied.\ncopy.py in the Python 2.7 standard library includes this message in its documentation:\n\nThis version does not copy types like module, class, function, method, ... | [
6,
4,
3
] | [] | [] | [
"copy_on_write",
"deep_copy",
"python"
] | stackoverflow_0006819610_copy_on_write_deep_copy_python.txt |
Q:
Django, topic model with subtopics
i wanted to create a topic model.
this model would have a foreign key, non required, to the topic above it
for example:
iphone has a foreign key to apple
but what do i do if i want apple to be linked to all of its sub elements
apple to iPhone
apple to mac
i know that there are ma... | Django, topic model with subtopics | i wanted to create a topic model.
this model would have a foreign key, non required, to the topic above it
for example:
iphone has a foreign key to apple
but what do i do if i want apple to be linked to all of its sub elements
apple to iPhone
apple to mac
i know that there are many to many fields, but how exactly would... | [
"You probably want to look at the documentation for related_name. Basically Django does this for you. For example:\nclass Topic(models.Model):\n master_topic = models.ForeignKey('self',\n null=True,\n blank=True,\n related_name=\"sub_topics\")\n\nThen... | [
2
] | [] | [] | [
"django",
"django_models",
"many_to_many",
"one_to_many",
"python"
] | stackoverflow_0006819640_django_django_models_many_to_many_one_to_many_python.txt |
Q:
Why can't I execute such code in my Python shell?
Why am I not able to run the following lines in my shell?
>>> try:
... x = int("a lot")
... except items["error"] as e:
... # Same as except ValueError as e
... print("Couldn't convert")
Error message:
>>> try: ... x=int("a lot") File "<stdin>", line 2... | Why can't I execute such code in my Python shell? | Why am I not able to run the following lines in my shell?
>>> try:
... x = int("a lot")
... except items["error"] as e:
... # Same as except ValueError as e
... print("Couldn't convert")
Error message:
>>> try: ... x=int("a lot") File "<stdin>", line 2 x=int("a lot")<&>
^
IndentationError: expect... | [
"Works for me:\n>>> items = {}\n>>> items[\"error\"] = ValueError\n>>> try:\n... x = int(\"a lot\")\n... except items[\"error\"] as e:\n... print \"Couldn't convert\"\n...\nCouldn't convert\n\n",
"Your indentation is wrong. Should be:\n>>> try:\n... x = int(\"a lot\")\n... except items[\"error\"] as e... | [
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0006819989_python.txt |
Q:
new to Python, help with loops
i have this opensource code which is used to echo back response to web-socket requests:
_GOODBYE_MESSAGE = 'Goodbye'
def web_socket_do_extra_handshake(request):
pass # Always accept.
def web_socket_transfer_data(request):
while True:
line = request.ws_stream.receive_mess... | new to Python, help with loops | i have this opensource code which is used to echo back response to web-socket requests:
_GOODBYE_MESSAGE = 'Goodbye'
def web_socket_do_extra_handshake(request):
pass # Always accept.
def web_socket_transfer_data(request):
while True:
line = request.ws_stream.receive_message()
if line == "hello":
... | [
"for your first question, you can just say\nif line == \"whatever\":\n # do stuff here, return, whatever...\n request.ws_stream.send_message(line)\nelse:\n # do something else....\n\nfor sleeping, you want\n import time\n time.sleep(seconds)\n\nif the \"import time\" line fails, you've got a problem with your... | [
3,
0
] | [] | [] | [
"mod_python",
"python",
"websocket"
] | stackoverflow_0006819881_mod_python_python_websocket.txt |
Q:
How can I be sure of the possible return values for platform.release()
I have a program that we create an exe with for distribution. My clients run XP and Vista and 7. We are trying to make the installation easier by adjusting where the log file writes to in Win7 and Vista as we did not have to worry about that ... | How can I be sure of the possible return values for platform.release() | I have a program that we create an exe with for distribution. My clients run XP and Vista and 7. We are trying to make the installation easier by adjusting where the log file writes to in Win7 and Vista as we did not have to worry about that in XP. We are trying to use platform.release() to then decide where to wri... | [
"The definitive answer can be found in the source code to the exact version of your Python interpreter. I am using CPython 2.7.1. Its source code available for free download, and here is the relevant code (found in Lib/platform.py):\nwinver = GetVersionEx()\nmaj,min,buildno,plat,csd = winver\nversion = '%i.%i.%i' %... | [
4
] | [] | [] | [
"platform",
"python"
] | stackoverflow_0006820040_platform_python.txt |
Q:
Python AttributeError
When I type this code into a python shell it works perfectly fine but within a program it gives an error.
import os
h = os.environ['HOME']
within a script it gives this error:
AttributeError: 'str' object has no attribute 'environ'
Why is this happening and is there any way I can fix it?
(... | Python AttributeError | When I type this code into a python shell it works perfectly fine but within a program it gives an error.
import os
h = os.environ['HOME']
within a script it gives this error:
AttributeError: 'str' object has no attribute 'environ'
Why is this happening and is there any way I can fix it?
(I'm kinda just learning pyt... | [
"Somewhere, you've created a string and named it os. The . is the attribute lookup operator, so it's complaining about the thing to the left of the ., in this case, os.\n",
"are you sure that between import os and h = os.environ['HOME'] you did not use os as a variable for a string?\nedit: If you do not work wit... | [
8,
3
] | [] | [] | [
"attributeerror",
"import",
"python"
] | stackoverflow_0006820209_attributeerror_import_python.txt |
Q:
Python to Objective C (Expected Learning Curve)
I'm a self-taught programmer who jumped into Python as my first language about 7-8 months ago. I'm fairly solid at making things work, though my foundational knowledge is limited thanks to my questionable choice in college to not study computer science.
Beyond Pyth... | Python to Objective C (Expected Learning Curve) | I'm a self-taught programmer who jumped into Python as my first language about 7-8 months ago. I'm fairly solid at making things work, though my foundational knowledge is limited thanks to my questionable choice in college to not study computer science.
Beyond Python, I'm not really familiar with C or other lower lev... | [
"You may take some time once you do not have experience with C. The \"C way\" is very important to understand Objective-C. You can learn Objective-C without C as well but you will find a lot of C pitfalls in your way.\nSaid that, I started a project in Objective-C some time ago after giving up Python with Cocoa. I ... | [
7,
3,
1,
1,
0
] | [] | [] | [
"c",
"iphone",
"objective_c",
"python"
] | stackoverflow_0006666499_c_iphone_objective_c_python.txt |
Q:
Fail using PyDev test runner
I have created a default unit test module in PyDev. The module is as follows:
import unittest
class Test(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def testName(self):
self.assertEqual(1, 2) #here I expect to see failure mes... | Fail using PyDev test runner | I have created a default unit test module in PyDev. The module is as follows:
import unittest
class Test(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def testName(self):
self.assertEqual(1, 2) #here I expect to see failure message
if __name__ == "__main__"... | [
"I think (operating from memory) that your should prefix the test name with test_ (underscore required).\n",
"OK, I've found the problem.\nIt turns out that several parts of inititalization code of my modules rely on parsing sys.argv[0]. This worked fine when using \"Run As -> Python Run\" as sys.argv[0] containe... | [
0,
0
] | [] | [] | [
"pydev",
"python",
"unit_testing"
] | stackoverflow_0006816552_pydev_python_unit_testing.txt |
Q:
Untarring in python, interactive vs script call
I am trying to untar a tar file via popen (from platform import popen) and am running into problems. The command runs if I use the interactive script, but does not if I put it in a .py file and run it.
Basically, I change to to that directory and run popen("tar xvf ... | Untarring in python, interactive vs script call | I am trying to untar a tar file via popen (from platform import popen) and am running into problems. The command runs if I use the interactive script, but does not if I put it in a .py file and run it.
Basically, I change to to that directory and run popen("tar xvf the_tar.tar")
Why would these be different? How come... | [
"You should use the tarfile library:\nfrom tarfile import TarFile\n\ntar = TarFile(\"the_tar.tar\")\ntar.extractall()\n\n",
"Given your info I can't see the problems you see. Probably a bit more of context. I.e. the exact script that does not work, please. \nI built a sample tar archive with an empty text file in... | [
5,
0
] | [] | [] | [
"python"
] | stackoverflow_0006820340_python.txt |
Q:
Fun with GAE: urlfetch rpc time out
I'm trying to write an image to the blob store. I've tried fetch_response = urlfetch.fetch(image_url, deadline=10) which timed out and now I'm trying rpc with the same result. Can someone tell me what's wrong with the following code? Thanks for your help:
media_items = ['log... | Fun with GAE: urlfetch rpc time out | I'm trying to write an image to the blob store. I've tried fetch_response = urlfetch.fetch(image_url, deadline=10) which timed out and now I'm trying rpc with the same result. Can someone tell me what's wrong with the following code? Thanks for your help:
media_items = ['logo.png']
content_type = 'image/png'
... | [
"If you are fetching the blob from your own application, you should probably use BlobReader or load the file from the file system.\n",
"As it seems the dev server is single threaded and you have to run 2 instaces if you want to send requests to it:\nGoogleAppEngine urlfetch timeout exception\n"
] | [
3,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0006820387_google_app_engine_python.txt |
Q:
Sqlite - how to use more memory and cache, and make it run faster
I'm inserting into a table in Sqlite around 220GB of data,
and I noticed it use a lot of Disk I/O, read and write,
but doesn't use the computer's memory in any significant way,
though there is a lot of free memory, and I don't use commit to often.
I... | Sqlite - how to use more memory and cache, and make it run faster | I'm inserting into a table in Sqlite around 220GB of data,
and I noticed it use a lot of Disk I/O, read and write,
but doesn't use the computer's memory in any significant way,
though there is a lot of free memory, and I don't use commit to often.
I think the disk I/O is my bottle neck not CPU nor Memory.
how can I ask... | [
"Review all options in http://www.sqlite.org/pragma.html. You can tuning a lot of performance relative aspect of SQLite in your application.\nAll I/O activity is for the integrity of data. SQLite by default is very safe.\nYour filesystem is also important for the performance. Not all FS play fair with fsync and the... | [
4
] | [] | [] | [
"database",
"python",
"sql",
"sqlite"
] | stackoverflow_0006818136_database_python_sql_sqlite.txt |
Q:
python: executing "start /wait someprocess"
I've used Python's subprocess.call() before, but how do you get it to act like the Windows START /WAIT myprogram?
I've tried subprocess.call(['start', '/wait', 'myprogram.exe']) but it can't find start and neither can I.
A:
If you want to wait for a spawned process, th... | python: executing "start /wait someprocess" | I've used Python's subprocess.call() before, but how do you get it to act like the Windows START /WAIT myprogram?
I've tried subprocess.call(['start', '/wait', 'myprogram.exe']) but it can't find start and neither can I.
| [
"If you want to wait for a spawned process, then use subprocess.Popen and then either wait or communicate. start is AFAIR a shell construct, not a real exec (so you'd have to use shell = True — but that still wouldn't do what you want).\n"
] | [
1
] | [] | [] | [
"python",
"subprocess",
"winapi"
] | stackoverflow_0006820856_python_subprocess_winapi.txt |
Q:
How do you get iPython to run on Console2?
How do you really get iPython to run on Console2? The instructions on the iPython site are not correct: http://ipython.scipy.org/moin/IpythonOnConsole. (it says the Shell needs to be set to: cmd.exe /k "ipython") I verified that python.exe is in my Path, etc. and I sti... | How do you get iPython to run on Console2? | How do you really get iPython to run on Console2? The instructions on the iPython site are not correct: http://ipython.scipy.org/moin/IpythonOnConsole. (it says the Shell needs to be set to: cmd.exe /k "ipython") I verified that python.exe is in my Path, etc. and I still get errors when I open an iPython tab saying ... | [
"I figured it out: the Shell in the tab settings actually needs to be set to this:\ncmd.exe /k \"<my python path>\\Scripts\\ipython.py -p sh\"\n\nWhere \"< my python path >\" is the dir of your python installation, such as \"C:\\Python26\".\nI added a page to the new wiki and added a link to it in the cookbook.\n"... | [
5
] | [] | [] | [
"console2",
"ipython",
"python"
] | stackoverflow_0006821370_console2_ipython_python.txt |
Q:
Python code performance decreases with threading
I've written a working program in Python that basically parses a batch of binary files, extracting data into a data structure. Each file takes around a second to parse, which translates to hours for thousands of files. I've successfully implemented a threaded versio... | Python code performance decreases with threading | I've written a working program in Python that basically parses a batch of binary files, extracting data into a data structure. Each file takes around a second to parse, which translates to hours for thousands of files. I've successfully implemented a threaded version of the batch parsing method with an adjustable numbe... | [
"This is sadly how things are in CPython, mainly due to the Global Interpreter Lock (GIL). Python code that's CPU-bound simply doesn't scale across threads (I/O-bound code, on the other hand, might scale to some extent).\nThere is a highly informative presentation by David Beazley where he discusses some of the iss... | [
44,
9
] | [] | [] | [
"io",
"multithreading",
"performance",
"python"
] | stackoverflow_0006821477_io_multithreading_performance_python.txt |
Q:
Optimizing your PyQt applications
For those of you who have written fairly complex PyQt applications, what tips and tricks would you offer for speeding up your applications? I have a few examples of where my program begins to slow down as it grows larger:
I have a 'dashboard' written that is destroyed and re-crea... | Optimizing your PyQt applications | For those of you who have written fairly complex PyQt applications, what tips and tricks would you offer for speeding up your applications? I have a few examples of where my program begins to slow down as it grows larger:
I have a 'dashboard' written that is destroyed and re-created when a user clicks on an item in a ... | [
"I'm not sure if this is exactly the same thing you are doing, but it sounds similar to something I have in some apps, where there is some list of custom widget. And it does significantly slow down when you are creating and destroying tons of widgets.\nIf its an issue of lesser amounts of total widgets, but just be... | [
8,
1
] | [] | [] | [
"optimization",
"pyqt",
"python"
] | stackoverflow_0006764329_optimization_pyqt_python.txt |
Q:
Change gtkListStore model dynamically
So I finally got around to understand how PyGTK really works and I'm working on a simple SQLite manager app.
To show the result of a query I'm using a gtk.ScrolledWindow with a gtk.TreeView. I've managed to add and even change the values in the ListStore object as I need, what... | Change gtkListStore model dynamically | So I finally got around to understand how PyGTK really works and I'm working on a simple SQLite manager app.
To show the result of a query I'm using a gtk.ScrolledWindow with a gtk.TreeView. I've managed to add and even change the values in the ListStore object as I need, what I can't do is change the model of the List... | [
"You can use gtk.TreeView.set_model to assign a new model to a TreeView. So you can generate a new model for each set of results, and then set the TreeView to show that model.\n"
] | [
5
] | [] | [] | [
"pygtk",
"python"
] | stackoverflow_0006819271_pygtk_python.txt |
Q:
force mysqldb dict cursor to return prefix all column names with table name
SELECT * FROM a, b WHERE ...
Mysql allows duplicate column names in the results of a query. So, in the terminal, none of the column names are prefixed using the above query.
However, I'm using mysqldb in python with the DictCursor. Result... | force mysqldb dict cursor to return prefix all column names with table name | SELECT * FROM a, b WHERE ...
Mysql allows duplicate column names in the results of a query. So, in the terminal, none of the column names are prefixed using the above query.
However, I'm using mysqldb in python with the DictCursor. Results are a list of dictionaries where the column names are the keys. Sometimes, the ... | [
"I'm not a big fan of using * in queries. List your columns and assign your own aliases as needed. As you'll see, I'm also not a fan of implicit joins.\nSELECT a.col1 AS acol1,\n a.col2 AS acol2,\n b.col1 AS bcol1,\n b.col2 AS bcol2\n FROM a\n INNER JOIN b\n ON ...\n WHERE.... | [
2,
1
] | [] | [] | [
"mysql",
"mysql_python",
"python",
"select"
] | stackoverflow_0006821677_mysql_mysql_python_python_select.txt |
Q:
Scraping Webpages with Javascript-loaded options
I am trying to use Python's mechanize module to submit an HTML POST form request. To do so, I must select an option from a <select> element, but the options are loaded dynamically by Javascript.
Since I know the <select> option I want to use, I tried to construct t... | Scraping Webpages with Javascript-loaded options | I am trying to use Python's mechanize module to submit an HTML POST form request. To do so, I must select an option from a <select> element, but the options are loaded dynamically by Javascript.
Since I know the <select> option I want to use, I tried to construct the form request using the not-yet-loaded option value, ... | [
"Perhaps you did this already, but when you try to append the option to the <select> list, use the more cumbersome document.createElement,parentNode.appendChild methods from javascript instead of innerHMTL=..., jQuery html(..) or jQuery $('<..>..</..>'), which do not always work fully or correctly (e.g. in your cas... | [
0
] | [] | [] | [
"html",
"javascript",
"python"
] | stackoverflow_0006819110_html_javascript_python.txt |
Q:
Custom Foreign Key Property
I have a model called Personnel which I'm using as the profile model for the User model. Here's my model
class Personnel(models.Model):
user = models.OneToOneField(
User
)
phone = models.CharField(
null=False, max_length=50, verbose_name="Phone"
)
I need... | Custom Foreign Key Property | I have a model called Personnel which I'm using as the profile model for the User model. Here's my model
class Personnel(models.Model):
user = models.OneToOneField(
User
)
phone = models.CharField(
null=False, max_length=50, verbose_name="Phone"
)
I need to use the above model in with a... | [
"There are two misconceptions in your question. Firstly, that you need to pass a value for the field even though you've excluded it; and secondly, that you can't include a field that's not on the model. Neither of these are true.\nIt's definitely possible to define a separate email field, display it on the form alo... | [
1
] | [] | [] | [
"django",
"django_forms",
"django_models",
"properties",
"python"
] | stackoverflow_0006821380_django_django_forms_django_models_properties_python.txt |
Q:
Apache ImportError when loading django module WSGI
I am following the integration with django tutorial on the mod_wsgi site, and I am receiving the following error when trying to load my site, I had the test script in the previous tutorial working fine. Here is the error log from my apache server, I have django in... | Apache ImportError when loading django module WSGI | I am following the integration with django tutorial on the mod_wsgi site, and I am receiving the following error when trying to load my site, I had the test script in the previous tutorial working fine. Here is the error log from my apache server, I have django installed fine, I can import it when I am running python s... | [
"Either install Django under the version of Python that mod_wsgi is built against, or build mod_wsgi for the version of Python that Django is installed under.\n"
] | [
2
] | [] | [] | [
"apache",
"django",
"mod_wsgi",
"python"
] | stackoverflow_0006822377_apache_django_mod_wsgi_python.txt |
Q:
Efficiently calling a Python function
I'm embedding Python into my game. The scripts will be used to define the character AI, how entities react to game events, etc — this means there's going to be a script for every type of entity in the game.
Each script will have a function like createEntity() or something whic... | Efficiently calling a Python function | I'm embedding Python into my game. The scripts will be used to define the character AI, how entities react to game events, etc — this means there's going to be a script for every type of entity in the game.
Each script will have a function like createEntity() or something which will return the constructed entity. What ... | [
"Ousterhout on the role of scripting languages is an oldie but goodie. In the case of a game where you have said that the gameplay is to be scripted, the model (Python) is already organizing the flow as you have described it. If PyGame or similar library isn't up to the task of presenting the view, find or build a ... | [
1,
1
] | [] | [] | [
"boost",
"c++",
"embed",
"python",
"scripting"
] | stackoverflow_0006807833_boost_c++_embed_python_scripting.txt |
Q:
bpython in Emacs
I've started using bpython for my python interpreting needs. I like the syntax highlighting and the tab completion mode. I'd like to get bpython working in emacs (note: simply running the bpython command in shell mode doesn't work) so that I can achieve Python nirvana. Any recommendations on ho... | bpython in Emacs | I've started using bpython for my python interpreting needs. I like the syntax highlighting and the tab completion mode. I'd like to get bpython working in emacs (note: simply running the bpython command in shell mode doesn't work) so that I can achieve Python nirvana. Any recommendations on how to get started writi... | [
"term-mode works or are you striving for a integration with the python mode like sending code to bpython?\n"
] | [
2
] | [] | [] | [
"bpython",
"emacs",
"python"
] | stackoverflow_0006822196_bpython_emacs_python.txt |
Q:
Obtaining loaded images from a given URL via Python
Is there anyway to load a URL via Python and then retrieve a list of all of the images that were loaded via that URL? I'm essentially looking to do something similar to TamperData or Fiddler and retrieve a list of all images that a given website loaded.
A:
Inte... | Obtaining loaded images from a given URL via Python | Is there anyway to load a URL via Python and then retrieve a list of all of the images that were loaded via that URL? I'm essentially looking to do something similar to TamperData or Fiddler and retrieve a list of all images that a given website loaded.
| [
"Interesting task. Here's one way of solving it, along the line suggested by Jochen Ritzel. \nIt uses pylibpcap instead of pycap. Personally, I find pycap to be hard to work with due to little amount of documentation available. For pylibpcap, you can translate most code directly from the libpcap examples (see for e... | [
1
] | [] | [] | [
"fiddler",
"image",
"python",
"url"
] | stackoverflow_0006522660_fiddler_image_python_url.txt |
Q:
Manipulating non-adjacent cells in python using arrays or rec-arrays
I’m trying to change non-adjacent values of an array simultaneously, and it doesn’t seem to be working. Trying the example below, the code does not break, but the values do not change. I have run into the same problem using recarrays. Has anyo... | Manipulating non-adjacent cells in python using arrays or rec-arrays | I’m trying to change non-adjacent values of an array simultaneously, and it doesn’t seem to be working. Trying the example below, the code does not break, but the values do not change. I have run into the same problem using recarrays. Has anyone run into this before? Any thoughts? For example:
import numpy as np
... | [
"The order of indexing can matter. Try:\nsimulants[:,0][simulants[:,4]==5]=np.array([1,2])\n\nThe reason why order matters is because simulants[:,0] is a view, while\nsimulants[simulants[:,4]==5] is a (sub)copy of the array. (Modifying a view of an array modifies the underlying array. Modifying a copy does not.)\ns... | [
3
] | [] | [] | [
"arrays",
"python"
] | stackoverflow_0006822315_arrays_python.txt |
Q:
python struct, Byte order and Alignment for Network application and difference between unsigned int and unsigned long
I have 2 questions about struct in the python documentation:
Byte Order, Size, and Alignment : For Network communication should i use ! instead of = ?
eg: struct.pack("!BBH", 1, 12, 512) or struct.... | python struct, Byte order and Alignment for Network application and difference between unsigned int and unsigned long | I have 2 questions about struct in the python documentation:
Byte Order, Size, and Alignment : For Network communication should i use ! instead of = ?
eg: struct.pack("!BBH", 1, 12, 512) or struct.pack("=BBH", 1, 12, 512) ?
Format characters : What is the difference between unsigned int (I) and unsigned long (L), since... | [
"If you want your code to produce the same output wherever it is run, why would you ever use =? So of course, yes, you should use a code that means the same thing to everyone. The standard is ! so use !.\nRead the header above the format code table:\n\nThe ‘Standard size’ column refers to the size of the packed val... | [
2
] | [] | [] | [
"endianness",
"python",
"struct"
] | stackoverflow_0006823134_endianness_python_struct.txt |
Q:
Scalable asynchronous image resizing
I'm considering a few options for the most scalable way of handling image resizing in a PHP (CodeIgniter) Web App. I need to resize an image into several sizes and then push them to Amazon S3. So here are the options I've come up with so far:
When file is uploaded add it to a ... | Scalable asynchronous image resizing | I'm considering a few options for the most scalable way of handling image resizing in a PHP (CodeIgniter) Web App. I need to resize an image into several sizes and then push them to Amazon S3. So here are the options I've come up with so far:
When file is uploaded add it to a queue. Have a background PHP or Python (Ap... | [
"I'd go for your first choice, as it would be more reliable and means you could do work on the backend without taking the front end down.\nIt would also scale much more gracefully, as you could move it off to another server if the queue becomes extreme.\n",
"your first idea sounds good for reasons already stated,... | [
3,
1
] | [] | [] | [
"codeigniter",
"image",
"imagemagick",
"php",
"python"
] | stackoverflow_0006823873_codeigniter_image_imagemagick_php_python.txt |
Q:
Django and MVC(MVT) layout
Im coming from using other MVC based frameworks, and going into Django, it seems a little awkward to what im used to. For example, in other MVC based frameworks. my layout might be like so:
root:
- config (houses the config files (like settings), url.conf, db connections, etc.)
- control... | Django and MVC(MVT) layout | Im coming from using other MVC based frameworks, and going into Django, it seems a little awkward to what im used to. For example, in other MVC based frameworks. my layout might be like so:
root:
- config (houses the config files (like settings), url.conf, db connections, etc.)
- controllers (houses the main logic of e... | [
"The biggest benefit is that apps are modularized. You can remove your Poll application by deleting one directory instead of hunting through several directories deleting each piece. The flip side is if you found a Poll application somewhere that you wanted to use you can just drop in the one folder and you're goo... | [
7,
6
] | [] | [] | [
"django",
"model_view_controller",
"python"
] | stackoverflow_0006822550_django_model_view_controller_python.txt |
Q:
Specifying site directory outside of the script
Is it possible to specify site directories through python command line or environment?
Right now I'm using site.addsitedir, but I would like to make the script agnostic of the site-setting logic
A:
The PYTHONPATH environment variable is essentially the same thing. ... | Specifying site directory outside of the script | Is it possible to specify site directories through python command line or environment?
Right now I'm using site.addsitedir, but I would like to make the script agnostic of the site-setting logic
| [
"The PYTHONPATH environment variable is essentially the same thing. Set it to a directory containing Python modules or packages and it will be added to sys.path at initialization.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0006823783_python.txt |
Q:
Python: Merging lists with lists
I have a list:
packets=[['B', 'A'], ['B', 'C'], ['A', 'D'], ['C', 'D'], ['C', 'E'], ['D', 'E'], []]
I have two for loops on the same list something like:
for a in packets[:]:
for b in packets[:]:
i.e., each time a=['B','A'] b iterates from ['B','A'] all the way to ['D','E']. T... | Python: Merging lists with lists | I have a list:
packets=[['B', 'A'], ['B', 'C'], ['A', 'D'], ['C', 'D'], ['C', 'E'], ['D', 'E'], []]
I have two for loops on the same list something like:
for a in packets[:]:
for b in packets[:]:
i.e., each time a=['B','A'] b iterates from ['B','A'] all the way to ['D','E']. This is what I want to do:
If the last ... | [
"Not sure if this is what you want, but\n>>> packets=[['B', 'A'], ['B', 'C'], ['A', 'D'], ['C', 'D'], ['C', 'E'], ['D', 'E'], []]\n>>> \n>>> for a in packets:\n... for b in packets:\n... if a and b and a[-1]==b[0]:\n... print a[:-1]+b\n... packets.append(a[:-1]+b)\n... \n['B', 'A... | [
2
] | [] | [] | [
"list",
"python"
] | stackoverflow_0006824212_list_python.txt |
Q:
Django timezone: feeling a bit confused
So, we have 'Europe/Moscow' TZ in our settings.
Currently this means daylight saving (this is going to change in the future, but at the moment it's UTC+03/04).
I understand that this TZ is used when saving dates to the DB, and when extracting them.
Now, I have to serialize t... | Django timezone: feeling a bit confused | So, we have 'Europe/Moscow' TZ in our settings.
Currently this means daylight saving (this is going to change in the future, but at the moment it's UTC+03/04).
I understand that this TZ is used when saving dates to the DB, and when extracting them.
Now, I have to serialize the datetime object to ISO string, including t... | [
"\nhow do I convert them to UTC if I don't know if the specific date is +03 (Moscow winter) or +04 (Moscow summer)\n\nThere is no need for UTC conversion, pytz handles such thing for you.\nHere's the code to convert from timezone-naive datetime to ISO with timezone offset:\nfrom datetime import datetime\nfrom pytz ... | [
5,
3,
1
] | [] | [] | [
"datetime",
"django",
"python",
"timezone",
"utc"
] | stackoverflow_0006822655_datetime_django_python_timezone_utc.txt |
Q:
PyAMF: How do you get the client's ip address?
Is there anyway to get the client's ip address when running PyAMF via the WSGI gateway interface (Apache)?
A:
It will be under the key REMOTE_ADDR in your server's request handler. For example, (from the Hello World script):
httpd = simple_server.WSGIServer(
('l... | PyAMF: How do you get the client's ip address? | Is there anyway to get the client's ip address when running PyAMF via the WSGI gateway interface (Apache)?
| [
"It will be under the key REMOTE_ADDR in your server's request handler. For example, (from the Hello World script):\nhttpd = simple_server.WSGIServer(\n ('localhost', 8000),\n simple_server.WSGIRequestHandler,\n)\n\ndef app(environ, start_response):\n # environ['REMOTE_ADDR'] is what you're looking for!\n ... | [
1
] | [] | [] | [
"flash",
"pyamf",
"python"
] | stackoverflow_0006824537_flash_pyamf_python.txt |
Q:
I need help with classes - class for displaying filenames, file size, path, and anything else
Alright I have a gigantic list of files I would like to copy from one place to another. I would like to make a class to store all of this data. I want to be able to call two class instances, one with files in one drive, t... | I need help with classes - class for displaying filenames, file size, path, and anything else | Alright I have a gigantic list of files I would like to copy from one place to another. I would like to make a class to store all of this data. I want to be able to call two class instances, one with files in one drive, the other with the files in the other drive. I then get the size, whether or not the other drive has... | [
"It is the other way around: you want a class to represent a single file's data, and not a class to represent a bunch of them. For that, you just make an ordinary list, and put file-data instances in the list. You can use ordinary functions to create these lists.\nfileName is a poor choice of name, because the clas... | [
1
] | [] | [] | [
"class",
"file",
"python"
] | stackoverflow_0006824658_class_file_python.txt |
Q:
Issue with decorator and keyword arguments
I'm using the decorator module to decorate some functions. I want the decorator to be quite general, so I'm allowing it to have any number of arguments and keyword arguments (as long as there are more than two arguments):
from decorator import decorator
def wrap(f):
... | Issue with decorator and keyword arguments | I'm using the decorator module to decorate some functions. I want the decorator to be quite general, so I'm allowing it to have any number of arguments and keyword arguments (as long as there are more than two arguments):
from decorator import decorator
def wrap(f):
return decorator(_wrap, f)
def _wrap(function, ... | [
"c and d are positional arguments. Their names are included in the function object's metadata (because you use decorator, it's also preserved on the wrapper) and therefore you can refer to their names when calling the function, but they're still positional arguments and specifying them by their names merely leads t... | [
2,
0
] | [] | [] | [
"decorator",
"python"
] | stackoverflow_0006824480_decorator_python.txt |
Q:
Page scroll bar freezes while div is updated by Ajax responseText
I'm using jQuery's $.ajax() to send Ajax request to server and bring back a large chunk of HTML content to replace the content of a div. Everything works fine except for the problem that while the div is being updated, the page is kind of frozen (ev... | Page scroll bar freezes while div is updated by Ajax responseText | I'm using jQuery's $.ajax() to send Ajax request to server and bring back a large chunk of HTML content to replace the content of a div. Everything works fine except for the problem that while the div is being updated, the page is kind of frozen (even the vertical scroll bar is not draggable). It comes back to normal a... | [
"Try to implement a loader with a freezing background. \n",
"Can you link your ajax code? I think you are doing a sync call, try setting async: true.\nStill without the code thats all I can think about.\n"
] | [
0,
0
] | [] | [] | [
"ajax",
"javascript",
"jquery",
"python"
] | stackoverflow_0006824062_ajax_javascript_jquery_python.txt |
Q:
Why does my python script download instead of run?
I am attempting to deploy my Django project on my shared web host using an .htaccess rewrite and a python script that runs FastCGI. I am using this method because I do not have the ability to change and Apache configuration. When I visit the site, instead of runni... | Why does my python script download instead of run? | I am attempting to deploy my Django project on my shared web host using an .htaccess rewrite and a python script that runs FastCGI. I am using this method because I do not have the ability to change and Apache configuration. When I visit the site, instead of running the FastCGI script it downloads or displays the conte... | [
"I think you need:\n<Files mysite.fcgi>\n SetHandler fastcgi-script\n</Files>\n\nsomewhere in your Apache configuration. AddHandler just puts a handler in Apache's list of available handlers; you have to use SetHandler to use it.\nThis is probably a security measure to prevent someone from uploading a file with ... | [
1
] | [] | [] | [
"django",
"fastcgi",
"python"
] | stackoverflow_0006825164_django_fastcgi_python.txt |
Q:
Python interface in C++ Windows Form Application
I am an mechanical engineer with some programing skills and I need some advice from much more experience people from programing. I am writing an optimization platform that will involve (at least at the beginning) one commercial optimization tool, one commercial desi... | Python interface in C++ Windows Form Application | I am an mechanical engineer with some programing skills and I need some advice from much more experience people from programing. I am writing an optimization platform that will involve (at least at the beginning) one commercial optimization tool, one commercial design program and one my program written in C++. The plat... | [
"\nYes\nThe application type in the examples shouldn't really matter. For the most part the Python bindings and supporting code will be the same, it will just differ in how you source the python code that you want to evaluate (i.e config file, or text box inside the application).\nBoost has a python module which su... | [
0
] | [] | [] | [
"macros",
"python",
"visual_c++"
] | stackoverflow_0006824797_macros_python_visual_c++.txt |
Q:
Keypress trigger TextEdit update Android
I have an app I'm trying to translate which uses tkinter and python, but I'm not comfortable with Java. I already have the UI but it's the coding part in Java I'm having trouble with.
The thing I want is a
"input triggered by change > processing > insert processed data into... | Keypress trigger TextEdit update Android | I have an app I'm trying to translate which uses tkinter and python, but I'm not comfortable with Java. I already have the UI but it's the coding part in Java I'm having trouble with.
The thing I want is a
"input triggered by change > processing > insert processed data into other EditText"
I know about the addTextChang... | [
"If your concern is an infinite loop, then use onKeyPressed() instead of onTextChanged():\ntext.setOnKeyListener(new EditText.OnKeyListener()\n{\n public boolean onKey(View v, int keyCode, KeyEvent event)\n {\n // Put your code here\n return false;\n }\n});\n\n"
] | [
1
] | [] | [] | [
"android",
"android_widget",
"java",
"python",
"tkinter"
] | stackoverflow_0006825366_android_android_widget_java_python_tkinter.txt |
Q:
how to run python scripts using tcl exec command
I have a tcl driver script which in turn calls several other programs.
I want to invoke a python script from my tcl script.
lets say this is my python script "1.py"
#!/usr/bin/python2.4
import os
import sys
try:
fi = open('sample_+_file', 'w')
except IOError:
... | how to run python scripts using tcl exec command | I have a tcl driver script which in turn calls several other programs.
I want to invoke a python script from my tcl script.
lets say this is my python script "1.py"
#!/usr/bin/python2.4
import os
import sys
try:
fi = open('sample_+_file', 'w')
except IOError:
print 'Can\'t open file for writing.'
sys.exit(... | [
"Your tcl script defines a procedure to execute a python script, but does not call the procedure. Add a call to your tcl script:\n#! /usr/bin/tclsh\nproc call_python {} {\n set output [exec python helloWorld.py]\n puts $output\n}\n\ncall_python\n\nAlso, anything written to stdout by the process launched via e... | [
17
] | [] | [] | [
"exec",
"python",
"tcl"
] | stackoverflow_0006825546_exec_python_tcl.txt |
Q:
Transparent Window Background (Python Tkinter)
What I need is a tkinter window that is transparent,
but with a image displayed on this window is not.
I've seen the
w.attributes('-alpha', 0.1)
thing, but that makes the image transparent as well.
I need just the background of the window transparent,
so that an im... | Transparent Window Background (Python Tkinter) | What I need is a tkinter window that is transparent,
but with a image displayed on this window is not.
I've seen the
w.attributes('-alpha', 0.1)
thing, but that makes the image transparent as well.
I need just the background of the window transparent,
so that an image on the window that has transparent parts,
will s... | [
"I would suggest another ui library\npretty much a duplicate to Is it possible to create a Tkinter Window with no frame, and no background?\nI just learnt that pygame don't support window transparency but according to the last post here wxPython does if that's an option\nmore links:\ndraws under windows over deskto... | [
1
] | [] | [] | [
"image",
"python",
"tkinter",
"transparency",
"windows_7"
] | stackoverflow_0006824462_image_python_tkinter_transparency_windows_7.txt |
Q:
Google hybrid OpenID+OAuth login not prompting for OAuth access
I'm trying to implement Google's hybrid OpenID+OAuth login on a Google AppEngine site. For some reason, my login link only prompts the user to give login access via their Google account (OpenID). It does not ask for access to Contacts/Docs/etc (OAuth)... | Google hybrid OpenID+OAuth login not prompting for OAuth access | I'm trying to implement Google's hybrid OpenID+OAuth login on a Google AppEngine site. For some reason, my login link only prompts the user to give login access via their Google account (OpenID). It does not ask for access to Contacts/Docs/etc (OAuth).
The example on Google's site uses this URL for login:
https://accou... | [
"For a hybrid request to be considered valid, the oauth2 consumer and the OpenID2 realm must 'match'. In this case, the realm would match some value for consumer such as 2.myapp.appspot.com, but not myapp.appspot.com\nOne possible solution would be to also register '2.myapp.appspot.com' as your OAuth2 consumer.\n"
... | [
4
] | [] | [] | [
"oauth",
"openid",
"python"
] | stackoverflow_0006825535_oauth_openid_python.txt |
Q:
how to set extended_permission using facebook-python-sdk?
i found this code for pyFacebook ..
client = facebook.Facebook(api_key, secret_key)
client.auth.createToken()
client.login()
client.auth.getSession()
client.request_extended_permission("publish_stream", popup=False)
but i want the simliar code for facebook... | how to set extended_permission using facebook-python-sdk? | i found this code for pyFacebook ..
client = facebook.Facebook(api_key, secret_key)
client.auth.createToken()
client.login()
client.auth.getSession()
client.request_extended_permission("publish_stream", popup=False)
but i want the simliar code for facebook-python-SDK that request the extended permission without poping... | [
"\nwe no longer support the Facebook python sdk.\nif memory serves, the Facebook python sdk required the use of JS SDK for authentication and the python sdk just pulled the cookie out.\nall permission requests require your app/site to display a web view with our permissions dialog.\nshowing this dialog, is very sim... | [
3
] | [] | [] | [
"facebook_graph_api",
"python"
] | stackoverflow_0005060924_facebook_graph_api_python.txt |
Q:
Using remote chrome devtools from Python
I want to use the remote socket debugging stuff for Chrome devtools (link) from Python.
I'm using code adapted from here.
I've managed to get ping and list_tabs working. But I can't figure out how to evaluate_javascript. Can anybody tell me what I'm doing wrong?
import su... | Using remote chrome devtools from Python | I want to use the remote socket debugging stuff for Chrome devtools (link) from Python.
I'm using code adapted from here.
I've managed to get ping and list_tabs working. But I can't figure out how to evaluate_javascript. Can anybody tell me what I'm doing wrong?
import subprocess
import time, json, socket
from jca.f... | [
"I'm sorry for spam, there's a Java library for this:\nhttp://code.google.com/p/chromedevtools/\nSince you probably chosen Python not at random, you could have it as a reference implementation if running Java code is OK for you. I guess you could check the actual messages sent and received from Java debugger.\n",
... | [
2,
2
] | [] | [] | [
"debugging",
"google_chrome",
"google_chrome_devtools",
"javascript",
"python"
] | stackoverflow_0006644748_debugging_google_chrome_google_chrome_devtools_javascript_python.txt |
Q:
Python - Best Module to write into XLS files
I want to read a text file, write into an windows .xls file ie., create a .xls file and later do some modifications to the created .xls file. I have google'd as to what are all the available packages:
Win32 Com client
--> xlrd (Only for Reading from xls files I guess)
... | Python - Best Module to write into XLS files | I want to read a text file, write into an windows .xls file ie., create a .xls file and later do some modifications to the created .xls file. I have google'd as to what are all the available packages:
Win32 Com client
--> xlrd (Only for Reading from xls files I guess)
|
--> xlwt (only for writing into xls files)
PyEx... | [
"xlwt works great.\nIf you want to create .xlsx files (the new format used in Office 2007 and 2010), there is openpyxl.\nI would recommend a native python library (xlwt or openpyxl) over using PyWin32 COM automation to drive Excel.\n"
] | [
15
] | [] | [] | [
"python"
] | stackoverflow_0006825300_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.