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: Equivalent of an HTML multiple SELECT box in wxPython I'd like to create a ListBox in wxPython with the same semantics as a multiple select box in HTML. Specifically I'd like the following semantics When the user clicks on an entry in the list, all other entries become de-selected and the clicked entry becomes ...
Equivalent of an HTML multiple SELECT box in wxPython
I'd like to create a ListBox in wxPython with the same semantics as a multiple select box in HTML. Specifically I'd like the following semantics When the user clicks on an entry in the list, all other entries become de-selected and the clicked entry becomes selected. If the entry was already selected then it stays ...
[ "I think what you're looking for is the wxLB_EXTENDED list box style. Specify style = wx.LB_EXTENDED when you create the ListBox.\nYou can then use the GetSelections method to obtain a list of the selected items.\n" ]
[ 3 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0000363907_python_wxpython.txt
Q: Best way to monitor services on a few servers with python What would be the best way to monitor services like HTTP/FTP/IMAP/POP3/SMTP for a few servers from python? Using sockets and trying to connect to service port http-80, ftp-21, etc... and if connection successful assume service is ok or use python libs to co...
Best way to monitor services on a few servers with python
What would be the best way to monitor services like HTTP/FTP/IMAP/POP3/SMTP for a few servers from python? Using sockets and trying to connect to service port http-80, ftp-21, etc... and if connection successful assume service is ok or use python libs to connect to specified services and handle exceptions/return codes/...
[ "update 1:\nActually, In your code there is no difference between the two option ( in FTP ). The second option should be Preferred for code readability. But way not login to the ftp server, And maybe read some file?\nupdate 0:\nWhen monitoring, testing the full stack is better. Because otherwise you can miss proble...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0000363968_python.txt
Q: Threaded code on mod_python I have written a Django app that makes use of Python threading to create a web spider, the spider operates as a series of threads to check links. When I run this app using the django test server (built in), the app runs fine and the threads seem to start and stop on time. However, runni...
Threaded code on mod_python
I have written a Django app that makes use of Python threading to create a web spider, the spider operates as a series of threads to check links. When I run this app using the django test server (built in), the app runs fine and the threads seem to start and stop on time. However, running the app on Apache it seems the...
[ "Most likely, you are missing the creation of new processes. Apache will not run in a single process, but fork new processes for requests every now and then (depending on a dozen or so configuration parameters). If you run django in each process, they will share no memory, and the results produced in one worker won...
[ 3 ]
[]
[]
[ "apache", "django", "multithreading", "python" ]
stackoverflow_0000364358_apache_django_multithreading_python.txt
Q: MVC and django fundamentals Pretty new to this scene and trying to find some documentation to adopt best practices. We're building a fairly large content site which will consist of various media catalogs and I'm trying to find some comparable data / architectural models so that we can get a better idea of the app...
MVC and django fundamentals
Pretty new to this scene and trying to find some documentation to adopt best practices. We're building a fairly large content site which will consist of various media catalogs and I'm trying to find some comparable data / architectural models so that we can get a better idea of the approach we should use using a frame...
[ "\"data / architectural models so that we can get a better idea of the approach we should use using a framework we've never made use of before\"\nDjango imposes best practices on you. You don't have a lot of choices and can't make a lot of mistakes.\nMVC (while a noble aspiration) is implemented as follows:\n\nDat...
[ 16, 5, 0 ]
[]
[]
[ "django", "django_models", "django_templates", "python" ]
stackoverflow_0000364015_django_django_models_django_templates_python.txt
Q: Can I use chart modules with wxpython? Is it possible to use any chart modules with wxpython? And are there any good ones out there? I'm thinking of the likes of PyCha (http://www.lorenzogil.com/projects/pycha/) or any equivalent. Many modules seem to require PyCairo, but I can't figure out if I can use those with...
Can I use chart modules with wxpython?
Is it possible to use any chart modules with wxpython? And are there any good ones out there? I'm thinking of the likes of PyCha (http://www.lorenzogil.com/projects/pycha/) or any equivalent. Many modules seem to require PyCairo, but I can't figure out if I can use those with my wxpython app. My app has a notebook pane...
[ "I recently revisited matplotlib, and am pretty happy with the results.\nIf you're on windows, there are windows installers available to make your installation process a little less painful.\nOne potential drawback though is that it requires numpy to be installed.\nI don't have experience with the interactivity of ...
[ 3, 1, 1 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0000358189_python_wxpython.txt
Q: Detect windows logout in Python How can I detect, or be notified, when windows is logging out in python? Edit: Martin v. Lรถwis' answer is good, and works for a full logout but it does not work for a 'fast user switching' event like pressing win+L which is what I really need it for. Edit: im not using a gui this is...
Detect windows logout in Python
How can I detect, or be notified, when windows is logging out in python? Edit: Martin v. Lรถwis' answer is good, and works for a full logout but it does not work for a 'fast user switching' event like pressing win+L which is what I really need it for. Edit: im not using a gui this is running as a service
[ "You can detect fast user switching events using the Terminal Services API, which you can access from Python using the win32ts module from pywin32. In a GUI application, call WTSRegisterSessionNotification to receive notification messages, WTSUnRegisterSessionNotification to stop receiving notifications, and handle...
[ 6, 3 ]
[]
[]
[ "python", "winapi" ]
stackoverflow_0000365058_python_winapi.txt
Q: run a function in another function in N times I have ask this kind of question before, but it seems my previous question is a bit misleading due to my poor English. I'm asking again to make clear. I am really confused about it. Thanks in advance. Suppose I have a function A for generating the state of a cell in a ...
run a function in another function in N times
I have ask this kind of question before, but it seems my previous question is a bit misleading due to my poor English. I'm asking again to make clear. I am really confused about it. Thanks in advance. Suppose I have a function A for generating the state of a cell in a certain rule, and I have another function which gen...
[ "def 1st_funtion(a_matrixA)\n #apply some rule on a_matrixA and return a new matrix(next state of the cell)\n return new_matrix\n\ndef 2nd_funtion(a_matrixB,repeat_times)\n\n for i in range(repeat_times):\n a_matrixB = 1st_funtion(a_matrixB)\n return a_matrixB\n\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0000365384_python.txt
Q: how to determine the period of a function if i have a function A,which can apply a certain rule on a given matrix to generate a another matrix which i call it the next state of the origin matrix,also the function can determine the the final state of the matrix by given times N(apply the rule on origin,and apply th...
how to determine the period of a function
if i have a function A,which can apply a certain rule on a given matrix to generate a another matrix which i call it the next state of the origin matrix,also the function can determine the the final state of the matrix by given times N(apply the rule on origin,and apply the rule on the next state of the origin matrix a...
[ "Use a for loop, or a while loop with a temporary result and a counter. The latter method is most efficient (in general).\nSimple version, in pseudocode:\niterations = 0;\ntmp = origin_matrix;\n\ndo\n tmp = operation(tmp);\n iterations += 1;\nwhile tmp != origin_matrix;\n\nreturn iterations;\n\nEDIT: You can...
[ 6 ]
[]
[]
[ "math", "python" ]
stackoverflow_0000365924_math_python.txt
Q: How to truncate matrix using NumPy (Python) just a quick question, if I have a matrix has n rows and m columns, how can I cut off the 4 sides of the matrix and return a new matrix? (the new matrix would have n-2 rows m-2 columns). Thanks in advance A: a[1:-1, 1:-1] A: A more general answer is: a[[slice(1, -1) ...
How to truncate matrix using NumPy (Python)
just a quick question, if I have a matrix has n rows and m columns, how can I cut off the 4 sides of the matrix and return a new matrix? (the new matrix would have n-2 rows m-2 columns). Thanks in advance
[ "a[1:-1, 1:-1]\n\n", "A more general answer is:\na[[slice(1, -1) for _ in a.shape]]\n\n" ]
[ 18, 5 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0000365395_numpy_python.txt
Q: Tracking redirects and cookies with Python I would like to do be able to follow and track redirects and the cookies that are set by the different webpages with Python (a bit like the tamper plugin for Firefox). So if website1 redirects to website2 which then redirects to website3, I would like to follow that and a...
Tracking redirects and cookies with Python
I would like to do be able to follow and track redirects and the cookies that are set by the different webpages with Python (a bit like the tamper plugin for Firefox). So if website1 redirects to website2 which then redirects to website3, I would like to follow that and also see what cookies each website sets. I have b...
[ "there are detailed turorial on this.\nIn dive into python and in voidspace. The short version is that urllib2 provide handlers (That you can override ) to control redirects and cookies.\n" ]
[ 2 ]
[]
[]
[ "python", "redirect", "urllib2" ]
stackoverflow_0000366037_python_redirect_urllib2.txt
Q: how to browse to a external url from turbogears/cherrypy application? I am writing a tinyurl clone to learn turbogears. I am wondering how do i redirect my browser to the external website (say www.yahoo.com) from my cherrypy/turbogears app? I googled about it, but could not find much useful info. A: Just raise a...
how to browse to a external url from turbogears/cherrypy application?
I am writing a tinyurl clone to learn turbogears. I am wondering how do i redirect my browser to the external website (say www.yahoo.com) from my cherrypy/turbogears app? I googled about it, but could not find much useful info.
[ "Just raise a HTTPRedirect exception, which lives in the cherrypy namespace. Like this:\nraise cherrypy.HTTPRedirect(\"http://www.yahoo.com\")\n\n" ]
[ 2 ]
[]
[]
[ "cherrypy", "python", "turbogears", "url_routing" ]
stackoverflow_0000366421_cherrypy_python_turbogears_url_routing.txt
Q: long <-> str binary conversion Is there any lib that convert very long numbers to string just copying the data? These one-liners are too slow: def xlong(s): return sum([ord(c) << e*8 for e,c in enumerate(s)]) def xstr(x): return chr(x&255) + xstr(x >> 8) if x else '' print xlong('abcd'*1024) % 666 print ...
long <-> str binary conversion
Is there any lib that convert very long numbers to string just copying the data? These one-liners are too slow: def xlong(s): return sum([ord(c) << e*8 for e,c in enumerate(s)]) def xstr(x): return chr(x&255) + xstr(x >> 8) if x else '' print xlong('abcd'*1024) % 666 print xstr(13**666)
[ "You want the struct module.\npacked = struct.pack('l', 123456)\nassert struct.unpack('l', packed)[0] == 123456\n\n", "How about\nfrom binascii import hexlify, unhexlify\n\ndef xstr(x):\n hex = '%x' % x\n return unhexlify('0'*(len(hex)%2) + hex)[::-1]\n\ndef xlong(s):\n return int(hexlify(s[::-1]), 16)\n...
[ 4, 2, 2, 1, 0 ]
[ "Performance of cPickle vs. marshal (Python 2.5.2, Windows):\npython -mtimeit -s\"from cPickle import loads,dumps;d=13**666\" \"loads(dumps(d))\"\n1000 loops, best of 3: 600 usec per loop\n\npython -mtimeit -s\"from marshal import loads,dumps;d=13**666\" \"loads(dumps(d))\"\n100000 loops, best of 3: 7.79 usec per l...
[ -1 ]
[ "bignum", "python", "string" ]
stackoverflow_0000328964_bignum_python_string.txt
Q: Beginner looking for beautiful and instructional Python code As a complete beginner with no programming experience, I am trying to find beautiful Python code to study and play with. Please answer by pointing to a website, a book or some software project. I have the following criterias: complete code listings (wor...
Beginner looking for beautiful and instructional Python code
As a complete beginner with no programming experience, I am trying to find beautiful Python code to study and play with. Please answer by pointing to a website, a book or some software project. I have the following criterias: complete code listings (working, hackable code) beautiful code (highly readable, simple but e...
[ "Buy Programming Collective Intelligence. Great book of interesting AI algorithms based on mining data and all of the examples are in very easy to read Python.\nThe other great book is Text Processing in Python\n", "Read the Python libraries themselves. They're working, hackable, elegant, and instructional. Som...
[ 19, 7, 5, 4, 2, 1, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000125019_python.txt
Q: No print output from child multiprocessing.Process unless the program crashes I am having trouble with the Python multiprocessing module. I am using the Process class to spawn a new process in order to utilize my second core. This second process loads a bunch of data into RAM and then waits patiently instead of co...
No print output from child multiprocessing.Process unless the program crashes
I am having trouble with the Python multiprocessing module. I am using the Process class to spawn a new process in order to utilize my second core. This second process loads a bunch of data into RAM and then waits patiently instead of consuming. I wanted to see what that process printed with the print command, however...
[ "Have you tried flushing stdout?\nimport sys\nprint \"foo\"\nsys.stdout.flush()\n\n" ]
[ 26 ]
[]
[]
[ "io", "multiprocessing", "multithreading", "python" ]
stackoverflow_0000367053_io_multiprocessing_multithreading_python.txt
Q: best way to print data in columnar format? I am using Python to read in data in a user-unfriendly format and transform it into an easier-to-read format. The records I am outputting are usually going to be just a last name, first name, and room code. I I would like to output a series of pages, each containing a c...
best way to print data in columnar format?
I am using Python to read in data in a user-unfriendly format and transform it into an easier-to-read format. The records I am outputting are usually going to be just a last name, first name, and room code. I I would like to output a series of pages, each containing a contiguous subset of the total records, divided i...
[ "\"If I knew for certain that the printable area of the paper would hold 20 records vertically and five horizontally\"\nYou do know that.\nYou know the size of your paper. You know the size of your font. You can easily do the math.\n\"almost certainly limited to HTML...\" doesn't make much sense. Is this a web a...
[ 3 ]
[]
[]
[ "css", "formatting", "html", "python" ]
stackoverflow_0000365601_css_formatting_html_python.txt
Q: Ruby timeout for Python? Does anyone know a good solution for implementing a function similar to Ruby's timeout in Python? I've googled it and didn't really see anything very good. Thanks for the help. Here's a link to the Ruby documentation http://www.ruby-doc.org/stdlib/libdoc/timeout/rdoc/index.html A: def ...
Ruby timeout for Python?
Does anyone know a good solution for implementing a function similar to Ruby's timeout in Python? I've googled it and didn't really see anything very good. Thanks for the help. Here's a link to the Ruby documentation http://www.ruby-doc.org/stdlib/libdoc/timeout/rdoc/index.html
[ "def timeout(func, args=(), kwargs={}, timeout_duration=1, default=None):\n import threading\n class InterruptableThread(threading.Thread):\n def __init__(self):\n threading.Thread.__init__(self)\n self.result = None\n\n def run(self):\n try:\n sel...
[ 2 ]
[]
[]
[ "python", "ruby", "timeout" ]
stackoverflow_0000367562_python_ruby_timeout.txt
Q: Setting up a foreign key to an abstract base class with Django I've factored out common attributes from two classes into an abstract base class, however I have another model that needs to reference either one of those classes. It's not possible to reference an ABC as it doesn't actually have a database table. The ...
Setting up a foreign key to an abstract base class with Django
I've factored out common attributes from two classes into an abstract base class, however I have another model that needs to reference either one of those classes. It's not possible to reference an ABC as it doesn't actually have a database table. The following example should illustrate my problem: class Answer(models....
[ "A generic relation seems to be the solution. But it will complicate things even further.\nIt seems to me; your model structure is already more complex than necessary. I would simply merge all three Answer models into one. This way:\n\nAnswer_Risk would work without modification.\nYou can set resident to None (NULL...
[ 18, 8 ]
[]
[]
[ "django", "django_models", "inheritance", "python" ]
stackoverflow_0000367461_django_django_models_inheritance_python.txt
Q: Application configuration incorrect with Python Imaging Library I'm trying to install the Python Imaging Library 1.1.6 for Python 2.6. After downloading the installation executable (Win XP), I receive the following error message: "Application failed to start because the application configuration is incorrect. Rei...
Application configuration incorrect with Python Imaging Library
I'm trying to install the Python Imaging Library 1.1.6 for Python 2.6. After downloading the installation executable (Win XP), I receive the following error message: "Application failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem" Any thoughts on what I...
[ "It looks like an SxS (\"side-by-side\") issue. Probably the runtime libraries PIL is linked against are missing. Try installing a redistributable package of a compiler which was used to build PIL.\nMSVC 2005 redist\nMSVC 2008 redist\n", "Install Python \"for all users\", not \"just for me\".\n", "I got that sa...
[ 3, 1, 0 ]
[ "I am shooting in the dark: could it be this?\n" ]
[ -1 ]
[ "image_processing", "python" ]
stackoverflow_0000321668_image_processing_python.txt
Q: Making a virtual package available via sys.modules Say I have a package "mylibrary". I want to make "mylibrary.config" available for import, either as a dynamically created module, or a module imported from an entirely different place that would then basically be "mounted" inside the "mylibrary" namespace. I.e., I...
Making a virtual package available via sys.modules
Say I have a package "mylibrary". I want to make "mylibrary.config" available for import, either as a dynamically created module, or a module imported from an entirely different place that would then basically be "mounted" inside the "mylibrary" namespace. I.e., I do: import sys, types sys.modules['mylibrary.config'] =...
[ "You need to monkey-patch the module not only into sys.modules, but also into its parent module:\n>>> import sys,types,xml\n>>> xml.config = sys.modules['xml.config'] = types.ModuleType('xml.config')\n>>> import xml.config\n>>> from xml import config\n>>> from xml import config as x\n>>> x\n<module 'xml.config' (bu...
[ 14, 2, 1 ]
[]
[]
[ "import", "module", "python" ]
stackoverflow_0000368057_import_module_python.txt
Q: How to expose std::vector as a Python list using SWIG? I'm trying to expose this function to Python using SWIG: std::vector<int> get_match_stats(); And I want SWIG to generate wrapping code for Python so I can see it as a list of integers. Adding this to the .i file: %include "typemaps.i" %include "std_vector.i"...
How to expose std::vector as a Python list using SWIG?
I'm trying to expose this function to Python using SWIG: std::vector<int> get_match_stats(); And I want SWIG to generate wrapping code for Python so I can see it as a list of integers. Adding this to the .i file: %include "typemaps.i" %include "std_vector.i" namespace std { %template(IntVector) vector<int>; } I'm...
[ "%template(IntVector) vector<int>;\n\n", "I don't have much experience with Swig, but are you #including your C++ header file in your .i file? Try one (or both) of\n%include \"myvector.h\"\n\n\n%{\n# include \"myvector.h\"\n%}\n\n" ]
[ 14, 0 ]
[]
[]
[ "c++", "python", "stl", "swig" ]
stackoverflow_0000276769_c++_python_stl_swig.txt
Q: Python regex to parse into a 2D array I have a string like this that I need to parse into a 2D array: str = "'813702104[813702106]','813702141[813702143]','813702172[813702174]'" the array equiv would be: arr[0][0] = 813702104 arr[0][1] = 813702106 arr[1][0] = 813702141 arr[1][1] = 813702143 #... etc ... I'm tr...
Python regex to parse into a 2D array
I have a string like this that I need to parse into a 2D array: str = "'813702104[813702106]','813702141[813702143]','813702172[813702174]'" the array equiv would be: arr[0][0] = 813702104 arr[0][1] = 813702106 arr[1][0] = 813702141 arr[1][1] = 813702143 #... etc ... I'm trying to do this by REGEX. The string above ...
[ "I would try findall or finditer instead of match.\nEdit by Oli: Yeah findall work brilliantly but I had to simplify the regex to:\nr\"'(?P<main>\\d+)\\[(?P<thumb>\\d+)\\]',?\"\n\n", "I think I will not go for regex for this task. Python list comprehension is quite powerful for this\nIn [27]: s = \"'813702104[813...
[ 5, 3, 1, 1, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0000346267_python_regex.txt
Q: Python: os.environ.get('SSH_ORIGINAL_COMMAND') returns None Trying to follow a technique found at bzr and gitosis I did the following: added to ~/.ssh/authorized_keys the command="my_parser" parameter which point to a python script file named 'my_parser' and located in /usr/local/bin (file was chmoded as 777) in...
Python: os.environ.get('SSH_ORIGINAL_COMMAND') returns None
Trying to follow a technique found at bzr and gitosis I did the following: added to ~/.ssh/authorized_keys the command="my_parser" parameter which point to a python script file named 'my_parser' and located in /usr/local/bin (file was chmoded as 777) in that script file '/usr/local/bin/my_parser' I got the following ...
[ "$SSH_ORIGINAL_COMMAND is set when you connect to a host with ssh to execute a single command:\n$ ssh username@host 'some command'\n\nYour \"my_parser\" would then return \"some command\".\nUnless you invoke a shell with my_parser, it will then exit, and the connection will close. You can use this to control the en...
[ 1 ]
[]
[]
[ "python", "ssh" ]
stackoverflow_0000369414_python_ssh.txt
Q: Passing a Python array to a C++ vector using Swig I have an array of objects in Python [obj1, obj2, obj3] and I want to pass them to off to a C++ function to perform some computation. I'm using SWIG to write my interface. The class type of the passed object is already defined in C++. What's the best way to do t...
Passing a Python array to a C++ vector using Swig
I have an array of objects in Python [obj1, obj2, obj3] and I want to pass them to off to a C++ function to perform some computation. I'm using SWIG to write my interface. The class type of the passed object is already defined in C++. What's the best way to do this?
[ "It depends on if your function is already written and cannot be changed, in which case you may need to check Swig docs to see if there is already a typemap from PyList to std::vector (I think there is). If not, taking PyObject* as the argument to the function and using the Python C API for manipulating lists shou...
[ 2 ]
[]
[]
[ "c++", "python", "swig" ]
stackoverflow_0000368980_c++_python_swig.txt
Q: email.retr retrieves strange =20 characters when the email body has chinese characters in it self.logger.info(msg) popinstance=poplib.POP3(self.account[0]) self.logger.info(popinstance.getwelcome()) popinstance.user(self.account[1]) popinstance.pass_(self.account[2]) try: (numMsgs, ...
email.retr retrieves strange =20 characters when the email body has chinese characters in it
self.logger.info(msg) popinstance=poplib.POP3(self.account[0]) self.logger.info(popinstance.getwelcome()) popinstance.user(self.account[1]) popinstance.pass_(self.account[2]) try: (numMsgs, totalSize)=popinstance.stat() self.logger.info("POP contains " + str(numMsgs) + " emails")...
[ "It is probably a Space character encoded in quoted-printable\n", "Use the quopri module to decode the string.\n" ]
[ 8, 5 ]
[]
[]
[ "asianfonts", "email", "fonts", "jython", "python" ]
stackoverflow_0000320166_asianfonts_email_fonts_jython_python.txt
Q: using existing rrule to generate a further set of occurrences I have an rrule instance e.g. r = rrule(WEEKLY, byweekday=SA, count=10, dtstart=parse('20081001')) where dtstart and byweekday may change. If I then want to generate the ten dates that follow on from this rrule, what's the best way of doing it? Ca...
using existing rrule to generate a further set of occurrences
I have an rrule instance e.g. r = rrule(WEEKLY, byweekday=SA, count=10, dtstart=parse('20081001')) where dtstart and byweekday may change. If I then want to generate the ten dates that follow on from this rrule, what's the best way of doing it? Can I assign a new value to the _dtstart member of r? That seems to w...
[ "Firstly, r._dtstart = list(r)[-1] will give you the last date in the original sequence of dates. If you use that, without modification, for the beginning of a new sequence, you will end up with a duplicate date, i.e. the last date of the first sequence will be the same as the first date of the new sequence, which ...
[ 1 ]
[]
[]
[ "python", "python_dateutil" ]
stackoverflow_0000369261_python_python_dateutil.txt
Q: How do I put a SQLAlchemy label on the result of an arithmetic expression? How do I translate something like this into SQLAlchemy? select x - y as difference... I know how to do: x.label('foo') ...but I'm not sure where to put the ".label()" method call below: select ([table.c.x - table.c.y], ... A: The Column...
How do I put a SQLAlchemy label on the result of an arithmetic expression?
How do I translate something like this into SQLAlchemy? select x - y as difference... I know how to do: x.label('foo') ...but I'm not sure where to put the ".label()" method call below: select ([table.c.x - table.c.y], ...
[ "The ColumnElement method is just a helper; label() can be used following way:\nselect([sql.expression.label('foo', table.c.x - table.c.y), ...])\n\n" ]
[ 9 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0000370077_python_sqlalchemy.txt
Q: How do I ORDER BY an arithmetic express in SQLAlchemy? How do I translate something like this into SQLAlchemy? SELECT (a * b) - (x + y) / z AS result FROM table ORDER BY result A: Just pass the label in as a string argument to order_by: result_exp = sqlalchemy.sql.expression.label('result', ((test2_table.c.a ...
How do I ORDER BY an arithmetic express in SQLAlchemy?
How do I translate something like this into SQLAlchemy? SELECT (a * b) - (x + y) / z AS result FROM table ORDER BY result
[ "Just pass the label in as a string argument to order_by:\nresult_exp = sqlalchemy.sql.expression.label('result',\n ((test2_table.c.a * test2_table.c.b)\n - (test2_table.c.x + test2_table.c.y)\n / test2_table.c.z))\nselect([result_exp], from_obj=[test2_table], order_by=\"result\")\n\n" ]
[ 3 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0000370160_python_sqlalchemy.txt
Q: String conversion in Python I'm using Python 2.5. The DLL I imported is created using the CLR. The DLL function is returning a string. I'm trying to apply "partition" attribute to it. I'm not able to do it. Even the partition is not working. I think "all strings returned from CLR are returned as Unicode". A: Cou...
String conversion in Python
I'm using Python 2.5. The DLL I imported is created using the CLR. The DLL function is returning a string. I'm trying to apply "partition" attribute to it. I'm not able to do it. Even the partition is not working. I think "all strings returned from CLR are returned as Unicode".
[ "Could you post your error message?\nCould you post what type of object you have (type(yourvar))?\nPlease check if you have a partition(sep) method for this object (dir(yourvar)).\nApplying partition method should look like:\n>>> us=u\"ะŸั€ะธะฒะตั‚, Unicode String!\"\n>>> us.partition(' ')\n(u'\\u041f\\u0440\\u0438\\u043...
[ 2, 1 ]
[]
[]
[ "clr", "python" ]
stackoverflow_0000371155_clr_python.txt
Q: When is white space not important in Python? When is white space not important in Python? It seems to be ignored inside a list, for example: for x in range(5): list += [x, 1 ,2,3, 4,5] A: White space is only important for indentation of statements. You have a single statement across several lines, and ...
When is white space not important in Python?
When is white space not important in Python? It seems to be ignored inside a list, for example: for x in range(5): list += [x, 1 ,2,3, 4,5]
[ "White space is only important for indentation of statements. You have a single statement across several lines, and only the indentation of the beginning of the statement on the first line is significant. See Python: Myths about Indentation for more information.\n", "Your question is really about when Python impl...
[ 14, 7 ]
[]
[]
[ "python", "whitespace" ]
stackoverflow_0000372007_python_whitespace.txt
Q: UTF in Python Regex I'm aware that Python 3 fixes a lot of UTF issues, I am not however able to use Python 3, I am using 2.5.1 I'm trying to regex a document but the document has UTF hyphens in it โ€“ rather than -. Python can't match these and if I put them in the regex it throws a wobbly. How can I force Python to...
UTF in Python Regex
I'm aware that Python 3 fixes a lot of UTF issues, I am not however able to use Python 3, I am using 2.5.1 I'm trying to regex a document but the document has UTF hyphens in it โ€“ rather than -. Python can't match these and if I put them in the regex it throws a wobbly. How can I force Python to use a UTF string or in s...
[ "You have to escape the character in question (โ€“) and put a u in front of the string literal to make it a unicode string. \nSo, for example, this:\nre.compile(\"โ€“\") \n\nbecomes this:\nre.compile(u\"\\u2013\")\n\n", "After a quick test and visit to PEP 0264: Defining Python Source Code Encodings, I see you may ne...
[ 7, 4, 3 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0000372102_python_regex.txt
Q: What's the most pythonic way of testing that inputs are well-formed numbers I have a function that expects real numbers (either integers or floats) as its input, and I'm trying to validate this input before doing mathematical operations on it. My first instinct is to cast inputs as floats from within a try-except ...
What's the most pythonic way of testing that inputs are well-formed numbers
I have a function that expects real numbers (either integers or floats) as its input, and I'm trying to validate this input before doing mathematical operations on it. My first instinct is to cast inputs as floats from within a try-except block. try: myinput = float(input) except: raise ValueError("input is not a...
[ "To quote myself from How much input validation should I be doing on my python functions/methods?:\n\nFor calculations like sum, factorial etc, pythons built-in type checks will do fine. The calculations will end upp calling add, mul etc for the types, and if they break, they will throw the correct exception anyway...
[ 12, 5, 2, 1 ]
[]
[]
[ "idioms", "python" ]
stackoverflow_0000371419_idioms_python.txt
Q: Protecting online static content How would I only allow users authenticated via Python code to access certain files on the server? For instance, say I have /static/book.txt which I want to protect. When a user accesses /some/path/that/validates/him, a Python script deems him worthy of accessing /static/book.txt an...
Protecting online static content
How would I only allow users authenticated via Python code to access certain files on the server? For instance, say I have /static/book.txt which I want to protect. When a user accesses /some/path/that/validates/him, a Python script deems him worthy of accessing /static/book.txt and redirects him to that path. How woul...
[ "Lighttpd has mod_secdownload for this. Basically, it won't serve the static content directly unless you generate a short-lived static URL for it.\nNote that you can do similar things on S3 for static content. It's a quite useful feature.\n", "You might want to just have your Python script open the file and dum...
[ 3, 3 ]
[]
[]
[ "apache", "download", "lighttpd", "python", "security" ]
stackoverflow_0000372465_apache_download_lighttpd_python_security.txt
Q: How can I capture all exceptions from a wxPython application? I'm writing a little debug app for a bit of kit we're developing and I'd like to roll it out to a few users to see if they can provoke any crashes. Does anyone know a way of effectively wrapping a wxPython app to catch any and all unhandled exceptions t...
How can I capture all exceptions from a wxPython application?
I'm writing a little debug app for a bit of kit we're developing and I'd like to roll it out to a few users to see if they can provoke any crashes. Does anyone know a way of effectively wrapping a wxPython app to catch any and all unhandled exceptions that would cause the app to crash? Ideally I'd want to capture all o...
[ "For the exception handling, assuming your log file is opened as log:\nimport sys\nimport traceback\n\ndef excepthook(type, value, tb):\n message = 'Uncaught exception:\\n'\n message += ''.join(traceback.format_exception(type, value, tb))\n log.write(message)\n\nsys.excepthook = excepthook\n\n", "For log...
[ 10, 6, 3, 1 ]
[]
[]
[ "error_handling", "error_reporting", "exception", "python", "wxwidgets" ]
stackoverflow_0000166198_error_handling_error_reporting_exception_python_wxwidgets.txt
Q: What is the object oriented programming computing overhead cost? I have a large set of data (a data cube of 250,000 X 1,000 doubles, about a 4 gig file) and I want to manipulate it using a previous set of OOP classes I have written in Python. Currently the data set is already so large that to read into my machine...
What is the object oriented programming computing overhead cost?
I have a large set of data (a data cube of 250,000 X 1,000 doubles, about a 4 gig file) and I want to manipulate it using a previous set of OOP classes I have written in Python. Currently the data set is already so large that to read into my machine memory I have to at least split it in half so computing overhead is a...
[ "You'd have similar issues with procedural/functional programming languages. How do you store that much data in memory? A struct or array wouldn't work either. \nYou need to take special steps to manage this scale of data.\nBTW: I wouldn't use this as a reason to pick either an OO language or not. \n", "See http:...
[ 3, 3, 3, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "data_analysis", "oop", "python" ]
stackoverflow_0000372511_data_analysis_oop_python.txt
Q: What is the best way to serialize a ModelForm object in Django? I am using Django and the Google Web Toolkit (GWT) for my current project. I would like to pass a ModelForm instance to GWT via an Http response so that I can "chop" it up and render it as I please. My goal is to keep the form in sync with changes to ...
What is the best way to serialize a ModelForm object in Django?
I am using Django and the Google Web Toolkit (GWT) for my current project. I would like to pass a ModelForm instance to GWT via an Http response so that I can "chop" it up and render it as I please. My goal is to keep the form in sync with changes to my models.py file, yet increase control I have over the look of the f...
[ "If you were using pure Django, you'd pass the form to your template, and could then call individual fields on the form for more precise rendering, rather than using ModelForm.to_table. You can use the following to iterate over each field and render it exactly how you want:\n{% for field in form.fields %}\n <di...
[ 2, 0 ]
[]
[]
[ "django", "json", "python", "serialization", "xml" ]
stackoverflow_0000369230_django_json_python_serialization_xml.txt
Q: List all the classes that currently exist I'm creating a simple API that creates typed classes based on JSON data that has a mandatory 'type' field defined in it. It uses this string to define a new type, add the fields in the JSON object, instantiate it, and then populate the fields on the instance. What I want ...
List all the classes that currently exist
I'm creating a simple API that creates typed classes based on JSON data that has a mandatory 'type' field defined in it. It uses this string to define a new type, add the fields in the JSON object, instantiate it, and then populate the fields on the instance. What I want to be able to do is allow for these types to be...
[ "If you want to reuse types that you created earlier, it's best to cache them yourself:\njson_types = {}\ndef get_json_type(name):\n try:\n return json_types[name]\n except KeyError:\n json_types[name] = t = type(json_object['type'], (object,), {})\n # any further initialization of t here\n return t\n...
[ 3, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000373067_python.txt
Q: How to organize python test in a way that I can run all tests in a single command? Currently my code is organized in the following tree structure: src/ module1.py module2.py test_module1.py test_module2.py subpackage1/ __init__.py moduleA.py moduleB.py test_modul...
How to organize python test in a way that I can run all tests in a single command?
Currently my code is organized in the following tree structure: src/ module1.py module2.py test_module1.py test_module2.py subpackage1/ __init__.py moduleA.py moduleB.py test_moduleA.py test_moduleB.py Where the module*.py files contains the source code and t...
[ "Whether you seperate or mix tests and modules is probably a matter of taste, although I would strongly advocate for keeping them apart (setup reasons, code stats etc).\nWhen you're using nosetests, make sure that all directories with tests are real packages:\nsrc/\n module1.py\n module2.py\n subpackage1/\...
[ 16, 8, 6, 2, 0 ]
[]
[]
[ "python", "python_nose", "unit_testing" ]
stackoverflow_0000366720_python_python_nose_unit_testing.txt
Q: Secure, sandboxable user exposed programming language / environment? Beyond offering an API for my website, I'd like to offer users the ability to write simple scripts that would run on my servers . The scripts would have access to objects owned by the user and be able to manipulate, modify, and otherwise process ...
Secure, sandboxable user exposed programming language / environment?
Beyond offering an API for my website, I'd like to offer users the ability to write simple scripts that would run on my servers . The scripts would have access to objects owned by the user and be able to manipulate, modify, and otherwise process their data. I'd like to be able to limit resources taken by these scripts ...
[ "I use Lua for this, but it's directed at a Lua capable community. So my answer would be who are your users?\nIf your users are internal, like my case, and proficient with Python use Python. However if this is something for the world wide web, I'd probably choose javascript, because its the lingua franca, (every de...
[ 2 ]
[]
[]
[ "javascript", "python", "sandbox" ]
stackoverflow_0000373406_javascript_python_sandbox.txt
Q: Getting TRAC to run on IIS7 Im trying to get Trac upp and running on my IIS/w2008 server using this FAQ: TracOnWindowsIisAjp Everything upp until "3. Install Tomcat AJP Connector for IIS" works ok. I then define my directories as : C:\wwwroot\trac.evju.biz\AJP\, in the bin catalog I place the dll file, and 3 confi...
Getting TRAC to run on IIS7
Im trying to get Trac upp and running on my IIS/w2008 server using this FAQ: TracOnWindowsIisAjp Everything upp until "3. Install Tomcat AJP Connector for IIS" works ok. I then define my directories as : C:\wwwroot\trac.evju.biz\AJP\, in the bin catalog I place the dll file, and 3 config files with this content: isapi_...
[ "Just stumbled upon this question from an unrelated Google search. Odd how that happens...\nIIS7 supports FastCGI natively, I'd highly recommend using that over AJP. If you're still watching this question leave a comment and I'll follow up with details of how to install.\n", "@Jeff Mc - I'm actually looking at se...
[ 0, 0 ]
[]
[]
[ "iis", "python", "trac" ]
stackoverflow_0000304567_iis_python_trac.txt
Q: conversion of unicode string in python I need to convert unicode strings in Python to other types such as unsigned and signed int 8 bits,unsigned and signed int 16 bits,unsigned and signed int 32 bits,unsigned and signed int 64 bits,double,float,string,unsigned and signed 8 bit,unsigned and signed 16 bit, unsigned...
conversion of unicode string in python
I need to convert unicode strings in Python to other types such as unsigned and signed int 8 bits,unsigned and signed int 16 bits,unsigned and signed int 32 bits,unsigned and signed int 64 bits,double,float,string,unsigned and signed 8 bit,unsigned and signed 16 bit, unsigned and signed 32 bit,unsigned and signed 64 bi...
[ "use int() to convert the string to an integer. Python doesn't have different fixed-width integers so you'll just get one type of thing out.\nThen use struct to pack the integer into a fixed width:\nres = struct.pack(\"=B\",i) ## uint8_t\nres = struct.pack(\"=b\",i) ## int8_t\n\nres = struct.pack(\"=H\",i) ## uint1...
[ 11 ]
[]
[]
[ "python", "signed", "string", "unicode", "unsigned" ]
stackoverflow_0000374318_python_signed_string_unicode_unsigned.txt
Q: XPath in XmlStream.addObserver doesn't work the way it should What I want to do is to react only on specified root elements. For example, if user sends XmlStream that looks like: <auth> <login>user</login> <pass>dupa.8</pass> </auth> My method ._auth should be executed. I've done it with addObserver metho...
XPath in XmlStream.addObserver doesn't work the way it should
What I want to do is to react only on specified root elements. For example, if user sends XmlStream that looks like: <auth> <login>user</login> <pass>dupa.8</pass> </auth> My method ._auth should be executed. I've done it with addObserver method called inside connectionMade method. self.addObserver("/auth", se...
[ "Ok, finally I got the answer. It's because of XmlStream itself. Connection is active as long as main root element is not closed (for example: <stream/>). Everything inside it is root element for XPath, that's why \"/auth\" means <stream><auth></auth></stream>.\n" ]
[ 1 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0000373189_python_twisted.txt
Q: need help-variable creation in Python I want to create variables as a1,a2,a3...a10. For that I used a for loop. As the variable in loop increments I need to create a variable as above. Can anyone give me an idea? At the time of creation I also need to be able to assign values to them. That's where I'm getting synt...
need help-variable creation in Python
I want to create variables as a1,a2,a3...a10. For that I used a for loop. As the variable in loop increments I need to create a variable as above. Can anyone give me an idea? At the time of creation I also need to be able to assign values to them. That's where I'm getting syntax error.
[ "Usually, we use a list, not a bunch of individual variables.\na = 10*[0]\na[0], a[1], a[2], a[9]\n\n", "Following what S.Lott said, you can also use a dict, if you really nead unique names and that the order of the items is not important:\ndata = {}\nfor i in range(0, 10):\n data['a%d' % i] = i\n\n>>>data\n{'a1...
[ 13, 4, 2 ]
[ "You can use the exec function:\nfor i in range(0,10):\n exec(\"a%d=%d\" % (i,i))\n\nNot very pythonic way of doing things.\n" ]
[ -1 ]
[ "python", "variables" ]
stackoverflow_0000374572_python_variables.txt
Q: How do you test a file.read() error in Python? I have the following code (adapted from an example given in Dive Into Python) that reads the entire contents of a file into a buffer. buffer = "" try: file = open(postFileName, 'rU') try: # Read the entire POST log file into a buffer buffer +=...
How do you test a file.read() error in Python?
I have the following code (adapted from an example given in Dive Into Python) that reads the entire contents of a file into a buffer. buffer = "" try: file = open(postFileName, 'rU') try: # Read the entire POST log file into a buffer buffer += file.read() finally: file.close() excep...
[ "I find that finally blocks are often overused. The file close (and a few other similar patterns) are so important that Python 3.0 will have a with statement just to cover this base in a slightly less obscure way.\n\nDo I need an except with a finally? \nThat hits on the confusing nature of this specific example, ...
[ 7, 3, 0 ]
[]
[]
[ "error_handling", "file_io", "python" ]
stackoverflow_0000374768_error_handling_file_io_python.txt
Q: Should I use get_/set_ prefixes in Python method names? In Python properties are used instead of the Java-style getters, setters. So one rarely sees get... or set.. methods in the public interfaces of classes. But in cases were a property is not appropriate one might still end up with methods that behave like gett...
Should I use get_/set_ prefixes in Python method names?
In Python properties are used instead of the Java-style getters, setters. So one rarely sees get... or set.. methods in the public interfaces of classes. But in cases were a property is not appropriate one might still end up with methods that behave like getters or setters. Now my questions: Should these method names s...
[ "You won't ever loose the chance to make your property behave like a getter/setter later by using descriptors. If you want to change a property to be read only you can also replace it with a getter method with the same name as the property and decorate it with @property. So my advice is to avoid getters/setters unl...
[ 7, 5, 4, 1, 0 ]
[]
[]
[ "coding_style", "python" ]
stackoverflow_0000374763_coding_style_python.txt
Q: Prevent ftplib from Downloading a File in Progress? We have a ftp system setup to monitor/download from remote ftp servers that are not under our control. The script connects to the remote ftp, and grabs the file names of files on the server, we then check to see if its something that has already been downloaded. ...
Prevent ftplib from Downloading a File in Progress?
We have a ftp system setup to monitor/download from remote ftp servers that are not under our control. The script connects to the remote ftp, and grabs the file names of files on the server, we then check to see if its something that has already been downloaded. If it hasn't been downloaded then we download the file an...
[ "โ€œDamn the torpedoes! Full speed ahead!โ€\nJust download the file. If it is a large file then after the download completes wait as long as is reasonable for your scenario and continue the download from the point it stopped. Repeat until there is no more stuff to download.\n", "You can't know when the OS copy is do...
[ 5, 0, 0, 0 ]
[]
[]
[ "ftp", "ftplib", "python" ]
stackoverflow_0000375620_ftp_ftplib_python.txt
Q: Programmatic mail-merge style data injection into existing Excel spreadsheets? I'd like to automate data entry into Excel spreadsheets. User data will exist on a web site, and when the user requests it, that data will need to be injected into an Excel spreadsheet. The complication is that the format of the Excel s...
Programmatic mail-merge style data injection into existing Excel spreadsheets?
I'd like to automate data entry into Excel spreadsheets. User data will exist on a web site, and when the user requests it, that data will need to be injected into an Excel spreadsheet. The complication is that the format of the Excel spreadsheet can vary significantly between users - it'll be user defined. I've been t...
[ "jXLS is maybe an option. You define an XLS file as a template and then you merge your data. \nQuick overview here\nhttp://jxls.sourceforge.net/\n", "WinHttpRequest (http://msdn.microsoft.com/en-us/library/aa384045(VS.85).aspx) may suit, you can use the document and so forth. Here is a snippet from the link. \nD...
[ 2, 1, 0 ]
[]
[]
[ "excel", "java", "python" ]
stackoverflow_0000376221_excel_java_python.txt
Q: Stackless python and multicores? So, I'm toying around with Stackless Python and a question popped up in my head, maybe this is "assumed" or "common" knowledge, but I couldn't find it actually written anywhere on the stackless site. Does Stackless Python take advantage of multicore CPUs? In normal Python you have ...
Stackless python and multicores?
So, I'm toying around with Stackless Python and a question popped up in my head, maybe this is "assumed" or "common" knowledge, but I couldn't find it actually written anywhere on the stackless site. Does Stackless Python take advantage of multicore CPUs? In normal Python you have the GIL being constantly present and t...
[ "Stackless python does not make use of any kind of multi-core environment it runs on.\nThis is a common misconception about Stackless, as it allows the programmer to take advantage of thread-based programming. For many people these two are closely intertwined, but are, in fact two separate things.\nInternally Stack...
[ 41 ]
[]
[]
[ "concurrency", "multicore", "multithreading", "python", "python_stackless" ]
stackoverflow_0000377254_concurrency_multicore_multithreading_python_python_stackless.txt
Q: Code not waiting for class initialization! I have a block of code that basically intializes several classes, but they are placed in a sequential order, as later ones reference early ones. For some reason the last one initializes before the first one...it seems to me there is some sort of threading going on. What I...
Code not waiting for class initialization!
I have a block of code that basically intializes several classes, but they are placed in a sequential order, as later ones reference early ones. For some reason the last one initializes before the first one...it seems to me there is some sort of threading going on. What I need to know is how can I stop it from doing th...
[ "Python upto 3.0 has a global lock, so everything is running in a single thread and in sequence.\nMy guess is that some side effect initializes the last class from a different place than you expect. Throw an exception in __init__ of that last class to see where it gets called.\n", "Spaces vs. Tabs issue...ugh. >....
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000377362_python.txt
Q: OOP and MVC programming style I'm writing some data analysis software and decided to use such approach: epn: model/data.py <- Model definition model/reader.py <- How to read data into model view/gui.py <- main gui frame (wx) view/dialogs.py <- different dialogs (wx) epn.py <- controller For communication between g...
OOP and MVC programming style
I'm writing some data analysis software and decided to use such approach: epn: model/data.py <- Model definition model/reader.py <- How to read data into model view/gui.py <- main gui frame (wx) view/dialogs.py <- different dialogs (wx) epn.py <- controller For communication between gui and data I used wx.lib.pubsub. S...
[ "Example 1: \"better (shorter, encapsulated, more error-proof)\"\nNot really.\n\nThe example 1 function call is no shorter than example 2; you have to set the instance variables before calling the function instead of passing the values as arguments. It's the same code.\n\nThe example 1 function call is no more enc...
[ 3 ]
[]
[]
[ "coding_style", "model_view_controller", "oop", "python" ]
stackoverflow_0000377337_coding_style_model_view_controller_oop_python.txt
Q: Python, Regular Expression Postcode search I am trying to use regular expressions to find a UK postcode within a string. I have got the regular expression working inside RegexBuddy, see below: \b[A-Z]{1,2}[0-9][A-Z0-9]? [0-9][ABD-HJLNP-UW-Z]{2}\b I have a bunch of addresses and want to grab the postcode from them...
Python, Regular Expression Postcode search
I am trying to use regular expressions to find a UK postcode within a string. I have got the regular expression working inside RegexBuddy, see below: \b[A-Z]{1,2}[0-9][A-Z0-9]? [0-9][ABD-HJLNP-UW-Z]{2}\b I have a bunch of addresses and want to grab the postcode from them, example below: 123 Some Road Name Town, City ...
[ "repeating your address 3 times with postcode PA23 6NH, PA2 6NH and PA2Q 6NH as test for you pattern and using the regex from wikipedia against yours, the code is..\nimport re\n\ns=\"123 Some Road Name\\nTown, City\\nCounty\\nPA23 6NH\\n123 Some Road Name\\nTown, City\"\\\n \"County\\nPA2 6NH\\n123 Some Road Nam...
[ 10, 0, 0 ]
[]
[]
[ "postal_code", "python", "regex" ]
stackoverflow_0000378157_postal_code_python_regex.txt
Q: Problem sub-classing BaseException in Python I wanted to create my own Python exception class, like this: class MyException(BaseException): def __init__(self, errno, address): if errno == 10048: mess = str(address) + ' is already in use' else: mess = 'Unable to open ' + ...
Problem sub-classing BaseException in Python
I wanted to create my own Python exception class, like this: class MyException(BaseException): def __init__(self, errno, address): if errno == 10048: mess = str(address) + ' is already in use' else: mess = 'Unable to open ' + str(address) BaseException.__init__(mess) ...
[ "You have to call the method of the base class with the instance as the first argument:\nBaseException.__init__(self, mess)\n\nTo quote from the tutorial:\n\nAn overriding method in a derived class may in fact want to extend rather than simply replace the base class method of the same name. There is a simple way to...
[ 10, 6 ]
[]
[]
[ "exception", "inheritance", "python" ]
stackoverflow_0000378493_exception_inheritance_python.txt
Q: Keeping GUIs responsive during long-running tasks Keeping the GUI responsive while the application does some CPU-heavy processing is one of the challenges of effective GUI programming. Here's a good discussion of how to do this in wxPython. To summarize, there are 3 ways: Use threads Use wxYield Chunk the work an...
Keeping GUIs responsive during long-running tasks
Keeping the GUI responsive while the application does some CPU-heavy processing is one of the challenges of effective GUI programming. Here's a good discussion of how to do this in wxPython. To summarize, there are 3 ways: Use threads Use wxYield Chunk the work and do it in the IDLE event handler Which method have yo...
[ "Threads. They're what I always go for because you can do it in every framework you need. \nAnd once you're used to multi-threading and parallel processing in one language/framework, you're good on all frameworks.\n", "Definitely threads. Why? The future is multi-core. Almost any new CPU has more than one core or...
[ 15, 7, 2, 1, 1, 0, 0, 0, 0 ]
[]
[]
[ "python", "user_interface", "wxpython" ]
stackoverflow_0000148963_python_user_interface_wxpython.txt
Q: Is there a python library for editing msword doc files? Possible Duplicate: Reading/Writing MS Word files in Python I know there are some libraries for editing excel files but is there anything for editing msword 97/2000/2003 .doc files in python? Ideally I'd like to make some minor changes to the formatting of ...
Is there a python library for editing msword doc files?
Possible Duplicate: Reading/Writing MS Word files in Python I know there are some libraries for editing excel files but is there anything for editing msword 97/2000/2003 .doc files in python? Ideally I'd like to make some minor changes to the formatting of the text based on the contents of the text. A really trivial...
[ "Why not look at using python-uno to load the document into OpenOffice and manipulate it using the UNO interface. There is some example code on the site I just linked to which can get you started.\n", "If platform independence is important, then I'd recommend using the OpenOffice API either through BASIC or Pytho...
[ 4, 3, 1, 1 ]
[]
[]
[ "ms_word", "python" ]
stackoverflow_0000376161_ms_word_python.txt
Q: What does the []-esque decorator syntax in Python mean? Here's a snippet of code from within TurboGears 1.0.6: [dispatch.generic(MultiorderGenericFunction)] def run_with_transaction(func, *args, **kw): pass I can't figure out how putting a list before a function definition can possibly affect it. In dispatch....
What does the []-esque decorator syntax in Python mean?
Here's a snippet of code from within TurboGears 1.0.6: [dispatch.generic(MultiorderGenericFunction)] def run_with_transaction(func, *args, **kw): pass I can't figure out how putting a list before a function definition can possibly affect it. In dispatch.generic's docstring, it mentions: Note that when using older...
[ "The decorator syntax is provided by PyProtocols.\n\"\"\"\nFinally, it's important to note that these \"magic\" decorators use a very sneaky hack: they abuse the sys.settrace() debugger hook to track whether assignments are taking place. Guido takes a very dim view of this, but the hook's existing functionality isn...
[ 11 ]
[ "Nothing mysterious, it's just how syntax was before.\nThe parser has changed, probably because the Python Zen claims that \"In the face of ambiguity, refuse the temptation to guess.\". \n[] should be for list only, and there is it.\n" ]
[ -2 ]
[ "decorator", "python", "syntax" ]
stackoverflow_0000379291_decorator_python_syntax.txt
Q: Idiomatic asynchronous design Are there any sorts of useful idioms I can make use of when writing an API that is asynchronous? I would like to standardize on something as I seem to be using a few different styles throughout. It seems hard to make asynchronous code simple; I suppose this is because asynchronous ope...
Idiomatic asynchronous design
Are there any sorts of useful idioms I can make use of when writing an API that is asynchronous? I would like to standardize on something as I seem to be using a few different styles throughout. It seems hard to make asynchronous code simple; I suppose this is because asynchronous operations are anything but. At the mo...
[ "You may want to look at Python Twisted. It is a nice Reactor based API that supports asynchronous operations. Proactor is the common term for asynchronous completion handler like frameworks.\n", "Also have a look at the Asynchronous Completion Token and ActiveObject patterns.\n", "This sounds like the Observer...
[ 4, 2, 2 ]
[]
[]
[ "asynchronous", "python" ]
stackoverflow_0000378564_asynchronous_python.txt
Q: How much slower is a wxWidget written in Python versus C++? I'm looking into writing a wxWidget that displays a graphical node network, and therefore does a lot of drawing operations. I know that using Python to do it is going to be slower, but I'd rather get it working and port it later when its functional. Ide...
How much slower is a wxWidget written in Python versus C++?
I'm looking into writing a wxWidget that displays a graphical node network, and therefore does a lot of drawing operations. I know that using Python to do it is going to be slower, but I'd rather get it working and port it later when its functional. Ideally, if the performance hit isn't too great, I'd prefer to keep ...
[ "IMHO, main bottleneck will be the data structures you are going to use for representing the network graph. I have coded a similar application for tracing dependencies between various component versions in a system and graphics was the last thing I had to worry about and I was certainly drawing more than 500 object...
[ 1, 1, 1 ]
[]
[]
[ "c++", "drawing", "performance", "python", "wxpython" ]
stackoverflow_0000379442_c++_drawing_performance_python_wxpython.txt
Q: How do you make a class attribute that isn't a standard data type? I have one class that needs to grab an attribute that is set in another. It's not a standard data type though. Here's the code; class graphics: def __init__(self, Fullscreen = False, Width = 640, Height = 480): print "Graphics Init" SCREEN_...
How do you make a class attribute that isn't a standard data type?
I have one class that needs to grab an attribute that is set in another. It's not a standard data type though. Here's the code; class graphics: def __init__(self, Fullscreen = False, Width = 640, Height = 480): print "Graphics Init" SCREEN_SIZE = (Width, Height) pygame.init() if Fullscreen: self...
[ "I'm thinking that a short explanation of the difference between class and instance attributes in Python might be helpful to you.\nWhen you write code like so:\nclass Graphics:\n screen_size = (1024, 768)\n\nThe class Graphics is actually an object itself -- a class object. Because you defined screen_size inside...
[ 1, 0, 0, 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0000379995_pygame_python.txt
Q: What are these tags @ivar @param and @type in python docstring? The ampoule project uses some tags in docstring, like the javadoc ones. For example from pool.py line 86: def start(self, ampChild=None): """ Starts the ProcessPool with a given child protocol. @param ampChild: a L{ampoule.child.AMPChild...
What are these tags @ivar @param and @type in python docstring?
The ampoule project uses some tags in docstring, like the javadoc ones. For example from pool.py line 86: def start(self, ampChild=None): """ Starts the ProcessPool with a given child protocol. @param ampChild: a L{ampoule.child.AMPChild} subclass. @type ampChild: L{ampoule.child.AMPChild} subclass ...
[ "Just for fun I'll note that the Python standard library is using Sphinx/reStructuredText, whose info field lists are similar.\ndef start(self, ampChild=None):\n \"\"\"Starts the ProcessPool with a given child protocol.\n\n :param ampChild: a :class:`ampoule.child.AMPChild` subclass.\n :type ampChild: :cla...
[ 15, 14 ]
[]
[]
[ "documentation", "javadoc", "python" ]
stackoverflow_0000379346_documentation_javadoc_python.txt
Q: How to set and preserve minimal width? I use some wx.ListCtrl classes in wx.LC_REPORT mode, augmented with ListCtrlAutoWidthMixin. The problem is: When user double clicks the column divider (to auto resize column), column width is set to match the width of contents. This is done by the wx library and resizes colum...
How to set and preserve minimal width?
I use some wx.ListCtrl classes in wx.LC_REPORT mode, augmented with ListCtrlAutoWidthMixin. The problem is: When user double clicks the column divider (to auto resize column), column width is set to match the width of contents. This is done by the wx library and resizes column to just few pixels when the control is emp...
[ "Honestly, I've stopped using the native wx.ListCtrl in favor of using ObjectListView. There is a little bit of a learning curve, but there are lots of examples. This would be of interest to your question.\n", "Ok, after some struggle I got working workaround for that. It is ugly from design point of view, but ...
[ 3, 1 ]
[]
[]
[ "listctrl", "python", "wxpython", "wxwidgets" ]
stackoverflow_0000377204_listctrl_python_wxpython_wxwidgets.txt
Q: Get psyco speedup on x64 architecture? Is there a way to get the same sort of speedup on x64 architecture as you can get from psyco on 32 bit processors? A: No, unfortunately, Psyco only runs on 32-bit x86 right now.
Get psyco speedup on x64 architecture?
Is there a way to get the same sort of speedup on x64 architecture as you can get from psyco on 32 bit processors?
[ "No, unfortunately, Psyco only runs on 32-bit x86 right now.\n" ]
[ 5 ]
[]
[]
[ "psyco", "python" ]
stackoverflow_0000381479_psyco_python.txt
Q: Python GTK MVC: Kiwi? I've been looking around for a good MVC framework for Python using PyGTK. I've looked at Kiwi but found it a bit lacking, especially with using the Gazpacho Glade-replacement. Are there any other nice desktop Python MVC frameworks? I'm one of the few (it seems) to not want a webapp. A: In ...
Python GTK MVC: Kiwi?
I've been looking around for a good MVC framework for Python using PyGTK. I've looked at Kiwi but found it a bit lacking, especially with using the Gazpacho Glade-replacement. Are there any other nice desktop Python MVC frameworks? I'm one of the few (it seems) to not want a webapp.
[ "In defense of Kiwi:\n\nKiwi works fine with Glade3 instead of Gazpacho. (who forced you to use Gazpacho?)\nKiwi is my first dependency for any PyGTK application commercial or open source.\nKiwi is very actively maintained.\n\nI have generally got to a stage where I think its irresponsible to not use Kiwi in a PyGT...
[ 4, 2, 2, 0 ]
[]
[]
[ "gtk", "model_view_controller", "python" ]
stackoverflow_0000310856_gtk_model_view_controller_python.txt
Q: need help-variable creation in Python (continuation) That was helpful kgiannakakis. I'm facing a problem as below: a = ['zbc','2.3'] for i in range(0,5): exec('E%d=%s' %(i,a[i])) This results in: Traceback (most recent call last): File "", line 2, in exec('E%d=%s' %(i,a[i])) File "", line 1, in Nam...
need help-variable creation in Python (continuation)
That was helpful kgiannakakis. I'm facing a problem as below: a = ['zbc','2.3'] for i in range(0,5): exec('E%d=%s' %(i,a[i])) This results in: Traceback (most recent call last): File "", line 2, in exec('E%d=%s' %(i,a[i])) File "", line 1, in NameError: name 'zbc' is not defined
[ "It looks like the code you're generating expands to:\nE0=zbc\nE1=2.3\n\nAt the next iteration through the loop, you'll get an IndexError exception because a is only two elements long.\nSo given the above, you are trying to assign the value of zbc to E0. If zbc doesn't exist (which it seems that it doesn't), then y...
[ 2, 0, 0, 0 ]
[]
[]
[ "python", "variables" ]
stackoverflow_0000377000_python_variables.txt
Q: Is @measured a standard decorator? What library is it in? In this blog article they use the construct: @measured def some_func(): #... # Presumably outputs something like "some_func() is finished in 121.333 s" somewhere This @measured directive doesn't seem to work with raw python. What is it? UPDATE: I...
Is @measured a standard decorator? What library is it in?
In this blog article they use the construct: @measured def some_func(): #... # Presumably outputs something like "some_func() is finished in 121.333 s" somewhere This @measured directive doesn't seem to work with raw python. What is it? UPDATE: I see from Triptych that @something is valid, but is where can I...
[ "@measured decorates the some_func() function, using a function or class named measured. The @ is the decorator syntax, measured is the decorator function name.\nDecorators can be a bit hard to understand, but they are basically used to either wrap code around a function, or inject code into one.\nFor example the m...
[ 13, 3, 0 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0000382624_decorator_python.txt
Q: Using Python's ctypes to pass/read a parameter declared as "struct_name *** param_name"? I am trying to use Python's ctypes library to access some methods in the scanning library SANE. This is my first experience with ctypes and the first time I have had to deal with C datatypes in over a year so there is a fair ...
Using Python's ctypes to pass/read a parameter declared as "struct_name *** param_name"?
I am trying to use Python's ctypes library to access some methods in the scanning library SANE. This is my first experience with ctypes and the first time I have had to deal with C datatypes in over a year so there is a fair learning curve here, but I think even without that this particular declaration would be troubl...
[ "A const SANE_Device *** is a three-level pointer: it's a pointer to a pointer to a pointer to a constant SANE_Device. You can use the program cdecl to decipher complicated C/C++ type definitions.\nAccording to the SANE documentation, SANE_get_devices() will store a pointer to a NULL-terminated list of pointers to...
[ 7 ]
[]
[]
[ "ctypes", "pointers", "python", "sane", "structure" ]
stackoverflow_0000383010_ctypes_pointers_python_sane_structure.txt
Q: Django: How can I use my model classes to interact with my database from outside Django? I'd like to write a script that interacts with my DB using a Django app's model. However, I would like to be able to run this script from the command line or via cron. What all do I need to import to allow this? A: You nee...
Django: How can I use my model classes to interact with my database from outside Django?
I'd like to write a script that interacts with my DB using a Django app's model. However, I would like to be able to run this script from the command line or via cron. What all do I need to import to allow this?
[ "You need to set up the Django environment variables. These tell Python where your project is, and what the name of the settings module is (the project name in the settings module is optional):\nimport os\n\nos.environ['PYTHONPATH'] = '/path/to/myproject'\nos.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings...
[ 15, 13, 5 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0000383073_django_django_models_python.txt
Q: How do you apply 'or' to all values of a list in Python? How do you apply 'or' to all values of a list in Python? I'm thinking something like: or([True, True, False]) or if it was possible: reduce(or, [True, True, False]) A: The built-in function any does what you want: >>> any([True, True, False]) True >>> any...
How do you apply 'or' to all values of a list in Python?
How do you apply 'or' to all values of a list in Python? I'm thinking something like: or([True, True, False]) or if it was possible: reduce(or, [True, True, False])
[ "The built-in function any does what you want:\n>>> any([True, True, False])\nTrue\n>>> any([False, False, False])\nFalse\n>>> any([False, False, True])\nTrue\n\nany has the advantage over reduce of shortcutting the test for later items in the sequence once it finds a true value. This can be very handy if the seque...
[ 31, 7, 3, 2, 1 ]
[]
[]
[ "list", "python", "reduce" ]
stackoverflow_0000383623_list_python_reduce.txt
Q: With Lua and Python embeddable, is there a place for Basic? I started off programming in Basic on the ZX81, then BASICA, GW-BASIC, and QBasic. I moved on to C (Ah, Turbo C 3.1, I hardly knew ye...) When I got started in microcontrollers I regressed with the BASIC Stamp from Parallax. However, BASIC is/was awesom...
With Lua and Python embeddable, is there a place for Basic?
I started off programming in Basic on the ZX81, then BASICA, GW-BASIC, and QBasic. I moved on to C (Ah, Turbo C 3.1, I hardly knew ye...) When I got started in microcontrollers I regressed with the BASIC Stamp from Parallax. However, BASIC is/was awesome because it was so easy to understand and so hard to make a mist...
[ "[This may come off sounding more negative than it really is. I'm not saying Basic is the root of all evil, others have said that. I'm saying it's a legacy we can afford to leave behind.]\n\"because it was so easy to understand and so hard to make a mistake\" That's certainly debatable. I've had some bad experie...
[ 11, 7, 2, 2, 1, 1, 1, 1, 0 ]
[]
[]
[ "basic", "interpreter", "lua", "python", "scripting" ]
stackoverflow_0000244138_basic_interpreter_lua_python_scripting.txt
Q: Django objects.filter, how "expensive" would this be? I am trying to make a search view in Django. It is a search form with freetext input + some options to select, so that you can filter on years and so on. This is some of the code I have in the view so far, the part that does the filtering. And I would like some...
Django objects.filter, how "expensive" would this be?
I am trying to make a search view in Django. It is a search form with freetext input + some options to select, so that you can filter on years and so on. This is some of the code I have in the view so far, the part that does the filtering. And I would like some input on how expensive this would be on the database serve...
[ "filter itself doesn't execute a query, no query is executed until you explicitly fetch items from query (e.g. get), and list( query ) also executes it.\n", "You can see the query that will be generated by using:\nsoknad_list.query.as_sql()[0]\n\nYou can then put that into your database shell to see how long the ...
[ 4, 2 ]
[ "As Aaron mentioned, you should get a hold of the query text that is going to be run against the database and use an EXPLAIN (or other some method) to view the query execution plan. Once you have a hold of the execution plan for the query you can see what is going on in the database itself. There are a lot of opera...
[ -1 ]
[ "django", "optimization", "python", "search", "sql" ]
stackoverflow_0000383760_django_optimization_python_search_sql.txt
Q: Best Practice: network communication I'm programming a simple network chat with a Python server and a Java client. But one question came into my mind: Which "network protocol" should I use for communication? There are some possibilities for me: YAML: Nice to parse, problem: parsed objects contain language specifi...
Best Practice: network communication
I'm programming a simple network chat with a Python server and a Java client. But one question came into my mind: Which "network protocol" should I use for communication? There are some possibilities for me: YAML: Nice to parse, problem: parsed objects contain language specific parts XML: Easy to parse, big overhead f...
[ "Check JSON. It is compatible accross many languages (Python and Java included), and it is human readable.\nhttp://www.json.org/\nIf you plan to do Web development, and plan to use Javascript, then JSON might be a good choice as it was originally designed for Javascript.\nMoreover compared to YAML, using JSON in Py...
[ 8, 4, 0 ]
[]
[]
[ "java", "networking", "python" ]
stackoverflow_0000377556_java_networking_python.txt
Q: Best way to return the language of a given string More specifically, I'm trying to check if given string (a sentence) is in Turkish. I can check if the string has Turkish characters such as ร‡, ลž, รœ, ร–, ฤž etc. However that's not very reliable as those might be converted to C, S, U, O, G before I receive the string...
Best way to return the language of a given string
More specifically, I'm trying to check if given string (a sentence) is in Turkish. I can check if the string has Turkish characters such as ร‡, ลž, รœ, ร–, ฤž etc. However that's not very reliable as those might be converted to C, S, U, O, G before I receive the string. Another method is to have the 100 most used words in ...
[ "One option would be to use a Bayesian Classifier such as Reverend. The Reverend homepage gives this suggestion for a naive language detector:\nfrom reverend.thomas import Bayes\nguesser = Bayes()\nguesser.train('french', 'le la les du un une je il elle de en')\nguesser.train('german', 'der die das ein eine')\ngue...
[ 13, 10 ]
[ "Why not just use an existing spell checking library?\nSpell check for several languages, choose language with lowest error count.\n" ]
[ -1 ]
[ "algorithm", "python", "string" ]
stackoverflow_0000383966_algorithm_python_string.txt
Q: Code refactoring help - how to reorganize validations We have a web application that takes user inputs or database lookups to form some operations against some physical resources. The design can be simply presented as following diagram: user input <=> model object <=> database storage validations are needed with r...
Code refactoring help - how to reorganize validations
We have a web application that takes user inputs or database lookups to form some operations against some physical resources. The design can be simply presented as following diagram: user input <=> model object <=> database storage validations are needed with request coming from user input but NOT when coming from data...
[ "Doing validation in the constructor really isn't the \"Django way\". Since the data you need to validate is coming from the client-side, using new forms (probably with a ModelForm) is the most idiomatic method to validate because it wraps all of your concerns into one API: it provides sensible validation defaults...
[ 1, 0 ]
[]
[]
[ "django", "optimization", "python", "refactoring", "web_applications" ]
stackoverflow_0000384291_django_optimization_python_refactoring_web_applications.txt
Q: Checking 2-dimensional array (like eight queens puzzle) My problem is very similar to eight queens puzzle. I've got 2-dimensional array (N x N) that for example, looks like this: 0,0,0,0,1 y 0,0,0,0,0 | 0,0,0,0,0 V 0,0,0,1,0 0,0,0,0,0 x-> I'm checking horizontally, vertically and diagonally for occurrences of 1 \...
Checking 2-dimensional array (like eight queens puzzle)
My problem is very similar to eight queens puzzle. I've got 2-dimensional array (N x N) that for example, looks like this: 0,0,0,0,1 y 0,0,0,0,0 | 0,0,0,0,0 V 0,0,0,1,0 0,0,0,0,0 x-> I'm checking horizontally, vertically and diagonally for occurrences of 1 \,0,|,0,/ 0,\,|,/,0 -,-,1,-,- 0,/,|,\,0 /,0,|,0,\ I'm thinkin...
[ "One possible solution:\ndef collision(x1, y1, x2, y2):\n return x1 == x2 or y1 == y2 or abs(x1-x2) == abs(y1-y2)\n\ni.e. there is a collision if the two points are on the same horizontal row, same vertical row or same diagonal (vertical distance == horizontal distance).\n", "Your description sounds like an in...
[ 20, 2, 0, 0 ]
[]
[]
[ "arrays", "puzzle", "python" ]
stackoverflow_0000384874_arrays_puzzle_python.txt
Q: Conway's Game Of Life I am currently writting a programe about Conway's Game of life and I am really a beginner of python, I don't know how to start at all. Anybody can help me with it? A: http://plife.sourceforge.net/ Send the 50 quid to me :) (I'm kidding, of course) A: You probably don't need to pay to lear...
Conway's Game Of Life
I am currently writting a programe about Conway's Game of life and I am really a beginner of python, I don't know how to start at all. Anybody can help me with it?
[ "http://plife.sourceforge.net/\nSend the 50 quid to me :)\n(I'm kidding, of course)\n", "You probably don't need to pay to learn python. Implementing cellular automata makes for good starting project. The best place to start with python is the official tutorial and you can follow that with dive into python.\nThe...
[ 4, 3, 1, 1, 0, 0 ]
[]
[]
[ "cellular_automata", "conways_game_of_life", "python" ]
stackoverflow_0000350230_cellular_automata_conways_game_of_life_python.txt
Q: need help - bit-field conversion I want to convert strings to bit-fields.Also,convert them to binary and then use. Need help with this..help me .. A: I think the struct module is what you're after. Example of usage: >>> from struct import * >>> pack('hhl', 1, 2, 3) '\x00\x01\x00\x02\x00\x00\x00\x03' >>> unpack(...
need help - bit-field conversion
I want to convert strings to bit-fields.Also,convert them to binary and then use. Need help with this..help me ..
[ "I think the struct module is what you're after.\nExample of usage: \n>>> from struct import *\n>>> pack('hhl', 1, 2, 3)\n'\\x00\\x01\\x00\\x02\\x00\\x00\\x00\\x03'\n>>> unpack('hhl', '\\x00\\x01\\x00\\x02\\x00\\x00\\x00\\x03')\n(1, 2, 3)\n>>> calcsize('hhl')\n8\n\n", "they're all binary already... Which language...
[ 2, 0 ]
[]
[]
[ "bit", "bit_fields", "python", "string" ]
stackoverflow_0000386151_bit_bit_fields_python_string.txt
Q: Does PyS60 produce sis files that are native? I am currently looking at developing a mobile apps for the S60 platform and is specifically looking at PyS60. It seems to suggest that the it can be compiled into native .sis files without the need for an embedded python interpreter. Reading through the documentations ...
Does PyS60 produce sis files that are native?
I am currently looking at developing a mobile apps for the S60 platform and is specifically looking at PyS60. It seems to suggest that the it can be compiled into native .sis files without the need for an embedded python interpreter. Reading through the documentations I could not find any statements where this is expli...
[ "Once you've written your code in python, you can convert this to a .sis file using ensymble.\nhttp://code.google.com/p/ensymble/\nThis software allows you to make your .py file into a .sis file using the py2sis option - however, it won't be much use on any phone without python installed, so you may also need to us...
[ 14, 1 ]
[]
[]
[ "pys60", "python", "s60", "symbian" ]
stackoverflow_0000334765_pys60_python_s60_symbian.txt
Q: Python 3 porting workflow? I have a small project I want to try porting to Python 3 - how do I go about this? I have made made the code run without warnings using python2.6 -3 (mostly removing .has_key() calls), but I am not sure of the best way to use the 2to3 tool. Use the 2to3 tool to convert this source code ...
Python 3 porting workflow?
I have a small project I want to try porting to Python 3 - how do I go about this? I have made made the code run without warnings using python2.6 -3 (mostly removing .has_key() calls), but I am not sure of the best way to use the 2to3 tool. Use the 2to3 tool to convert this source code to 3.0 syntax. Do not manually e...
[ "Aha, you can pipe the 2to3 output to the patch command, which can write the modified file to a new file:\nmv something.py py2.6_something.py\n2to3 py2.6_something.py | patch -o something.py\n\n", "2.x should be your codebase of active development, so 2to3 should really be run in a branch or temporary directory. ...
[ 6, 1 ]
[]
[]
[ "porting", "python", "python_3.x" ]
stackoverflow_0000385394_porting_python_python_3.x.txt
Q: US-format phone numbers to links in Python I'm working a piece of code to turn phone numbers into links for mobile phone - I've got it but it feels really dirty. import re from string import digits PHONE_RE = re.compile('([(]{0,1}[2-9]\d{2}[)]{0,1}[-_. ]{0,1}[2-9]\d{2}[-_. ]{0,1}\d{4})') def numbers2links(s): ...
US-format phone numbers to links in Python
I'm working a piece of code to turn phone numbers into links for mobile phone - I've got it but it feels really dirty. import re from string import digits PHONE_RE = re.compile('([(]{0,1}[2-9]\d{2}[)]{0,1}[-_. ]{0,1}[2-9]\d{2}[-_. ]{0,1}\d{4})') def numbers2links(s): result = "" last_match_index = 0 for m...
[ "Nice first take :) I think this version is a bit more readable (and probably a teensy bit faster). The key thing to note here is the use of re.sub. Keeps us away from the nasty match indexes...\nimport re\n\nPHONE_RE = re.compile('([(]{0,1}[2-9]\\d{2}[)]{0,1}[-_. ]{0,1}[2-9]\\d{2}[-_. ]{0,1}\\d{4})')\nNON_NUME...
[ 5, 1, 1, 1, 0 ]
[]
[]
[ "mobile_website", "phone_number", "python", "regex" ]
stackoverflow_0000385632_mobile_website_phone_number_python_regex.txt
Q: Tricky Python string literals in passing parameter to timeit.Timer() function I'm having a hard time with the setup statement in Python's timeit.Timer(stmt, setup_stmt). I appreciate any help to get me out of this tricky problem: So my sniplet looks like this: def compare(string1, string2): # compare 2 strings...
Tricky Python string literals in passing parameter to timeit.Timer() function
I'm having a hard time with the setup statement in Python's timeit.Timer(stmt, setup_stmt). I appreciate any help to get me out of this tricky problem: So my sniplet looks like this: def compare(string1, string2): # compare 2 strings if __name__ = '__main__': str1 = "This string has \n several new lines \n in ...
[ "Consider This as an alternative.\nt = timeit.Timer('compare(p1, p2)', \"from __main__ import compare; p1=%r; p2=%r\" % (str1,str2))\n\nThe %r uses the repr for the string, which Python always quotes and escapes correctly.\nEDIT: Fixed code by changing a comma to a semicolon; the error is now gone.\n", "Why bothe...
[ 7, 2 ]
[]
[]
[ "python", "string_literals", "timeit" ]
stackoverflow_0000386664_python_string_literals_timeit.txt
Q: printing a list of persons with more than one home, each home with more than one phone number I have a class Person which can have several Homes, each one with one or many Phone numbers. I have defined the classes, but now i am trying to create a view wich list every person, with all its homes and all the phone nu...
printing a list of persons with more than one home, each home with more than one phone number
I have a class Person which can have several Homes, each one with one or many Phone numbers. I have defined the classes, but now i am trying to create a view wich list every person, with all its homes and all the phone numbers for each home address... something like: john smith 123 fake str 305-99-8877 305-99-8876 ...
[ "You have what appears to be three nested collections: Person, Home, Phone Number.\nStep 1 - How would you write this in a view function?\nfor p in Person.objects.all():\n print \"person\", p\n for h in p.home_address_set.all():\n print \" home\", h\n for ph in h.phone_set.all():\n ...
[ 8 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0000387991_django_django_templates_python.txt
Q: How do you manage your Django applications? I just wanted to try to build a project with django. Therefore I have a (basic) question on how to manage such a project. Since I cannot find any guidelines or so on how to split a project into applications. Let's take a kind of SO as an example. Which applications would...
How do you manage your Django applications?
I just wanted to try to build a project with django. Therefore I have a (basic) question on how to manage such a project. Since I cannot find any guidelines or so on how to split a project into applications. Let's take a kind of SO as an example. Which applications would you use? I'd say there should be the application...
[ "There aren't hard-and-fast rules, but I would say it's better to err on the side of more specialized applications. Ideally an application should handle just one functional concern: i.e. \"tagging\" or \"commenting\" or \"auth/auth\" or \"posts.\" This type of design will also help you reuse available open source...
[ 6, 5, 3, 3, 0 ]
[]
[]
[ "django", "project", "python", "structure" ]
stackoverflow_0000384333_django_project_python_structure.txt
Q: Mysql Connection, one or many? I'm writing a script in python which basically queries WMI and updates the information in a mysql database. One of those "write something you need" to learn to program exercises. In case something breaks in the middle of the script, for example, the remote computer turns off, it's s...
Mysql Connection, one or many?
I'm writing a script in python which basically queries WMI and updates the information in a mysql database. One of those "write something you need" to learn to program exercises. In case something breaks in the middle of the script, for example, the remote computer turns off, it's separated out into functions. Query S...
[ "\"However, opening and closing the connection with each update seems more 'neat'. \" \nIt's also a huge amount of overhead -- and there's no actual benefit.\nCreating and disposing of connections is relatively expensive. More importantly, what's the actual reason? How does it improve, simplify, clarify?\nGeneral...
[ 7, 2, 1, 1 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0000387619_mysql_python.txt
Q: How can i create a lookup in Django? I have a Question model & Form, one of the fields in this model is userid=ForeignKey(User), this Works perfectly well on the Question Model, am able to pick the user from a drop down. But kind a tricky when i want to list the question from the model, which is the best way to l...
How can i create a lookup in Django?
I have a Question model & Form, one of the fields in this model is userid=ForeignKey(User), this Works perfectly well on the Question Model, am able to pick the user from a drop down. But kind a tricky when i want to list the question from the model, which is the best way to lookup the user name from the Users table? ...
[ "The name of your field (userid instead of user) makes me think that you may be confused about the behavior of Django's ForeignKey.\nIf you define a model like this:\nfrom django.contrib.auth.models import User\nfrom django.db import models\n\nclass Question(models.Model):\n user = models.ForeignKey(User)\n t...
[ 5, 0 ]
[]
[]
[ "django", "lookup", "python" ]
stackoverflow_0000388233_django_lookup_python.txt
Q: Python: flush a buffer before program termination via a finalizer I keep a cache of transactions to flush (to persistent storage) on the event of a watermark or object finalization. Since __del__ is no longer guaranteed to be called on every object, is the appropriate approach to hook a similar function (or __del_...
Python: flush a buffer before program termination via a finalizer
I keep a cache of transactions to flush (to persistent storage) on the event of a watermark or object finalization. Since __del__ is no longer guaranteed to be called on every object, is the appropriate approach to hook a similar function (or __del__ itself) into atexit.register (during initialization)? If I'm not mist...
[ "If you have to handle ressources the prefered way is to have an explicit call to a close() or finalize() method. Have a look at the with statement to abstract that. In your case the weakref module might be an option. The cached object can be garbage collected by the system and have their __del__() method called o...
[ 4, 3, 2, 2, 0 ]
[]
[]
[ "buffer", "destructor", "finalizer", "python" ]
stackoverflow_0000388154_buffer_destructor_finalizer_python.txt
Q: How to update turbogears application production database I am having a postgres production database in production (which contains a lot of Data). now I need to modify the model of the tg-app to add couple of new tables to the database. How do i do this? I am using sqlAlchemy. A: The simplest approach is to simp...
How to update turbogears application production database
I am having a postgres production database in production (which contains a lot of Data). now I need to modify the model of the tg-app to add couple of new tables to the database. How do i do this? I am using sqlAlchemy.
[ "The simplest approach is to simply write some sql update scripts and use those to update the database. Obviously that's a fairly low-level (as it were) approach.\nIf you think you will be doing this a lot and want to stick in Python you might want to look at sqlalchemy-migrate. There was an article about it in t...
[ 1, 1, 1, 0 ]
[]
[]
[ "data_migration", "database", "postgresql", "python", "turbogears" ]
stackoverflow_0000301566_data_migration_database_postgresql_python_turbogears.txt
Q: How can I read Perl data structures from Python? I've often seen people use Perl data structures in lieu of configuration files; i.e. a lone file containing only: %config = ( 'color' => 'red', 'numbers' => [5, 8], qr/^spam/ => 'eggs' ); What's the best way to convert the contents of these files into P...
How can I read Perl data structures from Python?
I've often seen people use Perl data structures in lieu of configuration files; i.e. a lone file containing only: %config = ( 'color' => 'red', 'numbers' => [5, 8], qr/^spam/ => 'eggs' ); What's the best way to convert the contents of these files into Python-equivalent data structures, using pure Python? F...
[ "Is using pure Python a requirement? If not, you can load it in Perl and convert it to YAML or JSON. Then use PyYAML or something similar to load them in Python.\n", "I'd just turn the Perl data structure into something else. Not seeing the actual file, there might be some extra work that my solution doesn't do.\...
[ 18, 14, 7, 0 ]
[]
[]
[ "configuration", "data_structures", "perl", "python" ]
stackoverflow_0000389945_configuration_data_structures_perl_python.txt
Q: Using Python Web GET data I'm trying to pass information to a python page via the url. I have the following link text: "<a href='complete?id=%s'>" % (str(r[0])) on the complete page, I have this: import cgi def complete(): form = cgi.FieldStorage() db = MySQLdb.connect(user="", passwd="", db="todo") c...
Using Python Web GET data
I'm trying to pass information to a python page via the url. I have the following link text: "<a href='complete?id=%s'>" % (str(r[0])) on the complete page, I have this: import cgi def complete(): form = cgi.FieldStorage() db = MySQLdb.connect(user="", passwd="", db="todo") c = db.cursor() c.execute("d...
[ "The error means that form[\"id\"] failed to find the key \"id\" in cgi.FieldStorage().\nTo test what keys are in the called URL, use cgi.test():\n\ncgi.test()\nRobust test CGI script, usable as main program. Writes minimal HTTP headers and formats all information provided to the script in HTML form.\n\nEDIT: a bas...
[ 1, 1, 0 ]
[]
[]
[ "form_data", "python" ]
stackoverflow_0000384336_form_data_python.txt
Q: Interpreting Excel Currency Values I am using python to read a currency value from excel. The returned from the range.Value method is a tuple that I don't know how to parse. For example, the cell appears as $548,982, but in python the value is returned as (1, 1194857614). How can I get the numerical amount from ex...
Interpreting Excel Currency Values
I am using python to read a currency value from excel. The returned from the range.Value method is a tuple that I don't know how to parse. For example, the cell appears as $548,982, but in python the value is returned as (1, 1194857614). How can I get the numerical amount from excel or how can I convert this tuple valu...
[ "Try this:\nimport struct\ntry: import decimal\nexcept ImportError:\n divisor= 10000.0\nelse:\n divisor= decimal.Decimal(10000)\n\ndef xl_money(i1, i2):\n byte8= struct.unpack(\">q\", struct.pack(\">ii\", i1, i2))[0]\n return byte8 / divisor\n\n>>> xl_money(1, 1194857614)\nDecimal(\"548982.491\")\n\nMon...
[ 3, 0 ]
[]
[]
[ "excel", "python", "pywin32" ]
stackoverflow_0000390263_excel_python_pywin32.txt
Q: pyGTK Radio Button Alright, I'll preface this with the fact that I'm a GTK and Python newb, but I haven't been able to dig up the information I needed. Basically what I have is a list of Radio Buttons, and based on which one is checked, I need to connect a button to a different function. I tried creating all my ra...
pyGTK Radio Button
Alright, I'll preface this with the fact that I'm a GTK and Python newb, but I haven't been able to dig up the information I needed. Basically what I have is a list of Radio Buttons, and based on which one is checked, I need to connect a button to a different function. I tried creating all my radio buttons, and then cr...
[ "Edit: (since you posted some code), just use:\nactive = [r for r in self.updatePageRadio.get_group() if r.get_active()][0]\n\nand use that to look up in a dict of functions and call it:\nmy_actions[active]()\n\n\nEdit: I totally forgot to mention that this is not a good use-case at all for RadioButtons, regular gt...
[ 7, 0 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0000391237_gtk_pygtk_python.txt
Q: Organising my Python project I'm starting a Python project and expect to have 20 or more classes in it. As is good practice I want to put them in a separate file each. However, the project directory quickly becomes swamped with files (or will when I do this). If I put a file to import in a folder I can no longer i...
Organising my Python project
I'm starting a Python project and expect to have 20 or more classes in it. As is good practice I want to put them in a separate file each. However, the project directory quickly becomes swamped with files (or will when I do this). If I put a file to import in a folder I can no longer import it. How do I import a file f...
[ "Create an __init__.py file in your projects folder, and it will be treated like a module by Python.\nClasses in your package directory can then be imported using syntax like:\nfrom package import class\nimport package.class\n\nWithin __init__.py, you may create an __all__ array that defines from package import * b...
[ 31, 22, 12, 6 ]
[]
[]
[ "project_organization", "python" ]
stackoverflow_0000391879_project_organization_python.txt
Q: Is there a Ruby/Python HTML reflow/layout library? I'm looking for a library in Ruby or Python that would take some HTML and CSS as the input and return data that contains the positions and sizes of the elements. If it helps, I don't need the info for all the elements but just the major divs of the page. A: Scri...
Is there a Ruby/Python HTML reflow/layout library?
I'm looking for a library in Ruby or Python that would take some HTML and CSS as the input and return data that contains the positions and sizes of the elements. If it helps, I don't need the info for all the elements but just the major divs of the page.
[ "Scriptor, I think what you likely are looking for might be something in JavaScript more then Ruby or Python. I mean - the positions and sizes are essentially going to be determined by the rendering engine (the browser). You might consider using something like jQuery to loop through all of your desired objects - ou...
[ 3 ]
[ "Both Ruby and Python have a Regex library. Why not search for things like /width=\\\"(\\d+)px\\\"/ and /height:(\\d+)px/. Use $1 to find the value in the group. I'm not a regex expert and I'm doing this from memory, so refer to any of the tutorials on the net for the correct syntax and variable usage, but that'...
[ -1 ]
[ "html", "layout", "python", "ruby" ]
stackoverflow_0000392217_html_layout_python_ruby.txt
Q: Is there anyone who has managed to compile mod_wsgi for apache on Mac OS X Leopard? I'm working on a Django project that requires debugging on a multithreaded server. I've found mod_wsgi 2.0+ to be the easiest to work with, because of easy workarounds for python module reloading. Problem is can't get it to compile...
Is there anyone who has managed to compile mod_wsgi for apache on Mac OS X Leopard?
I'm working on a Django project that requires debugging on a multithreaded server. I've found mod_wsgi 2.0+ to be the easiest to work with, because of easy workarounds for python module reloading. Problem is can't get it to compile on Leopard. Is there anyone who has managed to do it so far, either for the builtin Apac...
[ "This doesn't directly answer your question, but have you thought about using something like MacPorts for this sort of thing? If you're compiling a lot of software like this, MacPorts can really make your life easier, since building software and dependencies is practically automatic.\n" ]
[ 2 ]
[]
[]
[ "apache", "django", "python" ]
stackoverflow_0000369305_apache_django_python.txt
Q: How to make a color from a number I have a function that returns a float from 0 to 255. I would like to make a gradient in red color from this, but I need a string in "#FFFFFF" format. Is there a function for that? A: You could use: "#%02X0000" % x A: def rgbtohex(r,g,b): return "#%02X%02X%02X" % (r,g,b)
How to make a color from a number
I have a function that returns a float from 0 to 255. I would like to make a gradient in red color from this, but I need a string in "#FFFFFF" format. Is there a function for that?
[ "You could use:\n\"#%02X0000\" % x\n\n", "def rgbtohex(r,g,b):\n return \"#%02X%02X%02X\" % (r,g,b)\n\n" ]
[ 12, 3 ]
[]
[]
[ "colors", "python" ]
stackoverflow_0000392728_colors_python.txt
Q: How do I respond to mouse clicks on sprites in PyGame? What is the canonical way of making your sprites respond to mouse clicks in PyGame ? Here's something simple, in my event loop: for event in pygame.event.get(): if event.type == pygame.QUIT: exit_game() [...] elif ( event.type == pygame.M...
How do I respond to mouse clicks on sprites in PyGame?
What is the canonical way of making your sprites respond to mouse clicks in PyGame ? Here's something simple, in my event loop: for event in pygame.event.get(): if event.type == pygame.QUIT: exit_game() [...] elif ( event.type == pygame.MOUSEBUTTONDOWN and pygame.mouse.get_pressed()[0]...
[ "I usually give my clickable objects a click function, like in your example. I put all of those objects in a list, for easy iteration when the click functions are to be called.\nwhen checking for which mousebutton you press, use the button property of the event.\nimport pygame\nfrom pygame.locals import * #This let...
[ 11 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0000380420_pygame_python.txt
Q: Using user input to find information in a Mysql database I need to design a program using python that will ask the user for a barcode. Then, using this barcode, it will search a mysql to find its corresponding product. I am a bit stuck on how to get started. Does anyone have any tips for me? A: Use python-mysql...
Using user input to find information in a Mysql database
I need to design a program using python that will ask the user for a barcode. Then, using this barcode, it will search a mysql to find its corresponding product. I am a bit stuck on how to get started. Does anyone have any tips for me?
[ "Use python-mysql. It is a dbapi-compatible module that lets you talk to the database.\nimport MySQLdb\n\nuser_input = raw_input(\"Please enter barcode and press Enter button: \")\n\ndb = MySQLdb.connect(passwd=\"moonpie\",db=\"thangs\")\nmycursor = db.cursor()\nmycursor.execute(\"\"\"SELECT name, price FROM Produc...
[ 5, 1, 0, 0 ]
[]
[]
[ "python", "sql", "user_input" ]
stackoverflow_0000387606_python_sql_user_input.txt
Q: How do I create a Python class in C? I have a legacy C library that creates a tree of objects. I would like to convert the tree into a pre-existing Python class. How do I create the PyObject for that class? A: Cython is capable of doing this. It's a semi-fork of Pyrex, and it can wrap existing data structures a...
How do I create a Python class in C?
I have a legacy C library that creates a tree of objects. I would like to convert the tree into a pre-existing Python class. How do I create the PyObject for that class?
[ "Cython is capable of doing this. It's a semi-fork of Pyrex, and it can wrap existing data structures and expose them to Python. In fact, this is one of the sections in the user guide. Cython is relatively easy to use, and it includes an HTML-output format that shows all the generated code as well as highlighted...
[ 4, 2, 1 ]
[]
[]
[ "c", "python" ]
stackoverflow_0000378773_c_python.txt
Q: How to process two forms in one view? I have two completely different forms in one template. How to process them in one view? How can I distinguish which of the forms was submitted? How can I use prefix to acomplish that? Or maybe it's better to write separate views? regards chriss A: Personally, I'd use one vie...
How to process two forms in one view?
I have two completely different forms in one template. How to process them in one view? How can I distinguish which of the forms was submitted? How can I use prefix to acomplish that? Or maybe it's better to write separate views? regards chriss
[ "Personally, I'd use one view to handle each form's POST.\nOn the other hand, you could use a hidden input element that indicate which form was used\n<form action=\"/blog/\" method=\"POST\">\n {{ blog_form.as_p }}\n <input type=\"hidden\" name=\"form-type\" value\"blog-form\" /> <!-- set type -->\n <input ...
[ 5, 4, 0 ]
[]
[]
[ "django", "django_forms", "django_templates", "python" ]
stackoverflow_0000392784_django_django_forms_django_templates_python.txt
Q: What values to use for FastCGI maxrequests, maxspare, minspare, maxchildren? I'm running a Django app using FastCGI and lighttpd. Can somebody explain me what I should consider when deciding what value to use for maxrequests, maxspare, minspare, maxchildren? These options are not too well documented, but seem quit...
What values to use for FastCGI maxrequests, maxspare, minspare, maxchildren?
I'm running a Django app using FastCGI and lighttpd. Can somebody explain me what I should consider when deciding what value to use for maxrequests, maxspare, minspare, maxchildren? These options are not too well documented, but seem quite important. Don't just tell me what they do; I want to understand what implicatio...
[ "Let's start with the definition\n\n maxrequests: How many requests does a child server before being killed \n and a new one forked\n maxspare : Maximum number of spare processes to keep running\n minspare : Minimum number of spare processes to prefork\n maxchildren: Hard limit numbe...
[ 13 ]
[ "Don't forget to coordinate your fcgi settings with your apache worker settings. I usually keep more apache workers around than fcgi workers... they are lighter weight and will wait for an available fcgi worker to free up to process the request if the concurrency reaches higher than my maxspare.\n" ]
[ -1 ]
[ "django", "fastcgi", "python" ]
stackoverflow_0000393629_django_fastcgi_python.txt
Q: Programmatic Form Submit I want to scrape the contents of a webpage. The contents are produced after a form on that site has been filled in and submitted. I've read on how to scrape the end result content/webpage - but how to I programmatically submit the form? I'm using python and have read that I might need to...
Programmatic Form Submit
I want to scrape the contents of a webpage. The contents are produced after a form on that site has been filled in and submitted. I've read on how to scrape the end result content/webpage - but how to I programmatically submit the form? I'm using python and have read that I might need to get the original webpage with...
[ "you'll need to generate a HTTP request containing the data for the form. \nThe form will look something like:\n<form action=\"submit.php\" method=\"POST\"> ... </form>\n\nThis tells you the url to request is www.example.com/submit.php and your request should be a POST.\nIn the form will be several input items, eg...
[ 2, 2, 2 ]
[ "You can do it with javascript. If the form is something like:\n<form name='myform' ...\n\nThen you can do this in javascript:\n<script language=\"JavaScript\">\nfunction submitform()\n{\ndocument.myform.submit();\n}\n</script> \n\nYou can use the \"onClick\" attribute of links or buttons to invoke this code. To in...
[ -1 ]
[ "forms", "python", "screen_scraping", "submit" ]
stackoverflow_0000393738_forms_python_screen_scraping_submit.txt
Q: Python and regular expression with Unicode I need to delete some Unicode symbols from the string 'ุจูุณู’ู…ู ุงู„ู„ู‘ูŽู‡ู ุงู„ุฑู‘ูŽุญู’ู…ูŽูฐู†ู ุงู„ุฑู‘ูŽุญููŠู…ู' I know they exist here for sure. I tried: re.sub('([\u064B-\u0652\u06D4\u0670\u0674\u06D5-\u06ED]+)', '', 'ุจูุณู’ู…ู ุงู„ู„ู‘ูŽู‡ู ุงู„ุฑู‘ูŽุญู’ู…ูŽูฐู†ู ุงู„ุฑู‘ูŽุญููŠู…ู') but it doesn't work. String ...
Python and regular expression with Unicode
I need to delete some Unicode symbols from the string 'ุจูุณู’ู…ู ุงู„ู„ู‘ูŽู‡ู ุงู„ุฑู‘ูŽุญู’ู…ูŽูฐู†ู ุงู„ุฑู‘ูŽุญููŠู…ู' I know they exist here for sure. I tried: re.sub('([\u064B-\u0652\u06D4\u0670\u0674\u06D5-\u06ED]+)', '', 'ุจูุณู’ู…ู ุงู„ู„ู‘ูŽู‡ู ุงู„ุฑู‘ูŽุญู’ู…ูŽูฐู†ู ุงู„ุฑู‘ูŽุญููŠู…ู') but it doesn't work. String stays the same. What am I doing wrong?
[ "Are you using python 2.x or 3.0?\nIf you're using 2.x, try making the regex string a unicode-escape string, with 'u'. Since it's regex it's good practice to make your regex string a raw string, with 'r'. Also, putting your entire pattern in parentheses is superfluous.\nre.sub(ur'[\\u064B-\\u0652\\u06D4\\u0670\\u06...
[ 110, 78 ]
[]
[]
[ "character_properties", "python", "regex" ]
stackoverflow_0000393843_character_properties_python_regex.txt
Q: Scripting inside a Python application I'd like to include Python scripting in one of my applications, that is written in Python itself. My application must be able to call external Python functions (written by the user) as callbacks. There must be some control on code execution; for example, if the user provided ...
Scripting inside a Python application
I'd like to include Python scripting in one of my applications, that is written in Python itself. My application must be able to call external Python functions (written by the user) as callbacks. There must be some control on code execution; for example, if the user provided code with syntax errors, the application m...
[ "Use __import__ to import the files provided by the user. This function will return a module. Use that to call the functions from the imported file.\nUse try..except both on __import__ and on the actual call to catch errors.\nExample:\nm = None\ntry:\n m = __import__(\"external_module\")\nexcept:\n # invalid ...
[ 8, 8, 4, 0 ]
[]
[]
[ "python", "scripting" ]
stackoverflow_0000393871_python_scripting.txt