content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: Python, Convert 9 tuple UTC date to MySQL datetime format I am parsing RSS feeds with the format as specified here: http://www.feedparser.org/docs/date-parsing.html date tuple (2009, 3, 23, 13, 6, 34, 0, 82, 0) I am a bit stumped at how to get this into the MySQL datetime format (Y-m-d H:M:S)? A: tup = (2009, 3,...
Python, Convert 9 tuple UTC date to MySQL datetime format
I am parsing RSS feeds with the format as specified here: http://www.feedparser.org/docs/date-parsing.html date tuple (2009, 3, 23, 13, 6, 34, 0, 82, 0) I am a bit stumped at how to get this into the MySQL datetime format (Y-m-d H:M:S)?
[ "tup = (2009, 3, 23, 13, 6, 34, 0, 82, 0)\nimport datetime \nd = datetime.datetime(*(tup[0:6]))\n#two equivalent ways to format it:\ndStr = d.isoformat(' ')\n#or\ndStr = d.strftime('%Y-%m-%d %H:%M:%S')\n\n" ]
[ 21 ]
[]
[]
[ "datetime", "mysql", "python", "sql", "tuples" ]
stackoverflow_0000686717_datetime_mysql_python_sql_tuples.txt
Q: Problem using Python comtypes library to add a querytable to Excel I'm trying to create a QueryTable in an excel spreadsheet using the Python comtypes library, but getting a rather uninformative error... In vba (in a module within the workbook), the following code works fine: Sub CreateQuery() Dim con As ADODB...
Problem using Python comtypes library to add a querytable to Excel
I'm trying to create a QueryTable in an excel spreadsheet using the Python comtypes library, but getting a rather uninformative error... In vba (in a module within the workbook), the following code works fine: Sub CreateQuery() Dim con As ADODB.Connection Dim rs As ADODB.Recordset Dim ws As Worksheet Di...
[ "I simplified your code and this should work fine (I'll explain the changes below):\ndef create_querytable2():\n constring = \"OLEDB;Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\path\\to\\db.mdb;\"\n SQL = \"Select * from tblName;\"\n excel = client.CreateObject(\"Excel.Application\", dynamic=True)\n ...
[ 2, 1 ]
[]
[]
[ "com", "comtypes", "excel", "python", "vba" ]
stackoverflow_0000685589_com_comtypes_excel_python_vba.txt
Q: Embed Python script I have some Python Scripts which I would like to use from my VB.NET class library however instead of increasing the amount of files that I distribute is it possible to embed the script into my project/dll in Visual Studio and then run the script from the dll during my program runtime? Thanks fo...
Embed Python script
I have some Python Scripts which I would like to use from my VB.NET class library however instead of increasing the amount of files that I distribute is it possible to embed the script into my project/dll in Visual Studio and then run the script from the dll during my program runtime? Thanks for any help. Rob
[ "Yes, it is possible.\n", "I believe you may be looking for this, but I am not sure. This is possible, however.\nThe link above shows you how to add the file/script as an embedded resource. If that isn't what you are after, vartec's post describes how to embed the python runtime directly.\n" ]
[ 2, 0 ]
[]
[]
[ ".net", "deployment", "python", "vb.net", "visual_studio" ]
stackoverflow_0000686690_.net_deployment_python_vb.net_visual_studio.txt
Q: Python: Why can't I modify the current scope within a function using locals()? Why does creating/modifying a member of locals() not work within a function? Python 2.5 (release25-maint, Jul 20 2008, 20:47:25) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 Type "help", "copyright", "credits" or "licen...
Python: Why can't I modify the current scope within a function using locals()?
Why does creating/modifying a member of locals() not work within a function? Python 2.5 (release25-maint, Jul 20 2008, 20:47:25) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> # Here's an example of what I expect to be possible i...
[ "Why would it? It's designed to return a representation, and was never intended for editing the locals. It's not ever guaranteed to work as a tool for such, as the documentation warns.\n", "locals() return a copy of the namespace (which is the opposite of what globals() does). This means that any change you perfo...
[ 7, 3 ]
[]
[]
[ "introspection", "python", "scope" ]
stackoverflow_0000686715_introspection_python_scope.txt
Q: Redirecting function definitions in python Pointing the class method at the instance method is clearly causing problems: class A(dict): def __getitem__(self, name): return dict.__getitem__(self, name) class B(object): def __init__(self): self.a = A() B.__getitem__ = self...
Redirecting function definitions in python
Pointing the class method at the instance method is clearly causing problems: class A(dict): def __getitem__(self, name): return dict.__getitem__(self, name) class B(object): def __init__(self): self.a = A() B.__getitem__ = self.a.__getitem__ b1 = B() b1.a['a'] = 5 b2 = B()...
[ "__getitem__ only works in the class. You can't override it in a instance basis.\nThis works:\nclass A(dict): \n def __getitem__(self, name):\n return dict.__getitem__(self, name)\n\nclass B(object):\n def __init__(self):\n self.a = A()\n\n def __getitem__(self, item):\n ...
[ 7 ]
[]
[]
[ "class_attributes", "python" ]
stackoverflow_0000686899_class_attributes_python.txt
Q: Advice for C# programmer writing Python I've mainly been doing C# development for the past few years but recently started to do a bit of Python (not Iron Python). But I'm not sure if I've made the mental leap to Python...I kind of feel I'm trying to do things as I would in C#. Any advice on how I can fully take a...
Advice for C# programmer writing Python
I've mainly been doing C# development for the past few years but recently started to do a bit of Python (not Iron Python). But I'm not sure if I've made the mental leap to Python...I kind of feel I'm trying to do things as I would in C#. Any advice on how I can fully take advantage of Python? Or any tips\tricks, thing...
[ "First, check tgray's and Lundström's advice.\nThen, some things you may want to know:\n\nPython is dynamically typed, so unlike C#, you will not\ncheck type, but behavior. You may want to google about duck\ntyping. It implies you do not have to deal with boxing and\nunboxing.\nPython is fully object oriented, but ...
[ 157, 16, 13, 6, 5, 3, 2, 2, 1, 0 ]
[]
[]
[ "c#", "python" ]
stackoverflow_0000683273_c#_python.txt
Q: How to get the root node of an xml file in Python? Basically I am using: from xml.etree import ElementTree as ET path = 'C:\cool.xml' et = ET.parse ( path ) But I am not sure how to get the root from et? A: You probably want: et.getroot() Have a look at the official docs for ElementTree from the effbot site. N...
How to get the root node of an xml file in Python?
Basically I am using: from xml.etree import ElementTree as ET path = 'C:\cool.xml' et = ET.parse ( path ) But I am not sure how to get the root from et?
[ "You probably want:\net.getroot()\n\nHave a look at the official docs for ElementTree from the effbot site. Note that Python 2.5 (the first version of Python to include ElementTree out of the box) uses ElementTree 1.2, not the more recent 1.3. There aren't many differences, but just FYI in case.\n", "root = et.ge...
[ 10, 4, 2 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0000687177_python_xml.txt
Q: How to set up Python for .NET with Python 2.6.1? The "final" release of Python for .NET (link) isn't pre-compiled for Python 2.6. I don't have a problem changing the compilation symbol to PYTHON26 as specified in the docs, the solution rebuilds just fine, but when attempting to import the CLR, I get an error indic...
How to set up Python for .NET with Python 2.6.1?
The "final" release of Python for .NET (link) isn't pre-compiled for Python 2.6. I don't have a problem changing the compilation symbol to PYTHON26 as specified in the docs, the solution rebuilds just fine, but when attempting to import the CLR, I get an error indicating that python26.dll is missing. Anyone know how to...
[ "I managed it by following these instructions by one Feihong Hsu.\nI notice now that the author has made a follow-up post that may be important too if you're using SP1.\n" ]
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0000687487_python.txt
Q: Python game programming: is my IO object a legitimate candidate for being a global variable? I'm programming a game in Python, where all IO activities are done by an IO object (in the hope that it will be easy to swap that object out for another which implements a different user interface). Nearly all the other ob...
Python game programming: is my IO object a legitimate candidate for being a global variable?
I'm programming a game in Python, where all IO activities are done by an IO object (in the hope that it will be easy to swap that object out for another which implements a different user interface). Nearly all the other objects in the game need to access the IO system at some point (e.g. printing a message, updating th...
[ "Yes, this is a legitimate use of a global variable. If you'd rather not, passing around a context object that is equivalent to this global is another option, as you mentioned.\nSince I assume you're using multiple files (modules), why not do something like:\nimport io\nio.print('hello, world')\nio.clear()\n\nThis ...
[ 9, 1, 0 ]
[]
[]
[ "global_variables", "io", "python" ]
stackoverflow_0000687703_global_variables_io_python.txt
Q: How to get upper paths from a single path? How to get upper paths from a single path? So say you have a path like: 'C:\a\b\c\d\' How do I get to 'C:\a\b' or 'C:\a\b\c' Is there a pythonic way to do this? A: See os.path from os import path path.dirname("C:\\a\\b\\c\\d\\") A: Theres basic stuff like os.path met...
How to get upper paths from a single path?
How to get upper paths from a single path? So say you have a path like: 'C:\a\b\c\d\' How do I get to 'C:\a\b' or 'C:\a\b\c' Is there a pythonic way to do this?
[ "See os.path\nfrom os import path\npath.dirname(\"C:\\\\a\\\\b\\\\c\\\\d\\\\\")\n\n", "Theres basic stuff like os.path methods. \nIf you want a list of the full path names of each successive parent in the directory tree, heres a one liner:\nfrom os.path import dirname\n\ndef f1(n): return [n] if n == dirname(n) ...
[ 10, 4, 2, 2 ]
[]
[]
[ "directory", "python" ]
stackoverflow_0000687863_directory_python.txt
Q: soaplib with mod_wsgi/cherrypy I've followed the tutorials for setting up Apache with mod_wsgi to interface cherrypy and make a site running of it. This is my "myapp.wsgi", and opening http://localhost/ works great. Opening http://localhost/ape/ actually returns the text instead of a soap-response, and http://loca...
soaplib with mod_wsgi/cherrypy
I've followed the tutorials for setting up Apache with mod_wsgi to interface cherrypy and make a site running of it. This is my "myapp.wsgi", and opening http://localhost/ works great. Opening http://localhost/ape/ actually returns the text instead of a soap-response, and http://localhost/ape/service.wsdl returns a 500...
[ "I just tested this myself by replacing the last line of your file with\ncherrypy.quickstart(Root(), \"/\")\n\nand it worked just fine for me. I suggest trying this and seeing whether it works for you; if it does then you'll know that it's an issue relating to running it under Apache/mod_wsgi and not an inherent p...
[ 1, 1 ]
[]
[]
[ "cherrypy", "mod_wsgi", "python", "soap" ]
stackoverflow_0000678409_cherrypy_mod_wsgi_python_soap.txt
Q: Including Python standard libraries in your distribution For a project I'm working on I need to include some Python modules that come standard with the Python SDK because the platform I am targetting (to be precise, PyS60) does not include these modules. Are there any licensing issues I need to address? Do I need ...
Including Python standard libraries in your distribution
For a project I'm working on I need to include some Python modules that come standard with the Python SDK because the platform I am targetting (to be precise, PyS60) does not include these modules. Are there any licensing issues I need to address? Do I need to include the PSF license in my project? My project is licens...
[ "According to the PSF License FAQ:\n\nCan I bundle Python with my non-open-source application?\nYes. Unlike some open source licenses, the PSF License allows Python to be included in non-open applications, either in unmodified or modified form.\n\nThe FAQ goes on to explain about third-party module licensing.\nIn e...
[ 10, 7 ]
[]
[]
[ "licensing", "python" ]
stackoverflow_0000688096_licensing_python.txt
Q: How to compile Python 1.0 For some perverse reason, I want to try Python 1.0.. How would I go about compiling it, or rather, what is the earlier version that will compile cleanly with current compilers? I'm using Mac OS X 10.5, although since it's for nothing more than curiosity (about how the language has changed...
How to compile Python 1.0
For some perverse reason, I want to try Python 1.0.. How would I go about compiling it, or rather, what is the earlier version that will compile cleanly with current compilers? I'm using Mac OS X 10.5, although since it's for nothing more than curiosity (about how the language has changed), compiling in a Linux virtual...
[ "Python 1.0.1 compiles perfectly under Ubuntu 8.10 using GCC 4.3.2. It should compile under Leopard, too.\nDownload the source here, and compile the usual way:\n./configure\nmake\n\nUPDATE: I tested it, and it compiles under Leopard, too.\n", "Going further backwards in time, I pulled the 0.9.1p1 source from alt....
[ 10, 4 ]
[]
[]
[ "installation", "legacy", "python" ]
stackoverflow_0000685732_installation_legacy_python.txt
Q: Get the diff of two MSWord doc files and output to html Possible Duplicate: How to compare two word documents? How can you get the diff of two word .doc documents programatically? Where you can then take the resulting output and generate an html file of the result. (As you would expect to see in a normal gui dif...
Get the diff of two MSWord doc files and output to html
Possible Duplicate: How to compare two word documents? How can you get the diff of two word .doc documents programatically? Where you can then take the resulting output and generate an html file of the result. (As you would expect to see in a normal gui diff tool) I imagine if you grabed the docs via COM and convert...
[ "Use this option in Word 2003: \n\nTools | Compare and Merge Documents\n\nOr this in Word 2007: \n\nReview | Compare\n\nIt prompts you for a file with which to compare the file you're editing.\n\nThis question is a duplicate of How to compare two word documents?, and this answer is a duplicate of my answer there....
[ 7, 3, 3, 3, 0, 0 ]
[]
[]
[ "diff", "ms_word", "python" ]
stackoverflow_0000568320_diff_ms_word_python.txt
Q: Which version of python added the else clause for for loops? Which was the first version of python to include the else clause for for loops? I find that the python docs usually does a good job of documenting when features were added, but I can't seem to find the info on this feature. (It doesn't help that 'for' ...
Which version of python added the else clause for for loops?
Which was the first version of python to include the else clause for for loops? I find that the python docs usually does a good job of documenting when features were added, but I can't seem to find the info on this feature. (It doesn't help that 'for' and 'else' are particularly difficult terms to google for on a pro...
[ "It's been present since the beginning. To see that, get the source from alt.sources, specifically the message titled \"Python 0.9.1 part 17/21\". The date is Feb 21, 1991. This post included the grammar definition, which states:\nfor_stmt: 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite] \n\nYou might be ...
[ 33, 7, 1 ]
[]
[]
[ "for_loop", "python" ]
stackoverflow_0000682185_for_loop_python.txt
Q: Is there any use for Flex + Python/Ruby without a web framework (Django/Rails)? I often hear about Flex being combined with web frameworks on the backend. The idea being that Flex serves as the presentation framework while the web framework (Django/Rails) does the database lookups and sends the data to Flex to pre...
Is there any use for Flex + Python/Ruby without a web framework (Django/Rails)?
I often hear about Flex being combined with web frameworks on the backend. The idea being that Flex serves as the presentation framework while the web framework (Django/Rails) does the database lookups and sends the data to Flex to present in the form of XML. However, is there ever a situation where Flex and Python/Rub...
[ "You can still code against WSGI directly in Python. If that's the route you want to go, PEP 333 is about the only way to go.\nWith that said, doing so is a good learning experience, but WSGI wasn't really intended to be used directly. You don't have to use a full-stack framework like Django if you don't want to....
[ 4, 1 ]
[]
[]
[ "apache_flex", "django", "python", "ruby", "ruby_on_rails" ]
stackoverflow_0000686490_apache_flex_django_python_ruby_ruby_on_rails.txt
Q: Building Python PIL for JPEG looks okay, but fails the selftest I'm on Fedora Core 6 (64 bit) after "yum install libjpeg-devel" I have downloaded and built PIL. It gives the message: --- JPEG support ok Looks like JPEG built okay, but when running selftest.py: IOError: decoder jpeg not available Why would it appea...
Building Python PIL for JPEG looks okay, but fails the selftest
I'm on Fedora Core 6 (64 bit) after "yum install libjpeg-devel" I have downloaded and built PIL. It gives the message: --- JPEG support ok Looks like JPEG built okay, but when running selftest.py: IOError: decoder jpeg not available Why would it appear to have built correctly, but fail the selftest?
[ "You probably need more packages. Install libjpeg which includes /usr/lib/libjpeg.so* and try again.\nOn my Fedora (another version), PIL is installed with the python-imaging rpm :\nldd _imaging.so\n linux-gate.so.1 => (0x004c6000)\n libjpeg.so.62 => /usr/lib/libjpeg.so.62 (0x00a07000)\n libz.so.1 => /lib...
[ 1, 1 ]
[]
[]
[ "fedora", "jpeg", "libjpeg", "python", "python_imaging_library" ]
stackoverflow_0000689560_fedora_jpeg_libjpeg_python_python_imaging_library.txt
Q: Python XML - build flat record from dynamic nested "node" elements I need to parse an XML file and build a record-based output from the data. The problem is that the XML is in a "generic" form, in that it has several levels of nested "node" elements that represent some sort of data structure. I need to build the...
Python XML - build flat record from dynamic nested "node" elements
I need to parse an XML file and build a record-based output from the data. The problem is that the XML is in a "generic" form, in that it has several levels of nested "node" elements that represent some sort of data structure. I need to build the records dynamically based on the deepest level of the "node" element. ...
[ "That's why you have Element Tree find method with an XPath.\nclass Plan( object ):\n def __init__( self ):\n self.srv= None\n self.sub= None\n self.plan= None\n self.group= None\n self.subgroup= None\n self.defrate= None\n self.altrate= None\n def initFrom( se...
[ 4, 0 ]
[]
[]
[ "elementtree", "python", "xml" ]
stackoverflow_0000689339_elementtree_python_xml.txt
Q: Reading and Grouping a List of Data in Python I have been struggling with managing some data. I have data that I have turned into a list of lists each basic sublist has a structure like the following <1x>begins <2x>value-1 <3x>value-2 <4x>value-3 some indeterminate number of other values <1y>next observation beg...
Reading and Grouping a List of Data in Python
I have been struggling with managing some data. I have data that I have turned into a list of lists each basic sublist has a structure like the following <1x>begins <2x>value-1 <3x>value-2 <4x>value-3 some indeterminate number of other values <1y>next observation begins <2y>value-1 <3y>value-2 <4y>value-3 some indet...
[ "You're off to a good start by noticing that your original solution may work but lacks elegance. \nYou should parse the string in a loop, creating a new variable for each line.\nHere's some sample code: \nimport re\n\ns = \"\"\"<1x>begins\n<2x>value-1\n<3x>value-2\n<4x>value-3\n some indeterminate number of other v...
[ 1, 1, 1, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0000688461_list_python.txt
Q: Changing timezone on an existing Django project Like an idiot, I completely overlooked the timezone setting when I first built an application that collects datetime data. It wasn't an issue then because all I was doing was "time-since" style comparisons and ordering. Now I need to do full reports that show the act...
Changing timezone on an existing Django project
Like an idiot, I completely overlooked the timezone setting when I first built an application that collects datetime data. It wasn't an issue then because all I was doing was "time-since" style comparisons and ordering. Now I need to do full reports that show the actual datetime and of course, they're all stored at Ame...
[ "I would do a mass update to the database tables by adding or subtracting hours to/from the datetime fields.\nSomething like this works in SQL Server, and adds 2 hours to the date:\nupdate tblName set date_field = dateadd(\"hh\", 2, data_field)\n\n" ]
[ 3 ]
[]
[]
[ "database_agnostic", "django", "python", "pytz", "timezone" ]
stackoverflow_0000689831_database_agnostic_django_python_pytz_timezone.txt
Q: Is it possible to Access a Users Sent Email over POP? I have been asked to quote a project where they want to see sent email using POP. I am pretty sure this is not possible, but I thought if it was. So is it possible given a users POP email server details to access their sent mail? If so any examples in Python or...
Is it possible to Access a Users Sent Email over POP?
I have been asked to quote a project where they want to see sent email using POP. I am pretty sure this is not possible, but I thought if it was. So is it possible given a users POP email server details to access their sent mail? If so any examples in Python or fetchmail?
[ "POP3 only handles receiving email; sent mail is sent via SMTP in these situations, and may be sent via a different ISP to the receiver (say, when you host your own email server, but use your current ISP to send). As such, this isn't directly possible.\nIMAP could do it, as this offers server side email folders as ...
[ 5, 3, 1, 1 ]
[]
[]
[ "email", "fetchmail", "pop3", "python" ]
stackoverflow_0000690527_email_fetchmail_pop3_python.txt
Q: Is this the best way to get unique version of filename w/ Python? Still 'diving in' to Python, and want to make sure I'm not overlooking something. I wrote a script that extracts files from several zip files, and saves the extracted files together in one directory. To prevent duplicate filenames from being over-wr...
Is this the best way to get unique version of filename w/ Python?
Still 'diving in' to Python, and want to make sure I'm not overlooking something. I wrote a script that extracts files from several zip files, and saves the extracted files together in one directory. To prevent duplicate filenames from being over-written, I wrote this little function - and I'm just wondering if there i...
[ "One issue is that there is a race condition in your above code, since there is a gap between testing for existance, and creating the file. There may be security implications to this (think about someone maliciously inserting a symlink to a sensitive file which they wouldn't be able to overwrite, but your program ...
[ 24, 6, 2, 1, 1, 0 ]
[]
[]
[ "filenames", "python" ]
stackoverflow_0000183480_filenames_python.txt
Q: Handling output of python socket recv Apologies for the noob Python question but I've been stuck on this for far too long. I'm using python sockets to receive some data from a server. I do this: data = self.socket.recv(4) print "data is ", data print "repr(data) is ", repr(data) The output on the console is this...
Handling output of python socket recv
Apologies for the noob Python question but I've been stuck on this for far too long. I'm using python sockets to receive some data from a server. I do this: data = self.socket.recv(4) print "data is ", data print "repr(data) is ", repr(data) The output on the console is this: data is repr(data) is '\x00\x00\x00\...
[ "You probably want to use struct.\nThe code would look something like:\nimport struct\n\ndata = self.socket.recv(4)\nprint \"data is \", data\nprint \"repr(data) is \", repr(data)\nmyint = struct.unpack(\"!i\", data)[0]\n\n" ]
[ 10 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0000691345_python_sockets.txt
Q: How do I order referenced objects from a Google App Engine Datastore query? I have Exhibit objects which reference Gallery objects both of which are stored in the Google App Engine Datastore. How do I order the Exhibit collection on each Gallery object when I get around to iterating over the values (ultimately in ...
How do I order referenced objects from a Google App Engine Datastore query?
I have Exhibit objects which reference Gallery objects both of which are stored in the Google App Engine Datastore. How do I order the Exhibit collection on each Gallery object when I get around to iterating over the values (ultimately in a Django template)? i.e. this does not work class Gallery(db.Model): title = d...
[ "Instead of relying on the collection property App Engine creates, you need to construct your own query:\n\nexhibits = Exhibit.all().filter(\"gallery =\", gallery).order(\"position\")\n\nOr equivalently, in GQL:\n\nexhibits = db.GqlQuery(\"SELECT * FROM Exhibit WHERE gallery = :1 ORDER BY position\", gallery)\n\nIf...
[ 4 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0000691217_google_app_engine_google_cloud_datastore_python.txt
Q: Passing functions which have multiple return values as arguments in Python So, Python functions can return multiple values. It struck me that it would be convenient (though a bit less readable) if the following were possible. a = [[1,2],[3,4]] def cord(): return 1, 1 def printa(y,x): print a[y][x] print...
Passing functions which have multiple return values as arguments in Python
So, Python functions can return multiple values. It struck me that it would be convenient (though a bit less readable) if the following were possible. a = [[1,2],[3,4]] def cord(): return 1, 1 def printa(y,x): print a[y][x] printa(cord()) ...but it's not. I'm aware that you can do the same thing by dumping ...
[ "printa(*cord())\n\nThe * here is an argument expansion operator... well I forget what it's technically called, but in this context it takes a list or tuple and expands it out so the function sees each list/tuple element as a separate argument.\nIt's basically the reverse of the * you might use to capture all non-k...
[ 30, 6, 4 ]
[]
[]
[ "function_calls", "python", "return_value" ]
stackoverflow_0000691267_function_calls_python_return_value.txt
Q: Is there a method in python that's like os.path.split for other delimiters? I want to use something like this: os.path.split("C:\\a\\b\\c") With this kind of output: ('C:\a\b', 'c') However I want it to work on other delimiters like this: method ('a_b_c_d') With this kind of output: ('a_b_c', 'd') A: >>> 'a_b...
Is there a method in python that's like os.path.split for other delimiters?
I want to use something like this: os.path.split("C:\\a\\b\\c") With this kind of output: ('C:\a\b', 'c') However I want it to work on other delimiters like this: method ('a_b_c_d') With this kind of output: ('a_b_c', 'd')
[ ">>> 'a_b_c_d'.rsplit('_', 1)\n['a_b_c', 'd']\n\n\nHelp on built-in function rsplit:\nrsplit(...)\n S.rsplit([sep [,maxsplit]]) -> list of strings\nReturn a list of the words in the string S, using sep as the\n delimiter string, starting at the end of the string and working\n to the front. If maxsplit is given,...
[ 15, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0000691740_python_string.txt
Q: Python: How do you login to a page and view the resulting page in a browser? I've been googling around for quite some time now and can't seem to get this to work. A lot of my searches have pointed me to finding similar problems but they all seem to be related to cookie grabbing/storing. I think I've set that up pr...
Python: How do you login to a page and view the resulting page in a browser?
I've been googling around for quite some time now and can't seem to get this to work. A lot of my searches have pointed me to finding similar problems but they all seem to be related to cookie grabbing/storing. I think I've set that up properly, but when I try to open the 'hidden' page, it keeps bringing me back to the...
[ "First off, when doing cookie-based authentication, you need to have a CookieJar to store your cookies in, much in the same way that your browser stores its cookies a place where it can find them again.\nAfter opening a login-page through python, and saving the cookie from a successful login, you should use the Moz...
[ 4, 1, 0 ]
[]
[]
[ "authentication", "python" ]
stackoverflow_0000663490_authentication_python.txt
Q: How do I track an animated object in Python? I want to automate playing a video game with Python. I want to write a script that can grab the screen image, diff it with the next frame and track an object to click on. What libraries would be useful for this other than PIL? A: There are a few options here. The br...
How do I track an animated object in Python?
I want to automate playing a video game with Python. I want to write a script that can grab the screen image, diff it with the next frame and track an object to click on. What libraries would be useful for this other than PIL?
[ "There are a few options here. The brute force diff'ing approach will lead to a lot of frustration unless what you're tracking is very consistent. For this you could use any number of genetic approaches to train your program what to follow. After enough generations it would do the right thing reliably. If the thing...
[ 0, 0 ]
[]
[]
[ "animation", "image_manipulation", "python" ]
stackoverflow_0000692259_animation_image_manipulation_python.txt
Q: Resolving dependency in python between modules I am a newbie to python. I do have two modules. Model M1 and module m2. From m2 , i need to refer m1 and m2 and m1 resides at two different locations in disk. When I am trying to import m1 before executing m2 , of course it's saying can't find m1. How I can point my ...
Resolving dependency in python between modules
I am a newbie to python. I do have two modules. Model M1 and module m2. From m2 , i need to refer m1 and m2 and m1 resides at two different locations in disk. When I am trying to import m1 before executing m2 , of course it's saying can't find m1. How I can point my interpreter to m1's location. Thanks J
[ "It's not entirely clear what your specific problem is (give more details!), but you may find these useful (further Googling will help you reach concrete answers for your specific needs):\n\nThe PYTHONPATH environment variable\n.pth files in directories that appear in PYTHONPATH\nManipulating sys.path before import...
[ 3, 2, 0 ]
[]
[]
[ "dependencies", "python" ]
stackoverflow_0000692506_dependencies_python.txt
Q: What library is best for GUI in python? Duplicate: Cross-platform gui toolkit for deploying Python applications I want to create a GUI application in python. Which library is best one? A: From the question Cross-platform gui toolkit for deploying Python applications: PyQt It's build on top of Qt, a C++ fram...
What library is best for GUI in python?
Duplicate: Cross-platform gui toolkit for deploying Python applications I want to create a GUI application in python. Which library is best one?
[ "From the question Cross-platform gui toolkit for deploying Python applications:\n\nPyQt\nIt's build on top of Qt, a C++\n framework. It's quite advanced and has\n some good tools like the Qt Designer\n to design your applications. You\n should be aware though, that it\n doesn't feel like Python 100%, but\n c...
[ 7, 5, 3, 1, 0 ]
[ "TKInter. easiest.\n" ]
[ -1 ]
[ "python", "user_interface" ]
stackoverflow_0000692566_python_user_interface.txt
Q: Django or CodeIgniter for Turn-Key Web Application I'm going to build a turn-key solution for a vertical market, and would like to offer both options: software as a service, and give them the opportunity to host the application on their own. In other words, I'm aiming to have similar deployment options as Joel's F...
Django or CodeIgniter for Turn-Key Web Application
I'm going to build a turn-key solution for a vertical market, and would like to offer both options: software as a service, and give them the opportunity to host the application on their own. In other words, I'm aiming to have similar deployment options as Joel's FogBugz. I'm a Python programmer, and I could fly over th...
[ "Deployment is clearly a problem for all non-PHP based web apps, but I think things are getting better with the DreamHost/Engineyard type ISP's who provide Ruby/Python etc. out of the box. It also looks like there's going to be a lot of discussion at PyCon this week about ways to fix deployment problems. The grow...
[ 4, 3, 2 ]
[]
[]
[ "codeigniter", "django", "php", "python" ]
stackoverflow_0000690856_codeigniter_django_php_python.txt
Q: Is it ever polite to put code in a python configuration file? One of my favorite features about python is that you can write configuration files in python that are very simple to read and understand. If you put a few boundaries on yourself, you can be pretty confident that non-pythonistas will know exactly what y...
Is it ever polite to put code in a python configuration file?
One of my favorite features about python is that you can write configuration files in python that are very simple to read and understand. If you put a few boundaries on yourself, you can be pretty confident that non-pythonistas will know exactly what you mean and will be perfectly capable of reconfiguring your program...
[ "There is a Django wiki page, which addresses exactly the thing you're asking.\nhttp://code.djangoproject.com/wiki/SplitSettings\nDo not reinvent the wheel. Use configparser and INI files. Python files are to easy to break by someone, who doesn't know Python. \n", "Your heuristics are good. Rules are made so tha...
[ 11, 4, 4, 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000690221_django_python.txt
Q: Best practice for two way hashing in python? I want to allow users to validate their email address by clicking on a link. The link would look something like http://www.example.com/verifyemail?id=some-random-string When I am sending this email, I want to be able to easily generate this 'some-random-string' from row...
Best practice for two way hashing in python?
I want to allow users to validate their email address by clicking on a link. The link would look something like http://www.example.com/verifyemail?id=some-random-string When I am sending this email, I want to be able to easily generate this 'some-random-string' from row id of user, an integer. and when user clicks on t...
[ "Use encryption, that's exactly what it's designed for. Blowfish, AES, even DES3 if you don't need particularly high security.\nAlternatively, you could compute an SHA-256 or SHA-512 (or whatever) hash of the email address and store it in a database along with the email address itself. That way you can just look up...
[ 5, 5 ]
[]
[]
[ "python" ]
stackoverflow_0000693826_python.txt
Q: Python module for VBox? I want to make some python scripts to create an "Appliance" with VirtualBox. However, I can't find any documentation anywhere on making calls to VBoxService.exe. Well, I've found stuff that works from OUTSIDE the Machine, but nothing from working from inside the machine. Does anyone know an...
Python module for VBox?
I want to make some python scripts to create an "Appliance" with VirtualBox. However, I can't find any documentation anywhere on making calls to VBoxService.exe. Well, I've found stuff that works from OUTSIDE the Machine, but nothing from working from inside the machine. Does anyone know anything about this? If there's...
[ "Consider using libvirt. The VirtualBox support is bleeding-edge (not in any release, may not even be in source control yet, but is available as a set of patches on the mailing list) -- but this single API, available for C, Python and several other languages, lets you control virtual machines and images running in ...
[ 2 ]
[]
[]
[ "python", "virtualbox" ]
stackoverflow_0000693752_python_virtualbox.txt
Q: How do I read an Excel file into Python using xlrd? Can it read newer Office formats? My issue is below but would be interested comments from anyone with experience with xlrd. I just found xlrd and it looks like the perfect solution but I'm having a little problem getting started. I am attempting to extract data p...
How do I read an Excel file into Python using xlrd? Can it read newer Office formats?
My issue is below but would be interested comments from anyone with experience with xlrd. I just found xlrd and it looks like the perfect solution but I'm having a little problem getting started. I am attempting to extract data programatically from an Excel file I pulled from Dow Jones with current components of the Do...
[ "FWIW, I'm the author of xlrd, and the maintainer of xlwt (a fork of pyExcelerator). A few points:\n\nThe file ComponentReport-DJI.xls is misnamed; it is not an XLS file, it is a tab-separated-values file. Open it with a text editor (e.g. Notepad) and you'll see what I mean. You can also look at the not-very-raw ra...
[ 26, 3, 1, 0 ]
[ "Do you have to use xlrd? I just downloaded 'UPDATED - Dow Jones Industrial Average Movers - 2008' from that website and had no trouble reading it with pyExcelerator.\nimport pyExcelerator\nbook = pyExcelerator.parse_xls('DJIAMovers.xls')\n\n" ]
[ -1 ]
[ "import_from_excel", "python", "xlrd" ]
stackoverflow_0000118516_import_from_excel_python_xlrd.txt
Q: Do you have a copy of Unipath-0.2.0.tar.gz? I need a copy of this library installed on my system because my software depends on this library. Unfortunately, at the moment, it's impossible install it trough easy_install: andrea@puzzle:~$ sudo easy_install Unipath [sudo] password for andrea: Searching for Unipath R...
Do you have a copy of Unipath-0.2.0.tar.gz?
I need a copy of this library installed on my system because my software depends on this library. Unfortunately, at the moment, it's impossible install it trough easy_install: andrea@puzzle:~$ sudo easy_install Unipath [sudo] password for andrea: Searching for Unipath Reading http://pypi.python.org/simple/Unipath/ Rea...
[ "I found this newsgroup post written my Mike Orr (the creator of Unipath). In the last sentence he says that he's moving the project from the old server to Bitbucket. So may be that the problem will be fixed when the moving is finished.\nMike Orr message is dated March 10 2009, at the time of writing March 29 2009 ...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000671542_python.txt
Q: Shortening a oft-used code segment for testing a return value in Python Consider this Python segment: def someTestFunction(): if someTest: return value1 elif someOtherTest: return value2 elif yetSomeOtherTest: return value3 return None def SomeCallingFunction(): a = som...
Shortening a oft-used code segment for testing a return value in Python
Consider this Python segment: def someTestFunction(): if someTest: return value1 elif someOtherTest: return value2 elif yetSomeOtherTest: return value3 return None def SomeCallingFunction(): a = someTestFunction() if a != None: return a ... normal execution ...
[ "If you want to use a decorator, it would look like this:\ndef testDecorator(f):\n def _testDecorator():\n a = someTestFunction()\n if a is None:\n return f()\n else: return a\n return _testDecorator\n\n@testDecorator\ndef SomeCallingFunction():\n ... normal execution\n\nWhe...
[ 9, 4, 2 ]
[]
[]
[ "optimization", "python" ]
stackoverflow_0000694775_optimization_python.txt
Q: What is the best way to internationalize a Python app with multiple i18n domains? I'm internationalizing a Python application, with two goals in mind: The application loads classes from multiple packages, each with its own i18n domain. So modules in package A are using domain A, modules in package B are using do...
What is the best way to internationalize a Python app with multiple i18n domains?
I'm internationalizing a Python application, with two goals in mind: The application loads classes from multiple packages, each with its own i18n domain. So modules in package A are using domain A, modules in package B are using domain B, etc. The locale can be changed while the application is running. Python's gett...
[ "how about you bind _ to a function roughly like this (for each module):\ndef _(message):\n return my_gettext(__name__, message)\n\nThis allows you to use gettext while at the same time perform any lookup on a per-module-per-call-base that allows you to switch locale as well.\n" ]
[ 2 ]
[]
[]
[ "internationalization", "localization", "python" ]
stackoverflow_0000694768_internationalization_localization_python.txt
Q: Detect in python which keys are pressed I need to know which key is being pressed right now. I'm not looking to capture some specific keys to trigger an event or anything like that, I want to know which keys are pressed now and display a list of them. I also need to capture special keys like F1 ... F12, shift, al...
Detect in python which keys are pressed
I need to know which key is being pressed right now. I'm not looking to capture some specific keys to trigger an event or anything like that, I want to know which keys are pressed now and display a list of them. I also need to capture special keys like F1 ... F12, shift, alt, home, windows, etc. Basically all keys on ...
[ "PyKeylogger mentioned in the related question might do the job.\n", "The easiest way to do something like this, if you're not too fussy, is to bring in a GUI toolkit such as pygame or wxPython. For example, run the wxPython Demo, then go to the demo for KeyEvents.\n", "I found the answer using a link in a rel...
[ 6, 4, 2 ]
[]
[]
[ "events", "keyboard", "python" ]
stackoverflow_0000694296_events_keyboard_python.txt
Q: What is LLVM and How is replacing Python VM with LLVM increasing speeds 5x? Google is sponsoring an Open Source project to increase the speed of Python by 5x. Unladen-Swallow seems to have a good project plan Why is concurrency such a hard problem? Is LLVM going to solve the concurrency problem? Are there soluti...
What is LLVM and How is replacing Python VM with LLVM increasing speeds 5x?
Google is sponsoring an Open Source project to increase the speed of Python by 5x. Unladen-Swallow seems to have a good project plan Why is concurrency such a hard problem? Is LLVM going to solve the concurrency problem? Are there solutions other than Multi-core for Hardware advancement?
[ "LLVM is several things together - kind of a virtual machine/optimizing compiler, combined with different frontends that take the input in a particular language and output the result in an intermediate language. This intermediate output can be run with the virtual machine, or can be used to generate a standalone ex...
[ 31, 17, 15 ]
[]
[]
[ "llvm", "multicore", "python", "unladen_swallow" ]
stackoverflow_0000695370_llvm_multicore_python_unladen_swallow.txt
Q: Understanding Python Class instances I'm working on a problem which uses a python class and has a constructor function to give the number of sides to one die and a function to roll the die with a random number returned based on the number of sides. I realize the code is very basic, but I'm having troubles understa...
Understanding Python Class instances
I'm working on a problem which uses a python class and has a constructor function to give the number of sides to one die and a function to roll the die with a random number returned based on the number of sides. I realize the code is very basic, but I'm having troubles understanding how to sum up the total of three rol...
[ "You can store the results in a list:\nrolls = [Die(n).roll_die() for n in (6, 4, 12)]\n\nthen you can show the individual results\n>>> print rolls\n[5, 2, 6]\n\nor sum them\n>>> print sum(rolls)\n13\n\nOr, instead, you could keep a running total:\ntotal = 0\nfor n in (6, 4, 12):\n value = Die(n).roll_die()\n ...
[ 10, 3, 3, 1, 0, 0, 0, 0 ]
[]
[]
[ "class", "python", "sum" ]
stackoverflow_0000694002_class_python_sum.txt
Q: Help with Python loop weirdness? I'm learning Python as my second programming language (my first real one if you don't count HTML/CSS/Javascript). I'm trying to build something useful as my first real application - an IRC bot that alerts people via SMS when certain things happen in the channel. Per a request by ...
Help with Python loop weirdness?
I'm learning Python as my second programming language (my first real one if you don't count HTML/CSS/Javascript). I'm trying to build something useful as my first real application - an IRC bot that alerts people via SMS when certain things happen in the channel. Per a request by someone, I'm (trying) to build in sche...
[ "If this is a regular CSV file you should not try to parse it yourself. Use the standard library csv module.\nHere is a short example from the docs:\nimport csv\nreader = csv.reader(open(\"some.csv\", \"rb\"))\nfor row in reader:\n print row\n\n", "There are at least two bugs in your program:\ncurtime = time.s...
[ 9, 7, 5, 0, 0, 0 ]
[]
[]
[ "csv", "loops", "python" ]
stackoverflow_0000695040_csv_loops_python.txt
Q: Parsing template schema with Python and Regular Expressions I'm working on a script for work to extract data from an old template engine schema: [%price%] { $54.99 } [%/price%] [%model%] { WRT54G } [%/model%] [%brand%]{ LINKSYS } [%/brand%] everything within the [% %] is the key, and everything in the { } is t...
Parsing template schema with Python and Regular Expressions
I'm working on a script for work to extract data from an old template engine schema: [%price%] { $54.99 } [%/price%] [%model%] { WRT54G } [%/model%] [%brand%]{ LINKSYS } [%/brand%] everything within the [% %] is the key, and everything in the { } is the value. Using Python and regex, I was able to get this far: (?<...
[ "I agree with Devin that a single regex isn't the best solution. If there do happen to be any strange cases that aren't handled by your regex, there's a real risk that you won't find out.\nI'd suggest using a finite state machine approach. Parse the file line by line, first looking for a price-model-brand block, th...
[ 4, 0, 0 ]
[]
[]
[ "grouping", "parsing", "python", "regex" ]
stackoverflow_0000695505_grouping_parsing_python_regex.txt
Q: Limiting the results of cProfile to lines containing "something" _and/or_ "something_else" I am using cProfile to profile the leading function of my entire app. It's working great except for some 3rd party libraries that are being profiled, and shown in the output as well. This is not always desirable when reading...
Limiting the results of cProfile to lines containing "something" _and/or_ "something_else"
I am using cProfile to profile the leading function of my entire app. It's working great except for some 3rd party libraries that are being profiled, and shown in the output as well. This is not always desirable when reading the output. My question is, how can i limit this? The documentation on python profilers mention...
[ "Per the docs you linked, the strings are regular expressions:\n\nEach restriction is either an integer\n ..., or a regular expression (to\n pattern match the standard name that\n is printed; as of Python 1.5b1, this\n uses the Perl-style regular expression\n syntax defined by the re module)\n\nAccordingly:\np...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0000695501_python.txt
Q: Upgraded to ubuntu 9.04 django test are now slow Upgraded my laptop to Ubuntu 9.04 and runing latest trunk of django and my test suite has tripled in time to run. Python2.6 Mysql Django 1.1 beta 1 SVN-10137 A: Quote from the Official Jaunty IRC (#ubuntu+1 on Freenode) Jaunty is NOT RELEASED and NOT SUPPORTED. I...
Upgraded to ubuntu 9.04 django test are now slow
Upgraded my laptop to Ubuntu 9.04 and runing latest trunk of django and my test suite has tripled in time to run. Python2.6 Mysql Django 1.1 beta 1 SVN-10137
[ "Quote from the Official Jaunty IRC (#ubuntu+1 on Freenode)\n\nJaunty is NOT RELEASED and NOT SUPPORTED. It will most certainly break your system.\n\n", "You should verify that your tests are running in a transaction. Is MySQL using the InnoDB or MyISAM backend? If you were using InnoDB before and now MyISAM ther...
[ 3, 0 ]
[]
[]
[ "django", "python", "testing", "ubuntu", "ubuntu_9.04" ]
stackoverflow_0000692294_django_python_testing_ubuntu_ubuntu_9.04.txt
Q: Bad Pickle get error I have been using a flash card program called Mnemosyne which uses python script. A short time ago my database of flash cards became inaccessible after my computer froze and I had to shut it down manually. Whenever I try to load the data base containing my cards I get this error. Invalid fil...
Bad Pickle get error
I have been using a flash card program called Mnemosyne which uses python script. A short time ago my database of flash cards became inaccessible after my computer froze and I had to shut it down manually. Whenever I try to load the data base containing my cards I get this error. Invalid file format Traceback(innerm...
[ "(Whilst CLayton's copy may be a binary distribution, the source to mnemosyne is freely available.)\nIt's not much help though: line 1012 is just:\ndb = cPickle.load(infile)\n\nWhere ‘infile’ is the stored database file. So there's something corrupt in your database file. (BadPickleGet is a specific subclass of Unp...
[ 1 ]
[]
[]
[ "pickle", "python" ]
stackoverflow_0000694192_pickle_python.txt
Q: How to distinguish between a function and a class method? If a variable refers to either a function or a class method, how can I find out which one it is and get the class type in case it is a class method especially when the class is still being declared as in the given example. eg. def get_info(function_or_metho...
How to distinguish between a function and a class method?
If a variable refers to either a function or a class method, how can I find out which one it is and get the class type in case it is a class method especially when the class is still being declared as in the given example. eg. def get_info(function_or_method): print function_or_method class Foo(object): def __...
[ "You can distinguish between the two by checking the type:\n>>> type(bar)\n<type 'function'>\n>>> type(Foo.__init__)\n<type 'instancemethod'>\n\nor\n>>> import types\n>>> isinstance(bar, types.FunctionType)\nTrue\n>>> isinstance(bar, types.UnboundMethodType)\nTrue\n\nwhich is the way you'd do it in an if statement....
[ 13, 9, 4 ]
[]
[]
[ "metaprogramming", "python", "reflection" ]
stackoverflow_0000695679_metaprogramming_python_reflection.txt
Q: How can I make this recursive crawl function iterative? For academic and performance sake, given this crawl recursive web-crawling function (which crawls only within the given domain) what would be the best approach to make it run iteratively? Currently when it runs, by the time it finishes python has climbed to u...
How can I make this recursive crawl function iterative?
For academic and performance sake, given this crawl recursive web-crawling function (which crawls only within the given domain) what would be the best approach to make it run iteratively? Currently when it runs, by the time it finishes python has climbed to using over 1GB of memory which isn't acceptable for running in...
[ "Use a BFS instead of crawling recursively (DFS): http://en.wikipedia.org/wiki/Breadth_first_search\nYou can use an external storage solution (such as a database) for BFS queue to free up RAM.\nThe algorithm is:\n//pseudocode:\nvar urlsToVisit = new Queue(); // Could be a queue (BFS) or stack(DFS). (probably with a...
[ 12, 5, 2, 0 ]
[]
[]
[ "python", "recursion", "web_crawler" ]
stackoverflow_0000694366_python_recursion_web_crawler.txt
Q: Populate a list in python I have a series of Python tuples representing coordinates: tuples = [(1,1), (0,1), (1,0), (0,0), (2,1)] I want to create the following list: l = [] for t in tuples: l[ t[0] ][ t[1] ] = something I get an IndexError: list index out of range. My background is in PHP and I expected that ...
Populate a list in python
I have a series of Python tuples representing coordinates: tuples = [(1,1), (0,1), (1,0), (0,0), (2,1)] I want to create the following list: l = [] for t in tuples: l[ t[0] ][ t[1] ] = something I get an IndexError: list index out of range. My background is in PHP and I expected that in Python you can create lists ...
[ "No, you cannot create list with gaps. But you can create a dictionary with tuple keys:\ntuples = [(1,1), (0,1), (1,0), (0,0), (2,1)]\nl = {}\nfor t in tuples:\n l[t] = something\n\nUpdate:\nTry using NumPy, it provides wide range of operations over matrices and array. Cite from free pfd on NumPy available on th...
[ 8, 6, 3, 2, 1, 1, 0, 0 ]
[ "I think you have only declared a one dimensional list. \nI think you declare it as \nl = [][]\n\n\nEdit: That's a syntax error\n>>> l = [][]\n File \"<stdin>\", line 1\n l = [][]\n ^\nSyntaxError: invalid syntax\n>>> \n\n" ]
[ -2 ]
[ "list", "python", "tuples" ]
stackoverflow_0000696874_list_python_tuples.txt
Q: What is the pythonic way to share common files in multiple projects? Lets say I have projects x and y in brother directories: projects/x and projects/y. There are some utility funcs common to both projects in myutils.py and some db stuff in mydbstuff.py, etc. Those are minor common goodies, so I don't want to crea...
What is the pythonic way to share common files in multiple projects?
Lets say I have projects x and y in brother directories: projects/x and projects/y. There are some utility funcs common to both projects in myutils.py and some db stuff in mydbstuff.py, etc. Those are minor common goodies, so I don't want to create a single package for them. Questions arise about the whereabouts of s...
[ "The pythonic way is to create a single extra package for them.\nWhy don't you want to create a package? You can distribute this package with both projects, and the effect would be the same.\nYou'll never do it right for all instalation scenarios and platforms if you do it by mangling with PYTHONPATH and custom imp...
[ 9, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000696792_python.txt
Q: How do I get the filepath for a class in Python? Given a class C in Python, how can I determine which file the class was defined in? I need something that can work from either the class C, or from an instance off C. The reason I am doing this, is because I am generally a fan off putting files that belong together ...
How do I get the filepath for a class in Python?
Given a class C in Python, how can I determine which file the class was defined in? I need something that can work from either the class C, or from an instance off C. The reason I am doing this, is because I am generally a fan off putting files that belong together in the same folder. I want to create a class that uses...
[ "You can use the inspect module, like this:\nimport inspect\ninspect.getfile(C.__class__)\n\n", "try:\nimport sys, os\nos.path.abspath(sys.modules[LocationArtifact.__module__].__file__)\n\n", "This is the wrong approach for Django and really forcing things.\nThe typical Django app pattern is:\n\n/project\n\n/ap...
[ 172, 46, 5 ]
[]
[]
[ "class", "introspection", "python" ]
stackoverflow_0000697320_class_introspection_python.txt
Q: Importing in Python In Python 2.5, I import modules by changing environment variables. It works, but using site-packages does not. Is there another way to import modules in directories other than C:\Python25 ? A: On way is with PYTHONPATH environment variable. Other one is to add path to sys.path either direct...
Importing in Python
In Python 2.5, I import modules by changing environment variables. It works, but using site-packages does not. Is there another way to import modules in directories other than C:\Python25 ?
[ "On way is with PYTHONPATH environment variable. Other one is to add path to sys.path either directly by sys.path.append(path) or by defining .pth files and add them to with site.addsitedir(dirWithPths). Path files (.pth) are simple text files with a path in each line. Every .pth file in dirWithPths will be read.\n...
[ 7, 4, 4 ]
[ "sys.path is a list to which you can append custom paths to search like this:\nsys.path.append(\"/home/foo\")\n\n" ]
[ -1 ]
[ "import", "python" ]
stackoverflow_0000697281_import_python.txt
Q: Processing XML into MySQL in good form I need to process XML documents of varying formats into records in a MySQL database on a daily basis. The data I need from each XML document is interspersed with a good deal of data I don't need, and each document's node names are different. For example: source #1: <object ...
Processing XML into MySQL in good form
I need to process XML documents of varying formats into records in a MySQL database on a daily basis. The data I need from each XML document is interspersed with a good deal of data I don't need, and each document's node names are different. For example: source #1: <object id="1"> <title>URL 1</title> <url>ht...
[ "Using XSLT is an overkill. I like approach (2), it makes a lot of sense.\nUsing Python I'd try to make a class for every document type. The class would inherit from dict and on its __init__ parse the given document and populate itself with the 'id', 'interval' and 'url'.\nThen the code in main would be really triv...
[ 2, 0, 0 ]
[]
[]
[ "parsing", "python", "xml", "xslt" ]
stackoverflow_0000697741_parsing_python_xml_xslt.txt
Q: Easy way to parse .h file for comments using Python? How to parse in easy way a .h file written in C for comments and entity names using Python? We're suppose for a further writing the content into the word file already developed. Source comments are formatted using a simple tag-style rules. Comment tags used for ...
Easy way to parse .h file for comments using Python?
How to parse in easy way a .h file written in C for comments and entity names using Python? We're suppose for a further writing the content into the word file already developed. Source comments are formatted using a simple tag-style rules. Comment tags used for an easy distinguishing one entity comment from the other a...
[ "This has already been done. Several times over.\nHere is a parser for the C language written in Python. Start with this.\nhttp://wiki.python.org/moin/SeeGramWrap\nOther parsers.\nhttp://wiki.python.org/moin/LanguageParsing\nhttp://nedbatchelder.com/text/python-parsers.html\nYou could probably download any ANSI C...
[ 4, 3, 1 ]
[]
[]
[ "lexer", "parsing", "python" ]
stackoverflow_0000697945_lexer_parsing_python.txt
Q: Python tkinter label won't change at beginning of function I'm using tkinter with Python to create a user interface for a program that converts Excel files to CSV. I created a label to act as a status bar, and set statusBarText as a StringVar() as the textvariable. inputFileEntry and outputFileEntry are textvariab...
Python tkinter label won't change at beginning of function
I'm using tkinter with Python to create a user interface for a program that converts Excel files to CSV. I created a label to act as a status bar, and set statusBarText as a StringVar() as the textvariable. inputFileEntry and outputFileEntry are textvariables that contain the input and output file paths. def convertBut...
[ "Since you're doing all of this in a single method call, the GUI never gets a chance to update before you start your sub process. Check out update_idletasks() call...\nfrom http://infohost.nmt.edu/tcc/help/pubs/tkinter/universal.html\nw.update_idletasks()\nSome tasks in updating the display, such as resizing and re...
[ 11, 3 ]
[]
[]
[ "function", "label", "python", "statusbar", "tkinter" ]
stackoverflow_0000698707_function_label_python_statusbar_tkinter.txt
Q: Programmatically submitting a form in Python? Just started playing with Google App Engine & Python (as an excuse ;)). How do I correctly submit a form like this <form action="https://www.moneybookers.com/app/payment.pl" method="post" target="_blank"> <input type="hidden" name="pay_to_email" value="ENTER_YOUR_USER_...
Programmatically submitting a form in Python?
Just started playing with Google App Engine & Python (as an excuse ;)). How do I correctly submit a form like this <form action="https://www.moneybookers.com/app/payment.pl" method="post" target="_blank"> <input type="hidden" name="pay_to_email" value="ENTER_YOUR_USER_EMAIL@MERCHANT.COM"> <input type="hidden" name="sta...
[ "It sounds like you're looking for urllib.\nHere's an example of POSTing from the library's docs:\n>>> import urllib\n>>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})\n>>> f = urllib.urlopen(\"http://www.musi-cal.com/cgi-bin/query\", params)\n>>> print f.read()\n\n", "By hiding the sensitive bits...
[ 6, 0 ]
[]
[]
[ "forms", "google_app_engine", "post", "python" ]
stackoverflow_0000699238_forms_google_app_engine_post_python.txt
Q: Is it possible to create a class that represents another type in Python, when directly referenced? So if I have a class like: CustomVal I want to be able to represent a literal value, so like setting it in the constructor: val = CustomVal ( 5 ) val.SomeDefaultIntMethod Basically I want the CustomVal to represen...
Is it possible to create a class that represents another type in Python, when directly referenced?
So if I have a class like: CustomVal I want to be able to represent a literal value, so like setting it in the constructor: val = CustomVal ( 5 ) val.SomeDefaultIntMethod Basically I want the CustomVal to represent whatever is specified in the constructor. I am not talking about custom methods that know how to deal ...
[ "The usual way to wrap an object in Python is to override __getattr__ in your class:\nclass CustomVal(object):\n def __init__(self, value):\n self.value = value\n\n def __getattr__(self, attr):\n return getattr(self.value, attr)\n\nSo then you can do\n>>> obj = CustomVal(wrapped_obj)\n>>> obj.So...
[ 7, 2 ]
[]
[]
[ "class", "object", "python" ]
stackoverflow_0000699510_class_object_python.txt
Q: python decorators and methods New here. Also I'm (very) new to python and trying to understand the following behavior. Can someone explain to me why the two methods in this example have different output? def map_children(method): def wrapper(self,*args,**kwargs): res = method(self,*args,**kwargs) ...
python decorators and methods
New here. Also I'm (very) new to python and trying to understand the following behavior. Can someone explain to me why the two methods in this example have different output? def map_children(method): def wrapper(self,*args,**kwargs): res = method(self,*args,**kwargs) for child in self._children: ...
[ "In the decorator, you are looping over the node's children and calling the original, non-recursive method on them\nmethod(child, *args, **kwargs)\n\nso you'll only go one level deep. Try replacing that line with\nmap_children(method)(child, *args, **kwargs)\n\nand you'll get the same output as the manual recursive...
[ 7 ]
[]
[]
[ "decorator", "metaprogramming", "python" ]
stackoverflow_0000699526_decorator_metaprogramming_python.txt
Q: Python: Testing for unicode, and converting to time() Sometimes self.start is unicode: eg. >>>self.start u'07:30:00' Which makes datetime.combine complain start = datetime.combine(self.job_record.date, self.start) How does one: Test for unicode? Convert from u'07:30:00' to datetime.time? A: Checking for unico...
Python: Testing for unicode, and converting to time()
Sometimes self.start is unicode: eg. >>>self.start u'07:30:00' Which makes datetime.combine complain start = datetime.combine(self.job_record.date, self.start) How does one: Test for unicode? Convert from u'07:30:00' to datetime.time?
[ "Checking for unicode:\n>>> import types\n>>> type(u'07:30:00') is types.UnicodeType\nTrue\n>>> type('regular string') is types.UnicodeType\nFalse\n\nConverting strings to time:\n>>> import time\n>>> time.strptime(u'07:30:00', '%H:%M:%S')\n(1900, 1, 1, 7, 30, 0, 0, 1, -1)\n\n", "datetime.combine is complaining be...
[ 4, 2, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000699570_django_python.txt
Q: navigating through different drive letters in python os.system I am having a problem with a bit of code on one windows machine but not all windows machines. i have the following code: path = "F:/dir/" os.system(path[0:2] + " && cd " + path + " && git init") On all but one of my windows systems it runs fine but on...
navigating through different drive letters in python os.system
I am having a problem with a bit of code on one windows machine but not all windows machines. i have the following code: path = "F:/dir/" os.system(path[0:2] + " && cd " + path + " && git init") On all but one of my windows systems it runs fine but on a windows 2003 server it gives a "directory not found" error but if...
[ "os.path contains many usefull path manipulation functions. Probably just handling the path cleanly will resolve your problem.\n>>> import os\n>>>\n>>>\n>>> path = \"F:/dir/\"\n>>>\n>>> clean_path = os.path.normpath(path)\n>>> clean_path\n'F:\\\\dir'\n>>> drive, directory = os.path.splitdrive(clean_path)\n>>> driv...
[ 3 ]
[]
[]
[ "cmd", "python", "windows" ]
stackoverflow_0000699550_cmd_python_windows.txt
Q: Browser interface to command line python program I have a command line tool that I have written (in Python) that interfaces to a SQLite database (one DB per user). This program presents a lot of data to the user which can be cumbersome in a terminal. One option is to provide a wxPython interface, but another thoug...
Browser interface to command line python program
I have a command line tool that I have written (in Python) that interfaces to a SQLite database (one DB per user). This program presents a lot of data to the user which can be cumbersome in a terminal. One option is to provide a wxPython interface, but another thought is to leverage Firefox or Webkit to provide an inte...
[ "The django automatic admin interface (you can use legacy DBs, and sqlite), or databrowse application are worth considering as easy, (almost) no-coding web interfaces.\n", "You might also look at Qt's model/view framework. It's trivial to take a SQL result set and map it into a table view etc...\nhttp://doc.troll...
[ 4, 1 ]
[]
[]
[ "firefox", "python", "sqlite", "webkit" ]
stackoverflow_0000699649_firefox_python_sqlite_webkit.txt
Q: What's the best way to tell if a Python program has anything to read from stdin? I want a program to do one thing if executed like this: cat something | my_program.py and do another thing if run like this my_program.py But if I read from stdin, then it will wait for user input, so I want to see if there is anyth...
What's the best way to tell if a Python program has anything to read from stdin?
I want a program to do one thing if executed like this: cat something | my_program.py and do another thing if run like this my_program.py But if I read from stdin, then it will wait for user input, so I want to see if there is anything to read before trying to read from stdin.
[ "If you want to detect if someone is piping data into your program, or running it interactively you can use isatty to see if stdin is a terminal:\n$ python -c 'import sys; print sys.stdin.isatty()'\nTrue\n$ echo | python -c 'import sys; print sys.stdin.isatty()'\nFalse\n\n", "You want the select module (man selec...
[ 68, 10, 3 ]
[ "I do not know the Python commands off the top of my head, but you should be able to do something with poll or select to look for data ready to read on standard input.\nThat might be Unix OS specific and different on Windows Python.\n" ]
[ -2 ]
[ "python" ]
stackoverflow_0000699390_python.txt
Q: Format a number as a string How do you format a number as a string so that it takes a number of spaces in front of it? I want the shorter number 5 to have enough spaces in front of it so that the spaces plus the 5 have the same length as 52500. The procedure below works, but is there a built in way to do this? a...
Format a number as a string
How do you format a number as a string so that it takes a number of spaces in front of it? I want the shorter number 5 to have enough spaces in front of it so that the spaces plus the 5 have the same length as 52500. The procedure below works, but is there a built in way to do this? a = str(52500) b = str(5) lengthDi...
[ "Format operator:\n>>> \"%10d\" % 5\n' 5'\n>>> \n\nUsing * spec, the field length can be an argument:\n>>> \"%*d\" % (10,5)\n' 5'\n>>> \n\n", "You can just use the %*d formatter to give a width. int(math.ceil(math.log(x, 10))) will give you the number of digits. The * modifier consumes a number, t...
[ 8, 2, 2, 1, 0 ]
[]
[]
[ "format", "integer", "python", "string" ]
stackoverflow_0000700016_format_integer_python_string.txt
Q: function pointers in python I would like to do something like the following: def add(a, b): #some code def subtract(a, b): #some code operations = [add, subtract] operations[0]( 5,3) operations[1](5,3) In python, is it possible to assign something like a function pointer? A: Did you try it? What you w...
function pointers in python
I would like to do something like the following: def add(a, b): #some code def subtract(a, b): #some code operations = [add, subtract] operations[0]( 5,3) operations[1](5,3) In python, is it possible to assign something like a function pointer?
[ "Did you try it? What you wrote works exactly as written. Functions are first-class objects in Python.\n", "Python has nothing called pointers, but your code works as written. Function are first-class objects, assigned to names, and used as any other value.\nYou can use this to implement a Strategy pattern, for ...
[ 23, 8, 1 ]
[]
[]
[ "function_pointers", "python" ]
stackoverflow_0000307494_function_pointers_python.txt
Q: communication with long running tasks in python I have a python GUI app that uses a long running function from a .so/.dll it calls through ctypes. I'm looking for a way to communicate with the function while it's running in a separate thread or process, so that I can request it to terminate early (which requires s...
communication with long running tasks in python
I have a python GUI app that uses a long running function from a .so/.dll it calls through ctypes. I'm looking for a way to communicate with the function while it's running in a separate thread or process, so that I can request it to terminate early (which requires some work on the C side before returning a partial res...
[ "There's two parts you'll need to answer here: one if how to communicate between the two processes (your GUI and the process executing the function), and the other is how to change your function so it responds to asynchronous requests (\"oh, I've been told to just return whatever I've got\").\nWorking out the answe...
[ 2, 2, 0, 0 ]
[]
[]
[ "ctypes", "multithreading", "process", "python" ]
stackoverflow_0000700073_ctypes_multithreading_process_python.txt
Q: How to add a Python import path using a .pth file If I put a *.pth file in site-packages it's giving an ImportError. I'm not getting how to import by creating a *.pth file. (Refers to importing in python) A: If you put a .pth file in the site-packages directory containing a path, python searches this path for im...
How to add a Python import path using a .pth file
If I put a *.pth file in site-packages it's giving an ImportError. I'm not getting how to import by creating a *.pth file. (Refers to importing in python)
[ "If you put a .pth file in the site-packages directory containing a path, python searches this path for imports. So I have a sth.pth file there that simply contains:\nK:\\Source\\Python\\lib\n\nIn that directory there are some normal Python modules:\nlogger.py\nfstools.py\n...\n\nThis allows to directly import thes...
[ 41, 27 ]
[]
[]
[ "python", "python_import" ]
stackoverflow_0000700375_python_python_import.txt
Q: Why isn't keyword DateField.input_formats recognized in django 1.0.2 and Python 2.5? With django 1.0.2 and Python 2.5, when I use the keyword DateField.input_formats, I get the error that __init__() got an unexpected keyword argument 'input_formats'. When I look in the __init__ file, I don't see input_formats as o...
Why isn't keyword DateField.input_formats recognized in django 1.0.2 and Python 2.5?
With django 1.0.2 and Python 2.5, when I use the keyword DateField.input_formats, I get the error that __init__() got an unexpected keyword argument 'input_formats'. When I look in the __init__ file, I don't see input_formats as one of the acceptable keyword arguments. I thought that input_formats had been around long ...
[ "Having looked at the docs, like you suspected, models.DateField doesn't have an input_formats, but forms.DateField does (as does forms.DateTimeField)\n" ]
[ 17 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000690171_django_python.txt
Q: How to design multithreaded GUI-network application? I'm working on a small utility application in Python. The networking is gonna send and receive messages. The GUI is gonna display the messages from the GUI and provide user input for entering messages to be sent. There's also a storage part as I call it, which ...
How to design multithreaded GUI-network application?
I'm working on a small utility application in Python. The networking is gonna send and receive messages. The GUI is gonna display the messages from the GUI and provide user input for entering messages to be sent. There's also a storage part as I call it, which is gonna get all the network messages and save them in som...
[ "One, probably the best, solution for this problem is to use Twisted. It supports all the GUI toolkits.\n", "I think that you could use a Queue for passing messages between the GUI and the network threads.\nAs for GUI and threads in general, you might find the PyGTK and Threading article interesting.\n" ]
[ 2, 1 ]
[]
[]
[ "multithreading", "python", "user_interface" ]
stackoverflow_0000700905_multithreading_python_user_interface.txt
Q: Is there a standard 3rd party Python caching class? I'm working on a client class which needs to load data from a networked database. It's been suggested that adding a standard caching service to the client could improve it's performance. I'd dearly like not to have to build my own caching class - it's well known...
Is there a standard 3rd party Python caching class?
I'm working on a client class which needs to load data from a networked database. It's been suggested that adding a standard caching service to the client could improve it's performance. I'd dearly like not to have to build my own caching class - it's well known that these provide common points of failure. It would be...
[ "I'd recommend using memcached and using cmemcache to access it. You can't necessarily limit the number of objects in the cache, but you can set an expiration time and limit the amount of memory it uses. And memcached is used by a lot of big names. In fact, I'd call it kind of the industry standard.\nUPDATE:\n\n...
[ 4 ]
[]
[]
[ "design_patterns", "python" ]
stackoverflow_0000701264_design_patterns_python.txt
Q: What's the common practice for enums in Python? Possible Duplicate: How can I represent an 'enum' in Python? What's the common practice for enums in Python? I.e. how are they replicated in Python? public enum Materials { Shaded, Shiny, Transparent, Matte } A: class Materials: Shaded, Shiny,...
What's the common practice for enums in Python?
Possible Duplicate: How can I represent an 'enum' in Python? What's the common practice for enums in Python? I.e. how are they replicated in Python? public enum Materials { Shaded, Shiny, Transparent, Matte }
[ "class Materials:\n Shaded, Shiny, Transparent, Matte = range(4)\n\n>>> print Materials.Matte\n3\n\n", "I've seen this pattern several times:\n>>> class Enumeration(object):\n def __init__(self, names): # or *names, with no .split()\n for number, name in enumerate(names.split()):\n ...
[ 375, 21, 10, 7 ]
[]
[]
[ "enums", "python" ]
stackoverflow_0000702834_enums_python.txt
Q: URL encode a non-value pair in Python I'm trying to use Google's AJAX (JSON) Web Search API in Python. I'm stuck because Python's urllib.urlencode() only takes value pairs, not strings by themselves, to encode. In Google's API, the query string is the search term and it doesn't associate with a variable. query = "...
URL encode a non-value pair in Python
I'm trying to use Google's AJAX (JSON) Web Search API in Python. I'm stuck because Python's urllib.urlencode() only takes value pairs, not strings by themselves, to encode. In Google's API, the query string is the search term and it doesn't associate with a variable. query = "string that needs to be encoded" params = u...
[ "I think you're looking for urllib.quote instead.\n" ]
[ 37 ]
[]
[]
[ "json", "python", "urlencode" ]
stackoverflow_0000702986_json_python_urlencode.txt
Q: User editing own Active Directory data How can I build a web page that allows a logged on user of a Windows 2003 domain change details of his account (probably just First Name, Surname, and Phone number)? A: Check out Python-AD (Python Active Directory) which offers the bindings you'll want for communicating wit...
User editing own Active Directory data
How can I build a web page that allows a logged on user of a Windows 2003 domain change details of his account (probably just First Name, Surname, and Phone number)?
[ "Check out Python-AD (Python Active Directory) which offers the bindings you'll want for communicating with the AD server.\nAs for the very broad \"how can I build a web page\" portion of your request, SO has plenty of questions/answers on good web frameworks in python :-)\n", "Take a look at this http://www.nove...
[ 0, 0 ]
[]
[]
[ "active_directory", "asp.net", "python" ]
stackoverflow_0000702493_active_directory_asp.net_python.txt
Q: Executing Java programs through Python How do I do this? A: You can execute anything you want from Python with the os.system() function. os.system(command) Execute the command (a string) in a subshell. This is implemented by calling the Standard C function system, and has the same limitations. Changes...
Executing Java programs through Python
How do I do this?
[ "You can execute anything you want from Python with the os.system() function.\n\nos.system(command)\n Execute the command\n (a string) in a subshell. This is\n implemented by calling the Standard C\n function system, and has the same\n limitations. Changes to os.environ,\n sys.stdin, etc. are not reflected in...
[ 12, 5 ]
[]
[]
[ "java", "python" ]
stackoverflow_0000702861_java_python.txt
Q: Why does setuptools sometimes delete and then re-install the exact same egg? I'm trying to install an egg on a computer where an identical egg already exists. Why does it remove the egg and then re-install it? I'm calling easy_install from a script with the options: ['-v', '-m', '-f', 'R:/OPTIONS/Stephen/python_eg...
Why does setuptools sometimes delete and then re-install the exact same egg?
I'm trying to install an egg on a computer where an identical egg already exists. Why does it remove the egg and then re-install it? I'm calling easy_install from a script with the options: ['-v', '-m', '-f', 'R:/OPTIONS/Stephen/python_eggs', 'mypkg==1.0_r2009_03_12'] While running the easy_install command this was ob...
[ "Here is what I am guessing is happening... This is a guess based on your description of the symptoms.\nAssuming in your example mypkg and calyon are the same, the use of -r2009-03-12 on the end of your is not an expected format for setuptools (the standard format for post release tags is without hyphens YYYYMMDD) ...
[ 2, 0 ]
[]
[]
[ "python", "setuptools" ]
stackoverflow_0000685874_python_setuptools.txt
Q: Using email.HeaderParser with imaplib.fetch in python? Does anyone have a good example of using the HeaderParser class in Python for a message that you pull down with imaplib.fetch? I have been able to find a lot of related things, but nothing that does just this. Do I need to full down the fetch has an RFC822? ...
Using email.HeaderParser with imaplib.fetch in python?
Does anyone have a good example of using the HeaderParser class in Python for a message that you pull down with imaplib.fetch? I have been able to find a lot of related things, but nothing that does just this. Do I need to full down the fetch has an RFC822? I was hoping to simply pull down the subjects. Thanks!
[ "Good news: you're right... you don't need to pull down the RFC822. The message_parts parameter to fetch() lets you be quite fine-grained.\nHere's a simple example of how to fetch just the header:\nimport imaplib\nfrom email.parser import HeaderParser\n\nconn = imaplib.IMAP4('my.host.com')\nconn.login('my@username....
[ 18 ]
[]
[]
[ "email", "python" ]
stackoverflow_0000703185_email_python.txt
Q: Python: an iteration over a non-empty list with no if-clause comes up empty. Why? How can an iterator over a non-empty sequence, with no filtering and no aggregation (sum(), etc.), yield nothing? Consider a simple example: sequence = ['a', 'b', 'c'] list((el, ord(el)) for el in sequence) This yields [('a', 97), (...
Python: an iteration over a non-empty list with no if-clause comes up empty. Why?
How can an iterator over a non-empty sequence, with no filtering and no aggregation (sum(), etc.), yield nothing? Consider a simple example: sequence = ['a', 'b', 'c'] list((el, ord(el)) for el in sequence) This yields [('a', 97), ('b', 98), ('c', 99)] as expected. Now, just swap the ord(el) out for an expression that...
[ "odd_integers_up_to_length(el).next() will raise StopIteration, which isn't caught there, but is caught for the generator expression within it, stopping it without ever yielding anything.\nlook at the first iteration, when the value is 'a':\n>>> odd_integers_up_to_length('a').next()\nTraceback (most recent call las...
[ 13, 4, 0, 0 ]
[]
[]
[ "generator", "iterator", "leaky_abstraction", "python" ]
stackoverflow_0000703520_generator_iterator_leaky_abstraction_python.txt
Q: How would I compute exactly 30 days into the past with Python (down to the minute)? In Python, I'm attempting to retrieve the date/time that is exactly 30 days (30*24hrs) into the past. At present, I'm simply doing: >>> import datetime >>> start_date = datetime.date.today() + datetime.timedelta(-30) Which returns...
How would I compute exactly 30 days into the past with Python (down to the minute)?
In Python, I'm attempting to retrieve the date/time that is exactly 30 days (30*24hrs) into the past. At present, I'm simply doing: >>> import datetime >>> start_date = datetime.date.today() + datetime.timedelta(-30) Which returns a datetime object, but with no time data: >>> start_date.year 2009 >>> start_date.hour T...
[ "You want to use a datetime object instead of just a date object:\nstart_date = datetime.datetime.now() - datetime.timedelta(30)\n\ndate just stores a date and time just a time. datetime is a date with a time.\n" ]
[ 142 ]
[]
[]
[ "date", "datetime", "python", "time" ]
stackoverflow_0000703907_date_datetime_python_time.txt
Q: Most efficient way of loading formatted binary files in Python I have binary files no larger than 20Mb in size that have a header section and then a data section containing sequences of uchars. I have Numpy, SciPy, etc. and each library has different ways of loading in the data. Any suggestions for the most effici...
Most efficient way of loading formatted binary files in Python
I have binary files no larger than 20Mb in size that have a header section and then a data section containing sequences of uchars. I have Numpy, SciPy, etc. and each library has different ways of loading in the data. Any suggestions for the most efficient methods I should use?
[ "Use the struct module, or possibly a custom module written in C if performance is critical.\n", "struct should work for the header section, while numpy's memmap would be efficient for the data section if you are going to manipulate it in numpy anyways. There's no need to stress out about being inconsistent here....
[ 8, 4, 1, 0 ]
[]
[]
[ "binaryfiles", "input", "python" ]
stackoverflow_0000703262_binaryfiles_input_python.txt
Q: How to send a session message to an anonymous user in a Django site? I often show messages about user actions to logged in users in my Django app views using: request.user.message_set.create("message to user") How could I do the same for anonymous (not logged in) users? There is no request.user for anonymous use...
How to send a session message to an anonymous user in a Django site?
I often show messages about user actions to logged in users in my Django app views using: request.user.message_set.create("message to user") How could I do the same for anonymous (not logged in) users? There is no request.user for anonymous users, but the Django documentation says that using the "session" middleware ...
[ "This is what I do, using context processors:\nproject/application/context.py (check for messages and add them to the context):\ndef messages(request):\n messages = {}\n if 'message' in request.session:\n message_type = request.session.get('message_type', 'error')\n messages = {'message': reques...
[ 7, 4, 4 ]
[]
[]
[ "django", "django_views", "python", "session" ]
stackoverflow_0000697902_django_django_views_python_session.txt
Q: Importing in Python between three or more files not working I hav codes eg1.py , eg2.py , eg3.py eg3.py imports eg2.py which in turn imports eg1.py When i run eg3.py for first time everything is fine If i import it again and again only eg3.py runs I need a solution for this. I will code eg3.py in such a way that :...
Importing in Python between three or more files not working
I hav codes eg1.py , eg2.py , eg3.py eg3.py imports eg2.py which in turn imports eg1.py When i run eg3.py for first time everything is fine If i import it again and again only eg3.py runs I need a solution for this. I will code eg3.py in such a way that : while(1): import eg2.py Where I went wrong.Please give me a...
[ "Do you want to execute the code in eg2.py when you import it? That is not a good solution. You should have a function containing your code in eg2.py and then execute this function in your while loop.\nIn eg2.py:\ndef my_func():\n # do useful stuff\n pass\n\nIn eg3.py\nimport eg2\nwhile True:\n eg2.my_func...
[ 7, 1, 0 ]
[]
[]
[ "import", "python" ]
stackoverflow_0000704856_import_python.txt
Q: Add event to list I want to add event to list such that on adding items actions are taken based on the item e.g. genrating new data structures, change in screen output or raising exception. How do I accomplish this? A: You could create your own class that extends the list object: class myList(list): def myAp...
Add event to list
I want to add event to list such that on adding items actions are taken based on the item e.g. genrating new data structures, change in screen output or raising exception. How do I accomplish this?
[ "You could create your own class that extends the list object:\nclass myList(list):\n def myAppend(self, item):\n if isinstance(item, list):\n print 'Appending a list'\n self.append(item)\n elif isinstance(item, str):\n print 'Appending a string item'\n s...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0000705296_python.txt
Q: indentation of multiline string I have a script that uses the cmd Python module. The cmd module uses a triple quoted multiline string as it's help text. Something like this def x(self, strags = None): """class help text here and some more help text here""" When running the script, the command 'help x'...
indentation of multiline string
I have a script that uses the cmd Python module. The cmd module uses a triple quoted multiline string as it's help text. Something like this def x(self, strags = None): """class help text here and some more help text here""" When running the script, the command 'help x' will print the string. It will, howe...
[ "Personally I try to follow PEP 8 which refers the reader to PEP 257 for Docstring Conventions. It has an entire section on multi-line docstrings.\n", "I'd handle it by having consistent indents, like this:\ndef x(self, strags = None):\n \"\"\"\n class\n help text here\n and some more help text here\n...
[ 2, 1 ]
[]
[]
[ "cmd", "indentation", "python" ]
stackoverflow_0000705370_cmd_indentation_python.txt
Q: Using python ctypes to get buffer of floats from shared library into python string I'm trying to use python ctypes to use these two C functions from a shared library: bool decompress_rgb(unsigned char *data, long dataLen, int scale) float* getRgbBuffer() The first function is working fine. I can tell by putting s...
Using python ctypes to get buffer of floats from shared library into python string
I'm trying to use python ctypes to use these two C functions from a shared library: bool decompress_rgb(unsigned char *data, long dataLen, int scale) float* getRgbBuffer() The first function is working fine. I can tell by putting some debug code in the shared library and checking the input. The problem is getting the ...
[ "Not fully tested, but I think it's something along this line:\nbuffer_size = 720 * 288 * ctypes.sizeof(ctypes.c_float)\nrgb_buffer = ctypes.create_string_buffer(buffer_size) \nctypes.memmove(rgb_buffer, getRgbBuffer(), buffer_size)\n\nKey is the ctypes.memmove() function. From the ctypes documentation:\n\nmemmove(...
[ 4, 2 ]
[]
[]
[ "ctypes", "pointers", "python", "return_value" ]
stackoverflow_0000704777_ctypes_pointers_python_return_value.txt
Q: Inventory Control Across Multiple Servers .. Ideas? We currently have an inventory management system that was built in-house. It works great, and we are constantly innovating it. This past Fall, we began selling products directly on one of our websites via a Shopping Cart checkout. Our inventory management system...
Inventory Control Across Multiple Servers .. Ideas?
We currently have an inventory management system that was built in-house. It works great, and we are constantly innovating it. This past Fall, we began selling products directly on one of our websites via a Shopping Cart checkout. Our inventory management system runs off a server in the office, while the three website...
[ "One possibility would be to expose a web service interface on your inventory management system that allows the transactions used by the web shopfront to be accessed remotely. With a reasonably secure VPN link or ssh tunnel type arrangement, the web shopfront could get stock levels, place orders or execute searche...
[ 1, 0, 0 ]
[]
[]
[ "inventory", "python", "tracking" ]
stackoverflow_0000487642_inventory_python_tracking.txt
Q: any way to loop iteration with same item in python? It's a common programming task to loop iteration while not receiving next item. For example: for sLine in oFile : if ... some logic ... : sLine = oFile.next() ... some more logic ... # at this point i want to continue iteration but without # get...
any way to loop iteration with same item in python?
It's a common programming task to loop iteration while not receiving next item. For example: for sLine in oFile : if ... some logic ... : sLine = oFile.next() ... some more logic ... # at this point i want to continue iteration but without # getting next item from oFile. How can this be done in python...
[ "I first thought you wanted the continue keyword, but that would of course get you the next line of input.\nI think I'm stumped. When looping over the lines of a file, what exactly should happen if you continued the loop without getting a new line?\nDo you want to inspect the line again? If so, I suggest adding an ...
[ 3, 2, 1, 0, 0 ]
[ "You can assign your iterator to an variable then use the .next get te next one.\niter = oFile.xreadlines() # is this the correct iterator you want?\ntry:\n sLine = iter.next()\n while True:\n if ... some logic ... :\n sLine = iter.next()\n ... some more logic ...\n continue\n sLine = iter.ne...
[ -1, -1, -2 ]
[ "iterator", "python" ]
stackoverflow_0000705811_iterator_python.txt
Q: Caching data from other websites in Django Suppose I have a simple view which needs to parse data from an external website. Right now it looks something like this: def index(request): source = urllib2.urlopen(EXTERNAL_WEBSITE_URL) bs = BeautifulSoup.BeautifulSoup(source.read()) finalList = [] # do what...
Caching data from other websites in Django
Suppose I have a simple view which needs to parse data from an external website. Right now it looks something like this: def index(request): source = urllib2.urlopen(EXTERNAL_WEBSITE_URL) bs = BeautifulSoup.BeautifulSoup(source.read()) finalList = [] # do whatever with bs to populate the list return ren...
[ "First, don't optimize prematurely. Get this to work.\nThen, add enough logging to see what the performance problems (if any) really are.\nYou may find that end-user's PC is the slowest part; getting data from another site may, actually, be remarkably fast when you do not fetch .JS libraries and .CSS and artwork a...
[ 5, 3, 1 ]
[]
[]
[ "caching", "django", "python" ]
stackoverflow_0000705855_caching_django_python.txt
Q: Connection refused on Windows XP network This is only marginally a programming problem and more of a networking problem. I'm trying to get a Django web app to run in my home network and I can't get any machines on the network to get to the web page. I've run on ports 80 and 8000 with no luck. Error message is: "Fi...
Connection refused on Windows XP network
This is only marginally a programming problem and more of a networking problem. I'm trying to get a Django web app to run in my home network and I can't get any machines on the network to get to the web page. I've run on ports 80 and 8000 with no luck. Error message is: "Firefox can't establish a connection to the serv...
[ "I assume you're running the django dev server? If so, make sure you start it so that it will bind to the IP address the other machines need to use for the connection:\npython manage.py runserver 192.168.x.x:8000\n\nYou can ask the server to bind to all addresses with (haven't tried this on Windows myself, I admit)...
[ 3 ]
[]
[]
[ "networking", "python" ]
stackoverflow_0000707023_networking_python.txt
Q: Python source header comment What is the line #!/usr/bin/env python in the first line of a python script used for? A: In UNIX and Linux this tells which binary to use as an interpreter (see also Wiki page). For example shell script is interpreted by /bin/sh. #!/bin/sh Now with python it's a bit tricky, because...
Python source header comment
What is the line #!/usr/bin/env python in the first line of a python script used for?
[ "In UNIX and Linux this tells which binary to use as an interpreter (see also Wiki page).\nFor example shell script is interpreted by /bin/sh.\n#!/bin/sh\n\nNow with python it's a bit tricky, because you can't assume where the binary is installed, nor which you want to use. Thus the /usr/bin/env trick. It's use whi...
[ 27, 14, 5, 5, 3, 2 ]
[]
[]
[ "python", "shebang", "unix" ]
stackoverflow_0000707127_python_shebang_unix.txt
Q: how to hook to events / messages in windows using python in short: i want to intercept suspend/standby messages on my laptop, but my program doesn't receives all relevant messages. background: there's a bug in ms-excel on windows xp/2k, which prevents system suspend if a file is opened on a network/usb drive. i'm ...
how to hook to events / messages in windows using python
in short: i want to intercept suspend/standby messages on my laptop, but my program doesn't receives all relevant messages. background: there's a bug in ms-excel on windows xp/2k, which prevents system suspend if a file is opened on a network/usb drive. i'm trying to work-around it programmatically (my toolbox include ...
[ "I've found an ugly workaround:\nI wrote an AutoIt script which detects the Excel's error MessageBox, closes it, and runs a sysinternals' utility which forces the computer to standby.\n\nOpt(\"WinWaitDelay\",400)\n; -- exact text match, to save LOTS of cup cycles!\nOpt(\"WinTitleMatchMode\",3)\nOpt(\"WinDetectHidde...
[ 2 ]
[]
[]
[ "power_management", "python", "windows", "wmi" ]
stackoverflow_0000694475_power_management_python_windows_wmi.txt
Q: What is the best way to pass a method (with parameters) to another method in python What's the best way to pass a method and a method parameter to another method? Is there a better way to do the following? def method1(name) return 'Hello ' + name def method2(methodToCall, methodToCallParams, question): gr...
What is the best way to pass a method (with parameters) to another method in python
What's the best way to pass a method and a method parameter to another method? Is there a better way to do the following? def method1(name) return 'Hello ' + name def method2(methodToCall, methodToCallParams, question): greetings = methodToCall(methodToCallParams) return greetings + ', ' + question method...
[ "If you want to package the invocation up in one hit, you can use the functools module:\nfrom functools import partial\n\ndef some_function(param_one, param_two):\n print \"Param One: %s\" % param_one\n print \"Param Two: %s\" % param_two\n\ndef calling_function(target):\n target()\n\ncalling_function(part...
[ 11, 3, 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000706813_python.txt
Q: Python: import the containing package In a module residing inside a package, i have the need to use a function defined within the __init__.py of that package. how can i import the package within the module that resides within the package, so i can use that function? Importing __init__ inside the module will not im...
Python: import the containing package
In a module residing inside a package, i have the need to use a function defined within the __init__.py of that package. how can i import the package within the module that resides within the package, so i can use that function? Importing __init__ inside the module will not import the package, but instead a module name...
[ "Also, starting in Python 2.5, relative imports are possible. e.g.:\nfrom . import foo\n\nQuoting from http://docs.python.org/tutorial/modules.html#intra-package-references:\n\nStarting with Python 2.5, in addition to the implicit relative imports described above, you can write explicit relative imports with the fr...
[ 48, 23, 5, 1, 1 ]
[]
[]
[ "module", "package", "python", "python_import" ]
stackoverflow_0000436497_module_package_python_python_import.txt
Q: Debugging a running python process Is there a way to see a stacktrace of what various threads are doing inside a python process? Let's suppose I have a thread which allows me some sort of remote access to the process. A: Winpdb is a platform independent graphical GPL Python debugger with support for remote deb...
Debugging a running python process
Is there a way to see a stacktrace of what various threads are doing inside a python process? Let's suppose I have a thread which allows me some sort of remote access to the process.
[ "Winpdb is a platform independent graphical GPL Python debugger with support for remote debugging over a network, multiple threads, namespace modification, embedded debugging, encrypted communication and is up to 20 times faster than pdb.\nFeatures:\n\nGPL license. Winpdb is Free Software.\nCompatible with CPython ...
[ 6, 2 ]
[]
[]
[ "python", "remote_debugging" ]
stackoverflow_0000707999_python_remote_debugging.txt
Q: Decorators and in class Is there any way to write decorators within a class structure that nest well? For example, this works fine without classes: def wrap1(func): def loc(*args,**kwargs): print 1 return func(*args,**kwargs) return loc def wrap2(func): def loc(*args,**kwargs): ...
Decorators and in class
Is there any way to write decorators within a class structure that nest well? For example, this works fine without classes: def wrap1(func): def loc(*args,**kwargs): print 1 return func(*args,**kwargs) return loc def wrap2(func): def loc(*args,**kwargs): print 2 return func...
[ "\"Is there any good way to put the decorators within the namespace?\"\nThere's no compelling reason for this. You have module files. Those are a tidy container for a class and some decorators. \nYou don't ever need decorators as methods of the class -- you can just call one method from another. \n", "Actually...
[ 5, 2 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0000707090_decorator_python.txt
Q: Python comments: # vs. strings Regarding the "standard" way to put comments inside Python source code: def func(): "Func doc" ... <code> 'TODO: fix this' #badFunc() ... <more code> def func(): "Func doc" ... <code> #TODO: fix this #badFunc() ... <more code> I prefer to wri...
Python comments: # vs. strings
Regarding the "standard" way to put comments inside Python source code: def func(): "Func doc" ... <code> 'TODO: fix this' #badFunc() ... <more code> def func(): "Func doc" ... <code> #TODO: fix this #badFunc() ... <more code> I prefer to write general comments as strings inste...
[ "Don't misuse strings (no-op statements) as comments. Docstrings, e.g. the first string in a module, class or function, are special and definitely recommended.\nNote that docstrings are documentation, and documentation and comments are two different things!\n\nDocumentation is important to understand what the code ...
[ 67, 6, 6 ]
[]
[]
[ "python" ]
stackoverflow_0000708649_python.txt
Q: Create a standalone windows exe which does not require pythonXX.dll is there a way to create a standalone .exe from a python script. Executables generated with py2exe can run only with pythonXX.dll. I'd like to obtain a fully standalone .exe which does not require to install the python runtime library. It looks li...
Create a standalone windows exe which does not require pythonXX.dll
is there a way to create a standalone .exe from a python script. Executables generated with py2exe can run only with pythonXX.dll. I'd like to obtain a fully standalone .exe which does not require to install the python runtime library. It looks like a linking problem but using static library instead the dynamic one and...
[ "You can do this in the latest version of py2exe... Just add something like the code below in your setup.py file (key part is 'bundle_files': 1).\nTo include your TkInter package in the install, use the 'includes' key.\ndistutils.core.setup(\n windows=[\n {'script': 'yourmodule.py',\n 'i...
[ 17, 5, 4, 2, 1 ]
[]
[]
[ "py2exe", "python", "windows" ]
stackoverflow_0000707242_py2exe_python_windows.txt
Q: web.py: passing initialization / global variables to handler classes? I'm attempting to use web.py with Tokyo Cabinet / pytc and need to pass the db handle (the connection to tokyo cabinet) to my handler classes so they can talk to tokyo cabinet. Is there a way to pass the handler to the handler class's init func...
web.py: passing initialization / global variables to handler classes?
I'm attempting to use web.py with Tokyo Cabinet / pytc and need to pass the db handle (the connection to tokyo cabinet) to my handler classes so they can talk to tokyo cabinet. Is there a way to pass the handler to the handler class's init function? Or should I be putting the handle in globals() ? What is globals() an...
[ "The best way would be to add a load hook (described here for sqlalchemy). Define a function that connects to Tokyo Cabinet and adds the resulting db object as an .orm attribute to web.ctx, which is always available inside the controller.\n" ]
[ 2 ]
[]
[]
[ "python", "web.py" ]
stackoverflow_0000707841_python_web.py.txt
Q: python code convention using pylint I'm trying out pylint to check my source code for conventions. Somehow some variable names are matched with the regex for constants (const-rgx) instead of the variable name regex (variable-rgx). How to match the variable name with variable-rgx? Or should I extend const-rgx with ...
python code convention using pylint
I'm trying out pylint to check my source code for conventions. Somehow some variable names are matched with the regex for constants (const-rgx) instead of the variable name regex (variable-rgx). How to match the variable name with variable-rgx? Or should I extend const-rgx with my variable-rgx stuff? e.g. C0103: 31: In...
[ "\nSomehow some variable names are matched with the regex for constants (const-rgx) instead of the variable name regex (variable-rgx).\n\nAre those variables declared on module level? Maybe that's why they are treated as constants (at least that's how they should be declared, according to PEP-8).\n", "I just disa...
[ 27, 10, 0 ]
[]
[]
[ "conventions", "pylint", "python" ]
stackoverflow_0000709490_conventions_pylint_python.txt
Q: Accessing a MySQL database from python I have been trying for the past several hours to find a working method of accessing a mysql database in python. The only thing that I've managed to get to compile and install is pyodbc but the necessary driver is not available for ppc leopard. I already know about this. UPD...
Accessing a MySQL database from python
I have been trying for the past several hours to find a working method of accessing a mysql database in python. The only thing that I've managed to get to compile and install is pyodbc but the necessary driver is not available for ppc leopard. I already know about this. UPDATE: I've gotten setuptools to install, but ...
[ "Try SQL Alchemy.\nIt is awesome.\n", "Install fink. It includes the MySQLdb package.\n", "\nUPDATE: Now I've gotten sqlalchemy to\n install but while it will show up when\n called by the command line it won't\n import when used in my cgi script.\n\nCan you verify that the Python being invoked from your CGI ...
[ 2, 1, 0 ]
[]
[]
[ "database", "mysql", "python" ]
stackoverflow_0000621156_database_mysql_python.txt
Q: Is there a Perl equivalent to Python's `if __name__ == '__main__'`? Is there a way to determine if the current file is the one being executed in Perl source? In Python we do this with the following construct: if __name__ == '__main__': # This file is being executed. raise NotImplementedError I can hack so...
Is there a Perl equivalent to Python's `if __name__ == '__main__'`?
Is there a way to determine if the current file is the one being executed in Perl source? In Python we do this with the following construct: if __name__ == '__main__': # This file is being executed. raise NotImplementedError I can hack something together using FindBin and __FILE__, but I'm hoping there's a can...
[ "unless (caller) {\n print \"This is the script being executed\\n\";\n}\n\nSee caller. It returns undef in the main script. Note that that doesn't work inside a subroutine, only in top-level code.\n", "See the \"Subclasses for Applications (Chapter 18)\" portion of brian d foy's article Five Ways to Improve Yo...
[ 49, 10, 4 ]
[]
[]
[ "executable", "perl", "python" ]
stackoverflow_0000707022_executable_perl_python.txt
Q: Python server side AJAX library? I want to have a browser page that updates some information on a timer or events. I'd like to use Python on the server side. It's quite simple, I don't need anything massively complex. I can spend some time figuring out how to do all this the "AJAX way", but I'm sure someone has wr...
Python server side AJAX library?
I want to have a browser page that updates some information on a timer or events. I'd like to use Python on the server side. It's quite simple, I don't need anything massively complex. I can spend some time figuring out how to do all this the "AJAX way", but I'm sure someone has written a nice Python library to do all ...
[ "AJAX stands for Asynchronous JavaScript and XML. You don't need any special library, other than the Javascript installed on the browser to do AJAX calls. The AJAX requests comes from the client side Javascript code, and goes to the server side which in your case would be handled in python.\nYou probably want to ...
[ 5, 5, 1 ]
[]
[]
[ "ajax", "python" ]
stackoverflow_0000709868_ajax_python.txt