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: What python equivalent of Sinatra would you recommend? I like the sinatra framework, but might have to work in python. A quick web search has uncovered a few python equivalents including itty, flask and juno. I'd like to know people's experience of these, or other sinatra equivalents. Which would you recommend? A: Okay. So I'm biased because I'm the author of Flask, but here something to help you make the pick: itty - very minimal framework, Bottle is probably a more stable alternative if you want a single file installation. Flask - new and actively developed, shaped similar to Sinatra but also differs in a few points. Large number of extensions for SQLAlchemy, CouchDB and more. Juno - not updated for a year. Usually not the best sign. Besides the ones you mentioned there is also Bottle which is similar to Flask but more minimalistic. Unlike Flask it also re-implements everything from ground up instead of building on an independent foundation like Werkzeug. Other alternatives is web.py, one of the first microframeworks ever. Same rule as bottle: re-implements everything from the ground up.
What python equivalent of Sinatra would you recommend?
I like the sinatra framework, but might have to work in python. A quick web search has uncovered a few python equivalents including itty, flask and juno. I'd like to know people's experience of these, or other sinatra equivalents. Which would you recommend?
[ "Okay. So I'm biased because I'm the author of Flask, but here something to help you make the pick:\n\nitty - very minimal framework, Bottle is probably a more stable alternative if you want a single file installation.\nFlask - new and actively developed, shaped similar to Sinatra but also differs in a few points. Large number of extensions for SQLAlchemy, CouchDB and more.\nJuno - not updated for a year. Usually not the best sign.\n\nBesides the ones you mentioned there is also Bottle which is similar to Flask but more minimalistic. Unlike Flask it also re-implements everything from ground up instead of building on an independent foundation like Werkzeug.\nOther alternatives is web.py, one of the first microframeworks ever. Same rule as bottle: re-implements everything from the ground up.\n" ]
[ 39 ]
[]
[]
[ "frameworks", "python", "sinatra", "web_frameworks" ]
stackoverflow_0003070469_frameworks_python_sinatra_web_frameworks.txt
Q: py2app, pyObjc & macports compilation errors I'm currently writing a small python app that embeds cherrypy and django using py2app. It worked well until I tried to include pyobjc in my project, since my app needed a small GUI (which consists of a small icon in the top menu bar + a drop down menu). I can run my python script without any problem (I'm using python 2.6 with macports), but I can't launch the application bundle generated by py2app. A dialog box appears with the following message: ImportError: dlopen(/Users/denis/tlon/standalone/mac/dist/django_cherry.app/Contents/Resources/lib/python2.6/lib-dynload/CoreFoundation/_inlines.so, 2): no suitable image found. Did find: /Users/denis/tlon/standalone/mac/dist/django_cherry.app/Contents/Resources/lib/python2.6/lib-dynload/CoreFoundation/_inlines.so: mach-o, but wrong architecture I did a quick : sudo port -u install py26-pyobjc +universal but for some reason macports tries to build openssl, with which compilation fails each time. It seems the problem is related to zLib - this is what appears in the logs : :info:build ld: warning: in /opt/local/lib/libz.dylib, file is not of required architecture ...And here is the output of file /opt/local/lib/libz.dylib : /opt/local/lib/libz.dylib: Mach-O universal binary with 2 architectures /opt/local/lib/libz.dylib (for architecture x86_64): Mach-O 64-bit dynamically linked shared library x86_64 /opt/local/lib/libz.dylib (for architecture i386): Mach-O dynamically linked shared library i386 Nothing looks wrong to me. I'm a bit stuck here. I don't even understand what openssl has to do with pyObjc, but it looks like I can't go anywhere if I don't manage to compile it. Macports really suck sometimes :/ EDIT I manage to fix Macports issue, but not py2app one :/ A: I'm guessing it's because a required library is not in your library path, so the loader can't figure out where it is so it can link the symbols in. You should do one of two things: Add /opt/local/lib to your $LD_LIBRARY_PATH environment variable when launching the app; or Bundle the appropriate libraries with the .app file.
py2app, pyObjc & macports compilation errors
I'm currently writing a small python app that embeds cherrypy and django using py2app. It worked well until I tried to include pyobjc in my project, since my app needed a small GUI (which consists of a small icon in the top menu bar + a drop down menu). I can run my python script without any problem (I'm using python 2.6 with macports), but I can't launch the application bundle generated by py2app. A dialog box appears with the following message: ImportError: dlopen(/Users/denis/tlon/standalone/mac/dist/django_cherry.app/Contents/Resources/lib/python2.6/lib-dynload/CoreFoundation/_inlines.so, 2): no suitable image found. Did find: /Users/denis/tlon/standalone/mac/dist/django_cherry.app/Contents/Resources/lib/python2.6/lib-dynload/CoreFoundation/_inlines.so: mach-o, but wrong architecture I did a quick : sudo port -u install py26-pyobjc +universal but for some reason macports tries to build openssl, with which compilation fails each time. It seems the problem is related to zLib - this is what appears in the logs : :info:build ld: warning: in /opt/local/lib/libz.dylib, file is not of required architecture ...And here is the output of file /opt/local/lib/libz.dylib : /opt/local/lib/libz.dylib: Mach-O universal binary with 2 architectures /opt/local/lib/libz.dylib (for architecture x86_64): Mach-O 64-bit dynamically linked shared library x86_64 /opt/local/lib/libz.dylib (for architecture i386): Mach-O dynamically linked shared library i386 Nothing looks wrong to me. I'm a bit stuck here. I don't even understand what openssl has to do with pyObjc, but it looks like I can't go anywhere if I don't manage to compile it. Macports really suck sometimes :/ EDIT I manage to fix Macports issue, but not py2app one :/
[ "I'm guessing it's because a required library is not in your library path, so the loader can't figure out where it is so it can link the symbols in. You should do one of two things:\n\nAdd /opt/local/lib to your $LD_LIBRARY_PATH environment variable when launching the app; or\nBundle the appropriate libraries with the .app file.\n\n" ]
[ 0 ]
[]
[]
[ "macports", "py2app", "pyobjc", "python" ]
stackoverflow_0003051874_macports_py2app_pyobjc_python.txt
Q: how can i pass a value of variable defined in python to a procedure in mysql as an input? I made a procedure in mysql and i call it using python but it take an input and i need to pass the value of a variable in python to it but the mysql doesn't understand that it is a variable because the variable is not defined in it's list of fields . for example for a code written in python : variable = "someValue" cursor.execute("call procedure1(variable);") note the following is not a solution : cursor.execute("call procedure1("someValue");") A: you mean something like this? cursor.execute("call procedure('%s');" % variable )
how can i pass a value of variable defined in python to a procedure in mysql as an input?
I made a procedure in mysql and i call it using python but it take an input and i need to pass the value of a variable in python to it but the mysql doesn't understand that it is a variable because the variable is not defined in it's list of fields . for example for a code written in python : variable = "someValue" cursor.execute("call procedure1(variable);") note the following is not a solution : cursor.execute("call procedure1("someValue");")
[ "you mean something like this?\ncursor.execute(\"call procedure('%s');\" % variable )\n\n" ]
[ 1 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0003084721_mysql_python.txt
Q: Confused about using XPath or not This follows my previous questions on using lxml and Python. I have a question, as to when I have a choice between using the methods provided by the lxml.etree and where I can make use of XPath, what should I use? For example, to get a list of all the X tags in a XML document, I could either iterate through it using the getiterator() of lxml.etree, or I could write the XPath expression: //x. There may be many more examples, this is just one. Question is, which should when I have a choose and why? A: XPath is usually preferable to an explicit iteration over elements. XPath is more succinct, and will likely be faster since it is implemented inside the XML engine. You'd want to use an explicit iteration if there were complex criteria that couldn't be expressed easily (or at all) in XPath, or if you needed to visit all the nodes for some other processing anyway, or if you wanted to get rich debugging output.
Confused about using XPath or not
This follows my previous questions on using lxml and Python. I have a question, as to when I have a choice between using the methods provided by the lxml.etree and where I can make use of XPath, what should I use? For example, to get a list of all the X tags in a XML document, I could either iterate through it using the getiterator() of lxml.etree, or I could write the XPath expression: //x. There may be many more examples, this is just one. Question is, which should when I have a choose and why?
[ "XPath is usually preferable to an explicit iteration over elements. XPath is more succinct, and will likely be faster since it is implemented inside the XML engine.\nYou'd want to use an explicit iteration if there were complex criteria that couldn't be expressed easily (or at all) in XPath, or if you needed to visit all the nodes for some other processing anyway, or if you wanted to get rich debugging output.\n" ]
[ 1 ]
[]
[]
[ "lxml", "python" ]
stackoverflow_0003084627_lxml_python.txt
Q: How to workaround lack of multiple ao.lock? I'm programming a simple pyS60 app, not really done anything with python or using multiple threads before so this is all a bit new to me. In order to keep the app open, I set an e32.Ao_lock to wait() after the body of the application is initialised, and then signal the lock on the exit_key_handler. One of the tasks the program may do is open a third party app, UpCode. This scans a barcode and copies the barcode string to the clipboard. When I close UpCode, my application should resume and paste the input from the clipboard. I know this can be accomplished using Ao.lock, but I've already called an instance of this. Ideally my application would regain focus after noticing something had been pasted to the clipboard. Can I accomplish what I need with one of the sleep or timer functions? You can find the full script here, and I've abbreviated it to the necessary parts below: lock=e32.Ao_lock() # Quit the script def quit(): lock.signal() # Callback function will be called when the requested service is complete. def launch_app_callback(trans_id, event_id, input_params): if trans_id != appmanager_id and event_id != scriptext.EventCompleted: print "Error in servicing the request" print "Error code is: " + str(input_params["ReturnValue"]["ErrorCode"]) if "ErrorMessage" in input_params["ReturnValue"]: print "Error message is: " + input_params["ReturnValue"]["ErrorMessage"] else: print "\nWaiting for UpCode to close" #lock.signal() # launch UpCode to scan barcode and get barcode from clipboard def scan_barcode(): msg('Launching UpCode to scan barcode.\nPlease exit UpCode after the barcode has been copied to the clipboard') # Load appmanage service appmanager_handle = scriptext.load('Service.AppManager', 'IAppManager') # Make a request to query the required information in asynchronous mode appmanager_id = appmanager_handle.call('LaunchApp', {'ApplicationID': u's60uid://0x2000c83e'}, callback=launch_app_callback) #lock.wait() #print "Request complete!" barcode = clipboard.Get() return barcode # handle the selection made from the main body listbox def handle_selection(): if (lb.current() == 0): barcode = scan_barcode() elif (lb.current() ==1): barcode = clipboard.Get() elif (lb.current() ==2): barcode = input_barcode() found = False if is_barcode(barcode): found, mbid, album, artist = identify_release(barcode) else: msg('Valid barcode not found. Please try again/ another method/ another CD') return if found: go = appuifw.query(unicode('Found: ' + artist + ' - ' + album + '\nScrobble it?'), 'query') if (go == 1): now = datetime.datetime.utcnow() scrobble_tracks(mbid, album, artist, now) else: appuifw.note(u'Scrobbling cancelled', 'info') else: appuifw.note(u'No match found for this barcode.', 'info') # Set the application body up appuifw.app.exit_key_handler = quit appuifw.app.title = u"ScanScrobbler" entries = [(u"Scan a barcode", u"Opens UpCode for scanning"), (u"Submit barcode from clipboard", u"If you've already copied a barcode there"), (u"Enter barcode by hand", u"Using numeric keypad") ] lb = appuifw.Listbox(entries, handle_selection) appuifw.app.body = lb lock.wait() Any and all help appreciated. A: I solved this problem by defining a separate second lock, and making sure only one was waiting at a time. It seems to work without any problem. Current code can be found hosted on google code
How to workaround lack of multiple ao.lock?
I'm programming a simple pyS60 app, not really done anything with python or using multiple threads before so this is all a bit new to me. In order to keep the app open, I set an e32.Ao_lock to wait() after the body of the application is initialised, and then signal the lock on the exit_key_handler. One of the tasks the program may do is open a third party app, UpCode. This scans a barcode and copies the barcode string to the clipboard. When I close UpCode, my application should resume and paste the input from the clipboard. I know this can be accomplished using Ao.lock, but I've already called an instance of this. Ideally my application would regain focus after noticing something had been pasted to the clipboard. Can I accomplish what I need with one of the sleep or timer functions? You can find the full script here, and I've abbreviated it to the necessary parts below: lock=e32.Ao_lock() # Quit the script def quit(): lock.signal() # Callback function will be called when the requested service is complete. def launch_app_callback(trans_id, event_id, input_params): if trans_id != appmanager_id and event_id != scriptext.EventCompleted: print "Error in servicing the request" print "Error code is: " + str(input_params["ReturnValue"]["ErrorCode"]) if "ErrorMessage" in input_params["ReturnValue"]: print "Error message is: " + input_params["ReturnValue"]["ErrorMessage"] else: print "\nWaiting for UpCode to close" #lock.signal() # launch UpCode to scan barcode and get barcode from clipboard def scan_barcode(): msg('Launching UpCode to scan barcode.\nPlease exit UpCode after the barcode has been copied to the clipboard') # Load appmanage service appmanager_handle = scriptext.load('Service.AppManager', 'IAppManager') # Make a request to query the required information in asynchronous mode appmanager_id = appmanager_handle.call('LaunchApp', {'ApplicationID': u's60uid://0x2000c83e'}, callback=launch_app_callback) #lock.wait() #print "Request complete!" barcode = clipboard.Get() return barcode # handle the selection made from the main body listbox def handle_selection(): if (lb.current() == 0): barcode = scan_barcode() elif (lb.current() ==1): barcode = clipboard.Get() elif (lb.current() ==2): barcode = input_barcode() found = False if is_barcode(barcode): found, mbid, album, artist = identify_release(barcode) else: msg('Valid barcode not found. Please try again/ another method/ another CD') return if found: go = appuifw.query(unicode('Found: ' + artist + ' - ' + album + '\nScrobble it?'), 'query') if (go == 1): now = datetime.datetime.utcnow() scrobble_tracks(mbid, album, artist, now) else: appuifw.note(u'Scrobbling cancelled', 'info') else: appuifw.note(u'No match found for this barcode.', 'info') # Set the application body up appuifw.app.exit_key_handler = quit appuifw.app.title = u"ScanScrobbler" entries = [(u"Scan a barcode", u"Opens UpCode for scanning"), (u"Submit barcode from clipboard", u"If you've already copied a barcode there"), (u"Enter barcode by hand", u"Using numeric keypad") ] lb = appuifw.Listbox(entries, handle_selection) appuifw.app.body = lb lock.wait() Any and all help appreciated.
[ "I solved this problem by defining a separate second lock, and making sure only one was waiting at a time. It seems to work without any problem. Current code can be found hosted on google code\n" ]
[ 0 ]
[]
[]
[ "locking", "multithreading", "nokia", "pys60", "python" ]
stackoverflow_0001207497_locking_multithreading_nokia_pys60_python.txt
Q: How to set python enviroment variable on windows I've downloaded python installer from http://www.python.org/ftp/python/3.1.2/ , this python-3.1.2.msi file, I need to execute some python files? How do I do that? For example in php I'd do php filename.php from console, I do however have python command line but I don't know how to execute those files. So if I could set ENV variable to directly execute my file(s) if that is possible that would be great. A: There is an option in the installer called "Register Extensions" to associate Python files with the interpreter, so double-clicking them or entering filename.py in the console should work. Apart from that you might want to add C:\Python31 to your PATH variable (right-click on My Computer, choose Settings, choose the Advanced Tab - there you can access the system variables. Better do this as an admin. A: If you type python in the Windows command line, what happens? Is the Python interpreter in your PATH yet? If not, add the Python installation directory there (here's a good guide). Then just do python script.py just like with PHP. A: you can just execute python yourfile.py Or if the python command don't work you have to give the absolute path to you python installation or add it to windows path
How to set python enviroment variable on windows
I've downloaded python installer from http://www.python.org/ftp/python/3.1.2/ , this python-3.1.2.msi file, I need to execute some python files? How do I do that? For example in php I'd do php filename.php from console, I do however have python command line but I don't know how to execute those files. So if I could set ENV variable to directly execute my file(s) if that is possible that would be great.
[ "There is an option in the installer called \"Register Extensions\" to associate Python files with the interpreter, so double-clicking them or entering filename.py in the console should work.\nApart from that you might want to add C:\\Python31 to your PATH variable (right-click on My Computer, choose Settings, choose the Advanced Tab - there you can access the system variables. Better do this as an admin.\n", "If you type python in the Windows command line, what happens? Is the Python interpreter in your PATH yet?\nIf not, add the Python installation directory there (here's a good guide). Then just do python script.py just like with PHP.\n", "you can just execute\npython yourfile.py \nOr if the python command don't work you have to give the absolute path to you python installation or add it to windows path\n" ]
[ 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003085146_python.txt
Q: How to fetch multiple values of a class all at once without loop? I know this is simple but I couldn' figure this out, I am fetching all the instances for a given linkname but I want to call all their values(rating2) to perform a calculation, what I realized though is in looping through I believe this is making an individual call each time, (its slow) it takes 2 seconds for only 100 instances of the LinkRating2 class. So how would I call all of the rating2 values for a given linkname without a loop and populate a dictionary? Or quite frankly make this code faster? class LinkRating2(db.Model): user = db.StringProperty() link = db.StringProperty() rating2 = db.FloatProperty() def sim_distance(link1,link2,tabl): # Get the list of shared_items si={} query = tabl.all() query2 = tabl.all() a = query.filter('link = ', link1) b = query2.filter('link = ', link2) adic ={} bdic= {} ##populate dics aa = a.fetch(10000) bb = b.fetch(10000) for itema in aa: adic[itema.user]=itema.rating2 for itemb in bb: bdic[itemb.user]=itemb.rating2 EDIT: ok I debugged and realized the loop is taking essentially 0 seconds, all my time is in the query and fetch lines, I only have a table with 100 items and it is taking 2 seconds!!!!! How can it be this slow to fetch a few items out of a 100 table and how can I speed this up? A: Your app isn't making any more calls than it needs to be. The only RPCs occur when you do the .fetch() operations. Any source of slowness is likely elsewhere. A: If your concern is that an RPC is firing inside each loop iteration, I don't think it would be. You're using fetch to eager load your entities, and your model has no reference properties, so you should be doing exactly two queries, and no gets. To track RPC volume and timing empirically, use Guido's Appstats framework. That will show you the total runtime of each script, and how much of it is consumed by RPC execution. You could also put a logging.debug before and after your loops to confirm that they run quickly. A: If you want to get rid of the loop, you can use adic = zip([itema.user for itema in aa],[itema.rating2 for itema in aa]) bdic = zip([itema.user for itema in bb],[itema.rating2 for itema in bb]) This won't necessarily make your code faster. If you just want to improve performance, look at the psyco package, or look here.
How to fetch multiple values of a class all at once without loop?
I know this is simple but I couldn' figure this out, I am fetching all the instances for a given linkname but I want to call all their values(rating2) to perform a calculation, what I realized though is in looping through I believe this is making an individual call each time, (its slow) it takes 2 seconds for only 100 instances of the LinkRating2 class. So how would I call all of the rating2 values for a given linkname without a loop and populate a dictionary? Or quite frankly make this code faster? class LinkRating2(db.Model): user = db.StringProperty() link = db.StringProperty() rating2 = db.FloatProperty() def sim_distance(link1,link2,tabl): # Get the list of shared_items si={} query = tabl.all() query2 = tabl.all() a = query.filter('link = ', link1) b = query2.filter('link = ', link2) adic ={} bdic= {} ##populate dics aa = a.fetch(10000) bb = b.fetch(10000) for itema in aa: adic[itema.user]=itema.rating2 for itemb in bb: bdic[itemb.user]=itemb.rating2 EDIT: ok I debugged and realized the loop is taking essentially 0 seconds, all my time is in the query and fetch lines, I only have a table with 100 items and it is taking 2 seconds!!!!! How can it be this slow to fetch a few items out of a 100 table and how can I speed this up?
[ "Your app isn't making any more calls than it needs to be. The only RPCs occur when you do the .fetch() operations. Any source of slowness is likely elsewhere.\n", "If your concern is that an RPC is firing inside each loop iteration, I don't think it would be. You're using fetch to eager load your entities, and your model has no reference properties, so you should be doing exactly two queries, and no gets.\nTo track RPC volume and timing empirically, use Guido's Appstats framework. That will show you the total runtime of each script, and how much of it is consumed by RPC execution. You could also put a logging.debug before and after your loops to confirm that they run quickly.\n", "If you want to get rid of the loop, you can use\nadic = zip([itema.user for itema in aa],[itema.rating2 for itema in aa])\nbdic = zip([itema.user for itema in bb],[itema.rating2 for itema in bb])\n\nThis won't necessarily make your code faster. If you just want to improve performance, look at the psyco package, or look here.\n" ]
[ 3, 1, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003084697_google_app_engine_python.txt
Q: Cheat sheet documentation django python Is there any Cheat Sheet or Document where I can see all the build-in modules, functions, commands etc in Django and or Python and where I will get an overview of ALL possible elements I could use. I am sure this is would be a big file/image etc , but it would be very helpful to know what commands I could use. A: Run: pydoc -p 8080 And go here. A: For django use this. It is a little out of date but still relevant. For python I like this quick reference. A: There is the Global Module Index for Python. Here are some build-in functions A: If you're using django, a useful way of browsing the template tags, models and so on for your project is to enable admin docs. See this post on how to enable admin docs.
Cheat sheet documentation django python
Is there any Cheat Sheet or Document where I can see all the build-in modules, functions, commands etc in Django and or Python and where I will get an overview of ALL possible elements I could use. I am sure this is would be a big file/image etc , but it would be very helpful to know what commands I could use.
[ "Run:\npydoc -p 8080\n\nAnd go here.\n", "For django use this. It is a little out of date but still relevant.\nFor python I like this quick reference.\n", "\nThere is the Global Module Index\nfor Python.\nHere are some build-in functions\n\n", "If you're using django, a useful way of browsing the template tags, models and so on for your project is to enable admin docs. See this post on how to enable admin docs.\n" ]
[ 5, 2, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003085196_django_python.txt
Q: Using Crypto by placing folder in python path? - Python I'm using Django in order to serve a web service. I have only access to FTP and code refresh at the moment. No access to command-line or executing any kind of executable. I am using a Windows Server 2005 machine. Would I be able to use Crypto just by placing the folder within my Django project? Are there any good alternatives if not? Help would be amazing guys!!! A: You'll need to build pycrypto before you upload it. This will need to be done on a machine with as similar an environment to your server as possible. To build, run python setup.py build from inside the pycrypto-2.1.0 directory. This will create build\lib.win32-2.6\Crypto (the name of the libxxx directory might be a little different). FTP the Crypto folder to somewhere on your server's python path. Inside the Django project folder may or may not work. A safe bet is to put it right in your site-packages folder, if you have access to it. I don't know much about deploying on Windows, but usually you need to restart the server to reload the application whenever you make any changes. Hopefully that's what you meant by 'code refresh'
Using Crypto by placing folder in python path? - Python
I'm using Django in order to serve a web service. I have only access to FTP and code refresh at the moment. No access to command-line or executing any kind of executable. I am using a Windows Server 2005 machine. Would I be able to use Crypto just by placing the folder within my Django project? Are there any good alternatives if not? Help would be amazing guys!!!
[ "You'll need to build pycrypto before you upload it. This will need to be done on a machine with as similar an environment to your server as possible.\nTo build, run python setup.py build from inside the pycrypto-2.1.0 directory. This will create build\\lib.win32-2.6\\Crypto (the name of the libxxx directory might be a little different).\nFTP the Crypto folder to somewhere on your server's python path. Inside the Django project folder may or may not work. A safe bet is to put it right in your site-packages folder, if you have access to it.\nI don't know much about deploying on Windows, but usually you need to restart the server to reload the application whenever you make any changes. Hopefully that's what you meant by 'code refresh'\n" ]
[ 1 ]
[]
[]
[ "aes", "django", "pycrypto", "python" ]
stackoverflow_0003083366_aes_django_pycrypto_python.txt
Q: how to connect my app python code to gui? i had made a program for text to speech convertion in python..and now want to make an gui for it... i have installed wxpython..and have been trying few example available online to understand,but i am not exactly understanding it.. i basically want a frame and a text box to enter text and a button...on clicking the button it the text in the text should be copied to the file and run the app.py file for giving the result.. I am finding this difficult as i am new to wxwidgets.. looking for some help..can someone tell how to perform this simple task in wxpython??? can i do it in vb and connect my py code to it?? import wx app=wx.App(redirect=False) window=wx.Frame(None, title='sample gui app',pos=(100,100),size=(400,500)) hellobtn=wx.Button(window,label='hello',pos = (200, 200), size = (60,25)) byeBtn=wx.Button(window,label='bye',pos=(250,250),size=(60,25)) printArea=wx.TextCtrl(window,pos=(10,10),size=(400-120-15-10,25),style=wx.TE_MULTILINE) window.Show() app.MainLoop() this is the code i wrote for creating a frames and text box and button hjow to add events to this and connect to the my code..on clicking a button i want it to run my .py file from cmd prmt on anywhere.. Thanks in advance.. A: Since Ned Batchelder covered the VB part of your question, I'll outline a wxPython approach. In short you'll need to import your module that contains the code you've written previously, then bind the button's click event to a function that calls your code. import myText2Speech ... code above ... hellobtn.Bind(wx.EVT_BUTTON, self.OnButton) def OnButton(self, event): """Prep whatever's needed, and call function txt2speech module.""" Of course your final code should be cleaner than all this, but this should give you a jumping off point. A: If you want to create the GUI in vb, take a look at IronPython: it's a Python implementation on .net, so you can use the entire .net ecosystem with your Python code. A: I would like to add that as far a Python GUI programming goes, my best experience has been with Python and QT. I can only assume that the Windows experience is as good as the Linux one.
how to connect my app python code to gui?
i had made a program for text to speech convertion in python..and now want to make an gui for it... i have installed wxpython..and have been trying few example available online to understand,but i am not exactly understanding it.. i basically want a frame and a text box to enter text and a button...on clicking the button it the text in the text should be copied to the file and run the app.py file for giving the result.. I am finding this difficult as i am new to wxwidgets.. looking for some help..can someone tell how to perform this simple task in wxpython??? can i do it in vb and connect my py code to it?? import wx app=wx.App(redirect=False) window=wx.Frame(None, title='sample gui app',pos=(100,100),size=(400,500)) hellobtn=wx.Button(window,label='hello',pos = (200, 200), size = (60,25)) byeBtn=wx.Button(window,label='bye',pos=(250,250),size=(60,25)) printArea=wx.TextCtrl(window,pos=(10,10),size=(400-120-15-10,25),style=wx.TE_MULTILINE) window.Show() app.MainLoop() this is the code i wrote for creating a frames and text box and button hjow to add events to this and connect to the my code..on clicking a button i want it to run my .py file from cmd prmt on anywhere.. Thanks in advance..
[ "Since Ned Batchelder covered the VB part of your question, I'll outline a wxPython approach.\nIn short you'll need to import your module that contains the code you've written previously, then bind the button's click event to a function that calls your code.\nimport myText2Speech\n... code above ...\n\nhellobtn.Bind(wx.EVT_BUTTON, self.OnButton)\n\ndef OnButton(self, event):\n \"\"\"Prep whatever's needed, and call function txt2speech module.\"\"\"\n\nOf course your final code should be cleaner than all this, but this should give you a jumping off point.\n", "If you want to create the GUI in vb, take a look at IronPython: it's a Python implementation on .net, so you can use the entire .net ecosystem with your Python code.\n", "I would like to add that as far a Python GUI programming goes, my best experience has been with Python and QT. I can only assume that the Windows experience is as good as the Linux one.\n" ]
[ 1, 0, 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0003084898_python_wxpython.txt
Q: Rejecting files with Windows line endings using Perforce triggers Using Perforce, I'd like to be able to reject submits which contain files with Windows line endings (\r\n IIRC, maybe just \r anywhere as really we only want files with Unix line endings). Rather than dos2unix incoming files or similar, to help track down instances where users attempt to submit files with Windows line endings, I'd like to add a trigger to reject text submissions which contain files with non-Unix line endings. Could someone demonstrate how the trigger itself could be written, perhaps with bash or python? Thanks A: Here's the minimal edit I can thing of for the bash example found in the p4 docs: #!/bin/sh # Set target string, files to search, location of p4 executable... TARGET='\r\n' DEPOT_PATH="//depot/src/..." CHANGE=$1 P4CMD="/usr/local/bin/p4 -p 1666 -c copychecker" XIT=0 echo "" # For each file, strip off #version and other non-filename info # Use sed to swap spaces w/"%" to obtain single arguments for "for" for FILE in `$P4CMD files $DEPOT_PATH@=$CHANGE | \ sed -e 's/\(.*\)\#[0-9]* - .*$/\1/' -e 's/ /%/g'` do # Undo the replacement to obtain filename... FILE="`echo $FILE | sed -e 's/%/ /g'`" # ...and use @= specifier to access file contents: # p4 print -q //depot/src/file.c@=12345 if $P4CMD print -q "$FILE@=$CHANGE" | fgrep "$TARGET" > /dev/null then echo "Submit fails: '$TARGET' not found in $FILE" XIT=1 else echo "" fi done exit $XIT The original example fails if the target is missing, this one fails if it's present -- just switching the then and else branches of the if. You could edit it further of course (e.g. giving grep, or fgrep, the -q flag to suppress output, if your grep supports it as e.g. GNU's does).
Rejecting files with Windows line endings using Perforce triggers
Using Perforce, I'd like to be able to reject submits which contain files with Windows line endings (\r\n IIRC, maybe just \r anywhere as really we only want files with Unix line endings). Rather than dos2unix incoming files or similar, to help track down instances where users attempt to submit files with Windows line endings, I'd like to add a trigger to reject text submissions which contain files with non-Unix line endings. Could someone demonstrate how the trigger itself could be written, perhaps with bash or python? Thanks
[ "Here's the minimal edit I can thing of for the bash example found in the p4 docs:\n#!/bin/sh\n# Set target string, files to search, location of p4 executable...\nTARGET='\\r\\n'\nDEPOT_PATH=\"//depot/src/...\"\nCHANGE=$1\nP4CMD=\"/usr/local/bin/p4 -p 1666 -c copychecker\"\nXIT=0\necho \"\"\n# For each file, strip off #version and other non-filename info\n# Use sed to swap spaces w/\"%\" to obtain single arguments for \"for\"\nfor FILE in `$P4CMD files $DEPOT_PATH@=$CHANGE | \\\n sed -e 's/\\(.*\\)\\#[0-9]* - .*$/\\1/' -e 's/ /%/g'`\ndo\n # Undo the replacement to obtain filename...\n FILE=\"`echo $FILE | sed -e 's/%/ /g'`\"\n# ...and use @= specifier to access file contents:\n # p4 print -q //depot/src/file.c@=12345\n if $P4CMD print -q \"$FILE@=$CHANGE\" | fgrep \"$TARGET\" > /dev/null\n then \n echo \"Submit fails: '$TARGET' not found in $FILE\"\n XIT=1\n else\n echo \"\"\n\n fi\ndone\nexit $XIT\n\nThe original example fails if the target is missing, this one fails if it's present -- just switching the then and else branches of the if. You could edit it further of course (e.g. giving grep, or fgrep, the -q flag to suppress output, if your grep supports it as e.g. GNU's does).\n" ]
[ 4 ]
[]
[]
[ "bash", "perforce", "python", "triggers" ]
stackoverflow_0003085825_bash_perforce_python_triggers.txt
Q: Is it possible to get the value of an item contained in Django's "changed_data" list? I have the following code in my Django application: if 'book' in authorForm.changed_data: #Do something here... I realize Django can tell me which values have changed in my form by utilizing the "changed_data" list object, but I'd like to know the new values of the fields that have changed. Any thoughts? A: Hmm... Try this: if authorForm.is_valid() and 'book' in authorForm.changed_data: new_value = authorForm.cleaned_data['book'] A: The short answer to my original question is "No".
Is it possible to get the value of an item contained in Django's "changed_data" list?
I have the following code in my Django application: if 'book' in authorForm.changed_data: #Do something here... I realize Django can tell me which values have changed in my form by utilizing the "changed_data" list object, but I'd like to know the new values of the fields that have changed. Any thoughts?
[ "Hmm... Try this:\nif authorForm.is_valid() and 'book' in authorForm.changed_data:\n new_value = authorForm.cleaned_data['book']\n\n", "The short answer to my original question is \"No\".\n" ]
[ 2, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000247922_django_python.txt
Q: How to extract data from an irregularly formatted data file in python I need to extract certain data from a file, but this file is formatted to be read by humans, and is therefore irregular. First off there is a large amount of text before any of the data actually begins: DL_POLY Version 2.20 Running on 10 nodes *************** DLPOLY: LiNbO3 >*************** SIMULATION CONTROL PARAMETERS simulation temperature 1.4500E+03 simulation pressure (katm) 0.0000E+00 selected number of timesteps 8000 equilibration period 500 data printing interval 80 statistics file interval 80 simulation timestep 5.0000E-04 Nose-Hoover (Melchionna) isotropic N-P-T thermostat relaxation time 1.0000E-01 barostat relaxation time 5.0000E-01 trajectory file option on trajectory file start 1 trajectory file interval 80 trajectory file info key 2 ... Then after a while there is the actual data but it is in this funny form: step eng_tot temp_tot eng_cfg eng_vdw eng_cou eng_bnd > eng_ang eng_dih eng_tet time(ps) eng_pv temp_rot vir_cfg vir_vdw vir_cou vir_bnd >vir_ang vir_con vir_tet cpu (s) volume temp_shl eng_shl vir_shl alpha beta >gamma vir_pmf press 1 -1.1289E+05 1.4750E+03 -1.1386E+05 1.7276E+04 -1.3114E+05 0.0000E+00 >0.0000E+00 0.0000E+00 0.0000E+00 0.0 -1.1545E+05 0.0000E+00 9.6539E+03 -1.2118E+05 1.3083E+05 0.0000E+00 >0.0000E+00 0.0000E+00 0.0000E+00 0.8 5.3733E+04 1.2367E+02 0.0000E+00 0.0000E+00 5.6396E+01 5.6396E+01 >5.6396E+01 0.0000E+00 -7.5549E+01 rolling -1.1289E+05 1.4750E+03 -1.1386E+05 1.7276E+04 -1.3114E+05 0.0000E+00 >0.0000E+00 0.0000E+00 0.0000E+00 averages -1.1545E+05 0.0000E+00 9.6539E+03 -1.2118E+05 1.3083E+05 0.0000E+00 >0.0000E+00 0.0000E+00 0.0000E+00 5.3733E+04 1.2367E+02 0.0000E+00 0.0000E+00 5.6396E+01 5.6396E+01 >5.6396E+01 0.0000E+00 -7.5549E+01 80 -1.1290E+05 1.5021E+03 -1.1392E+05 2.1894E+04 -1.3726E+05 0.0000E+00 >0.0000E+00 0.0000E+00 0.0000E+00 0.0 -1.1256E+05 0.0000E+00 8.6671E+02 -1.3974E+05 1.3707E+05 0.0000E+00 >0.0000E+00 0.0000E+00 0.0000E+00 10.6 5.3149E+04 1.1377E+03 1.4419E+03 3.5382E+03 5.6396E+01 5.6396E+01 >5.6396E+01 0.0000E+00 1.1119E+01 rolling -1.1290E+05 1.6145E+03 -1.1398E+05 2.0750E+04 -1.3588E+05 0.0000E+00 >0.0000E+00 0.0000E+00 0.0000E+00 averages -1.1333E+05 0.0000E+00 3.3694E+03 -1.3512E+05 1.3565E+05 0.0000E+00 >0.0000E+00 0.0000E+00 0.0000E+00 5.3481E+04 1.0997E+03 1.1430E+03 2.8391E+03 5.6396E+01 5.6396E+01 >5.6396E+01 0.0000E+00 -1.2096E+01 160 -1.1287E+05 1.2629E+03 -1.1376E+05 2.1450E+04 -1.3633E+05 0.0000E+00 >0.0000E+00 0.0000E+00 0.0000E+00 0.1 -1.1249E+05 0.0000E+00 3.8761E+02 -1.3824E+05 1.3612E+05 0.0000E+00 >0.0000E+00 0.0000E+00 0.0000E+00 20.5 5.3375E+04 4.9015E+02 1.1243E+03 2.5052E+03 5.6396E+01 5.6396E+01 >5.6396E+01 0.0000E+00 1.2676E+01 rolling -1.1288E+05 1.4677E+03 -1.1389E+05 2.1589E+04 -1.3663E+05 0.0000E+00 0.0000E+00 0.0000E+00 0.0000E+00 averages -1.1235E+05 0.0000E+00 2.1147E+02 -1.3884E+05 1.3643E+05 0.0000E+00 >0.0000E+00 0.0000E+00 0.0000E+00 5.3152E+04 7.4818E+02 1.1440E+03 2.6211E+03 5.6396E+01 5.6396E+01 >5.6396E+01 0.0000E+00 1.7174E+01 On the 9th data interval there is a slight anamoly: switching off temperature scaling at step 500 560 -1.1287E+05 1.4709E+03 -1.1390E+05 2.1600E+04 -1.3678E+05 0.0000E+00 >0.0000E+00 0.0000E+00 0.0000E+00 0.3 -1.1292E+05 0.0000E+00 1.9253E+03 -1.3743E+05 1.3656E+05 0.0000E+00 >0.0000E+00 0.0000E+00 0.0000E+00 68.4 5.4300E+04 1.5043E+02 1.2775E+03 2.7947E+03 5.6396E+01 5.6396E+01 >5.6396E+01 0.0000E+00 2.0576E-01 rolling -1.1286E+05 1.4784E+03 -1.1390E+05 2.1546E+04 -1.3673E+05 0.0000E+00 >0.0000E+00 0.0000E+00 0.0000E+00 averages -1.1298E+05 0.0000E+00 2.1361E+03 -1.3717E+05 1.3651E+05 0.0000E+00 >0.0000E+00 0.0000E+00 0.0000E+00 5.4303E+04 2.2261E+02 1.2785E+03 2.8027E+03 5.6396E+01 5.6396E+01 >5.6396E+01 0.0000E+00 -1.7421E+00 As you can see there is a pair of '----' lines which may interfere with proper parsing of the data. Lets say I want to get just 'the eng_tot' data from this file (the bolded numbers), how would I go about doing that in Python? The number is always in the same place in the file (second quantity, first row after second set of ----s. By the way the header part with all the definitions in it repeats every 8 steps, execpt the first step in which there are 9 lines. I'd like to just ignore the first step. For now lets say I want to start with line 295 inclusive. Just so you know, I'm quite new to python and programming in general so all the help you can provide is appreciated. Here's the code I tried, but Eng_Total is still an empty set: import re import inspect def lineno(): """Returns the current line number""" linenum = inspect.currentframe().f_back.f_lineno infile = open('FilePath/OUTPUT.01').read() Eng_Total = [] for line in infile: # if 'eng_tot' in line.split(): if re.match("\s+-+\s+", line): lineno(line) line = linenum+1 sanitized_line = line[8:] eng_total = line.split()[0] Eng_Total.append(eng_total) print Eng_Total A: I'd probably do this: iterate over lines in the output search for one containing eng_tot: if 'eng_tot' in line.split(): process_blocks gobble up lines until one matches all dashes (with optional spaces on either side) if re.match("\s+-+\s+", line): proccess_metrics_block process the first line of metrics: cut the first column off the line (it makes it harder to parse, because it might not be there) sanitized_line = line[8:] eng_total = line.split()[0] , the first column is now eng_total skip lines until you reach another line of dashes, then start again After seeing your edits: You need to import the re (regular expression) module, at the top of the file : import re The process_blocks and process_metrics_block were pseudo code. Those don't exist unless you define them. :) You don't need those functions exactly, you can avoid them using basic looping (while) and conditional (if) statements. You'll have to make sure you understand what you're doing, not just copy from stack overflow! :) It looks like you're trying to do something like this. It seems to work, but I'm sure with some effort, you can come up with something nicer: import re def find_header(lines): for (i, line) in enumerate(lines): if 'eng_tot' in line.split(): return i return None def find_next_separator(lines, start): for (i, line) in enumerate(lines[start+1:]): if re.match("\s*-+\s*", line): return i + start + 1 return None if __name__ == '__main__': totals = [] lines = open('so.txt').readlines() header = find_header(lines) start = find_next_separator(lines, header+1) while True: end = find_next_separator(lines, start+1) if end is None: break # Pull out block, after line of dashes. metrics_block = lines[start+1:end] # Pull out 2nd column from 1st line of metrics. eng_total = metrics_block[0].split()[1] totals.append(eng_total) start = end print totals You can use a generator to be a little more pythonic: def metric_block_iter(lines): start = find_next_separator(lines, find_header(lines)+1) while True: end = find_next_separator(lines, start+1) if end is None: break yield (start, end) start = end if __name__ == '__main__': totals = [] lines = open('so.txt').readlines() for (start, end) in metric_block_iter(lines): # Pull out block, after line of dashes. metrics_block = lines[start+1:end] # Pull out 2nd column from 1st line of metrics. eng_total = metrics_block[0].split()[1] totals.append(eng_total) print totals A: You're going to need to define the file format explicitly, and then you should be able to parse that easily. The first step is figuring out where the data you need is defined. Then throw away everything up to that point. Then start reading. If the eng_tot can move, you need to figure out where in the block of useful data it is. So, read a line, entries = line.split(); location = entries.index('eng_tot'), then read th entry out of that location in the associated line in the output data. The key is that you need to break down your problem into steps that you know you can do. When looking at something new it's easy to get overwhelmed. If you can just start doing something, you'll find that you can reach the solution without too much trouble after all.
How to extract data from an irregularly formatted data file in python
I need to extract certain data from a file, but this file is formatted to be read by humans, and is therefore irregular. First off there is a large amount of text before any of the data actually begins: DL_POLY Version 2.20 Running on 10 nodes *************** DLPOLY: LiNbO3 >*************** SIMULATION CONTROL PARAMETERS simulation temperature 1.4500E+03 simulation pressure (katm) 0.0000E+00 selected number of timesteps 8000 equilibration period 500 data printing interval 80 statistics file interval 80 simulation timestep 5.0000E-04 Nose-Hoover (Melchionna) isotropic N-P-T thermostat relaxation time 1.0000E-01 barostat relaxation time 5.0000E-01 trajectory file option on trajectory file start 1 trajectory file interval 80 trajectory file info key 2 ... Then after a while there is the actual data but it is in this funny form: step eng_tot temp_tot eng_cfg eng_vdw eng_cou eng_bnd > eng_ang eng_dih eng_tet time(ps) eng_pv temp_rot vir_cfg vir_vdw vir_cou vir_bnd >vir_ang vir_con vir_tet cpu (s) volume temp_shl eng_shl vir_shl alpha beta >gamma vir_pmf press 1 -1.1289E+05 1.4750E+03 -1.1386E+05 1.7276E+04 -1.3114E+05 0.0000E+00 >0.0000E+00 0.0000E+00 0.0000E+00 0.0 -1.1545E+05 0.0000E+00 9.6539E+03 -1.2118E+05 1.3083E+05 0.0000E+00 >0.0000E+00 0.0000E+00 0.0000E+00 0.8 5.3733E+04 1.2367E+02 0.0000E+00 0.0000E+00 5.6396E+01 5.6396E+01 >5.6396E+01 0.0000E+00 -7.5549E+01 rolling -1.1289E+05 1.4750E+03 -1.1386E+05 1.7276E+04 -1.3114E+05 0.0000E+00 >0.0000E+00 0.0000E+00 0.0000E+00 averages -1.1545E+05 0.0000E+00 9.6539E+03 -1.2118E+05 1.3083E+05 0.0000E+00 >0.0000E+00 0.0000E+00 0.0000E+00 5.3733E+04 1.2367E+02 0.0000E+00 0.0000E+00 5.6396E+01 5.6396E+01 >5.6396E+01 0.0000E+00 -7.5549E+01 80 -1.1290E+05 1.5021E+03 -1.1392E+05 2.1894E+04 -1.3726E+05 0.0000E+00 >0.0000E+00 0.0000E+00 0.0000E+00 0.0 -1.1256E+05 0.0000E+00 8.6671E+02 -1.3974E+05 1.3707E+05 0.0000E+00 >0.0000E+00 0.0000E+00 0.0000E+00 10.6 5.3149E+04 1.1377E+03 1.4419E+03 3.5382E+03 5.6396E+01 5.6396E+01 >5.6396E+01 0.0000E+00 1.1119E+01 rolling -1.1290E+05 1.6145E+03 -1.1398E+05 2.0750E+04 -1.3588E+05 0.0000E+00 >0.0000E+00 0.0000E+00 0.0000E+00 averages -1.1333E+05 0.0000E+00 3.3694E+03 -1.3512E+05 1.3565E+05 0.0000E+00 >0.0000E+00 0.0000E+00 0.0000E+00 5.3481E+04 1.0997E+03 1.1430E+03 2.8391E+03 5.6396E+01 5.6396E+01 >5.6396E+01 0.0000E+00 -1.2096E+01 160 -1.1287E+05 1.2629E+03 -1.1376E+05 2.1450E+04 -1.3633E+05 0.0000E+00 >0.0000E+00 0.0000E+00 0.0000E+00 0.1 -1.1249E+05 0.0000E+00 3.8761E+02 -1.3824E+05 1.3612E+05 0.0000E+00 >0.0000E+00 0.0000E+00 0.0000E+00 20.5 5.3375E+04 4.9015E+02 1.1243E+03 2.5052E+03 5.6396E+01 5.6396E+01 >5.6396E+01 0.0000E+00 1.2676E+01 rolling -1.1288E+05 1.4677E+03 -1.1389E+05 2.1589E+04 -1.3663E+05 0.0000E+00 0.0000E+00 0.0000E+00 0.0000E+00 averages -1.1235E+05 0.0000E+00 2.1147E+02 -1.3884E+05 1.3643E+05 0.0000E+00 >0.0000E+00 0.0000E+00 0.0000E+00 5.3152E+04 7.4818E+02 1.1440E+03 2.6211E+03 5.6396E+01 5.6396E+01 >5.6396E+01 0.0000E+00 1.7174E+01 On the 9th data interval there is a slight anamoly: switching off temperature scaling at step 500 560 -1.1287E+05 1.4709E+03 -1.1390E+05 2.1600E+04 -1.3678E+05 0.0000E+00 >0.0000E+00 0.0000E+00 0.0000E+00 0.3 -1.1292E+05 0.0000E+00 1.9253E+03 -1.3743E+05 1.3656E+05 0.0000E+00 >0.0000E+00 0.0000E+00 0.0000E+00 68.4 5.4300E+04 1.5043E+02 1.2775E+03 2.7947E+03 5.6396E+01 5.6396E+01 >5.6396E+01 0.0000E+00 2.0576E-01 rolling -1.1286E+05 1.4784E+03 -1.1390E+05 2.1546E+04 -1.3673E+05 0.0000E+00 >0.0000E+00 0.0000E+00 0.0000E+00 averages -1.1298E+05 0.0000E+00 2.1361E+03 -1.3717E+05 1.3651E+05 0.0000E+00 >0.0000E+00 0.0000E+00 0.0000E+00 5.4303E+04 2.2261E+02 1.2785E+03 2.8027E+03 5.6396E+01 5.6396E+01 >5.6396E+01 0.0000E+00 -1.7421E+00 As you can see there is a pair of '----' lines which may interfere with proper parsing of the data. Lets say I want to get just 'the eng_tot' data from this file (the bolded numbers), how would I go about doing that in Python? The number is always in the same place in the file (second quantity, first row after second set of ----s. By the way the header part with all the definitions in it repeats every 8 steps, execpt the first step in which there are 9 lines. I'd like to just ignore the first step. For now lets say I want to start with line 295 inclusive. Just so you know, I'm quite new to python and programming in general so all the help you can provide is appreciated. Here's the code I tried, but Eng_Total is still an empty set: import re import inspect def lineno(): """Returns the current line number""" linenum = inspect.currentframe().f_back.f_lineno infile = open('FilePath/OUTPUT.01').read() Eng_Total = [] for line in infile: # if 'eng_tot' in line.split(): if re.match("\s+-+\s+", line): lineno(line) line = linenum+1 sanitized_line = line[8:] eng_total = line.split()[0] Eng_Total.append(eng_total) print Eng_Total
[ "I'd probably do this:\n\niterate over lines in the output\nsearch for one containing eng_tot:\n\n\nif 'eng_tot' in line.split(): process_blocks\n\ngobble up lines until one matches all dashes (with optional spaces on either side)\n\n\nif re.match(\"\\s+-+\\s+\", line): proccess_metrics_block\n\nprocess the first line of metrics:\n\n\ncut the first column off the line (it makes it harder to parse, because it might not be there)\n\n\nsanitized_line = line[8:]\neng_total = line.split()[0] , the first column is now eng_total\n\n\nskip lines until you reach another line of dashes, then start again\n\nAfter seeing your edits:\n\nYou need to import the re (regular expression) module, at the top of the file : import re\nThe process_blocks and process_metrics_block were pseudo code. Those don't exist unless you define them. :) You don't need those functions exactly, you can avoid them using basic looping (while) and conditional (if) statements.\nYou'll have to make sure you understand what you're doing, not just copy from stack overflow! :)\n\nIt looks like you're trying to do something like this. It seems to work, but I'm sure with some effort, you can come up with something nicer:\nimport re\n\ndef find_header(lines):\n for (i, line) in enumerate(lines):\n if 'eng_tot' in line.split():\n return i\n return None\n\ndef find_next_separator(lines, start):\n for (i, line) in enumerate(lines[start+1:]):\n if re.match(\"\\s*-+\\s*\", line):\n return i + start + 1\n return None\n\nif __name__ == '__main__':\n totals = []\n lines = open('so.txt').readlines()\n\n header = find_header(lines)\n start = find_next_separator(lines, header+1)\n\n while True:\n end = find_next_separator(lines, start+1)\n if end is None: break\n\n # Pull out block, after line of dashes.\n metrics_block = lines[start+1:end]\n\n # Pull out 2nd column from 1st line of metrics.\n eng_total = metrics_block[0].split()[1]\n totals.append(eng_total)\n\n start = end\n\n print totals\n\nYou can use a generator to be a little more pythonic:\ndef metric_block_iter(lines):\n start = find_next_separator(lines, find_header(lines)+1)\n while True:\n end = find_next_separator(lines, start+1)\n if end is None: break\n yield (start, end)\n start = end\n\n\nif __name__ == '__main__':\n totals = []\n lines = open('so.txt').readlines()\n\n for (start, end) in metric_block_iter(lines):\n # Pull out block, after line of dashes.\n metrics_block = lines[start+1:end]\n\n # Pull out 2nd column from 1st line of metrics.\n eng_total = metrics_block[0].split()[1]\n totals.append(eng_total)\n\n print totals\n\n", "You're going to need to define the file format explicitly, and then you should be able to parse that easily.\nThe first step is figuring out where the data you need is defined. Then throw away everything up to that point. Then start reading.\nIf the eng_tot can move, you need to figure out where in the block of useful data it is. So, read a line, entries = line.split(); location = entries.index('eng_tot'), then read th entry out of that location in the associated line in the output data.\nThe key is that you need to break down your problem into steps that you know you can do. When looking at something new it's easy to get overwhelmed. If you can just start doing something, you'll find that you can reach the solution without too much trouble after all.\n" ]
[ 1, 0 ]
[]
[]
[ "parsing", "python" ]
stackoverflow_0003086257_parsing_python.txt
Q: Django: return one filtered object per foreign key Is it possible to return querysets that return only one object per foreign key? For instance, I want the to get the latest comments from django_comments, but I only want one comment (the latest comment) per object, i.e., only return the latest comment on an object and exclude all the past comments on that object. I guess this would be similar to a sql group_by on django_comments.content_type and django_comments.object_pk. ++ADDED INFO++ The end goal is to create a list of active comment "threads" displayed/ordered by which thread has the most recent comment, just like your standard discussion board whose topics are listed by recent activity. I figure the best way to do this would be grabbing the latest comments, and then sorting or grouping them by content type and object_pk so that only one comment (the latest) is returned per related content object. I can then use that comment to get all the info I need, so the word thread is used loosely since I'm really just grabbing a comment and following it's pk's. The MODEL is django_threadedcomments which extends django_comments with some added fields for trees, children, and parents. VIEW: ...this returns all comments including all instances of parent comments = ThreadedComment.objects.all().exclude(is_public='0').order_by("-submit_date") ...and this is ideal comments = ThreadedComment.objects.all().exclude(is_public='0').order_by("submit_date").[plus sorting logic to exclude multiple instances of the same object_pk and content_type] TEMPLATE: {% for comment in comments %} TITLE: {{comment.content_object.title}} STARTED BY : {{comment.content_object.user}} MOST RECENT REPLY : {{comment.user}} on {{comment.submit_date}} {% endfor %} Thanks again! A: This is a fairly difficult thing to do in SQL at all; you probably won't be able to do it through the ORM. You can't use GROUP BY for this. That's used for telling SQL how to group items for aggregation, which isn't what you're doing here. "SELECT x, y FROM table GROUP BY x" is illegal SQL, because the value of y is meaningless. Let's look at this with a clear schema in mind: CREATE TABLE objects ( id INTEGER PRIMARY KEY, name VARCHAR ); CREATE TABLE comments ( object_id INTEGER REFERENCES objects (id), text VARCHAR NOT NULL, date TIMESTAMP NOT NULL ); INSERT INTO objects (id, name) VALUES (1, 'object 1'), (2, 'object 2'); INSERT INTO comments (object_id, text, date) VALUES (1, 'object 1 comment 1', '2010-01-02'), (1, 'object 1 comment 2', '2010-01-05'), (2, 'object 2 comment 1', '2010-01-08'), (2, 'object 2 comment 2', '2010-01-09'); SELECT * FROM objects o JOIN comments c ON (o.id = c.object_id); The most elegant way I've seen for doing this is Postgresql 8.4's windowing functions. SELECT * FROM ( SELECT o.*, c.*, rank() OVER (PARTITION BY object_id ORDER BY date DESC) AS r FROM objects o JOIN comments c ON (o.id = c.object_id) ) AS s WHERE r = 1; That'll select the first comment for each object by date, newest first. If you don't see what this is doing, execute the inner SELECT on its own and watch how it generates rank(), which makes it pretty straightforward. I know other ways of doing this with Postgresql, but I don't know how to do this in other databases. Trying to compute this dynamically is likely to give you serious headaches--and it takes more work to make these complex queries perform well, too. Chances are you're better off doing this the simple way: store a last_comment_id field for each object and update it when a comment is added or deleted, so you can just join and sort. You could probably use SQL triggers to handle this updating automatically. A: Thanks Glenn and vdboor. Agreed, the proposed idea creates way to much sql complexity and will seriously impact performance. The last_comment_id suggestion is very good, but I believe that for my particular situation the best thing to do is create a separate "THREAD" model that stores the content_type and object_pk of the original object commented upon as well as the id and timestamp of the object's last comment, among a few other things. This will allow simple content object lookups and chronologically filtered querysets, and will make what's happening under the hood more closely mirror the front-end presentation, which is probably a good idea for posterity. :) Cheers, jnh
Django: return one filtered object per foreign key
Is it possible to return querysets that return only one object per foreign key? For instance, I want the to get the latest comments from django_comments, but I only want one comment (the latest comment) per object, i.e., only return the latest comment on an object and exclude all the past comments on that object. I guess this would be similar to a sql group_by on django_comments.content_type and django_comments.object_pk. ++ADDED INFO++ The end goal is to create a list of active comment "threads" displayed/ordered by which thread has the most recent comment, just like your standard discussion board whose topics are listed by recent activity. I figure the best way to do this would be grabbing the latest comments, and then sorting or grouping them by content type and object_pk so that only one comment (the latest) is returned per related content object. I can then use that comment to get all the info I need, so the word thread is used loosely since I'm really just grabbing a comment and following it's pk's. The MODEL is django_threadedcomments which extends django_comments with some added fields for trees, children, and parents. VIEW: ...this returns all comments including all instances of parent comments = ThreadedComment.objects.all().exclude(is_public='0').order_by("-submit_date") ...and this is ideal comments = ThreadedComment.objects.all().exclude(is_public='0').order_by("submit_date").[plus sorting logic to exclude multiple instances of the same object_pk and content_type] TEMPLATE: {% for comment in comments %} TITLE: {{comment.content_object.title}} STARTED BY : {{comment.content_object.user}} MOST RECENT REPLY : {{comment.user}} on {{comment.submit_date}} {% endfor %} Thanks again!
[ "This is a fairly difficult thing to do in SQL at all; you probably won't be able to do it through the ORM.\nYou can't use GROUP BY for this. That's used for telling SQL how to group items for aggregation, which isn't what you're doing here. \"SELECT x, y FROM table GROUP BY x\" is illegal SQL, because the value of y is meaningless.\nLet's look at this with a clear schema in mind:\nCREATE TABLE objects ( id INTEGER PRIMARY KEY, name VARCHAR );\nCREATE TABLE comments ( object_id INTEGER REFERENCES objects (id), text VARCHAR NOT NULL, date TIMESTAMP NOT NULL );\n\nINSERT INTO objects (id, name) VALUES (1, 'object 1'), (2, 'object 2');\nINSERT INTO comments (object_id, text, date) VALUES\n (1, 'object 1 comment 1', '2010-01-02'),\n (1, 'object 1 comment 2', '2010-01-05'),\n (2, 'object 2 comment 1', '2010-01-08'),\n (2, 'object 2 comment 2', '2010-01-09');\n\nSELECT * FROM objects o JOIN comments c ON (o.id = c.object_id);\n\nThe most elegant way I've seen for doing this is Postgresql 8.4's windowing functions.\nSELECT * FROM (\n SELECT\n o.*, c.*,\n rank() OVER (PARTITION BY object_id ORDER BY date DESC) AS r\n FROM objects o JOIN comments c ON (o.id = c.object_id)\n) AS s\nWHERE r = 1;\n\nThat'll select the first comment for each object by date, newest first. If you don't see what this is doing, execute the inner SELECT on its own and watch how it generates rank(), which makes it pretty straightforward.\nI know other ways of doing this with Postgresql, but I don't know how to do this in other databases.\nTrying to compute this dynamically is likely to give you serious headaches--and it takes more work to make these complex queries perform well, too. Chances are you're better off doing this the simple way: store a last_comment_id field for each object and update it when a comment is added or deleted, so you can just join and sort. You could probably use SQL triggers to handle this updating automatically.\n", "Thanks Glenn and vdboor. Agreed, the proposed idea creates way to much sql complexity and will seriously impact performance. \nThe last_comment_id suggestion is very good, but I believe that for my particular situation the best thing to do is create a separate \"THREAD\" model that stores the content_type and object_pk of the original object commented upon as well as the id and timestamp of the object's last comment, among a few other things. This will allow simple content object lookups and chronologically filtered querysets, and will make what's happening under the hood more closely mirror the front-end presentation, which is probably a good idea for posterity. :)\nCheers,\njnh\n" ]
[ 2, 0 ]
[ "Consider storing the last post as a foreign key somewhere (e.g. in the parent object table). Each time a message is posted or deleted, update this key.\nYes, it's duplication, but worth considering. Having to run complex queries for each request (especially the index page) could take your application performance down. This is the pragmatic way to get the desired effect without losing performance.\n" ]
[ -1 ]
[ "content_type", "django", "django_comments", "django_orm", "python" ]
stackoverflow_0003080326_content_type_django_django_comments_django_orm_python.txt
Q: Python memory usage: Which of my objects is hogging the most memory? The program I've written stores a large amount of data in dictionaries. Specifically, I'm creating 1588 instances of a class, each of which contains 15 dictionaries with 1500 float to float mappings. This process has been using up the 2GB of memory on my laptop pretty quickly (I start writing to swap at about the 1000th instance of the class). My question is, which of the following is using up my memory? 34 million some pairs of floats? The overhead of 22,500 dictionaries? the overhead of 1500 classes? To me it seems like the memory hog should be the huge number of floating point numbers that I'm holding in memory. However, If what I've read so far is correct, each of my floating point numbers take up 16 bytes. Since I have 34 million pairs, this should be about 108 million bytes, which should be just over a gigabyte. Is there something I'm not taking into consideration here? A: The floats do take up 16 bytes apiece, and a dict with 1500 entries about 100k: >> sys.getsizeof(1.0) 16 >>> d = dict.fromkeys((float(i) for i in range(1500)), 2.0) >>> sys.getsizeof(d) 98444 so the 22,500 dicts take over 2GB all by themselves, the 68 million floats another GB or so. Not sure how you compute 68 million times 16 equal only 100M -- you may have dropped a zero somewhere. The class itself takes up a negligible amount, and 1500 instances thereof (net of the objects they refer to of course, just as getsizeof gives us such net amounts for the dicts) not much more than a smallish dict each, so, that's hardly the problem. I.e.: >>> sys.getsizeof(Sic) 452 >>> sys.getsizeof(Sic()) 32 >>> sys.getsizeof(Sic().__dict__) 524 452 for the class, (524 + 32) * 1550 = 862K for all the instances, as you see that's not the worry when you have gigabytes each in dicts and floats.
Python memory usage: Which of my objects is hogging the most memory?
The program I've written stores a large amount of data in dictionaries. Specifically, I'm creating 1588 instances of a class, each of which contains 15 dictionaries with 1500 float to float mappings. This process has been using up the 2GB of memory on my laptop pretty quickly (I start writing to swap at about the 1000th instance of the class). My question is, which of the following is using up my memory? 34 million some pairs of floats? The overhead of 22,500 dictionaries? the overhead of 1500 classes? To me it seems like the memory hog should be the huge number of floating point numbers that I'm holding in memory. However, If what I've read so far is correct, each of my floating point numbers take up 16 bytes. Since I have 34 million pairs, this should be about 108 million bytes, which should be just over a gigabyte. Is there something I'm not taking into consideration here?
[ "The floats do take up 16 bytes apiece, and a dict with 1500 entries about 100k:\n>> sys.getsizeof(1.0)\n16\n>>> d = dict.fromkeys((float(i) for i in range(1500)), 2.0)\n>>> sys.getsizeof(d)\n98444\n\nso the 22,500 dicts take over 2GB all by themselves, the 68 million floats another GB or so. Not sure how you compute 68 million times 16 equal only 100M -- you may have dropped a zero somewhere.\nThe class itself takes up a negligible amount, and 1500 instances thereof (net of the objects they refer to of course, just as getsizeof gives us such net amounts for the dicts) not much more than a smallish dict each, so, that's hardly the problem. I.e.:\n>>> sys.getsizeof(Sic)\n452\n>>> sys.getsizeof(Sic())\n32\n>>> sys.getsizeof(Sic().__dict__)\n524\n\n452 for the class, (524 + 32) * 1550 = 862K for all the instances, as you see that's not the worry when you have gigabytes each in dicts and floats.\n" ]
[ 7 ]
[]
[]
[ "memory_management", "python" ]
stackoverflow_0003086514_memory_management_python.txt
Q: What's the equivalent of python's __file__ in ruby? In python after imports, one can see the file, that has been loaded/where the module comes from. >>> import os >>> os.__file__ '/Users/tm/lib/python2.6/os.pyc' What would be the equivalent in ruby? >> require 'xmlrpc/client' => true >> ... A: There's nothing that's an exact match. It's easy to find it yourself, though: # Find where a path `p` was loaded from. def locate(p) # Find the first path in your load-paths that contains a file matching `p`. $:.find { |l| File.exists?(File.join(l, p)) } end ruby-1.9.1-p378 > locate('yaml') => "/home/johnf/.rvm/rubies/ruby-1.9.1-p378/lib/ruby/1.9.1" # --> This tells you that 'yaml.rb' was loaded from here. ruby-1.9.1-p378 > locate('zzz') => nil # --> There's no matches for this library. ruby-1.9.1-p378 > locate('haml') => "/home/johnf/.rvm/gems/ruby-1.9.1-p378@standard/gems/haml-3.0.12/bin" # --> Here's a third-party library from my gems. A: There's nothing exactly equivalent. All files that have been required are listed in $LOADED_FEATURES in the order they were required. So, if you want to know where a file came from directly after it was required, you simply need to look at the end: $LOADED_FEATURES.last if require 'yaml' # => 'C:/Program Files/Ruby/lib/ruby/1.9.1/yaml.rb' However, unless you record every call to require it's going to be hard to figure out which entry corresponds to which call. Also, if a file is already in $LOADED_FEATURES, it will not get loaded again: require 'yaml' # => true # true means: the file was loaded $LOADED_FEATURES.last # => 'C:/Program Files/Ruby/lib/ruby/1.9.1/yaml.rb' require 'json' $LOADED_FEATURES.last # => 'C:/Program Files/Ruby/lib/ruby/1.9.1/json.rb' require 'yaml' # => false # false means: the file wasn't loaded again, because it has already been loaded $LOADED_FEATURES.last # => 'C:/Program Files/Ruby/lib/ruby/1.9.1/json.rb' # Last loaded feature is still JSON, because YAML wasn't actually loaded twice Also, many libraries aren't contained in a single file. So, the required files might themselves contain calls to require. In my case, for example, require 'yaml' not only loads yaml.rb but a whole bunch of files (15 to be exact): C:/Program Files/Ruby/lib/ruby/1.9.1/i386-mingw32/stringio.so C:/Program Files/Ruby/lib/ruby/1.9.1/i386-mingw32/syck.so C:/Program Files/Ruby/lib/ruby/1.9.1/syck/error.rb C:/Program Files/Ruby/lib/ruby/1.9.1/syck/basenode.rb C:/Program Files/Ruby/lib/ruby/1.9.1/syck/syck.rb C:/Program Files/Ruby/lib/ruby/1.9.1/syck/tag.rb C:/Program Files/Ruby/lib/ruby/1.9.1/syck/stream.rb C:/Program Files/Ruby/lib/ruby/1.9.1/syck/constants.rb C:/Program Files/Ruby/lib/ruby/1.9.1/date/format.rb C:/Program Files/Ruby/lib/ruby/1.9.1/date.rb C:/Program Files/Ruby/lib/ruby/1.9.1/syck/rubytypes.rb C:/Program Files/Ruby/lib/ruby/1.9.1/syck/types.rb C:/Program Files/Ruby/lib/ruby/1.9.1/yaml/syck.rb C:/Program Files/Ruby/lib/ruby/1.9.1/syck.rb C:/Program Files/Ruby/lib/ruby/1.9.1/yaml.rb A: Assuming you are using rubygems, you can find out which file it loads by using Gem.find_files(file). e.g.: >> puts Gem.find_files('active_record') /Library/Ruby/Gems/1.8/gems/activerecord-3.0.0.beta2/lib/active_record.rb /Library/Ruby/Gems/1.8/gems/activerecord-2.3.8/lib/active_record.rb /Library/Ruby/Gems/1.8/gems/activerecord-2.3.5/lib/active_record.rb /Library/Ruby/Gems/1.8/gems/activerecord-2.3.4/lib/active_record.rb /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record.rb /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/gems/1.8/gems/activerecord-1.15.6/lib/active_record.rb The first element of the array will be the file that is loaded by require 'active_record'. Another way to find out which file is loaded by require, would be to call $ gem which foo from the command line.
What's the equivalent of python's __file__ in ruby?
In python after imports, one can see the file, that has been loaded/where the module comes from. >>> import os >>> os.__file__ '/Users/tm/lib/python2.6/os.pyc' What would be the equivalent in ruby? >> require 'xmlrpc/client' => true >> ...
[ "There's nothing that's an exact match. It's easy to find it yourself, though:\n# Find where a path `p` was loaded from.\ndef locate(p)\n # Find the first path in your load-paths that contains a file matching `p`.\n $:.find { |l|\n File.exists?(File.join(l, p))\n }\nend\n\nruby-1.9.1-p378 > locate('yaml')\n => \"/home/johnf/.rvm/rubies/ruby-1.9.1-p378/lib/ruby/1.9.1\" \n# --> This tells you that 'yaml.rb' was loaded from here.\n\nruby-1.9.1-p378 > locate('zzz')\n => nil\n# --> There's no matches for this library.\n\nruby-1.9.1-p378 > locate('haml')\n => \"/home/johnf/.rvm/gems/ruby-1.9.1-p378@standard/gems/haml-3.0.12/bin\" \n# --> Here's a third-party library from my gems.\n\n", "There's nothing exactly equivalent.\nAll files that have been required are listed in $LOADED_FEATURES in the order they were required. So, if you want to know where a file came from directly after it was required, you simply need to look at the end:\n$LOADED_FEATURES.last if require 'yaml'\n# => 'C:/Program Files/Ruby/lib/ruby/1.9.1/yaml.rb'\n\nHowever, unless you record every call to require it's going to be hard to figure out which entry corresponds to which call. Also, if a file is already in $LOADED_FEATURES, it will not get loaded again:\nrequire 'yaml'\n# => true\n# true means: the file was loaded\n\n$LOADED_FEATURES.last\n# => 'C:/Program Files/Ruby/lib/ruby/1.9.1/yaml.rb'\n\nrequire 'json'\n$LOADED_FEATURES.last\n# => 'C:/Program Files/Ruby/lib/ruby/1.9.1/json.rb'\n\nrequire 'yaml'\n# => false\n# false means: the file wasn't loaded again, because it has already been loaded\n\n$LOADED_FEATURES.last\n# => 'C:/Program Files/Ruby/lib/ruby/1.9.1/json.rb'\n# Last loaded feature is still JSON, because YAML wasn't actually loaded twice\n\nAlso, many libraries aren't contained in a single file. So, the required files might themselves contain calls to require. In my case, for example, require 'yaml' not only loads yaml.rb but a whole bunch of files (15 to be exact):\n\nC:/Program Files/Ruby/lib/ruby/1.9.1/i386-mingw32/stringio.so\nC:/Program Files/Ruby/lib/ruby/1.9.1/i386-mingw32/syck.so\nC:/Program Files/Ruby/lib/ruby/1.9.1/syck/error.rb\nC:/Program Files/Ruby/lib/ruby/1.9.1/syck/basenode.rb\nC:/Program Files/Ruby/lib/ruby/1.9.1/syck/syck.rb\nC:/Program Files/Ruby/lib/ruby/1.9.1/syck/tag.rb\nC:/Program Files/Ruby/lib/ruby/1.9.1/syck/stream.rb\nC:/Program Files/Ruby/lib/ruby/1.9.1/syck/constants.rb\nC:/Program Files/Ruby/lib/ruby/1.9.1/date/format.rb\nC:/Program Files/Ruby/lib/ruby/1.9.1/date.rb\nC:/Program Files/Ruby/lib/ruby/1.9.1/syck/rubytypes.rb\nC:/Program Files/Ruby/lib/ruby/1.9.1/syck/types.rb\nC:/Program Files/Ruby/lib/ruby/1.9.1/yaml/syck.rb\nC:/Program Files/Ruby/lib/ruby/1.9.1/syck.rb\nC:/Program Files/Ruby/lib/ruby/1.9.1/yaml.rb\n\n", "Assuming you are using rubygems, you can find out which file it loads by using Gem.find_files(file).\ne.g.:\n>> puts Gem.find_files('active_record')\n/Library/Ruby/Gems/1.8/gems/activerecord-3.0.0.beta2/lib/active_record.rb\n/Library/Ruby/Gems/1.8/gems/activerecord-2.3.8/lib/active_record.rb\n/Library/Ruby/Gems/1.8/gems/activerecord-2.3.5/lib/active_record.rb\n/Library/Ruby/Gems/1.8/gems/activerecord-2.3.4/lib/active_record.rb\n/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record.rb\n/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/gems/1.8/gems/activerecord-1.15.6/lib/active_record.rb\n\nThe first element of the array will be the file that is loaded by require 'active_record'.\nAnother way to find out which file is loaded by require, would be to call $ gem which foo from the command line.\n" ]
[ 1, 1, 1 ]
[]
[]
[ "module", "path", "python", "ruby" ]
stackoverflow_0003085949_module_path_python_ruby.txt
Q: python postgres Hi i want to store null value in a column.The column is nullable.The column value is not null always it depends on certain conditions.I dont want to write two queries in this case.I have tried None,null both but it gives me error saying worng type for double precision A: You do not say which Python / PostGreSQL interface module you're using -- there are several, not all DB API compliant. In DB API compliant modules, the None singleton is definitely the way to represent SQL NULLs on the Python side of things -- the API docs leave no doubt: SQL NULL values are represented by the Python None singleton on input and output. Maybe you're erroneously using, e.g., 'None' (with quotes making it a string, not the singleton None object), just as I imagine you're using 'null' with quotes in that erroneous attempt (if you didn't have quotes you'd get a NameError -- unless you've defined a variable by that name, which I sure hope you haven't!-). We can be more helpful if you don't hide from us all the crucial data you're hiding: which PostgreSQL interface module, what's the table's schema, a simple snippet that fails, etc.
python postgres
Hi i want to store null value in a column.The column is nullable.The column value is not null always it depends on certain conditions.I dont want to write two queries in this case.I have tried None,null both but it gives me error saying worng type for double precision
[ "You do not say which Python / PostGreSQL interface module you're using -- there are several, not all DB API compliant. In DB API compliant modules, the None singleton is definitely the way to represent SQL NULLs on the Python side of things -- the API docs leave no doubt:\n\nSQL NULL values are represented by the\n Python None singleton on\n input and output.\n\nMaybe you're erroneously using, e.g., 'None' (with quotes making it a string, not the singleton None object), just as I imagine you're using 'null' with quotes in that erroneous attempt (if you didn't have quotes you'd get a NameError -- unless you've defined a variable by that name, which I sure hope you haven't!-).\nWe can be more helpful if you don't hide from us all the crucial data you're hiding: which PostgreSQL interface module, what's the table's schema, a simple snippet that fails, etc.\n" ]
[ 2 ]
[]
[]
[ "postgresql", "python" ]
stackoverflow_0003086265_postgresql_python.txt
Q: Problem with cgi-bin python program putting output in wrong place I have a cgi python program which runs an os.system command and this command is printing output and causing havoc. How do I get python to run the os.system command and have that command print to the webpage it is being run on? A: Do you have to use os.system? I would use stdout, stderr = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr.PIPE).communicate()
Problem with cgi-bin python program putting output in wrong place
I have a cgi python program which runs an os.system command and this command is printing output and causing havoc. How do I get python to run the os.system command and have that command print to the webpage it is being run on?
[ "Do you have to use os.system? I would use \nstdout, stderr = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr.PIPE).communicate()\n\n" ]
[ 0 ]
[]
[]
[ "cgi", "python" ]
stackoverflow_0003086832_cgi_python.txt
Q: wxPython: VirtualTreeListCtrl with millions of items I would like to add 1,000,000+ entries to the root node of a TreeListCtrl. Therefore I would like to make it "virtual", i.e. work just like a virtual ListCtrl so that it's still fast and I can easily scroll around due to the currently-displayed items being loaded on-demand. But I can't use a virtual ListCtrl because I also want to be able to expand any of the 1,000,000 items to display its children (the items will always have less than 50 children). Can this be done efficiently with a TreeListCtrl? Or with a different class? From my own experiments with treemixin.VirtualTree and wx.gizmos.TreeListCtrl, overloading the OnGetItemText method does not work the same way as it does with a plain virtual ListCtrl. It doesn't get called on-demand as the user is scrolling around, meaning all 1,000,000 items have to be added to the TreeListCtrl in advance. A: One thing you might do is leave the sub-nodes empty, and catch the expand-node event. Then you check to see if the node's sub-nodes are populated. If they aren't, you add them before expanding the node. If they are populated, you simply ignore the event. A: You're right that the treemixin doesn't make the TreeListCtrl really virtual. I thought about that when I was developing treemixin, but the one thing I didn't know how to solve was how to know which lines to draw to the left of items when the user is looking at items deep down the tree, e.g. 10000 to 10030. If you know of a solution for that I'll gladly adapt treemixin. Frank Author treemixin A: I think what I'll do is use a virtual ListCtrl along with a skip-list for the data model. Initially, the data model will contain the 1 million top-layer nodes. When a node is expanded, I can insert its children into the skip-list in log time (much better than the linear time for an array). I will indent the names of the children in the ListCtrl so that you can visually tell who their parent is. I think the log search time for the skip-list (as opposed to instant random-access time for an array) will be fast enough to handle the user's scrolling. If someone has a better suggestion, please let me know. I will provide an update in the future as to whether my idea worked or not.
wxPython: VirtualTreeListCtrl with millions of items
I would like to add 1,000,000+ entries to the root node of a TreeListCtrl. Therefore I would like to make it "virtual", i.e. work just like a virtual ListCtrl so that it's still fast and I can easily scroll around due to the currently-displayed items being loaded on-demand. But I can't use a virtual ListCtrl because I also want to be able to expand any of the 1,000,000 items to display its children (the items will always have less than 50 children). Can this be done efficiently with a TreeListCtrl? Or with a different class? From my own experiments with treemixin.VirtualTree and wx.gizmos.TreeListCtrl, overloading the OnGetItemText method does not work the same way as it does with a plain virtual ListCtrl. It doesn't get called on-demand as the user is scrolling around, meaning all 1,000,000 items have to be added to the TreeListCtrl in advance.
[ "One thing you might do is leave the sub-nodes empty, and catch the expand-node event. Then you check to see if the node's sub-nodes are populated. If they aren't, you add them before expanding the node. If they are populated, you simply ignore the event.\n", "You're right that the treemixin doesn't make the TreeListCtrl really virtual. I thought about that when I was developing treemixin, but the one thing I didn't know how to solve was how to know which lines to draw to the left of items when the user is looking at items deep down the tree, e.g. 10000 to 10030. If you know of a solution for that I'll gladly adapt treemixin.\nFrank\nAuthor treemixin\n", "I think what I'll do is use a virtual ListCtrl along with a skip-list for the data model. Initially, the data model will contain the 1 million top-layer nodes. When a node is expanded, I can insert its children into the skip-list in log time (much better than the linear time for an array). I will indent the names of the children in the ListCtrl so that you can visually tell who their parent is. I think the log search time for the skip-list (as opposed to instant random-access time for an array) will be fast enough to handle the user's scrolling. If someone has a better suggestion, please let me know. I will provide an update in the future as to whether my idea worked or not.\n" ]
[ 0, 0, 0 ]
[]
[]
[ "listctrl", "python", "treecontrol", "virtual", "wxpython" ]
stackoverflow_0003074175_listctrl_python_treecontrol_virtual_wxpython.txt
Q: How to match a word that doesn't start with X but ends with Y with regex Example; X=This Y=That not matching; ThisWordShouldNotMatchThat ThisWordShouldNotMatch WordShouldNotMatch matching; AWordShouldMatchThat I tried (?<!...) but seems not to be easy :) A: ^(?!This).*That$ As a free-spacing regex: ^ # Start of string (?!This) # Assert that "This" can't be matched here .* # Match the rest of the string That # making sure we match "That" $ # right at the end of the string This will match a single word that fulfills your criteria, but only if this word is the only input to the regex. If you need to find words inside a string of many other words, then use \b(?!This)\w*That\b \b is the word boundary anchor, so it matches at the start and at the end of a word. \w means "alphanumeric character. If you also want to allow non-alphanumerics as part of your "word", then use \S instead - this will match anything that's not a space. In Python, you could do words = re.findall(r"\b(?!This)\w*That\b", text).
How to match a word that doesn't start with X but ends with Y with regex
Example; X=This Y=That not matching; ThisWordShouldNotMatchThat ThisWordShouldNotMatch WordShouldNotMatch matching; AWordShouldMatchThat I tried (?<!...) but seems not to be easy :)
[ "^(?!This).*That$\n\nAs a free-spacing regex:\n^ # Start of string\n (?!This) # Assert that \"This\" can't be matched here\n .* # Match the rest of the string\n That # making sure we match \"That\"\n$ # right at the end of the string\n\nThis will match a single word that fulfills your criteria, but only if this word is the only input to the regex. If you need to find words inside a string of many other words, then use\n\\b(?!This)\\w*That\\b\n\n\\b is the word boundary anchor, so it matches at the start and at the end of a word. \\w means \"alphanumeric character. If you also want to allow non-alphanumerics as part of your \"word\", then use \\S instead - this will match anything that's not a space.\nIn Python, you could do words = re.findall(r\"\\b(?!This)\\w*That\\b\", text).\n" ]
[ 14 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003087398_python_regex.txt
Q: How to print out the line after the line found in re.compile() Using this code import re file = open('FilePath/OUTPUT.01') lines = file.read() file.close() for match in re.finditer(r"(?m)^\s*-+\s+\S+\s+(\S+)", lines): eng = match.group(1) open('Tmp.txt', 'w').writelines(eng) print match.group(1) I get a column of data that looks like this: -1.1266E+05 -1.1265E+05 -1.1265E+05 -1.1265E+05 -1.1264E+05 -1.1264E+05 -1.1264E+05 -1.1263E+05 step -1.1263E+05 -1.1262E+05 -1.1262E+05 -1.1261E+05 -1.1261E+05 -1.1260E+05 -1.1260E+05 -1.1259E+05 step -1.1259E+05 -1.1258E+05 -1.1258E+05 -1.1258E+05 -1.1257E+05 terminating. eng_tot -1.1274E+05 3D How do I write it a file (Tmp.txt)? As of now it only writes the last line '3D'. Also I'd like to eliminate all the lines that aren't of the form x.xxxxExxx (i.e. just the numbers). A: You could use a single regex: file = open('FilePath/OUTPUT.01') lines = file.read() file.close() with open("output.txt","w") as f: for match in re.finditer(r"(?m)^\s*-+\s+\S+\s+(-?[\d.]+E[+-]\d+)", lines): f.write(match.group(1)+"\n") This should write all the second numbers that occur after a line that consists entirely of - into the file output.txt. This regex assumes that the columns are space-separated, and that the first column will never be empty. Explanation: (?m) # allow ^ to match at start of line, not just start of string ^ # anchor the search at the start of the line \s* # match any leading whitespace -+ # match one or more dashes \s+ # match trailing whitespace, including linebreak characters \S+ # match a run of non-whitespace characters (we're now one line ahead of the dashes \s+ # match a run of whitespace (-?[\d.]+E[+-]\d+) # match a number in scientific notation A: i is the index into lines that line is at, so i+1 is the next line: print lines[i+1] Make sure the ---- isn't the last line or this will try to read from a location that doesn't exist. Also, your regular expression \s+-+\s+ requires that there be spaces before and after the -s, as \s+ means 1 or more spaces; you probably meant \s* A: I wouldn't bother with REs for this. Try the following: output = file("tmp.txt", "w") # open a file for writing flagged = False # when 'flagged == True' we will print the line for line in file("FilePath/OUTPUT.01"): if flagged: try: result = line.split()[1] # python is zero-indexed! print>>output, result # print to output only if the split worked except IndexError: # otherwise do nothing pass flagged = False # but reset the flag else: if set(line.strip()) == set(["-"]): # does the line consist only of '-'? flagged = True # if so, set the flag to print the next line Here's a version which allows you to specify the number of lines offset, and the column number: OFFSET = 3 # the third line after the `----` COLUMN = 2 # column index 2 output = file("tmp.txt", "w") counter = 0 # 0 evaluates as False for line in file("FilePath/OUTPUT.01"): if counter: # any non-zero value evaluates as True if counter == OFFSET: try: result = line.split()[COLUMN] print>>output, result # print to output only if the split worked except IndexError: # otherwise do nothing pass counter = 0 # reset the flag once you've reached the OFFSET line else: counter += 1 else: if set(line.strip()) == set(["-"]): # does the line consist only of '-'? counter = 1
How to print out the line after the line found in re.compile()
Using this code import re file = open('FilePath/OUTPUT.01') lines = file.read() file.close() for match in re.finditer(r"(?m)^\s*-+\s+\S+\s+(\S+)", lines): eng = match.group(1) open('Tmp.txt', 'w').writelines(eng) print match.group(1) I get a column of data that looks like this: -1.1266E+05 -1.1265E+05 -1.1265E+05 -1.1265E+05 -1.1264E+05 -1.1264E+05 -1.1264E+05 -1.1263E+05 step -1.1263E+05 -1.1262E+05 -1.1262E+05 -1.1261E+05 -1.1261E+05 -1.1260E+05 -1.1260E+05 -1.1259E+05 step -1.1259E+05 -1.1258E+05 -1.1258E+05 -1.1258E+05 -1.1257E+05 terminating. eng_tot -1.1274E+05 3D How do I write it a file (Tmp.txt)? As of now it only writes the last line '3D'. Also I'd like to eliminate all the lines that aren't of the form x.xxxxExxx (i.e. just the numbers).
[ "You could use a single regex:\nfile = open('FilePath/OUTPUT.01')\nlines = file.read()\nfile.close()\nwith open(\"output.txt\",\"w\") as f:\n for match in re.finditer(r\"(?m)^\\s*-+\\s+\\S+\\s+(-?[\\d.]+E[+-]\\d+)\", lines):\n f.write(match.group(1)+\"\\n\")\n\nThis should write all the second numbers that occur after a line that consists entirely of - into the file output.txt.\nThis regex assumes that the columns are space-separated, and that the first column will never be empty.\nExplanation:\n(?m) # allow ^ to match at start of line, not just start of string\n^ # anchor the search at the start of the line\n\\s* # match any leading whitespace\n-+ # match one or more dashes\n\\s+ # match trailing whitespace, including linebreak characters\n\\S+ # match a run of non-whitespace characters (we're now one line ahead of the dashes\n\\s+ # match a run of whitespace\n(-?[\\d.]+E[+-]\\d+) # match a number in scientific notation\n\n", "i is the index into lines that line is at, so i+1 is the next line:\nprint lines[i+1]\n\nMake sure the ---- isn't the last line or this will try to read from a location that doesn't exist. Also, your regular expression \\s+-+\\s+ requires that there be spaces before and after the -s, as \\s+ means 1 or more spaces; you probably meant \\s*\n", "I wouldn't bother with REs for this. Try the following:\noutput = file(\"tmp.txt\", \"w\") # open a file for writing\nflagged = False # when 'flagged == True' we will print the line\nfor line in file(\"FilePath/OUTPUT.01\"):\n if flagged:\n try:\n result = line.split()[1] # python is zero-indexed!\n print>>output, result # print to output only if the split worked\n except IndexError: # otherwise do nothing\n pass\n flagged = False # but reset the flag\n else:\n if set(line.strip()) == set([\"-\"]): # does the line consist only of '-'?\n flagged = True # if so, set the flag to print the next line\n\nHere's a version which allows you to specify the number of lines offset, and the column number:\nOFFSET = 3 # the third line after the `----`\nCOLUMN = 2 # column index 2\n\noutput = file(\"tmp.txt\", \"w\")\ncounter = 0 # 0 evaluates as False\nfor line in file(\"FilePath/OUTPUT.01\"):\n if counter: # any non-zero value evaluates as True\n if counter == OFFSET:\n try:\n result = line.split()[COLUMN] \n print>>output, result # print to output only if the split worked\n except IndexError: # otherwise do nothing\n pass\n counter = 0 # reset the flag once you've reached the OFFSET line\n else:\n counter += 1\n else:\n if set(line.strip()) == set([\"-\"]): # does the line consist only of '-'?\n counter = 1\n\n" ]
[ 2, 0, 0 ]
[]
[]
[ "parsing", "python" ]
stackoverflow_0003087175_parsing_python.txt
Q: texmate and django, is there intellisense? New to mac and textmate AND python. I don't seem to be getting any intellisensewith textmate, is there a plugin? what are the keyboard shortcuts I should know about (basic ones at this point). thanks! A: There are bundles for Django that make it easier to work with Django projects in TextMate. They offer the ability to search online for documentation, and there are a lot of "snippets" defined so you can type a few characters, hit Tab, and "auto"-complete some frequently-used strings, but none offer anything on the scope of IntelliSense. A: There are a couple of TextMate bundles that will satisfy you: PySmell -- Gives you VS-like dropdown of available methods. Tempy -- ToolTips only. Not well built but extremely useful.
texmate and django, is there intellisense?
New to mac and textmate AND python. I don't seem to be getting any intellisensewith textmate, is there a plugin? what are the keyboard shortcuts I should know about (basic ones at this point). thanks!
[ "There are bundles for Django that make it easier to work with Django projects in TextMate. They offer the ability to search online for documentation, and there are a lot of \"snippets\" defined so you can type a few characters, hit Tab, and \"auto\"-complete some frequently-used strings, but none offer anything on the scope of IntelliSense.\n", "There are a couple of TextMate bundles that will satisfy you:\n\nPySmell -- Gives you VS-like dropdown of available methods.\nTempy -- ToolTips only. Not well built but extremely useful.\n\n" ]
[ 1, 1 ]
[]
[]
[ "macos", "python", "textmate" ]
stackoverflow_0003081602_macos_python_textmate.txt
Q: django-haystack more_like_this returns nothing I've installed the haystack app and I'm using the solr backend. Search works perfectly although when I try to use the more_like_this template tag, nothing is returned. I have added <requestHandler name="/mlt" class="solr.MoreLikeThisHandler" /> to solrconfig.xml and I can make queries at http://127.0.0.1:8080/solr/mlt The template is fairly basic {% load more_like_this %} {% more_like_this video as related_videos limit 5 %} {{ related_videos }} A: I found that mlt was pretty picky, I had to improve my indexing templates to get good mlt results.
django-haystack more_like_this returns nothing
I've installed the haystack app and I'm using the solr backend. Search works perfectly although when I try to use the more_like_this template tag, nothing is returned. I have added <requestHandler name="/mlt" class="solr.MoreLikeThisHandler" /> to solrconfig.xml and I can make queries at http://127.0.0.1:8080/solr/mlt The template is fairly basic {% load more_like_this %} {% more_like_this video as related_videos limit 5 %} {{ related_videos }}
[ "I found that mlt was pretty picky, I had to improve my indexing templates to get good mlt results.\n" ]
[ 1 ]
[]
[]
[ "django", "django_haystack", "python", "solr" ]
stackoverflow_0003064046_django_django_haystack_python_solr.txt
Q: Memory issues: Should I be writing to file/database if I'm using swap? (Python) I'm creating and processing a very large data set, with about 34 million data points, and I'm currently storing them in python dictionaries in memory (about 22,500 dictionaries, with 15 dictionaries in each of 1588 class instances). While I'm able to manage this all in memory, I'm using up all of my RAM and most of my swap. I need to be able to first generate all of this data, and then do analysis on select portions of it at a time. Would it be beneficial from an efficiency standpoint to write some of this data to file, or store it in a database? Or am I better off just taking the hit to efficiency that comes with using my swap space. If I should be writing to file/a database, are there any python tools that you would recommend to do so? A: Because you will be looking at "select portions", your application will be able to make better use of core than Virtual Memory will. VM is convenient, but - by definition - kinda stupid about locality of reference. Use a database. I'd probably start with module sqlite3 on the basis of simplicity, unless or until I find that it is a bottlenck. A: Get a relational database, fast! Or a whole lot more RAM. If you're using Python, then start with Python Database Programming. SQLite would be a choice, but I'd suggest MySQL based upon the amount of data you're dealing with. If you want an object-oriented approach to storing your data, you might want to look at SQLAlchemy, but you'll probably get more efficiency if you end up mapping each of your object classes to a table yourself and just coping with rows and columns. A: If you have this data in Python data structures already, assuming you're not doing a lot of in-memory indexing (more than the obvious dictionary keys index), you really don't want to use a relational database - you'll pay a considerable performance penalty for no particular benefit. You just need to get your already key-value-pair data out of memory, not change its' format. You should look into key-value stores like BDB, Voldemort, MongoDB, or Scalaris (just to name a few - some more involved and functional than others, but all should easily handle your dataset), or for a dataset that you think might grow even larger or more complex you can look into systems like Cassandra, Riak, or CouchDB (among others). ALL of these systems will offer you vastly superior performance to a relational database and more directly map to an in-memory data model. All that being said, of course, if your dataset really could be more performant by leveraging the benefits of a relational database (complex relationships, multiple views, etc.), then go for it, but you shouldn't use a relational database if all you're trying to do is get your data structures out of memory. (It's also possible that just marshaling/pickling your data in segments and managing it yourself would offer better performance than a relational database, assuming your access pattern made paging in/out a relatively infrequent event. It's a long shot, but if you're just holding old data around and no one really looks at it, you might as well just throw that to disk yourself.)
Memory issues: Should I be writing to file/database if I'm using swap? (Python)
I'm creating and processing a very large data set, with about 34 million data points, and I'm currently storing them in python dictionaries in memory (about 22,500 dictionaries, with 15 dictionaries in each of 1588 class instances). While I'm able to manage this all in memory, I'm using up all of my RAM and most of my swap. I need to be able to first generate all of this data, and then do analysis on select portions of it at a time. Would it be beneficial from an efficiency standpoint to write some of this data to file, or store it in a database? Or am I better off just taking the hit to efficiency that comes with using my swap space. If I should be writing to file/a database, are there any python tools that you would recommend to do so?
[ "Because you will be looking at \"select portions\", your application will be able to make better use of core than Virtual Memory will. VM is convenient, but - by definition - kinda stupid about locality of reference. \nUse a database.\nI'd probably start with module sqlite3 on the basis of simplicity, unless or until I find that it is a bottlenck.\n", "Get a relational database, fast! Or a whole lot more RAM.\nIf you're using Python, then start with Python Database Programming. SQLite would be a choice, but I'd suggest MySQL based upon the amount of data you're dealing with. If you want an object-oriented approach to storing your data, you might want to look at SQLAlchemy, but you'll probably get more efficiency if you end up mapping each of your object classes to a table yourself and just coping with rows and columns.\n", "If you have this data in Python data structures already, assuming you're not doing a lot of in-memory indexing (more than the obvious dictionary keys index), you really don't want to use a relational database - you'll pay a considerable performance penalty for no particular benefit.\nYou just need to get your already key-value-pair data out of memory, not change its' format. You should look into key-value stores like BDB, Voldemort, MongoDB, or Scalaris (just to name a few - some more involved and functional than others, but all should easily handle your dataset), or for a dataset that you think might grow even larger or more complex you can look into systems like Cassandra, Riak, or CouchDB (among others). ALL of these systems will offer you vastly superior performance to a relational database and more directly map to an in-memory data model.\nAll that being said, of course, if your dataset really could be more performant by leveraging the benefits of a relational database (complex relationships, multiple views, etc.), then go for it, but you shouldn't use a relational database if all you're trying to do is get your data structures out of memory.\n(It's also possible that just marshaling/pickling your data in segments and managing it yourself would offer better performance than a relational database, assuming your access pattern made paging in/out a relatively infrequent event. It's a long shot, but if you're just holding old data around and no one really looks at it, you might as well just throw that to disk yourself.)\n" ]
[ 1, 1, 1 ]
[]
[]
[ "memory", "python", "swap" ]
stackoverflow_0003087741_memory_python_swap.txt
Q: what does python.exe take as arguments? does it take the filename of the .py and then what? A: Documentation here. A: It takes any options for python.exe itself, then the name of the file (or command or module), then any arguments to be passed to your program. If no file is specified, it puts you in interactive mode. As indicated in the comments by Adam, type python -h to see the full list.
what does python.exe take as arguments?
does it take the filename of the .py and then what?
[ "Documentation here.\n", "It takes any options for python.exe itself, then the name of the file (or command or module), then any arguments to be passed to your program.\nIf no file is specified, it puts you in interactive mode.\nAs indicated in the comments by Adam, type python -h to see the full list. \n" ]
[ 19, 8 ]
[]
[]
[ "arguments", "python" ]
stackoverflow_0003088493_arguments_python.txt
Q: Create an utf-8 csv file in Python I can't create an utf-8 csv file in Python. I'm trying to read it's docs, and in the examples section, it says: For all other encodings the following UnicodeReader and UnicodeWriter classes can be used. They take an additional encoding parameter in their constructor and make sure that the data passes the real reader or writer encoded as UTF-8: Ok. So I have this code: values = (unicode("Ñ", "utf-8"), unicode("é", "utf-8")) f = codecs.open('eggs.csv', 'w', encoding="utf-8") writer = UnicodeWriter(f) writer.writerow(values) And I keep getting this error: line 159, in writerow self.stream.write(data) File "/usr/lib/python2.6/codecs.py", line 686, in write return self.writer.write(data) File "/usr/lib/python2.6/codecs.py", line 351, in write data, consumed = self.encode(object, self.errors) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 22: ordinal not in range(128) Can someone please give me a light so I can understand what the hell am I doing wrong since I set all the encoding everywhere before calling UnicodeWriter class? class UnicodeWriter: """ A CSV writer which will write rows to CSV file "f", which is encoded in the given encoding. """ def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds): # Redirect output to a queue self.queue = cStringIO.StringIO() self.writer = csv.writer(self.queue, dialect=dialect, **kwds) self.stream = f self.encoder = codecs.getincrementalencoder(encoding)() def writerow(self, row): self.writer.writerow([s.encode("utf-8") for s in row]) # Fetch UTF-8 output from the queue ... data = self.queue.getvalue() data = data.decode("utf-8") # ... and reencode it into the target encoding data = self.encoder.encode(data) # write to the target stream self.stream.write(data) # empty queue self.queue.truncate(0) def writerows(self, rows): for row in rows: self.writerow(row) A: You don't have to use codecs.open; UnicodeWriter takes Unicode input and takes care of encoding everything into UTF-8. When UnicodeWriter writes into the file handle you passed to it, everything is already in UTF-8 encoding (therefore it works with a normal file you opened with open). By using codecs.open, you essentially convert your Unicode objects to UTF-8 strings in UnicodeWriter, then try to re-encode these strings into UTF-8 again as if these strings contained Unicode strings, which obviously fails. A: As you have figured out it works if you use plain open. The reason for this is that you tried to encode UTF-8 twice. Once in f = codecs.open('eggs.csv', 'w', encoding="utf-8") and then later in UnicodeWriter.writeRow # ... and reencode it into the target encoding data = self.encoder.encode(data) To check that this works use your original code and outcomment that line. Greetz A: I ran into the csv / unicode challenge a while back and tossed this up on bitbucket: http://bitbucket.org/famousactress/dude_csv .. might work for you, if your needs are simple :) A: You don't need to "double-encode" everything. Your application should work entirely in Unicode. Do your encoding only in the codecs.open to write UTF-8 bytes to an external file. Do no other encoding within your application.
Create an utf-8 csv file in Python
I can't create an utf-8 csv file in Python. I'm trying to read it's docs, and in the examples section, it says: For all other encodings the following UnicodeReader and UnicodeWriter classes can be used. They take an additional encoding parameter in their constructor and make sure that the data passes the real reader or writer encoded as UTF-8: Ok. So I have this code: values = (unicode("Ñ", "utf-8"), unicode("é", "utf-8")) f = codecs.open('eggs.csv', 'w', encoding="utf-8") writer = UnicodeWriter(f) writer.writerow(values) And I keep getting this error: line 159, in writerow self.stream.write(data) File "/usr/lib/python2.6/codecs.py", line 686, in write return self.writer.write(data) File "/usr/lib/python2.6/codecs.py", line 351, in write data, consumed = self.encode(object, self.errors) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 22: ordinal not in range(128) Can someone please give me a light so I can understand what the hell am I doing wrong since I set all the encoding everywhere before calling UnicodeWriter class? class UnicodeWriter: """ A CSV writer which will write rows to CSV file "f", which is encoded in the given encoding. """ def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds): # Redirect output to a queue self.queue = cStringIO.StringIO() self.writer = csv.writer(self.queue, dialect=dialect, **kwds) self.stream = f self.encoder = codecs.getincrementalencoder(encoding)() def writerow(self, row): self.writer.writerow([s.encode("utf-8") for s in row]) # Fetch UTF-8 output from the queue ... data = self.queue.getvalue() data = data.decode("utf-8") # ... and reencode it into the target encoding data = self.encoder.encode(data) # write to the target stream self.stream.write(data) # empty queue self.queue.truncate(0) def writerows(self, rows): for row in rows: self.writerow(row)
[ "You don't have to use codecs.open; UnicodeWriter takes Unicode input and takes care of encoding everything into UTF-8. When UnicodeWriter writes into the file handle you passed to it, everything is already in UTF-8 encoding (therefore it works with a normal file you opened with open).\nBy using codecs.open, you essentially convert your Unicode objects to UTF-8 strings in UnicodeWriter, then try to re-encode these strings into UTF-8 again as if these strings contained Unicode strings, which obviously fails.\n", "As you have figured out it works if you use plain open.\nThe reason for this is that you tried to encode UTF-8 twice. Once in\nf = codecs.open('eggs.csv', 'w', encoding=\"utf-8\")\n\nand then later in UnicodeWriter.writeRow\n# ... and reencode it into the target encoding\ndata = self.encoder.encode(data)\n\nTo check that this works use your original code and outcomment that line. \nGreetz\n", "I ran into the csv / unicode challenge a while back and tossed this up on bitbucket: http://bitbucket.org/famousactress/dude_csv .. might work for you, if your needs are simple :)\n", "You don't need to \"double-encode\" everything.\nYour application should work entirely in Unicode. \nDo your encoding only in the codecs.open to write UTF-8 bytes to an external file. Do no other encoding within your application.\n" ]
[ 14, 1, 1, 0 ]
[]
[]
[ "csv", "encoding", "python", "utf_8" ]
stackoverflow_0003085263_csv_encoding_python_utf_8.txt
Q: Basic HTTP Parsing Using Twisted I am a newcomer to the Python and Twisted game so excuse the ignorance I will likely be asking this question with. As a sort of first program, I am trying to write a basic HTTP server using twisted.web.sever which would simply print to screen the HTTP request, and then print to screen the HTTP response. I am trying to print the entire message. Here is what I have so far: from twisted.internet import reactor from twisted.web.server import Site from twisted.web.resource import Resource import time class TestPage(Resource): isLeaf = True def render_GET(self, request): response = "Success" print "You're request was %s" % request print "The sever's response was %s" % response return response resource = TestPage() factory = Site(resource) reactor.listenTCP(8000, factory) reactor.run() So far, I am having success printing the request. What I want to know is where I can access the raw response data, not just the textual message. Also, if I wanted to start parsing the request/response for information, what would be the best way to go about doing that? Edit: I'm also new to stackoverflow, how do I get this code to display properly? A: Take a look at the Request and IRequest API docs to get an idea of what that request parameter offers you. You should be able to find just about everything in the request there. I'm not sure what you mean by raw response data though. The response is up to you to generate.
Basic HTTP Parsing Using Twisted
I am a newcomer to the Python and Twisted game so excuse the ignorance I will likely be asking this question with. As a sort of first program, I am trying to write a basic HTTP server using twisted.web.sever which would simply print to screen the HTTP request, and then print to screen the HTTP response. I am trying to print the entire message. Here is what I have so far: from twisted.internet import reactor from twisted.web.server import Site from twisted.web.resource import Resource import time class TestPage(Resource): isLeaf = True def render_GET(self, request): response = "Success" print "You're request was %s" % request print "The sever's response was %s" % response return response resource = TestPage() factory = Site(resource) reactor.listenTCP(8000, factory) reactor.run() So far, I am having success printing the request. What I want to know is where I can access the raw response data, not just the textual message. Also, if I wanted to start parsing the request/response for information, what would be the best way to go about doing that? Edit: I'm also new to stackoverflow, how do I get this code to display properly?
[ "Take a look at the Request and IRequest API docs to get an idea of what that request parameter offers you. You should be able to find just about everything in the request there.\nI'm not sure what you mean by raw response data though. The response is up to you to generate.\n" ]
[ 2 ]
[]
[]
[ "http", "logging", "python", "twisted", "twisted.web" ]
stackoverflow_0003087651_http_logging_python_twisted_twisted.web.txt
Q: MySQL database back up using Python I'm trying to write a python script which backs up the database every midnight. The code i am using is below: from subprocess import call call (["mysqldump", "-u", "root", "-p*****", "normalisation", ">", "date_here.sql"]) The first problem i came across is that mysql thinks the ">" is a table when it is not, the query works fine when i run it from the command line (see below) $ mysqldump -u root -p***** normalisation > date_here.sql $ ls backup.py date_here.sql $ Sencondly, how do i get the script to automatically run everymidnight? Thirdly, i need the .sql file to be saved as the date of the back up. A: use a shell script. there's a million that do this task already online. you can generate the filename using the date command with the right format string, and you can make it run at a scheduled time using cron. A: Your command is failing because output redirection is a function of the shell, not mysqldump. Try using Popen instead of call, as follows: from subprocess import Popen f = open( "date_here.sql", "w" ) x = Popen( ["mysqldump", "-u", "root", "-p*****", "normalisation"], stdout = f ) x.wait() f.close() This will allow you to handle redirecting to stdout within your program.
MySQL database back up using Python
I'm trying to write a python script which backs up the database every midnight. The code i am using is below: from subprocess import call call (["mysqldump", "-u", "root", "-p*****", "normalisation", ">", "date_here.sql"]) The first problem i came across is that mysql thinks the ">" is a table when it is not, the query works fine when i run it from the command line (see below) $ mysqldump -u root -p***** normalisation > date_here.sql $ ls backup.py date_here.sql $ Sencondly, how do i get the script to automatically run everymidnight? Thirdly, i need the .sql file to be saved as the date of the back up.
[ "use a shell script. there's a million that do this task already online. you can generate the filename using the date command with the right format string, and you can make it run at a scheduled time using cron.\n", "Your command is failing because output redirection is a function of the shell, not mysqldump. Try using Popen instead of call, as follows:\nfrom subprocess import Popen\n\nf = open( \"date_here.sql\", \"w\" )\nx = Popen( [\"mysqldump\", \"-u\", \"root\", \"-p*****\", \"normalisation\"], stdout = f )\nx.wait()\nf.close()\n\nThis will allow you to handle redirecting to stdout within your program.\n" ]
[ 1, 1 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0003088497_mysql_python.txt
Q: Twisted: tcp server with push producer example? I want to put together simple TCP server using Python and Twisted. The server starts up and waits for connection - I already have client - non-python application. Once connection is made server starts sending data at some interval (e.g. 1 sec). The server reads data from a static file (a record at a time), I should be able to figure out this part. I assume that I would use push producer to start pushing data once client is connected. I have simple tcp server with factory in twisted and I can react to connectionMade/dataReceived and so on but I can't figure out how to plug in the push producer. Anyone knows any examples showing push producer with tcp server in twisted? A: Here is a complete example of a push producer. It's been added to the twisted svn as an example. A: What about something simplistic like: thedata = ''' Questa mattina mi son svegliato o bella ciao, bella ciao, bella ciao, ciao, ciao questa mattina mi son svegliato ho trovato l'invasor! '''.splitlines(True) class Push(protocol.Protocol): """This is just about the simplest possible protocol""" def connectionMade(self): for line in thedata: if not line or line.isspace(): continue self.transport.write(line) time.sleep(1.0) self.transport.loseConnection() This has hard-coded data, but you say that reading it from a file instead is not your problem. If you can tell us what's wrong with this overly simplistic "push server", maybe we can offer better help!-)
Twisted: tcp server with push producer example?
I want to put together simple TCP server using Python and Twisted. The server starts up and waits for connection - I already have client - non-python application. Once connection is made server starts sending data at some interval (e.g. 1 sec). The server reads data from a static file (a record at a time), I should be able to figure out this part. I assume that I would use push producer to start pushing data once client is connected. I have simple tcp server with factory in twisted and I can react to connectionMade/dataReceived and so on but I can't figure out how to plug in the push producer. Anyone knows any examples showing push producer with tcp server in twisted?
[ "Here is a complete example of a push producer. It's been added to the twisted svn as an example.\n", "What about something simplistic like:\nthedata = '''\nQuesta mattina\nmi son svegliato\no bella ciao, bella ciao,\nbella ciao, ciao, ciao\nquesta mattina\nmi son svegliato\nho trovato l'invasor!\n'''.splitlines(True)\n\nclass Push(protocol.Protocol):\n \"\"\"This is just about the simplest possible protocol\"\"\"\n def connectionMade(self):\n for line in thedata:\n if not line or line.isspace():\n continue\n self.transport.write(line)\n time.sleep(1.0)\n self.transport.loseConnection()\n\nThis has hard-coded data, but you say that reading it from a file instead is not your problem. If you can tell us what's wrong with this overly simplistic \"push server\", maybe we can offer better help!-)\n" ]
[ 4, 2 ]
[]
[]
[ "python", "tcpserver", "twisted" ]
stackoverflow_0001591787_python_tcpserver_twisted.txt
Q: Object/XML Backwards-Compatibility We store objects in XML. Sometimes we update the base objects, then we have to save more data in our files to represent the extra attributes of our objects. How to organize/implement a system to ensure backwards compatibility with old versions of our files? The complicated part comes when looking at several versions at once. Version 1 -> Version 2 -> Version 3 -> Version 4 Should we write four file readers, one for each version of the file to read it into the current latest version of our object? Or, should we keep all the old versions of the classes around from versions 1-3 so that the old readers can read the data into those classes, and then have incremental updaters to update 1->2 and then 2->3 and then 3->4. A: When I increment versions like this I typically keep the old reader, and just update it to write into the new model. This means I only have the current model for the rest of my code to deal with, but I can still read old files. I would not keep old classes around, no matter what other choices you may make - you want to localize the number of places in your code that have to understand old versions to as few as possible (preferably one). If you keep old classes around, then any code that deals with those classes (even as derived from a common base) runs the risk of having to "know" about old versions, and that creates an unmitigated maintenance disaster after a while. This is NOT a panacea...all the obvious options have issues. Once you have more than a few old readers, it becomes really time consuming to update them all (and god forbid you refactor some code they require into a new namespace and then have to edit effectively the same code 100 times to replace names). However, I usually just use this as a gateway to getting rid of old versions entirely - if you resolve to only have a few old version readers floating around for backwards compatibility, you can start deleting the oldest ones every time you make a new one, making the maintenance considerably less of a headache.
Object/XML Backwards-Compatibility
We store objects in XML. Sometimes we update the base objects, then we have to save more data in our files to represent the extra attributes of our objects. How to organize/implement a system to ensure backwards compatibility with old versions of our files? The complicated part comes when looking at several versions at once. Version 1 -> Version 2 -> Version 3 -> Version 4 Should we write four file readers, one for each version of the file to read it into the current latest version of our object? Or, should we keep all the old versions of the classes around from versions 1-3 so that the old readers can read the data into those classes, and then have incremental updaters to update 1->2 and then 2->3 and then 3->4.
[ "When I increment versions like this I typically keep the old reader, and just update it to write into the new model. This means I only have the current model for the rest of my code to deal with, but I can still read old files. I would not keep old classes around, no matter what other choices you may make - you want to localize the number of places in your code that have to understand old versions to as few as possible (preferably one). If you keep old classes around, then any code that deals with those classes (even as derived from a common base) runs the risk of having to \"know\" about old versions, and that creates an unmitigated maintenance disaster after a while.\nThis is NOT a panacea...all the obvious options have issues. Once you have more than a few old readers, it becomes really time consuming to update them all (and god forbid you refactor some code they require into a new namespace and then have to edit effectively the same code 100 times to replace names). However, I usually just use this as a gateway to getting rid of old versions entirely - if you resolve to only have a few old version readers floating around for backwards compatibility, you can start deleting the oldest ones every time you make a new one, making the maintenance considerably less of a headache.\n" ]
[ 1 ]
[]
[]
[ "backwards_compatibility", "python", "xml" ]
stackoverflow_0003088269_backwards_compatibility_python_xml.txt
Q: Python: Elegant way to replace a given dictionary by child key somewhere in a tree? Is there some kind of enumeration library or method I should use or should I write from scratch with recursion? I'm parsing a JSON tree into an object tree as it happens, and I'd like to replace some nodes with other kinds of objects. E.g: db = {'bigBang' : {'stars': {'planets': {}, 'is_list':true } } } db.deepReplace( 'is_list', ['earth', 'mars'] ) >> db is now: >> {'bigBang' : >> {'stars': >> {'planets': >> { >> ['earth', 'mars'] >> } >> } >> } >> } A: It's hard to tell exactly what you're trying to accomplish; I guess you want deepReplace to replace any node named "planets" with a map containing "earth" and "mars"? It's pretty easy to write that function, especially if you know the tree will contain dicts. If not, you need to test the type (or catch the errors) when you try and recurse. def deep_replace(d, key, replacement): for k, value in d.items(): if k == key: d[k] = replacement else: deep_replace(value, key, replacement) A: If you know there's only one node to replace: def deepReplace(d, key, value): if isinstance(d, dict): if key in d: d[key] = value return True else: for k,v in d.iteritems(): if deepReplace(v, key, value): return True return False Otherwise: def deepReplace(d, key, value): if isinstance(d, dict): if key in d: d[key] = value else: for k,v in d.iteritems(): deepReplace(v, key, value):
Python: Elegant way to replace a given dictionary by child key somewhere in a tree?
Is there some kind of enumeration library or method I should use or should I write from scratch with recursion? I'm parsing a JSON tree into an object tree as it happens, and I'd like to replace some nodes with other kinds of objects. E.g: db = {'bigBang' : {'stars': {'planets': {}, 'is_list':true } } } db.deepReplace( 'is_list', ['earth', 'mars'] ) >> db is now: >> {'bigBang' : >> {'stars': >> {'planets': >> { >> ['earth', 'mars'] >> } >> } >> } >> }
[ "It's hard to tell exactly what you're trying to accomplish; I guess you want deepReplace to replace any node named \"planets\" with a map containing \"earth\" and \"mars\"?\nIt's pretty easy to write that function, especially if you know the tree will contain dicts. If not, you need to test the type (or catch the errors) when you try and recurse.\ndef deep_replace(d, key, replacement):\n for k, value in d.items():\n if k == key:\n d[k] = replacement\n else:\n deep_replace(value, key, replacement)\n\n", "If you know there's only one node to replace:\ndef deepReplace(d, key, value):\n if isinstance(d, dict):\n if key in d:\n d[key] = value\n return True\n else:\n for k,v in d.iteritems():\n if deepReplace(v, key, value):\n return True\n return False\n\nOtherwise:\ndef deepReplace(d, key, value):\n if isinstance(d, dict):\n if key in d:\n d[key] = value\n else:\n for k,v in d.iteritems():\n deepReplace(v, key, value):\n\n" ]
[ 1, 1 ]
[]
[]
[ "oop", "python", "recursion" ]
stackoverflow_0003088841_oop_python_recursion.txt
Q: Python Exceptions: EAFP and What is Really Exceptional? It's been said in a couple places (here and here) that Python's emphasis on "it's easier to ask for forgiveness than permission" (EAFP) should be tempered with the idea that exceptions should only be called in truly exceptional cases. Consider the following, in which we're popping and pushing on a priority queue until only one element is left: import heapq ... pq = a_list[:] heapq.heapify(pq) while True: min1 = heapq.heappop(pq) try: min2 = heapq.heappop(pq) except IndexError: break else heapq.heappush(pq, min1 + min2) # do something with min1 The exception is only raised once in len(a_list) iterations of the loop, but it's not really exceptional, because we know its going to happen eventually. This setup saves us from checking whether a_list is empty a bunch of times, but (maybe) it's less readable than using explicit conditions. What's the consensus on using exceptions for this kind of non-exceptional program logic? A: exceptions should only be called in truly exceptional cases Not in Python: for example, every for loop (unless it prematurely breaks or returns) terminates by an exception (StopIteration) being thrown and caught. So, an exception that happens once per loop is hardly strange to Python -- it's there more often than not! The principle in question may be crucial in other languages, but that's definitely no reason to apply that principle to Python, where it's so contrary to the language's ethos. In this case I like Jon's rewrite (which should be further simplified by removing the else branch) because it makes the code more compact -- a pragmatical reason, most definitely not the "tempering" of Python style with an alien principle. A: Throwing exceptions is expensive in most low-level languages like C++. That influences a lot of the "common wisdom" about exceptions, and doesn't apply so much to languages that run in a VM, like Python. There's not such a major cost in Python for using an exception instead of a conditional. (This is a case where the "common wisdom" becomes a matter of habit. People come to it from experience in one type of environment--low-level languages--and then apply it to new domains without evaluating whether it makes sense.) Exceptions are still, in general, exceptional. That doesn't mean that they don't happen often; it means that they're the exception. They're the things that will tend to break from ordinary code flow, and which most of the time you don't want to have to handle one by one--which is the point of exception handlers. This part is the same in Python as in C++ and all other languages with exceptions. However, that tends to define when exceptions are thrown. You're talking about when exceptions should be caught. Very simply, don't worry about it: exceptions aren't expensive, so don't go to lengths to try to prevent them from being thrown. A lot of Python code is designed around this. I don't agree with Jon's suggestion to try to test for and avoid exceptions in advance. That's fine if it leads to clearer code, as in his example. However, in many cases it's just going to complicate things--it can effectively lead to duplicating checks and introducing bugs. For example, import os, errno, stat def read_file(fn): """ Read a file and return its contents. If the file doesn't exist or can't be read, return "". """ try: return open(fn).read() except IOError, e: return "" def read_file_2(fn): """ Read a file and return its contents. If the file doesn't exist or can't be read, return "". """ if not os.access(fn, os.R_OK): return "" st = os.stat(fn) if stat.S_ISDIR(st.st_mode): return "" return open(fn).read() print read_file("x") Sure, we can test for and avoid the failure--but we've complicated things badly. We're trying to guess all the ways the file access might fail (and this doesn't catch all of them), we may have introduced race conditions, and we're doing a lot more I/O work. This is all done for us--just catch the exception. A: Looking at the docs I think you can safely re-write the function as follows: import heapq ... pq = heapq.heapify(a_list) while pq: min1 = heapq.heappop(pq) if pq: min2 = heapq.heappop(pq) heapq.heappush(pq, min1 + min2) # do something with min1 ..and thereby avoid the try-except. Getting to the end of a list which is something you know is going to happen here isn't exceptional - it's garaunteed! So better practice would be to handle it in advance. If you had something else in another thread which was consuming from the same heap then using try-except there would make a lot more sense (i.e. handling a special / unpredictable case). More generally, I would avoid try-excepts wherever I can test for and avoid a failure in advance. This forces you to say "I know this bad situation might happen so here's how I deal with it". In my opinion, you'll tend to write more readable code as a result. [Edit] Updated the example as per Alex's suggestion A: Just for the record, i'd write is like this: import heapq a_list = range(20) pq = a_list[:] heapq.heapify(pq) try: while True: min1 = heapq.heappop(pq) min2 = heapq.heappop(pq) heapq.heappush(pq, min1 + min2) except IndexError: pass # we ran out of numbers in pq Exceptions can leave a loop (even functions) and you can use them for that. Since Python throws them everywhere, I think this pattern is quite useful (even pythonic). A: I've found the practice of using exceptions as "normal" flow control tools to be a fairly widely accepted in Python. It's most commonly used in situations like the one you describe, when you get to the end of some sort of sequence. In my opinion, that's a perfectly valid use of an exception. You do want to be careful about using exception handling willy-nilly though. Raising an exception is a reasonably expensive operation, and therefore it's best to ensure you only rely on an exception at the end of the sequence, not in each iteration.
Python Exceptions: EAFP and What is Really Exceptional?
It's been said in a couple places (here and here) that Python's emphasis on "it's easier to ask for forgiveness than permission" (EAFP) should be tempered with the idea that exceptions should only be called in truly exceptional cases. Consider the following, in which we're popping and pushing on a priority queue until only one element is left: import heapq ... pq = a_list[:] heapq.heapify(pq) while True: min1 = heapq.heappop(pq) try: min2 = heapq.heappop(pq) except IndexError: break else heapq.heappush(pq, min1 + min2) # do something with min1 The exception is only raised once in len(a_list) iterations of the loop, but it's not really exceptional, because we know its going to happen eventually. This setup saves us from checking whether a_list is empty a bunch of times, but (maybe) it's less readable than using explicit conditions. What's the consensus on using exceptions for this kind of non-exceptional program logic?
[ "\nexceptions should only be called in\n truly exceptional cases\n\nNot in Python: for example, every for loop (unless it prematurely breaks or returns) terminates by an exception (StopIteration) being thrown and caught. So, an exception that happens once per loop is hardly strange to Python -- it's there more often than not!\nThe principle in question may be crucial in other languages, but that's definitely no reason to apply that principle to Python, where it's so contrary to the language's ethos.\nIn this case I like Jon's rewrite (which should be further simplified by removing the else branch) because it makes the code more compact -- a pragmatical reason, most definitely not the \"tempering\" of Python style with an alien principle.\n", "Throwing exceptions is expensive in most low-level languages like C++. That influences a lot of the \"common wisdom\" about exceptions, and doesn't apply so much to languages that run in a VM, like Python. There's not such a major cost in Python for using an exception instead of a conditional.\n(This is a case where the \"common wisdom\" becomes a matter of habit. People come to it from experience in one type of environment--low-level languages--and then apply it to new domains without evaluating whether it makes sense.)\nExceptions are still, in general, exceptional. That doesn't mean that they don't happen often; it means that they're the exception. They're the things that will tend to break from ordinary code flow, and which most of the time you don't want to have to handle one by one--which is the point of exception handlers. This part is the same in Python as in C++ and all other languages with exceptions.\nHowever, that tends to define when exceptions are thrown. You're talking about when exceptions should be caught. Very simply, don't worry about it: exceptions aren't expensive, so don't go to lengths to try to prevent them from being thrown. A lot of Python code is designed around this.\nI don't agree with Jon's suggestion to try to test for and avoid exceptions in advance. That's fine if it leads to clearer code, as in his example. However, in many cases it's just going to complicate things--it can effectively lead to duplicating checks and introducing bugs. For example,\nimport os, errno, stat\n\ndef read_file(fn):\n \"\"\"\n Read a file and return its contents. If the file doesn't exist or\n can't be read, return \"\".\n \"\"\"\n try:\n return open(fn).read()\n except IOError, e:\n return \"\"\n\ndef read_file_2(fn):\n \"\"\"\n Read a file and return its contents. If the file doesn't exist or\n can't be read, return \"\".\n \"\"\"\n if not os.access(fn, os.R_OK):\n return \"\"\n st = os.stat(fn)\n if stat.S_ISDIR(st.st_mode):\n return \"\"\n return open(fn).read()\n\nprint read_file(\"x\")\n\nSure, we can test for and avoid the failure--but we've complicated things badly. We're trying to guess all the ways the file access might fail (and this doesn't catch all of them), we may have introduced race conditions, and we're doing a lot more I/O work. This is all done for us--just catch the exception.\n", "Looking at the docs I think you can safely re-write the function as follows:\nimport heapq\n...\npq = heapq.heapify(a_list)\nwhile pq:\n min1 = heapq.heappop(pq)\n if pq:\n min2 = heapq.heappop(pq)\n heapq.heappush(pq, min1 + min2)\n# do something with min1\n\n..and thereby avoid the try-except.\nGetting to the end of a list which is something you know is going to happen here isn't exceptional - it's garaunteed! So better practice would be to handle it in advance. If you had something else in another thread which was consuming from the same heap then using try-except there would make a lot more sense (i.e. handling a special / unpredictable case).\nMore generally, I would avoid try-excepts wherever I can test for and avoid a failure in advance. This forces you to say \"I know this bad situation might happen so here's how I deal with it\". In my opinion, you'll tend to write more readable code as a result.\n[Edit] Updated the example as per Alex's suggestion\n", "Just for the record, i'd write is like this:\nimport heapq\na_list = range(20)\npq = a_list[:]\nheapq.heapify(pq)\ntry:\n while True:\n min1 = heapq.heappop(pq)\n min2 = heapq.heappop(pq)\n heapq.heappush(pq, min1 + min2)\nexcept IndexError:\n pass # we ran out of numbers in pq\n\nExceptions can leave a loop (even functions) and you can use them for that. Since Python throws them everywhere, I think this pattern is quite useful (even pythonic).\n", "I've found the practice of using exceptions as \"normal\" flow control tools to be a fairly widely accepted in Python. It's most commonly used in situations like the one you describe, when you get to the end of some sort of sequence.\nIn my opinion, that's a perfectly valid use of an exception. You do want to be careful about using exception handling willy-nilly though. Raising an exception is a reasonably expensive operation, and therefore it's best to ensure you only rely on an exception at the end of the sequence, not in each iteration.\n" ]
[ 32, 9, 7, 4, 3 ]
[]
[]
[ "exception", "python" ]
stackoverflow_0003086806_exception_python.txt
Q: Not all of arguments converted during string formatting Im wrtiting a script which saves the current date and time as a filename but I get an error stating "TypeError: not all arguments converted during string formatting" I am new to Python andmay of missed something obvious. Code below: from subprocess import Popen import datetime today = datetime.date.today() today = str(today) print today f = open("%s.sql", "w" % (today)) x = Popen(["mysqldump", "-u", "root", "-pucsdrv", "normalisationtion"], stdout = f) x.wait() f.close() A: You're putting the string formatting in the wrong place; it needs to be right after the string that's being formatted: f = open("%s.sql" % (today), "w") It's legal to not pass any formatting arguments, like you did with "%s.sql", but it's not legal to pass arguments but not the right amount ("w" % (today) passes one, but there's no string formatting in "w", so you get an error that not all of the arguments were used) A: f = open("%s.sql" % today, "w")
Not all of arguments converted during string formatting
Im wrtiting a script which saves the current date and time as a filename but I get an error stating "TypeError: not all arguments converted during string formatting" I am new to Python andmay of missed something obvious. Code below: from subprocess import Popen import datetime today = datetime.date.today() today = str(today) print today f = open("%s.sql", "w" % (today)) x = Popen(["mysqldump", "-u", "root", "-pucsdrv", "normalisationtion"], stdout = f) x.wait() f.close()
[ "You're putting the string formatting in the wrong place; it needs to be right after the string that's being formatted:\nf = open(\"%s.sql\" % (today), \"w\")\n\nIt's legal to not pass any formatting arguments, like you did with \"%s.sql\", but it's not legal to pass arguments but not the right amount (\"w\" % (today) passes one, but there's no string formatting in \"w\", so you get an error that not all of the arguments were used)\n", "f = open(\"%s.sql\" % today, \"w\")\n\n" ]
[ 30, 4 ]
[]
[]
[ "datetime", "formatting", "python", "string" ]
stackoverflow_0003089038_datetime_formatting_python_string.txt
Q: explicit joining of python threads? I need to start some threads in a python program. The threads perform a background task which might take a long time, so I don't want to block the main thread waiting on the task to happen. Python provides the ability to 'reap' threads using Thread.join() and Thread.isAlive(). But I don't actually care about finding out when the thread has finished. I'm content to start up the thread, let it do it's thing and never worry about it again. The question is, do I need to keep references around to the Thread objects that I start so that I can later join() them? Or can I just let the reference to the Thread object go out of scope and not worry about it? Is there a 'right' thing to do in this case? A: You don't have to explicitly join threads -- just make sure they're not "daemonized" (leave their daemon attribute to the default, False) so they'll keep the process alive until they're all done (if you make your threads daemons, then you must make sure the main thread does not terminate until all relevant threads are done, or else the threads will be killed by the OS). I think the right thing is the simplest one: forget about your "background threads", just make them non-daemons (which is after all their default state).
explicit joining of python threads?
I need to start some threads in a python program. The threads perform a background task which might take a long time, so I don't want to block the main thread waiting on the task to happen. Python provides the ability to 'reap' threads using Thread.join() and Thread.isAlive(). But I don't actually care about finding out when the thread has finished. I'm content to start up the thread, let it do it's thing and never worry about it again. The question is, do I need to keep references around to the Thread objects that I start so that I can later join() them? Or can I just let the reference to the Thread object go out of scope and not worry about it? Is there a 'right' thing to do in this case?
[ "You don't have to explicitly join threads -- just make sure they're not \"daemonized\" (leave their daemon attribute to the default, False) so they'll keep the process alive until they're all done (if you make your threads daemons, then you must make sure the main thread does not terminate until all relevant threads are done, or else the threads will be killed by the OS).\nI think the right thing is the simplest one: forget about your \"background threads\", just make them non-daemons (which is after all their default state).\n" ]
[ 1 ]
[]
[]
[ "background", "multithreading", "python" ]
stackoverflow_0003088449_background_multithreading_python.txt
Q: Overwrite global var in one line in Python? I know that I can write: foo = 'bar' def update_foo(): global foo foo = 'baz' But do I really need two lines of code there? Python, alas, won't allow me to say global foo = 'baz' I could also mash the two lines together with the unfortunately repetitive global foo; foo = 'baz' Any other shortcuts? I'm on Python 2.6.5, but I'd be curious to hear responses for Python 3 as well. A: You could use my favorite alternative to global (a pretty idiosyncratic taste...): import sys thismodule = sys.modules[__name__] thismodule.foo = 'bar' def update_foo(): thismodule.foo = 'baz' Once you've made the thismodule reference, you don't need to use global in this module, because you're always working with qualified names rather than bare names (a much better idea IMHO... but maybe in MHO only, I've not been able to convince Guido to supply thismodule [[or some other identifier with this functionality]] back when Python 3 was gestating). Note that the first assignment to foo, at global level, can be done either with this explicit syntax, or by assigning to barename foo as you do in your code (I guess it's not surprising that my preference goes to the explicit form, though, in this case, just barely). A: It's two statements, there aren't any other forms. A: You could write it like this using the globals() dictionary: def update_foo(): globals()['foo'] = 'baz' but I would just stick with the 2 lines or the separating with a ; approach. A: def update_foo(): globals().update(foo='baz') A: If it makes you feel better to put it all on one line... global foo; foo = 'baz'
Overwrite global var in one line in Python?
I know that I can write: foo = 'bar' def update_foo(): global foo foo = 'baz' But do I really need two lines of code there? Python, alas, won't allow me to say global foo = 'baz' I could also mash the two lines together with the unfortunately repetitive global foo; foo = 'baz' Any other shortcuts? I'm on Python 2.6.5, but I'd be curious to hear responses for Python 3 as well.
[ "You could use my favorite alternative to global (a pretty idiosyncratic taste...):\nimport sys\nthismodule = sys.modules[__name__]\nthismodule.foo = 'bar'\n\ndef update_foo():\n thismodule.foo = 'baz'\n\nOnce you've made the thismodule reference, you don't need to use global in this module, because you're always working with qualified names rather than bare names (a much better idea IMHO... but maybe in MHO only, I've not been able to convince Guido to supply thismodule [[or some other identifier with this functionality]] back when Python 3 was gestating).\nNote that the first assignment to foo, at global level, can be done either with this explicit syntax, or by assigning to barename foo as you do in your code (I guess it's not surprising that my preference goes to the explicit form, though, in this case, just barely).\n", "It's two statements, there aren't any other forms.\n", "You could write it like this using the globals() dictionary:\ndef update_foo():\n globals()['foo'] = 'baz'\n\nbut I would just stick with the 2 lines or the separating with a ; approach.\n", "def update_foo():\n globals().update(foo='baz')\n\n", "If it makes you feel better to put it all on one line...\nglobal foo; foo = 'baz'\n\n" ]
[ 19, 7, 6, 5, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003089208_python.txt
Q: Pydev in Eclipse default working directory What is the default working directory for my project? I have several projects under my workspace, and a couple of run configurations. I use os.getcwd() and the directory goes to other project's folder, after deleting all run configurations, the directory goes to eclipse's install folder. How to make the default working directory goes to my project folder or the \src folder? EDIT: In my PYTHONPATH that will be used in the run: C:\Program Files\eclipse\dropins\plugins\org.python.pydev_1.5.4.2010011921\PySrc\pydev_sitecustomize; C:\(MyProjectDirecotry)\\src; C:\Python26; C:\Python26\DLLs; C:\Python26\lib; C:\Python26\lib\lib-tk; C:\Python26\lib\plat-win; C:\Python26\lib\site-packages maybe there's C:\Program Files\eclipse\dropins\plugins\org.python.pydev_1.5.4.2010011921\PySrc\pydev_sitecustomize; in the first line causing the issue. Why is this happened? How to revert it back to default? Thanks. A: Open Run Dialog...-> Select your run configuration->Arguments Tab->Working directory: mine is set to ${workspace_loc}:test/src/ for a project name test i created in my workspace
Pydev in Eclipse default working directory
What is the default working directory for my project? I have several projects under my workspace, and a couple of run configurations. I use os.getcwd() and the directory goes to other project's folder, after deleting all run configurations, the directory goes to eclipse's install folder. How to make the default working directory goes to my project folder or the \src folder? EDIT: In my PYTHONPATH that will be used in the run: C:\Program Files\eclipse\dropins\plugins\org.python.pydev_1.5.4.2010011921\PySrc\pydev_sitecustomize; C:\(MyProjectDirecotry)\\src; C:\Python26; C:\Python26\DLLs; C:\Python26\lib; C:\Python26\lib\lib-tk; C:\Python26\lib\plat-win; C:\Python26\lib\site-packages maybe there's C:\Program Files\eclipse\dropins\plugins\org.python.pydev_1.5.4.2010011921\PySrc\pydev_sitecustomize; in the first line causing the issue. Why is this happened? How to revert it back to default? Thanks.
[ "Open Run Dialog...-> Select your run configuration->Arguments Tab->Working directory:\nmine is set to ${workspace_loc}:test/src/ for a project name test i created in my workspace\n" ]
[ 8 ]
[]
[]
[ "eclipse", "python" ]
stackoverflow_0003089070_eclipse_python.txt
Q: How to use python on webserver for web pages I have read in the documentation that there are 4 or 5 ways in which i can python for web pages. Like With CGI Mod_python : mod_python does have some problems. Unlike the PHP interpreter, the Python interpreter uses caching when executing files, so changes to a file will require the web server to be restarted FastCGI and SCGI mod_wsgi SO which way should i go . does it means that python is not for webistes if there are too many problems while using it I have to build the live business website with thousands of users so i should not use it if that has many probelms A: I believe mod_python is deprecated so you shouldn't use it. see http://blog.dscpl.com.au/2010/05/modpython-project-soon-to-be-officially.html mod_wsgi is mentioned as a replacement. A: I am a big fan of cherrypy. Yes there are a lot of choices out there. A: You could also use Google App Engine with Python and Django A: Personally I use CGI or the Python *HTTPServer modules. CGI is very easy and seems a reasonable "unixy" approach. The *HTTPServer modules are minimal, and easy to extend if you're familiar with HTTP. I've heard very good things about mod_wsgi, and hope to learn to use it sometime. My vote then is that you go with mod_wsgi, it's not even specific to just Python. A: The important thing is that whatever you use to develop your Python web application, that it support the WSGI (http://www.wsgi.org) interface for hosting. So long as you do that, it can be hosted with any of options 1-4, albeit that CGI/WSGI bridge would only be used for small scripts and not large frameworks because of fact that new process has to be created for each request. So, don't worry about the hosting mechanism as many exist and not just those above. Instead, start looking at the various framework and toolkits available. The most mainstream of these for Python is Django (http://www.djangoproject.com). A: I think those problems are not strong enough to say Python is not for websites. And Python syntax is very clear and easy read. You should try Django for web development. It can reali speed up your development process.
How to use python on webserver for web pages
I have read in the documentation that there are 4 or 5 ways in which i can python for web pages. Like With CGI Mod_python : mod_python does have some problems. Unlike the PHP interpreter, the Python interpreter uses caching when executing files, so changes to a file will require the web server to be restarted FastCGI and SCGI mod_wsgi SO which way should i go . does it means that python is not for webistes if there are too many problems while using it I have to build the live business website with thousands of users so i should not use it if that has many probelms
[ "I believe mod_python is deprecated so you shouldn't use it. \nsee http://blog.dscpl.com.au/2010/05/modpython-project-soon-to-be-officially.html\nmod_wsgi is mentioned as a replacement.\n", "I am a big fan of cherrypy. Yes there are a lot of choices out there.\n", "You could also use Google App Engine with Python and Django\n", "Personally I use CGI or the Python *HTTPServer modules. CGI is very easy and seems a reasonable \"unixy\" approach. The *HTTPServer modules are minimal, and easy to extend if you're familiar with HTTP.\nI've heard very good things about mod_wsgi, and hope to learn to use it sometime. My vote then is that you go with mod_wsgi, it's not even specific to just Python.\n", "The important thing is that whatever you use to develop your Python web application, that it support the WSGI (http://www.wsgi.org) interface for hosting. So long as you do that, it can be hosted with any of options 1-4, albeit that CGI/WSGI bridge would only be used for small scripts and not large frameworks because of fact that new process has to be created for each request.\nSo, don't worry about the hosting mechanism as many exist and not just those above. Instead, start looking at the various framework and toolkits available. The most mainstream of these for Python is Django (http://www.djangoproject.com).\n", "I think those problems are not strong enough to say Python is not for websites. And Python syntax is very clear and easy read. You should try Django for web development. It can reali speed up your development process.\n" ]
[ 1, 0, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003089450_python.txt
Q: Django-modpython deploying project I am deploying a Django project on apache server with mod_python in linux. I have created a directory structure like: /var/www/html/django/demoInstall where demoInstall is my project. In the httpd.conf I have put the following code. <Location "/django/demoInstall"> SetHandler python-program PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE demoInstall.settings PythonOption django.root django/demoInstall PythonDebug On PythonPath "['/var/www/html/django'] + sys.path" </Location> It is getting me the django environment but the issue is that the urls mentioned in urls.py are not working correctly. In my url file I have mentioned the url like: (r'^$', views.index), Now, in the browser I am putting the url like : http://domainname/django/demoInstall/ and I am expecting the views.index to be invoked. But I guess it is expecting the url to be only: http://domainname/ . When I change the url mapping to: (r'^django/demoInstall$', views.index), it works fine. Please suggest as I do not want to change all the mappings in url config file. Thanks in advance. A: There's a fairly simple way around this using just django, without having to touch apache. Rename your urls.py to something else, e.g. site_urls.py Then create a new urls.py which includes that from django.conf.urls.defaults import * urlpatterns = patterns('', (r'^django/demoInstall/', include('site_urls.py')), ) This will ensure that all the url reversing continues to work, too. A: That should be: PythonOption django.root /django/demoInstall Ie., must match sub URL in Location directive. You shouldn't be using that prefix in urls.py.
Django-modpython deploying project
I am deploying a Django project on apache server with mod_python in linux. I have created a directory structure like: /var/www/html/django/demoInstall where demoInstall is my project. In the httpd.conf I have put the following code. <Location "/django/demoInstall"> SetHandler python-program PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE demoInstall.settings PythonOption django.root django/demoInstall PythonDebug On PythonPath "['/var/www/html/django'] + sys.path" </Location> It is getting me the django environment but the issue is that the urls mentioned in urls.py are not working correctly. In my url file I have mentioned the url like: (r'^$', views.index), Now, in the browser I am putting the url like : http://domainname/django/demoInstall/ and I am expecting the views.index to be invoked. But I guess it is expecting the url to be only: http://domainname/ . When I change the url mapping to: (r'^django/demoInstall$', views.index), it works fine. Please suggest as I do not want to change all the mappings in url config file. Thanks in advance.
[ "There's a fairly simple way around this using just django, without having to touch apache.\nRename your urls.py to something else, e.g. site_urls.py\nThen create a new urls.py which includes that \nfrom django.conf.urls.defaults import *\n\nurlpatterns = patterns('',\n (r'^django/demoInstall/', include('site_urls.py')),\n)\n\nThis will ensure that all the url reversing continues to work, too.\n", "That should be:\nPythonOption django.root /django/demoInstall\n\nIe., must match sub URL in Location directive.\nYou shouldn't be using that prefix in urls.py.\n" ]
[ 2, 0 ]
[]
[]
[ "django", "mod_python", "python" ]
stackoverflow_0003060311_django_mod_python_python.txt
Q: Python not opening Japanese filenames I've been working on a python script to open up a file with a unicode name (Japanese mostly) and save to a randomly generated (Non-unicode) filename in Windows Vista 64-bit, and I'm having issues... It just doesn't work, it works fine with non-unicode filenames (Even if it has unicode content), but the second you try to pass a unicode filename in - it doesn't work. Here's the code: try: import sys, os inpath = sys.argv[1] outpath = sys.argv[2] filein = open(inpath, "rb") contents = filein.read() fileSave = open(outpath, "wb") fileSave.write(contents) fileSave.close() testfile = open(outpath + '.test', 'wb') testfile.write(inpath) testfile.close() except: errlog = open('G:\\log.txt', 'w') errlog.write(str(sys.exc_info())) errlog.close() And the error: (<type 'exceptions.IOError'>, IOError(2, 'No such file or directory'), <traceback object at 0x01092A30>) A: You have to convert your inpath to unicode, like this: inpath = sys.argv[1] inpath = inpath.decode("UTF-8") filein = open(inpath, "rb") I'm guessing you are using Python 2.6, because in Python 3, all strings are unicode by default, so this problem wouldn't happen. A: My guess is that sys.argv1 and sys.argv[2] are just byte arrays and don't support natively Unicode. You could confirm this by printing them and seeing if they are the character you expect. You should also print type(sys.argv1) to make sure they are of the correct type. Where do the command-line parameters come from? Do they come from another program or are you typing them on the command-line? If they come from another program, you could have the other program encode them to UTF-8 and then have your Python program decode them from UTF-8. Which version of Python are you using? Edit: here's a robust solution: http://code.activestate.com/recipes/572200/
Python not opening Japanese filenames
I've been working on a python script to open up a file with a unicode name (Japanese mostly) and save to a randomly generated (Non-unicode) filename in Windows Vista 64-bit, and I'm having issues... It just doesn't work, it works fine with non-unicode filenames (Even if it has unicode content), but the second you try to pass a unicode filename in - it doesn't work. Here's the code: try: import sys, os inpath = sys.argv[1] outpath = sys.argv[2] filein = open(inpath, "rb") contents = filein.read() fileSave = open(outpath, "wb") fileSave.write(contents) fileSave.close() testfile = open(outpath + '.test', 'wb') testfile.write(inpath) testfile.close() except: errlog = open('G:\\log.txt', 'w') errlog.write(str(sys.exc_info())) errlog.close() And the error: (<type 'exceptions.IOError'>, IOError(2, 'No such file or directory'), <traceback object at 0x01092A30>)
[ "You have to convert your inpath to unicode, like this:\ninpath = sys.argv[1]\ninpath = inpath.decode(\"UTF-8\")\nfilein = open(inpath, \"rb\")\n\nI'm guessing you are using Python 2.6, because in Python 3, all strings are unicode by default, so this problem wouldn't happen.\n", "My guess is that sys.argv1 and sys.argv[2] are just byte arrays and don't support natively Unicode. You could confirm this by printing them and seeing if they are the character you expect. You should also print type(sys.argv1) to make sure they are of the correct type.\nWhere do the command-line parameters come from? Do they come from another program or are you typing them on the command-line? If they come from another program, you could have the other program encode them to UTF-8 and then have your Python program decode them from UTF-8.\nWhich version of Python are you using?\nEdit: here's a robust solution: http://code.activestate.com/recipes/572200/\n" ]
[ 3, 1 ]
[]
[]
[ "file_io", "python", "unicode", "windows" ]
stackoverflow_0003089700_file_io_python_unicode_windows.txt
Q: Is there a python equivalent to the Unix `which` command? I'd like to know where the module I'm about to import is coming from. Is there a which command in python? Example: >>> which module_name /usr/lib/python2.6/site-packages/module_name.py A: import imp imp.find_module(module_name) Help on built-in function find_module in module imp: find_module(...) find_module(name, [path]) -> (file, filename, (suffix, mode, type)) Search for a module. If path is omitted or None, search for a built-in, frozen or special module and continue search in sys.path. The module name cannot contain '.'; to search for a submodule of a package, pass the submodule name and the package's __path__.
Is there a python equivalent to the Unix `which` command?
I'd like to know where the module I'm about to import is coming from. Is there a which command in python? Example: >>> which module_name /usr/lib/python2.6/site-packages/module_name.py
[ "import imp\nimp.find_module(module_name)\n\n\nHelp on built-in function find_module\n in module imp: \nfind_module(...)\n find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n Search for a module. If path is omitted or None, search for a\n built-in, frozen or special module and continue search in sys.path.\n The module name cannot contain '.'; to search for a submodule of a\n package, pass the submodule name and the package's __path__.\n\n" ]
[ 8 ]
[]
[]
[ "python" ]
stackoverflow_0003089939_python.txt
Q: Python getattr equivalent for dictionaries? What's the most succinct way of saying, in Python, "Give me dict['foo'] if it exists, and if not, give me this other value bar"? If I were using an object rather than a dictionary, I'd use getattr: getattr(obj, 'foo', bar) but this raises a key error if I try using a dictionary instead (a distinction I find unfortunate coming from JavaScript/CoffeeScript). Likewise, in JavaScript/CoffeeScript I'd just write dict['foo'] || bar but, again, this yields a KeyError. What to do? Something succinct, please! A: dict.get(key, default) returns dict[key] if key in dict, else returns default. Note that the default for default is None so if you say dict.get(key) and key is not in dict then this will just return None rather than raising a KeyError as happens when you use the [] key access notation. A: Also take a look at collections module's defaultdict class. It's a dict for which you can specify what it must return when the key is not found. With it you can do things like: class MyDefaultObj: def __init__(self): self.a = 1 from collections import defaultdict d = defaultdict(MyDefaultObj) i = d['NonExistentKey'] type(i) <instance of class MyDefalutObj> which allows you to use the familiar d[i] convention. However, as mikej said, .get() also works, but here is the form closer to your JavaScript example: d = {} i = d.get('NonExistentKey') or MyDefaultObj() # the reason this is slightly better than d.get('NonExistent', MyDefaultObj()) # is that instantiation of default value happens only when 'NonExistent' does not exist. # With d.get('NonExistent', MyDefaultObj()) you spin up a default every time you .get() type(i) <instance of class MyDefalutObj>
Python getattr equivalent for dictionaries?
What's the most succinct way of saying, in Python, "Give me dict['foo'] if it exists, and if not, give me this other value bar"? If I were using an object rather than a dictionary, I'd use getattr: getattr(obj, 'foo', bar) but this raises a key error if I try using a dictionary instead (a distinction I find unfortunate coming from JavaScript/CoffeeScript). Likewise, in JavaScript/CoffeeScript I'd just write dict['foo'] || bar but, again, this yields a KeyError. What to do? Something succinct, please!
[ "dict.get(key, default) returns dict[key] if key in dict, else returns default.\nNote that the default for default is None so if you say dict.get(key) and key is not in dict then this will just return None rather than raising a KeyError as happens when you use the [] key access notation. \n", "Also take a look at collections module's defaultdict class. It's a dict for which you can specify what it must return when the key is not found. With it you can do things like:\nclass MyDefaultObj:\n def __init__(self):\n self.a = 1\n\nfrom collections import defaultdict\nd = defaultdict(MyDefaultObj)\ni = d['NonExistentKey']\ntype(i)\n<instance of class MyDefalutObj>\n\nwhich allows you to use the familiar d[i] convention. \nHowever, as mikej said, .get() also works, but here is the form closer to your JavaScript example:\nd = {}\ni = d.get('NonExistentKey') or MyDefaultObj()\n# the reason this is slightly better than d.get('NonExistent', MyDefaultObj())\n# is that instantiation of default value happens only when 'NonExistent' does not exist.\n# With d.get('NonExistent', MyDefaultObj()) you spin up a default every time you .get()\ntype(i)\n<instance of class MyDefalutObj>\n\n" ]
[ 104, 5 ]
[]
[]
[ "python" ]
stackoverflow_0003089186_python.txt
Q: Django Inlines user permissions + view only - permissions issues I'm not sure if this is a bug or I'm just missing something (although I have already parsed the documentation about inlines), but: Let's say I have a model A. Model A is an inline of model B. User U has full access to model B, but only change permissions to model A (so, no add, nor delete). However, when editing model B, user U can still see the "Add another A" link at the bottom, although U hasn't add permissions for that respective model. What's wrong? Why does that link keep on showing? My logic says that if U does not have permissions to add A, the link shouldn't appear anymore. Also, ideally, I would like to give U only view rights to model A (so no add, delete or change - only view), but I've read about that (strange, if you ask me) philosophy according to which "If you don't trust U, just deny him access to the admin area all together". Kind of a stupid doctrine. Right now, I'm trying to simulate this 'view only permissions' by leaving U with just change rights and set all fields as read only. But I think this is kind of a stupid approach and may also cause problems like the permissions thing above... How does an average Django programmer like me achieve view-only permissions, and most of all how should I get rid of the "Add another A" link at the bottom of the admin edit form? Thanks in advance! A: If I want a read-only version of what's in the admin, I just write some normal Django views and keep them out of the admin. I don't think the kind of thing you're talking about (allowing changes to an object but not its inlines) is really supported by the admin. Don't get me wrong: the admin is very flexible and useful, but it's not intended to do everything for you. The only way I see you being able to have this much control in the admin is to not inline A. "If you don't trust U, just deny him access to the admin area all together". Kind of a stupid doctrine. Not really, when you consider that the admin isn't intended to have the required level of security hardening to guarantee that fine-grain level of access control. There are many, many places in the admin, due to its open and extensible nature, where bugs can lurk (usually in user-written code) that can be exploited by bad actors. This is why untrusted users should always see all admin URLs return 404. Anyway, when access control requirements are that fine-grained, it becomes unlikely that a general (i.e. django.contrib) solution will fit.
Django Inlines user permissions + view only - permissions issues
I'm not sure if this is a bug or I'm just missing something (although I have already parsed the documentation about inlines), but: Let's say I have a model A. Model A is an inline of model B. User U has full access to model B, but only change permissions to model A (so, no add, nor delete). However, when editing model B, user U can still see the "Add another A" link at the bottom, although U hasn't add permissions for that respective model. What's wrong? Why does that link keep on showing? My logic says that if U does not have permissions to add A, the link shouldn't appear anymore. Also, ideally, I would like to give U only view rights to model A (so no add, delete or change - only view), but I've read about that (strange, if you ask me) philosophy according to which "If you don't trust U, just deny him access to the admin area all together". Kind of a stupid doctrine. Right now, I'm trying to simulate this 'view only permissions' by leaving U with just change rights and set all fields as read only. But I think this is kind of a stupid approach and may also cause problems like the permissions thing above... How does an average Django programmer like me achieve view-only permissions, and most of all how should I get rid of the "Add another A" link at the bottom of the admin edit form? Thanks in advance!
[ "If I want a read-only version of what's in the admin, I just write some normal Django views and keep them out of the admin.\nI don't think the kind of thing you're talking about (allowing changes to an object but not its inlines) is really supported by the admin. Don't get me wrong: the admin is very flexible and useful, but it's not intended to do everything for you.\nThe only way I see you being able to have this much control in the admin is to not inline A.\n\n\"If you don't trust U, just deny him access to the admin area all together\". Kind of a stupid doctrine.\n\nNot really, when you consider that the admin isn't intended to have the required level of security hardening to guarantee that fine-grain level of access control. There are many, many places in the admin, due to its open and extensible nature, where bugs can lurk (usually in user-written code) that can be exploited by bad actors. This is why untrusted users should always see all admin URLs return 404.\nAnyway, when access control requirements are that fine-grained, it becomes unlikely that a general (i.e. django.contrib) solution will fit.\n" ]
[ 2 ]
[]
[]
[ "django", "inlines", "permissions", "python" ]
stackoverflow_0002858040_django_inlines_permissions_python.txt
Q: Parse items from text file I have a text file that includes data inside {[]} tags. What would be the suggested way to parse that data so I can just use the data inside the tags? Example text file would look like this: 'this is a bunch of text that is not {[really]} useful in any {[way]}. I need to {[get]} some items {[from]} it.' I would like to end up with 'really', 'way', 'get', 'from' in a list. I guess I could use split to do it.. but seems like there might be a better way out there. I have seen a ton parsing libraries, is there one that would be perfect for what I want to do? A: I would use regular expressions. This answer assumes that none of the tag characters {}[] appear within other tag characters. import re text = 'this is a bunch of text that is not {[really]} useful in any {[way]}. I need to {[get]} some items {[from]} it.' for s in re.findall(r'\{\[(.*?)\]\}', text): print s Using the verbose mode in python regular expressions: re.findall(''' \{ # opening curly brace \[ # followed by an opening square bracket ( # capture the next pattern .*? # followed by shortest possible sequence of anything ) # end of capture \] # followed by closing square bracket \} # followed by a closing curly brace ''', text, re.VERBOSE) A: This is a job for regex: >>> import re >>> text = 'this is a bunch of text that is not {[really]} useful in any {[way]}. I need to {[get]} some items {[from]} it.' >>> re.findall(r'\{\[(\w+)\]\}', text) ['really', 'way', 'get', 'from'] A: slower, bigger, no regular expresions the old school way :P def f(s): result = [] tmp = '' for c in s: if c in '{[': stack.append(c) elif c in ']}': stack.pop() if c == ']': result.append(tmp) tmp = '' elif stack and stack[-1] == '[': tmp += c return result >>> s 'this is a bunch of text that is not {[really]} useful in any {[way]}. I need to {[get]} some items {[from]} it.' >>> f(s) ['really', 'way', 'get', 'from'] A: Another way def between_strings(source, start='{[', end=']}'): words = [] while True: start_index = source.find(start) if start_index == -1: break end_index = source.find(end) words.append(source[start_index+len(start):end_index]) source = source[end_index+len(end):] return words text = "this is a bunch of text that is not {[really]} useful in any {[way]}. I need to {[get]} some items {[from]} it." assert between_strings(text) == ['really', 'way', 'get', 'from']
Parse items from text file
I have a text file that includes data inside {[]} tags. What would be the suggested way to parse that data so I can just use the data inside the tags? Example text file would look like this: 'this is a bunch of text that is not {[really]} useful in any {[way]}. I need to {[get]} some items {[from]} it.' I would like to end up with 'really', 'way', 'get', 'from' in a list. I guess I could use split to do it.. but seems like there might be a better way out there. I have seen a ton parsing libraries, is there one that would be perfect for what I want to do?
[ "I would use regular expressions. This answer assumes that none of the tag characters {}[] appear within other tag characters.\nimport re\ntext = 'this is a bunch of text that is not {[really]} useful in any {[way]}. I need to {[get]} some items {[from]} it.'\n\nfor s in re.findall(r'\\{\\[(.*?)\\]\\}', text):\n print s\n\nUsing the verbose mode in python regular expressions:\nre.findall('''\n \\{ # opening curly brace\n \\[ # followed by an opening square bracket\n ( # capture the next pattern\n .*? # followed by shortest possible sequence of anything\n ) # end of capture\n \\] # followed by closing square bracket\n \\} # followed by a closing curly brace\n ''', text, re.VERBOSE)\n\n", "This is a job for regex:\n>>> import re\n>>> text = 'this is a bunch of text that is not {[really]} useful in any {[way]}. I need to {[get]} some items {[from]} it.'\n>>> re.findall(r'\\{\\[(\\w+)\\]\\}', text)\n['really', 'way', 'get', 'from']\n\n", "slower, bigger, no regular expresions\nthe old school way :P\ndef f(s):\n result = []\n tmp = ''\n for c in s:\n if c in '{[':\n stack.append(c)\n elif c in ']}':\n stack.pop()\n if c == ']':\n result.append(tmp)\n tmp = ''\n elif stack and stack[-1] == '[':\n tmp += c\n return result\n\n>>> s\n'this is a bunch of text that is not {[really]} useful in any {[way]}. I need to {[get]} some items {[from]} it.'\n>>> f(s)\n['really', 'way', 'get', 'from']\n\n", "Another way\ndef between_strings(source, start='{[', end=']}'):\n words = []\n while True:\n start_index = source.find(start)\n if start_index == -1:\n break\n end_index = source.find(end)\n words.append(source[start_index+len(start):end_index])\n source = source[end_index+len(end):]\n return words\n\n\ntext = \"this is a bunch of text that is not {[really]} useful in any {[way]}. I need to {[get]} some items {[from]} it.\"\nassert between_strings(text) == ['really', 'way', 'get', 'from']\n\n" ]
[ 6, 3, 2, 1 ]
[]
[]
[ "python", "string", "text_processing" ]
stackoverflow_0003040115_python_string_text_processing.txt
Q: Pylons and NodeJS / Comet I'm building Pylons web applications that use a lot of jQuery and AJAX/JSON to make these apps more Web 2.0'ie. I've been looking at the server push technologies and have questions about how to do this with Pylons. I've looked at Comet and NodeJS (though I don't know much about NodeJS yet) and am confused about what would be a good method to implement server push techniques in Pylons. I'm currently "emulating" this by having my JavasScript client app perform periodic polling in order to update the app content. Does anyone have any information/pointers/hints/help about what I'm talking about in the paragraph above? Your help would most definitely be appreciated! Thanks in advance! Doug A: Pylons is unlikely to help you with "Comet" (aka Server Push) Comet relies on "seeping" data over connections open for long time. Pylons is WSGI in the core - which really precludes long-open connections. You will likely need a separate ASYNCHRONOUS messaging server that will be your "comet" server. For starters, take a look at a good example of Comet functionality in action: http://code.stanziq.com/speeqe/ Site is interesting because they note the more popular kits for gluing Comet together on Python: Punjab, BOSH, XMPP. After that, take a look at Orbited. Then, take a look at Tornado. After about a day of reading up on all that, you will know what to choose as back-end for a "comet" functionality. A: If you don't know much about NodeJS yet, I highly recommend watching Ryan Dahl's talk from JSConf.
Pylons and NodeJS / Comet
I'm building Pylons web applications that use a lot of jQuery and AJAX/JSON to make these apps more Web 2.0'ie. I've been looking at the server push technologies and have questions about how to do this with Pylons. I've looked at Comet and NodeJS (though I don't know much about NodeJS yet) and am confused about what would be a good method to implement server push techniques in Pylons. I'm currently "emulating" this by having my JavasScript client app perform periodic polling in order to update the app content. Does anyone have any information/pointers/hints/help about what I'm talking about in the paragraph above? Your help would most definitely be appreciated! Thanks in advance! Doug
[ "Pylons is unlikely to help you with \"Comet\" (aka Server Push) Comet relies on \"seeping\" data over connections open for long time. Pylons is WSGI in the core - which really precludes long-open connections.\nYou will likely need a separate ASYNCHRONOUS messaging server that will be your \"comet\" server.\nFor starters, take a look at a good example of Comet functionality in action:\nhttp://code.stanziq.com/speeqe/\nSite is interesting because they note the more popular kits for gluing Comet together on Python: Punjab, BOSH, XMPP.\nAfter that, take a look at Orbited. Then, take a look at Tornado. After about a day of reading up on all that, you will know what to choose as back-end for a \"comet\" functionality.\n", "If you don't know much about NodeJS yet, I highly recommend watching Ryan Dahl's talk from JSConf.\n" ]
[ 4, 1 ]
[]
[]
[ "ajax", "jquery", "pylons", "python" ]
stackoverflow_0003077490_ajax_jquery_pylons_python.txt
Q: sine wave glissando from one pitch to another in Numpy I have been working on a program where I need to slowly and smoothly change the pitch of a sine wave from one pitch to another. I am able to get an array of the frequency the pitch should be at any given moment (for instance, [440, 526.5, 634.2 794.8, 880], though much, much longer) but it seems I am unable to actually apply that frequency to a wave. My best attempt is: numpy.sin(2*math.pi*x*freq/self.sample_rate) where "freq" is the array of frequencies and x is an enumeration array ([0,1, 2, 3, 4...]). This method sort of works, however it makes the frequency go above the expected frequency, and then back down. I have been working on this problem for a very long time and have been unable to make any progress on finding a more appropriate method. Any advice? Was I clear enough in expressing my dilemma? Thank you. A: The issue is that as you ramp through the frequencies, each frequency effectively has a different phase for the given time. When you scroll through these phases quickly and continuously, they drive the sine wave at higher frequency (or lower is also possible). Imagine, for example, that you changed the frequency instantaneously -- to do this you'd have to supply the phase correction p_1 = p_0 + 2*pi*t*(f_0-f_1) to make the phases match up at time t. As you do this is little steps, you also have to make a similar phase correction, with each phase correction adding to the previous. Here's the resulting figure, with the code below. The top figure is the frequency the middle is without the phase correction, and the bottom has the continuously corrected phase. from pylab import * sample_rate = .001 f0, f1 = 10, 20 t_change = 2 times = arange(0, 4, sample_rate) ramp = 1./(1+exp(-6.*(times-t_change))) freq = f0*(1-ramp)+f1*ramp phase_correction = add.accumulate(times*concatenate((zeros(1), 2*pi*(freq[:-1]-freq[1:])))) figure() subplot(311) plot(times, freq) subplot(312) plot(times, sin(2*pi*freq*times)) subplot(313) plot(times, sin(2*pi*freq*times+phase_correction)) show() A: I like to think of frequency as the rate at which you are stepping through your sound sample - in this case a sine wave. Here's an attempt at some Python code to do what you want. We assume that the freq() method gives frequency as a function of time. For your purposes, it will be some kind of exponential. We are trying to fill a pre-allocated list called wave. index = 0 t = 0 while t < len(wave): wave[t] = math.sin(2*math.pi*index/sample_rate) t = t+1 index = index + freq(t/sample_rate) Excuse my Python, I'm still learning the language.
sine wave glissando from one pitch to another in Numpy
I have been working on a program where I need to slowly and smoothly change the pitch of a sine wave from one pitch to another. I am able to get an array of the frequency the pitch should be at any given moment (for instance, [440, 526.5, 634.2 794.8, 880], though much, much longer) but it seems I am unable to actually apply that frequency to a wave. My best attempt is: numpy.sin(2*math.pi*x*freq/self.sample_rate) where "freq" is the array of frequencies and x is an enumeration array ([0,1, 2, 3, 4...]). This method sort of works, however it makes the frequency go above the expected frequency, and then back down. I have been working on this problem for a very long time and have been unable to make any progress on finding a more appropriate method. Any advice? Was I clear enough in expressing my dilemma? Thank you.
[ "The issue is that as you ramp through the frequencies, each frequency effectively has a different phase for the given time. When you scroll through these phases quickly and continuously, they drive the sine wave at higher frequency (or lower is also possible). \nImagine, for example, that you changed the frequency instantaneously -- to do this you'd have to supply the phase correction p_1 = p_0 + 2*pi*t*(f_0-f_1) to make the phases match up at time t. As you do this is little steps, you also have to make a similar phase correction, with each phase correction adding to the previous. \nHere's the resulting figure, with the code below. The top figure is the frequency the middle is without the phase correction, and the bottom has the continuously corrected phase.\n\nfrom pylab import *\n\nsample_rate = .001\nf0, f1 = 10, 20\nt_change = 2\n\ntimes = arange(0, 4, sample_rate)\n\nramp = 1./(1+exp(-6.*(times-t_change)))\nfreq = f0*(1-ramp)+f1*ramp\nphase_correction = add.accumulate(times*concatenate((zeros(1), 2*pi*(freq[:-1]-freq[1:]))))\n\nfigure()\nsubplot(311)\nplot(times, freq)\nsubplot(312)\nplot(times, sin(2*pi*freq*times))\nsubplot(313)\nplot(times, sin(2*pi*freq*times+phase_correction))\n\nshow()\n\n", "I like to think of frequency as the rate at which you are stepping through your sound sample - in this case a sine wave. Here's an attempt at some Python code to do what you want. We assume that the freq() method gives frequency as a function of time. For your purposes, it will be some kind of exponential. We are trying to fill a pre-allocated list called wave.\nindex = 0\nt = 0\nwhile t < len(wave):\n wave[t] = math.sin(2*math.pi*index/sample_rate)\n t = t+1\n index = index + freq(t/sample_rate)\n\nExcuse my Python, I'm still learning the language.\n" ]
[ 11, 0 ]
[]
[]
[ "audio", "math", "numpy", "python", "trigonometry" ]
stackoverflow_0003089832_audio_math_numpy_python_trigonometry.txt
Q: Help with py2exe error I'm trying to compile to an exe my script of python, but I'm getting an error that I'm not know how to resolve... my script include this libraries import pyHook import pythoncom import time import win32com.client and the py2exe script is from distutils.core import setup import py2exe import sys sys.argv.append('py2exe') setup( options = {'py2exe': dict(bundle_files=1, optimize=1)}, console = ["login.macro.py"], zipfile = None, ) and I'm getting the error Traceback (most recent call last): File "login.macro.py", line 4, in <module> File "zipextimporter.pyo", line 82, in load_module File "win32com\__init__.pyo", line 5, in <module> File "zipextimporter.pyo", line 98, in load_module ImportError: MemoryLoadLibrary failed loading win32api.pyd How can I solve it? I've just compiled another script and went everything ok A: Try bundle_files=3 : http://mail.python.org/pipermail/python-win32/2009-June/009227.html
Help with py2exe error
I'm trying to compile to an exe my script of python, but I'm getting an error that I'm not know how to resolve... my script include this libraries import pyHook import pythoncom import time import win32com.client and the py2exe script is from distutils.core import setup import py2exe import sys sys.argv.append('py2exe') setup( options = {'py2exe': dict(bundle_files=1, optimize=1)}, console = ["login.macro.py"], zipfile = None, ) and I'm getting the error Traceback (most recent call last): File "login.macro.py", line 4, in <module> File "zipextimporter.pyo", line 82, in load_module File "win32com\__init__.pyo", line 5, in <module> File "zipextimporter.pyo", line 98, in load_module ImportError: MemoryLoadLibrary failed loading win32api.pyd How can I solve it? I've just compiled another script and went everything ok
[ "Try bundle_files=3 :\nhttp://mail.python.org/pipermail/python-win32/2009-June/009227.html\n" ]
[ 0 ]
[]
[]
[ "py2exe", "python", "windows" ]
stackoverflow_0003089677_py2exe_python_windows.txt
Q: In Pylons, how do I perform actions after writing the response? In a pylons controller, I would like to first return the response to the request (so that the user gets a response ASAP), and then perform some additional operations (say, updating view counts, etc.) that didn't need to happen to generate the response. What's the best-practice for doing things like this? Thanks! A: On most wsgi-based servers (like the standard wsgiref, nwsgi etc) there is a way to send some portion of a body out work a little more and send some more. I guess the "send some more" is optional. Use yield instead of return. WSGI example (not sure if it translates well into Pylons): def application(environ, start_response): start_response('200 OK', [('Content-type','text/plain')]) yield 'body starts. You should see this in browser already' # do something yield 'some more of body' Once the request handler runs out of code to run, it closes the connection. Now, this is sure to work on standard wsgi servers I tried. I would like to hear if this works on Pylons. A: I did not have the chance to try Python threads yet, but you could do something like: def controller_method(self): # controller logic here html = render('/template.mako') # start a thread here return html By starting the thread after all the logic, but just before returning, you should avoid conflicts between the threads. You might also have a look at RabbitMQ or other message queuing software. You could offload your main web application by sending the jobs in a queue.
In Pylons, how do I perform actions after writing the response?
In a pylons controller, I would like to first return the response to the request (so that the user gets a response ASAP), and then perform some additional operations (say, updating view counts, etc.) that didn't need to happen to generate the response. What's the best-practice for doing things like this? Thanks!
[ "On most wsgi-based servers (like the standard wsgiref, nwsgi etc) there is a way to send some portion of a body out work a little more and send some more. I guess the \"send some more\" is optional. \nUse yield instead of return. WSGI example (not sure if it translates well into Pylons):\ndef application(environ, start_response):\n start_response('200 OK', [('Content-type','text/plain')])\n yield 'body starts. You should see this in browser already'\n # do something\n yield 'some more of body'\n\nOnce the request handler runs out of code to run, it closes the connection.\nNow, this is sure to work on standard wsgi servers I tried. I would like to hear if this works on Pylons.\n", "I did not have the chance to try Python threads yet, but you could do something like:\ndef controller_method(self):\n # controller logic here\n html = render('/template.mako')\n # start a thread here\n return html\n\nBy starting the thread after all the logic, but just before returning, you should avoid conflicts between the threads.\nYou might also have a look at RabbitMQ or other message queuing software. You could offload your main web application by sending the jobs in a queue.\n" ]
[ 1, 0 ]
[]
[]
[ "pylons", "python" ]
stackoverflow_0002907966_pylons_python.txt
Q: OpenSSL for HTTPS without a certificate I'm looking to create an application in Django which will allow for each client to point their domain to my server. At this point, I would want their domain to be accessed via https protocol and have a valid SSL connection. With OpenSSL, more specifically M2Crypto, can I do this right out the gate? Or, do I still need to purchase an SSL cert? Also, if the former is true (can do without purchase), does this mean I need to have a Python-based web server listening on 443 or does this all somehow still work with NGINX, et al? Any help is appreciated. A: You will need a certificate, but there are even free SSL certs now that work in most common browsers. For very low volume site you could let M2Crypto handle SSL. However, for any public service you should go with a regular server to handle the SSL. In theory you can serve multiple SSL domains from the same IP address, but this is not supported in older browsers and OSes. See SNI on Wikipedia. A: You will need a SSL cert, and let the web server handle the HTTPS.
OpenSSL for HTTPS without a certificate
I'm looking to create an application in Django which will allow for each client to point their domain to my server. At this point, I would want their domain to be accessed via https protocol and have a valid SSL connection. With OpenSSL, more specifically M2Crypto, can I do this right out the gate? Or, do I still need to purchase an SSL cert? Also, if the former is true (can do without purchase), does this mean I need to have a Python-based web server listening on 443 or does this all somehow still work with NGINX, et al? Any help is appreciated.
[ "You will need a certificate, but there are even free SSL certs now that work in most common browsers.\nFor very low volume site you could let M2Crypto handle SSL. However, for any public service you should go with a regular server to handle the SSL.\nIn theory you can serve multiple SSL domains from the same IP address, but this is not supported in older browsers and OSes. See SNI on Wikipedia.\n", "You will need a SSL cert, and let the web server handle the HTTPS.\n" ]
[ 3, 2 ]
[]
[]
[ "m2crypto", "openssl", "python", "ssl" ]
stackoverflow_0003078487_m2crypto_openssl_python_ssl.txt
Q: WHich framework should i use for building ecommerce site in Python I have chosen Python as a langauge to build my ecommerce webiste. The site will contains 1)Logins 2)registration 3)SHop Cart 4)Payment gateway 5)Admin can edit some content pages I have started learning basic python. But i want to build website and i have to start with one framework the web users can vary fromm 100's to 1000's SO which Framework will be best . I have to use some Machine learning tools using python on some webistes. Will Django be enough for me A: I bet you already reviewed your choices: http://wiki.python.org/moin/WebFrameworks If you understand the value proposition of using SQLAlchemy (as compared to being forced to do "ActiveRecord" style database (non)abstraction) stick with those platforms that offer native support for SQLAlchemy. Mastering it = half of your business logic becomes portable to any Python platform or database type. If you want to "slap something together" go with Django. If you know you will stay the course until you are done, take a strong look at Pylons and stick with it if you can stomach the extra effort. It will give you more freedom than Django, at a cost of more coding. Take special note of web2py and go for it if the special benefits it provides (see their video presentation) are worth the limitations. Twisted will look technically interesting to you, but go for it only if you are a masochist. Either way. Good luck. On a related note, there is a movement out there to separate "shopping cart + check out" from the page-serving framework. One good example is http://www.ecwid.com/ It provides javascript that you put in your regular site. That javascript pull the entire shopping cart system into customer's browser directly from ecwid.com. However, all of that is presented on top of your site's actual "shop" page. I work in payment processing industry (not in the ecwid.com) and messing around with your own payment pages and security is a pain. Might as well outsource the payment glue to a processor and concentrate on presentation, merchandise, customer service. A: Check out Satchmo for building e-commerce sites in Django. If your needs aren't that complex I'd give Shopify a look. A: framework choice won't limit you. You can use any framework and still do all those things.
WHich framework should i use for building ecommerce site in Python
I have chosen Python as a langauge to build my ecommerce webiste. The site will contains 1)Logins 2)registration 3)SHop Cart 4)Payment gateway 5)Admin can edit some content pages I have started learning basic python. But i want to build website and i have to start with one framework the web users can vary fromm 100's to 1000's SO which Framework will be best . I have to use some Machine learning tools using python on some webistes. Will Django be enough for me
[ "I bet you already reviewed your choices:\nhttp://wiki.python.org/moin/WebFrameworks\nIf you understand the value proposition of using SQLAlchemy (as compared to being forced to do \"ActiveRecord\" style database (non)abstraction) stick with those platforms that offer native support for SQLAlchemy. Mastering it = half of your business logic becomes portable to any Python platform or database type.\nIf you want to \"slap something together\" go with Django.\nIf you know you will stay the course until you are done, take a strong look at Pylons and stick with it if you can stomach the extra effort. It will give you more freedom than Django, at a cost of more coding. \nTake special note of web2py and go for it if the special benefits it provides (see their video presentation) are worth the limitations.\nTwisted will look technically interesting to you, but go for it only if you are a masochist.\nEither way. Good luck.\nOn a related note, there is a movement out there to separate \"shopping cart + check out\" from the page-serving framework. One good example is http://www.ecwid.com/ It provides javascript that you put in your regular site. That javascript pull the entire shopping cart system into customer's browser directly from ecwid.com. However, all of that is presented on top of your site's actual \"shop\" page. I work in payment processing industry (not in the ecwid.com) and messing around with your own payment pages and security is a pain. Might as well outsource the payment glue to a processor and concentrate on presentation, merchandise, customer service.\n", "Check out Satchmo for building e-commerce sites in Django. \nIf your needs aren't that complex I'd give Shopify a look.\n", "framework choice won't limit you. You can use any framework and still do all those things.\n" ]
[ 7, 4, 0 ]
[]
[]
[ "frameworks", "python" ]
stackoverflow_0003089554_frameworks_python.txt
Q: problem with inheritance in python in school we got this class file: class Konto: def __init__(self, nummer): self.__nr = nummer self.__stand = 0 self.__minimum = -1000.0 def getStand(self): return self.__stand def getNr(self): return self.__nr def einzahlen(self, betrag): self.__stand = self.__stand + betrag def auszahlen(self, betrag): if self.__stand - betrag >= self.__minimum: self.__stand = self.__stand - betrag else: print("Auszahlung nicht möglich!") class Sparkonto(Konto): def __init__(self, nummer): Konto.__init__(self, nummer) self.__zinssatz = None self.__minimum = 0 self.__maxAuszahlung = 2000.0 def setZinssatz(self, zinssatz): self.__zinssatz = zinssatz def getZinssatz(self): return self.__zinssatz def auszahlen(self, betrag): if betrag <= self.__maxAuszahlung: Konto.auszahlen(self, betrag) else: print("Auszahlung nicht möglich!") def zinsenGutschreiben(self): zinsen = self.__stand * (self.__zinssatz / 100) self.einzahlen(zinsen) When I run this test programm: #Test from sparkonto import * s = Sparkonto(1) s.einzahlen(1000) print(s.getStand()) s.setZinssatz(4) print(s.getZinssatz()) s.zinsenGutschreiben() print(s.getStand()) s.auszahlen(2500) print(s.getStand()) I get this error 1000 4 Traceback (most recent call last): File "/home/malte/home/py3/sparkonto/test.py", line 8, in <module> s.zinsenGutschreiben() File "/home/malte/home/py3/sparkonto/sparkonto.py", line 44, in zinsenGutschreiben AttributeError: 'Sparkonto' object has no attribute '_Sparkonto__einzahlen' >>> We do not know what we are doing wrong. Any guess? A: Daniel was halfway there, you do need to change self.__einzahlen -> self.einzaheln, as he said. Also, self.__stand belongs to the parent class. With the double underscore in the name, it gets mangled used anywhere else. But you don't need to use self.__stand directly. Konto gives you getStand(). Try something like this: def zinsenGutschreiben(self): zinsen = self.getStand() * (self.__zinssatz / 100) self.einzahlen(zinsen) A: self.__einzahlen(zinsen) -> self.einzahlen(zinsen) A: Double leading underscores invoke name mangling, using the current class's name. Use a single leading underscore instead.
problem with inheritance in python
in school we got this class file: class Konto: def __init__(self, nummer): self.__nr = nummer self.__stand = 0 self.__minimum = -1000.0 def getStand(self): return self.__stand def getNr(self): return self.__nr def einzahlen(self, betrag): self.__stand = self.__stand + betrag def auszahlen(self, betrag): if self.__stand - betrag >= self.__minimum: self.__stand = self.__stand - betrag else: print("Auszahlung nicht möglich!") class Sparkonto(Konto): def __init__(self, nummer): Konto.__init__(self, nummer) self.__zinssatz = None self.__minimum = 0 self.__maxAuszahlung = 2000.0 def setZinssatz(self, zinssatz): self.__zinssatz = zinssatz def getZinssatz(self): return self.__zinssatz def auszahlen(self, betrag): if betrag <= self.__maxAuszahlung: Konto.auszahlen(self, betrag) else: print("Auszahlung nicht möglich!") def zinsenGutschreiben(self): zinsen = self.__stand * (self.__zinssatz / 100) self.einzahlen(zinsen) When I run this test programm: #Test from sparkonto import * s = Sparkonto(1) s.einzahlen(1000) print(s.getStand()) s.setZinssatz(4) print(s.getZinssatz()) s.zinsenGutschreiben() print(s.getStand()) s.auszahlen(2500) print(s.getStand()) I get this error 1000 4 Traceback (most recent call last): File "/home/malte/home/py3/sparkonto/test.py", line 8, in <module> s.zinsenGutschreiben() File "/home/malte/home/py3/sparkonto/sparkonto.py", line 44, in zinsenGutschreiben AttributeError: 'Sparkonto' object has no attribute '_Sparkonto__einzahlen' >>> We do not know what we are doing wrong. Any guess?
[ "Daniel was halfway there, you do need to change self.__einzahlen -> self.einzaheln, as he said.\nAlso, self.__stand belongs to the parent class. With the double underscore in the name, it gets mangled used anywhere else. But you don't need to use self.__stand directly. Konto gives you getStand().\nTry something like this:\ndef zinsenGutschreiben(self):\n zinsen = self.getStand() * (self.__zinssatz / 100)\n self.einzahlen(zinsen)\n\n", "self.__einzahlen(zinsen) -> self.einzahlen(zinsen)\n", "Double leading underscores invoke name mangling, using the current class's name. Use a single leading underscore instead.\n" ]
[ 2, 1, 1 ]
[]
[]
[ "inheritance", "python" ]
stackoverflow_0003090683_inheritance_python.txt
Q: How to improve the performance? I had prepared a project on making a software application. It is complete and working fine except that the speed of execution is very slow.. I have taken several chunks of code and optimized it.. I tried psyco.. ie I installed psyco and added two lines on the top of my code import psyco psyco.full() Don't know whether this is the way using psyco.. if this is wrong. Please tell me how to use psyco.. because I added this and found no improvement.. I have tried profiling and I know the code lines taking time but these can't be further optimized and are unavoidable line of code.. I also thought of option of rewriting the code in 'c' using some python package.. but I always had a very bad experience in using additional package of python which are not part of basic python.. I am using python 2.6 and windows vista.. please kindly tell methods method for increasing the speed of execution of the whole code significantly.. at least 5x times.. please.. I haven't written my code in method, there few method in between thou.. there is no main.. Yes as few suggested my is an IO bound problem.. as I need to call the code some 500 times and this involves opening and closing of files of at least 2 per call.. And here when opening a .pm file, it has two columns and I need the first columns only, so I am copying the entire first columns into the list and passing it to a function to get its row number and then opening other file to get the elements of that row number into a list... This is the task I wanted... I guess loading the elements of first columns into the list is time consuming any idea to rectify this.. How can I improve the performance for IO bound bottlenecks Looking for help desperately A: You could get a lot better performance if you could switch to binary file formats. Most of your code is doing parsing and string manipulation. You're doing a lot of converting strings to floats, which is slower than you think. A: You are unlikely to see a 5x performance difference by just tweaking the code around. First you should look at improving your algorithm - are you using the best datastructures for the job? Perhaps using a dict or a set in the right place can speed your code up a alot. Writing a C module is not all that hard, and is another option if you can find no way to improve the Python code. Usually you would expect more than a 5x speed up by using C code. Maybe your problem is IO bound. Then you need to look at ways to improve the performance of the IO If you want more help here, you'll probably have to show some code or at least describe what your program does. UPDATE: Looks like you are opening and closing lots of files which tends to be painfully slow on windows. A: psyco can be used as simple as import and call psyco.full(). so you are right about your psyco usage. If you are trying to build a python module using C/C++, have a look at boost::python You should really post your code for further analysis. A: To optimize your code for speed you simply have to profile it and see where the problem is. Guessing does not help. But once you know where, the most bang for your buck usually come from those in descending order: improving algorithm, using more appropriate data structures, removing resource bottlenecks (io,memory,cpu), reducing memory allocation, reducing context switching (processes and subroutines). A: Here's one opportunity for optimization: you're calling get_list twice, with very similar arguments: join_cost_index_end[index] = get_list(file, float(abs1), fout) join_cost_index_strt[index] = get_list(file, float(abs2), fout) That means that most of the work in get_list is being done twice for no good reason. Rewrite it so that get_list is being called once, and have it return both index_end and index_strt at the same time. A: why bot just try using cython? You should get much better performance without changing any of the code. With a little bit of modification this should help even more.
How to improve the performance?
I had prepared a project on making a software application. It is complete and working fine except that the speed of execution is very slow.. I have taken several chunks of code and optimized it.. I tried psyco.. ie I installed psyco and added two lines on the top of my code import psyco psyco.full() Don't know whether this is the way using psyco.. if this is wrong. Please tell me how to use psyco.. because I added this and found no improvement.. I have tried profiling and I know the code lines taking time but these can't be further optimized and are unavoidable line of code.. I also thought of option of rewriting the code in 'c' using some python package.. but I always had a very bad experience in using additional package of python which are not part of basic python.. I am using python 2.6 and windows vista.. please kindly tell methods method for increasing the speed of execution of the whole code significantly.. at least 5x times.. please.. I haven't written my code in method, there few method in between thou.. there is no main.. Yes as few suggested my is an IO bound problem.. as I need to call the code some 500 times and this involves opening and closing of files of at least 2 per call.. And here when opening a .pm file, it has two columns and I need the first columns only, so I am copying the entire first columns into the list and passing it to a function to get its row number and then opening other file to get the elements of that row number into a list... This is the task I wanted... I guess loading the elements of first columns into the list is time consuming any idea to rectify this.. How can I improve the performance for IO bound bottlenecks Looking for help desperately
[ "You could get a lot better performance if you could switch to binary file formats. Most of your code is doing parsing and string manipulation. You're doing a lot of converting strings to floats, which is slower than you think.\n", "You are unlikely to see a 5x performance difference by just tweaking the code around.\nFirst you should look at improving your algorithm - are you using the best datastructures for the job? Perhaps using a dict or a set in the right place can speed your code up a alot.\nWriting a C module is not all that hard, and is another option if you can find no way to improve the Python code. Usually you would expect more than a 5x speed up by using C code.\nMaybe your problem is IO bound. Then you need to look at ways to improve the performance of the IO\nIf you want more help here, you'll probably have to show some code or at least describe what your program does. \nUPDATE:\nLooks like you are opening and closing lots of files which tends to be painfully slow on windows.\n", "psyco can be used as simple as import and call psyco.full(). so you are right about your psyco usage. \nIf you are trying to build a python module using C/C++, have a look at boost::python\nYou should really post your code for further analysis.\n", "To optimize your code for speed you simply have to profile it and see where the problem is. Guessing does not help. But once you know where, the most bang for your buck usually come from those in descending order: improving algorithm, using more appropriate data structures, removing resource bottlenecks (io,memory,cpu), reducing memory allocation, reducing context switching (processes and subroutines). \n", "Here's one opportunity for optimization: you're calling get_list twice, with very similar arguments:\njoin_cost_index_end[index] = get_list(file, float(abs1), fout)\njoin_cost_index_strt[index] = get_list(file, float(abs2), fout)\n\nThat means that most of the work in get_list is being done twice for no good reason. Rewrite it so that get_list is being called once, and have it return both index_end and index_strt at the same time.\n", "why bot just try using cython? You should get much better performance without changing any of the code. With a little bit of modification this should help even more.\n" ]
[ 3, 1, 0, 0, 0, 0 ]
[]
[]
[ "optimization", "psyco", "python" ]
stackoverflow_0003090397_optimization_psyco_python.txt
Q: What is the lightest way of doing this task? I have a file whose contents are of the form: .2323 1 .2327 1 .3432 1 .4543 1 and so on some 10,000 lines in each file. I have a variable whose value is say a=.3344 From the file I want to get the row number of the row whose first column is closest to this variable...for example it should give row_num='3' as .3432 is closest to it. I have tried in a method of loading the first columns element in a list and then comparing the variable to each element and getting the index number If I do in this method it is very much time consuming and slow my model...I want a very quick method as this need to to called some 1000 times minimum... I want a method with least overhead and very quick can anyone please tell me how can it be done very fast. As the file size is maximum of 100kb can this be done directly without loading into any list of anything...if yes how can it be done. Any method quicker than the method mentioned above are welcome but I am desperate to improve the speed -- please help. def get_list(file, cmp, fout): ind, _ = min(enumerate(file), key=lambda x: abs(x[1] - cmp)) return fout[ind].rstrip('\n').split(' ') #root = r'c:\begpython\wavnk' header = 6 for lst in lists: save = database_index[lst] #print save index, base,abs2, _ , abs1 = save using_data[index] = save base = 'C:/begpython/wavnk/'+ base.replace('phone', 'text') fin, fout = base + '.pm', base + '.mcep' file = open(fin) fout = open(fout).readlines() [next(file) for _ in range(header)] file = [float(line.partition(' ')[0]) for line in file] join_cost_index_end[index] = get_list(file, float(abs1), fout) join_cost_index_strt[index] = get_list(file, float(abs2), fout) this is the code i was using..copying file into a list.and all please give better alternarives to this A: Is the data in the file sorted in numerical order? Are all the lines of the same length? If not, the simplest approach is best. Namely, reading through the file line by line. There's no need to store more than one line in memory at a time. Code: def closest(num): closest_row = None closest_value = None for row_num, row in enumerate(file('numbers.txt')): value = float(row.split()[0]) if closest_value is None or abs(value - num) < abs(closest_value - num): closest_row = row closest_row_num = row_num closest_value = value return (closest_row_num, closest_row) print closest(.3344) Output for sample data: (2, '.3432 1\n') If the lines are all the same length and the data is sorted then there are some optimizations that will make this a very fast process. All the lines being the same length would let you seek directly to particular lines (you can't do this in a normal text file with lines of different length). Which would then enable you to do a binary search. A binary search would be massively faster than a linear search. A linear search will on average have to read 5,000 lines of a 10,000 line file each time, whereas a binary search would on average only read log2 10,000 ≈ 13 lines. A: Building on John Kugelman's answer, here's a way you might be able to do a binary search on a file with fixed-length lines: class SubscriptableFile(object): def __init__(self, file): self._file = file file.seek(0,0) self._line_length = len(file.readline()) file.seek(0,2) self._len = file.tell() / self._line_length def __len__(self): return self._len def __getitem__(self, key): self._file.seek(key * self._line_length) s = self._file.readline() if s: return float(s.split()[0]) else: raise KeyError('Line number too large') This class wraps a file in a list-like structure, so that now you can use the functions of the bisect module on it: def find_row(file, target): fw = SubscriptableFile(file) i = bisect.bisect_left(fw, target) if fw[i + 1] - target < target - fw[i]: return i + 1 else: return i Here file is an open file object and target is the number you want to find. The function returns the number of the line with the closest value. I will note, however, that the bisect module will try to use a C implementation of its binary search when it is available, and I'm not sure if the C implementation supports this kind of behavior. It might require a true list, rather than a "fake list" (like my SubscriptableFile). A: Load it into a list then use bisect.
What is the lightest way of doing this task?
I have a file whose contents are of the form: .2323 1 .2327 1 .3432 1 .4543 1 and so on some 10,000 lines in each file. I have a variable whose value is say a=.3344 From the file I want to get the row number of the row whose first column is closest to this variable...for example it should give row_num='3' as .3432 is closest to it. I have tried in a method of loading the first columns element in a list and then comparing the variable to each element and getting the index number If I do in this method it is very much time consuming and slow my model...I want a very quick method as this need to to called some 1000 times minimum... I want a method with least overhead and very quick can anyone please tell me how can it be done very fast. As the file size is maximum of 100kb can this be done directly without loading into any list of anything...if yes how can it be done. Any method quicker than the method mentioned above are welcome but I am desperate to improve the speed -- please help. def get_list(file, cmp, fout): ind, _ = min(enumerate(file), key=lambda x: abs(x[1] - cmp)) return fout[ind].rstrip('\n').split(' ') #root = r'c:\begpython\wavnk' header = 6 for lst in lists: save = database_index[lst] #print save index, base,abs2, _ , abs1 = save using_data[index] = save base = 'C:/begpython/wavnk/'+ base.replace('phone', 'text') fin, fout = base + '.pm', base + '.mcep' file = open(fin) fout = open(fout).readlines() [next(file) for _ in range(header)] file = [float(line.partition(' ')[0]) for line in file] join_cost_index_end[index] = get_list(file, float(abs1), fout) join_cost_index_strt[index] = get_list(file, float(abs2), fout) this is the code i was using..copying file into a list.and all please give better alternarives to this
[ "Is the data in the file sorted in numerical order? Are all the lines of the same length? If not, the simplest approach is best. Namely, reading through the file line by line. There's no need to store more than one line in memory at a time.\nCode:\ndef closest(num):\n closest_row = None\n closest_value = None\n\n for row_num, row in enumerate(file('numbers.txt')):\n value = float(row.split()[0])\n\n if closest_value is None or abs(value - num) < abs(closest_value - num):\n closest_row = row\n closest_row_num = row_num\n closest_value = value\n\n return (closest_row_num, closest_row)\n\nprint closest(.3344)\n\nOutput for sample data:\n(2, '.3432 1\\n')\n\nIf the lines are all the same length and the data is sorted then there are some optimizations that will make this a very fast process. All the lines being the same length would let you seek directly to particular lines (you can't do this in a normal text file with lines of different length). Which would then enable you to do a binary search.\nA binary search would be massively faster than a linear search. A linear search will on average have to read 5,000 lines of a 10,000 line file each time, whereas a binary search would on average only read log2 10,000 ≈ 13 lines.\n", "Building on John Kugelman's answer, here's a way you might be able to do a binary search on a file with fixed-length lines:\nclass SubscriptableFile(object):\n def __init__(self, file):\n self._file = file\n file.seek(0,0)\n self._line_length = len(file.readline())\n file.seek(0,2)\n self._len = file.tell() / self._line_length\n def __len__(self):\n return self._len\n def __getitem__(self, key):\n self._file.seek(key * self._line_length)\n s = self._file.readline()\n if s:\n return float(s.split()[0])\n else:\n raise KeyError('Line number too large')\n\nThis class wraps a file in a list-like structure, so that now you can use the functions of the bisect module on it:\ndef find_row(file, target):\n fw = SubscriptableFile(file)\n i = bisect.bisect_left(fw, target)\n if fw[i + 1] - target < target - fw[i]:\n return i + 1\n else:\n return i\n\nHere file is an open file object and target is the number you want to find. The function returns the number of the line with the closest value.\nI will note, however, that the bisect module will try to use a C implementation of its binary search when it is available, and I'm not sure if the C implementation supports this kind of behavior. It might require a true list, rather than a \"fake list\" (like my SubscriptableFile).\n", "Load it into a list then use bisect.\n" ]
[ 3, 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003090746_python.txt
Q: +\ operator in Python What does the +\ operator do in Python? I came across this piece of code - rows=urllib2.urlopen('http://ichart.finance.yahoo.com/table.csv?'+\ 's=%s&d=11&e=26&f=2006&g=d&a=3&b=12&c=1996'%t +\ '&ignore=.csv').readlines( ) and can't find any references that explain it. A: The + is addition. The \ at the end of the line continues the current statement or expression on the next line. A: N.B. The \ continuation is unnecessary in this case since the expression is inside parentheses. Python is smart enough to know that a line continues until all brackets, braces and parentheses are balanced. Unnecessary continuation characters are a minor bugbear of mine, and I delete them at every opportunity. They clutter the code, confuse newbies who think they are some kind of operator and can be invisibly broken by accidentally putting a space after them. Also the first + character is unnecessary - Python will concatenate string literals automatically. I would also move the % operator to the end of the expression and eliminate the second +, so the line could be rewritten as: rows=urllib2.urlopen('http://ichart.finance.yahoo.com/table.csv?' 's=%s&d=11&e=26&f=2006&g=d&a=3&b=12&c=1996' '&ignore=.csv' % t).readlines( ) A: It's not an operator, it's just the + operator followed by the line continuation \ A: You can rewrite your code like so rows=urllib2.urlopen('http://ichart.finance.yahoo.com/table.csv?' 's=%s&d=11&e=26&f=2006&g=d&a=3&b=12&c=1996' '&ignore=.csv'%t).readlines() The parser joins the lines together into one, so you are not wasting time by uselessly adding strings together at runtime
+\ operator in Python
What does the +\ operator do in Python? I came across this piece of code - rows=urllib2.urlopen('http://ichart.finance.yahoo.com/table.csv?'+\ 's=%s&d=11&e=26&f=2006&g=d&a=3&b=12&c=1996'%t +\ '&ignore=.csv').readlines( ) and can't find any references that explain it.
[ "The + is addition. The \\ at the end of the line continues the current statement or expression on the next line.\n", "N.B. The \\ continuation is unnecessary in this case since the expression is inside parentheses. Python is smart enough to know that a line continues until all brackets, braces and parentheses are balanced. \nUnnecessary continuation characters are a minor bugbear of mine, and I delete them at every opportunity. They clutter the code, confuse newbies who think they are some kind of operator and can be invisibly broken by accidentally putting a space after them.\nAlso the first + character is unnecessary - Python will concatenate string literals automatically.\nI would also move the % operator to the end of the expression and eliminate the second +, so the line could be rewritten as:\nrows=urllib2.urlopen('http://ichart.finance.yahoo.com/table.csv?'\n 's=%s&d=11&e=26&f=2006&g=d&a=3&b=12&c=1996' \n '&ignore=.csv' % t).readlines( )\n\n", "It's not an operator, it's just the + operator followed by the line continuation \\\n", "You can rewrite your code like so\nrows=urllib2.urlopen('http://ichart.finance.yahoo.com/table.csv?'\n 's=%s&d=11&e=26&f=2006&g=d&a=3&b=12&c=1996'\n '&ignore=.csv'%t).readlines()\n\nThe parser joins the lines together into one, so you are not wasting time by uselessly adding strings together at runtime\n" ]
[ 18, 11, 7, 1 ]
[]
[]
[ "operators", "python", "string" ]
stackoverflow_0003090780_operators_python_string.txt
Q: Disable (mako) template caching in Pylons 1.0 I recently jumped on a project using Pylons. I'm not familiar with either Python or Pylons, but I haven't had very much trouble getting the hang of things. Pylon projects seem to cache templates indefinitely by default and I can't figure out a way to clear the cached templates (stored by default in /data/templates) except by manually deleting them and restarting the server. Better yet, can template caching be disabled? The page, http://wiki.pylonshq.com/display/pylonsdocs/Caching+in+Templates+and+Controllers, on template caching doesn't seem helpful and there's a brief mention of disabling cache globally by setting in the .ini file: cache_enabled = false But it doesn't seem to work. This should be relatively straight-forward, shouldn't it? A: The problem was entirely something else.. Pylons always caches templates, but updates its template cache automatically by comparing the last-modified timestamp of the template and its cached version. The problem had to do with synchronizing the server's clock with real time. It was a couple minutes ahead and uploads from my computer (with a synchronized clock) would pull the template's timestamp back a couple of minutes; Pylons would interpret that as the template being older than the cached version and not update the cache. A: false should be uppercased to False -- and if it still doesn't work when you do that, adding a comment to that page (pointing out the doc error, or bug as the case may be) is appropriate (it may simply be that mako's template caching is not using beaker, in which case it's just a lack of clarity in the docs). Per Mako's docs, you should also be able to invalidate it with the invalidate method of the cache objects, and/or disable it for a template with <%page cached=False%>.
Disable (mako) template caching in Pylons 1.0
I recently jumped on a project using Pylons. I'm not familiar with either Python or Pylons, but I haven't had very much trouble getting the hang of things. Pylon projects seem to cache templates indefinitely by default and I can't figure out a way to clear the cached templates (stored by default in /data/templates) except by manually deleting them and restarting the server. Better yet, can template caching be disabled? The page, http://wiki.pylonshq.com/display/pylonsdocs/Caching+in+Templates+and+Controllers, on template caching doesn't seem helpful and there's a brief mention of disabling cache globally by setting in the .ini file: cache_enabled = false But it doesn't seem to work. This should be relatively straight-forward, shouldn't it?
[ "The problem was entirely something else..\nPylons always caches templates, but updates its template cache automatically by comparing the last-modified timestamp of the template and its cached version. The problem had to do with synchronizing the server's clock with real time.\nIt was a couple minutes ahead and uploads from my computer (with a synchronized clock) would pull the template's timestamp back a couple of minutes; Pylons would interpret that as the template being older than the cached version and not update the cache.\n", "false should be uppercased to False -- and if it still doesn't work when you do that, adding a comment to that page (pointing out the doc error, or bug as the case may be) is appropriate (it may simply be that mako's template caching is not using beaker, in which case it's just a lack of clarity in the docs).\nPer Mako's docs, you should also be able to invalidate it with the invalidate method of the cache objects, and/or disable it for a template with <%page cached=False%>.\n" ]
[ 2, 1 ]
[]
[]
[ "caching", "mako", "pylons", "python" ]
stackoverflow_0003089114_caching_mako_pylons_python.txt
Q: Python ? (conditional/ternary) operator for assignments C and many other languages have a conditional (AKA ternary) operator. This allows you to make very terse choices between two values based on the truth of a condition, which makes expressions, including assignments, very concise. I miss this because I find that my code has lots of conditional assignments that take four lines in Python: if condition: var = something else: var = something_else Whereas in C it'd be: var = condition ? something : something_else; Once or twice in a file is fine, but if you have lots of conditional assignments, the number of lines explode, and worst of all the eye is drawn to them. I like the terseness of the conditional operator, because it keeps things I deem un-strategic from distracting me when skimming the code. So, in Python, is there a trick you can use to get the assignment onto a single line to approximate the advantages of the conditional operator as I outlined them? A: Python has such an operator: variable = something if condition else something_else Alternatively, although not recommended (see karadoc's comment): variable = (condition and something) or something_else A: In older Python code, you may see the trick: condition and something or something_else However, this has been superseded by the vastly superior ... if ... else ... construct: something if condition else something_else
Python ? (conditional/ternary) operator for assignments
C and many other languages have a conditional (AKA ternary) operator. This allows you to make very terse choices between two values based on the truth of a condition, which makes expressions, including assignments, very concise. I miss this because I find that my code has lots of conditional assignments that take four lines in Python: if condition: var = something else: var = something_else Whereas in C it'd be: var = condition ? something : something_else; Once or twice in a file is fine, but if you have lots of conditional assignments, the number of lines explode, and worst of all the eye is drawn to them. I like the terseness of the conditional operator, because it keeps things I deem un-strategic from distracting me when skimming the code. So, in Python, is there a trick you can use to get the assignment onto a single line to approximate the advantages of the conditional operator as I outlined them?
[ "Python has such an operator:\nvariable = something if condition else something_else\n\nAlternatively, although not recommended (see karadoc's comment):\nvariable = (condition and something) or something_else\n\n", "In older Python code, you may see the trick:\ncondition and something or something_else\n\nHowever, this has been superseded by the vastly superior ... if ... else ... construct:\nsomething if condition else something_else\n\n" ]
[ 235, 21 ]
[]
[]
[ "c", "language_features", "python" ]
stackoverflow_0003091316_c_language_features_python.txt
Q: In Amazon EC2, how do I make it run a python script when I "clone" that instance? Suppose I have a script in /home/myuser/go.py How do I run that script, when a new instance is booted? (I'm used to using the point-and-click control panel Amazon has...) A: I'm gonna try my nonexistent Linux skills here - create a shell script that runs your go.py and add a symlink to the shell script in /etc/init.d/ /home/myser/go.sh #!/bin/bash python /home/myuser/go.py symlink ln -s /etc/init.d/go.sh /home/myuser/go.sh After reading up a bit myself, /etc/rc.local is probably a better place for this. Just edit it and add /home/myuser/go.sh there (again, make sure your go.sh is executable).
In Amazon EC2, how do I make it run a python script when I "clone" that instance?
Suppose I have a script in /home/myuser/go.py How do I run that script, when a new instance is booted? (I'm used to using the point-and-click control panel Amazon has...)
[ "I'm gonna try my nonexistent Linux skills here - create a shell script that runs your go.py and add a symlink to the shell script in /etc/init.d/\n/home/myser/go.sh\n#!/bin/bash\npython /home/myuser/go.py\n\nsymlink\nln -s /etc/init.d/go.sh /home/myuser/go.sh\n\n\nAfter reading up a bit myself, /etc/rc.local is probably a better place for this. Just edit it and add /home/myuser/go.sh there (again, make sure your go.sh is executable).\n" ]
[ 2 ]
[]
[]
[ "amazon_ec2", "amazon_web_services", "linux", "python", "unix" ]
stackoverflow_0003091454_amazon_ec2_amazon_web_services_linux_python_unix.txt
Q: Where to trigger ast modifications in Python? I'm doing some AST modifications in Python. This may be done for optimization purpose or other. Where is the right place to put it, so when you do something like: python myfile.py or python runserver.py myapp the modifications took place for every .py executed file? A: Put your modifications in a site.py or sitecustomize.py (Python < 2.6) file (in the lib/site-packages directory ; Python will try to import and run it @ interpreter startup).
Where to trigger ast modifications in Python?
I'm doing some AST modifications in Python. This may be done for optimization purpose or other. Where is the right place to put it, so when you do something like: python myfile.py or python runserver.py myapp the modifications took place for every .py executed file?
[ "Put your modifications in a site.py or sitecustomize.py (Python < 2.6) file (in the lib/site-packages directory ; Python will try to import and run it @ interpreter startup).\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0003091544_python.txt
Q: MacOS X Error when installing python MySQLdb I am trying to install python mysqldb in my mac but I got the following errors. For mysql I am using the one that is bundled with MAMP. Thanks! here is the error message: running build running build_py copying MySQLdb/release.py -> build/lib.darwin-8.11.1-i386-2.3/MySQLdb running build_ext building '_mysql' extension gcc -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused-madd -fno-common -dynamic -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -Dversion_info=(1,2,3,'final',0) -D__version__=1.2.3 -I/Applications/MAMP/Library/include/mysql -I/System/Library/Frameworks/Python.framework/Versions/2.3/include/python2.3 -c _mysql.c -o build/temp.darwin-8.11.1-i386-2.3/_mysql.o _mysql.c:36:23: error: my_config.h: No such file or directory _mysql.c:38:19: error: mysql.h: No such file or directory _mysql.c:39:26: error: mysqld_error.h: No such file or directory _mysql.c:40:20: error: errmsg.h: No such file or directory _mysql.c:76: error: parse error before 'MYSQL' _mysql.c:76: warning: no semicolon at end of struct or union _mysql.c:79: error: parse error before '}' token _mysql.c:79: warning: type defaults to 'int' in declaration of '_mysql_ConnectionObject' _mysql.c:79: warning: data definition has no type or storage class .... A: I guess it's not enough to use the MySQL that's bundled with MAMP, as it does not contain the C development tools for MySQL (i.e. the header files such as mysql.h). Here is a step-by-step tutorial on compiling the MySQL extension for Python on Mac OS X, but it looks like you will need the "official" MySQL distribution for that.
MacOS X Error when installing python MySQLdb
I am trying to install python mysqldb in my mac but I got the following errors. For mysql I am using the one that is bundled with MAMP. Thanks! here is the error message: running build running build_py copying MySQLdb/release.py -> build/lib.darwin-8.11.1-i386-2.3/MySQLdb running build_ext building '_mysql' extension gcc -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused-madd -fno-common -dynamic -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -Dversion_info=(1,2,3,'final',0) -D__version__=1.2.3 -I/Applications/MAMP/Library/include/mysql -I/System/Library/Frameworks/Python.framework/Versions/2.3/include/python2.3 -c _mysql.c -o build/temp.darwin-8.11.1-i386-2.3/_mysql.o _mysql.c:36:23: error: my_config.h: No such file or directory _mysql.c:38:19: error: mysql.h: No such file or directory _mysql.c:39:26: error: mysqld_error.h: No such file or directory _mysql.c:40:20: error: errmsg.h: No such file or directory _mysql.c:76: error: parse error before 'MYSQL' _mysql.c:76: warning: no semicolon at end of struct or union _mysql.c:79: error: parse error before '}' token _mysql.c:79: warning: type defaults to 'int' in declaration of '_mysql_ConnectionObject' _mysql.c:79: warning: data definition has no type or storage class ....
[ "I guess it's not enough to use the MySQL that's bundled with MAMP, as it does not contain the C development tools for MySQL (i.e. the header files such as mysql.h). Here is a step-by-step tutorial on compiling the MySQL extension for Python on Mac OS X, but it looks like you will need the \"official\" MySQL distribution for that.\n" ]
[ 3 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0003090709_mysql_python.txt
Q: Copy files to network path or drive using python on OSX I have a similar question like the one asked here but I need it to work on OSX. How to copy files to network path or drive using Python So i want to save a file on a SMB network share. Can this be done? Thanks! A: Yes, it can be done. First, mount your SMB network share to the local filesystem by calling a command like this from Python: mount -t smbfs //user@server/sharename share (You can do it using the subprocess module). share is the name of the directory where the SMB network share will be mounted to, and I guess it has to be writable by the user. After that, you can copy the file using shutil.copyfile. Finally, you have to un-mount the SMB network share: umount share Probably it's the best to create a context manager in Python that takes care of mounting and unmounting: from contextlib import contextmanager import os import shutil import subprocess @contextmanager def mounted(remote_dir, local_dir): local_dir = os.path.abspath(local_dir) retcode = subprocess.call(["/sbin/mount", "-t", "smbfs", remote_dir, local_dir]) if retcode != 0: raise OSError("mount operation failed") try: yield finally: retcode = subprocess.call(["/sbin/umount", local_dir]) if retcode != 0: raise OSError("umount operation failed") with mounted(remote_dir, local_dir): shutil.copy(file_to_be_copied, local_dir) The above code snippet is not tested, but it should work in general (apart from syntax errors that I did not notice). Also note that mounted is very similar to the network_share_auth context manager I posted in my other answer, so you might as well combine the two by checking what platform you are on using the platform module and then calling the appropriate commands.
Copy files to network path or drive using python on OSX
I have a similar question like the one asked here but I need it to work on OSX. How to copy files to network path or drive using Python So i want to save a file on a SMB network share. Can this be done? Thanks!
[ "Yes, it can be done. First, mount your SMB network share to the local filesystem by calling a command like this from Python:\nmount -t smbfs //user@server/sharename share\n\n(You can do it using the subprocess module). share is the name of the directory where the SMB network share will be mounted to, and I guess it has to be writable by the user. After that, you can copy the file using shutil.copyfile. Finally, you have to un-mount the SMB network share:\numount share\n\nProbably it's the best to create a context manager in Python that takes care of mounting and unmounting:\nfrom contextlib import contextmanager\nimport os\nimport shutil\nimport subprocess\n\n@contextmanager\ndef mounted(remote_dir, local_dir):\n local_dir = os.path.abspath(local_dir)\n retcode = subprocess.call([\"/sbin/mount\", \"-t\", \"smbfs\", remote_dir, local_dir])\n if retcode != 0:\n raise OSError(\"mount operation failed\")\n try:\n yield\n finally:\n retcode = subprocess.call([\"/sbin/umount\", local_dir])\n if retcode != 0:\n raise OSError(\"umount operation failed\")\n\nwith mounted(remote_dir, local_dir):\n shutil.copy(file_to_be_copied, local_dir)\n\nThe above code snippet is not tested, but it should work in general (apart from syntax errors that I did not notice). Also note that mounted is very similar to the network_share_auth context manager I posted in my other answer, so you might as well combine the two by checking what platform you are on using the platform module and then calling the appropriate commands.\n" ]
[ 19 ]
[]
[]
[ "macos", "network_programming", "python", "smb" ]
stackoverflow_0003090724_macos_network_programming_python_smb.txt
Q: Django: Call self function inside a Django model I want to call for a self function of a model class as such in upload_to: class Foo(models.Model): filestack = models.FileField(upload_to=self. gen_save_path) def gen_save_path(self): """ gen_save_path: void -> String Generates the path as a string for fileStack field. """ return "some generated string" However I am getting NameError: name 'self' is not defined error A: filestack is a class attribute and while declaring it you can not use self as there is no object of class (self) yet created, anyway according to django docs upload_to takes two arguments, instance (An instance of the model where the FileField is defined) and filename (The filename that was originally given to the file), so you can set upload_to to such function def gen_save_path(instance, filename): """ gen_save_path: void -> String Generates the path as a string for fileStack field. """ return "some generated string" class Foo(models.Model): filestack = models.FileField(upload_to=gen_save_path) If you wish to include gen_save_path inside the class, you can use a lambda to call self.gen_save_path e.g. class Foo(models.Model): filestack = models.FileField(upload_to=lambda self, fname:self.gen_save_path(fname)) def gen_save_path(self, filename): return "some generated string"
Django: Call self function inside a Django model
I want to call for a self function of a model class as such in upload_to: class Foo(models.Model): filestack = models.FileField(upload_to=self. gen_save_path) def gen_save_path(self): """ gen_save_path: void -> String Generates the path as a string for fileStack field. """ return "some generated string" However I am getting NameError: name 'self' is not defined error
[ "filestack is a class attribute and while declaring it you can not use self as there is no object of class (self) yet created, anyway according to django docs upload_to takes two arguments, instance (An instance of the model where the FileField is defined) and filename (The filename that was originally given to the file), so you can set upload_to to such function\ndef gen_save_path(instance, filename):\n \"\"\"\n gen_save_path: void -> String\n Generates the path as a string for fileStack field.\n \"\"\"\n return \"some generated string\"\n\nclass Foo(models.Model):\n\n filestack = models.FileField(upload_to=gen_save_path)\n\nIf you wish to include gen_save_path inside the class, you can use a lambda to call self.gen_save_path e.g.\nclass Foo(models.Model):\n\n filestack = models.FileField(upload_to=lambda self, fname:self.gen_save_path(fname))\n\n def gen_save_path(self, filename):\n return \"some generated string\"\n\n" ]
[ 5 ]
[ "I think this will work if you use a lambda function:\nclass Foo(models.Model):\n filestack = models.FileField(upload_to=lambda: self.gen_save_path())\n\n def gen_save_path(self):\n \"\"\"\n gen_save_path: void -> String\n Generates the path as a string for fileStack field.\n \"\"\"\n return \"some generated string\"\n\n", "in your code, the filestack is a class wide scope variable since not defined in a method.\nso there is no available self in this scope.\ni think you can use :\nfilestack =models.FileField(upload_to=Foo.gen_save_path)\n\nor\ndefine filestack value within a __init__ constructor, where you can use self !!\n" ]
[ -2, -2 ]
[ "django", "django_models", "python" ]
stackoverflow_0003091667_django_django_models_python.txt
Q: question regarding universal feed parser I faced a problem grabbing the content from a couple of blog feeds I have crawled. I'm uncertain what is the reason, but by parsing one or two blogs with the feedparser returns me this particular error: results = feedparser.parse(url) ent = [] for entry in results.entries: e = {} e['title'] = entry.title e['content'] = entry.content[0].value object has no attribute 'content' or object has no attribute 'link' This hasn't been the case for the rest of my other blogs. Does empty entry content results in this? A: There is a mapping between the XML tags used in the feed and the attributes available on the entries in feedparser. View the source of one of the feeds that has been causing the problem and see what tags it uses. You might find it doesn't include content for the entries or that the links are in a field like uid rather than link. You will then need to write your code to handle the slight variations, either by using try/catch or checking for specific attributes with hasattr. If you post a link to one of the feeds in question I might be able to offer some more advice.
question regarding universal feed parser
I faced a problem grabbing the content from a couple of blog feeds I have crawled. I'm uncertain what is the reason, but by parsing one or two blogs with the feedparser returns me this particular error: results = feedparser.parse(url) ent = [] for entry in results.entries: e = {} e['title'] = entry.title e['content'] = entry.content[0].value object has no attribute 'content' or object has no attribute 'link' This hasn't been the case for the rest of my other blogs. Does empty entry content results in this?
[ "There is a mapping between the XML tags used in the feed and the attributes available on the entries in feedparser. View the source of one of the feeds that has been causing the problem and see what tags it uses. You might find it doesn't include content for the entries or that the links are in a field like uid rather than link.\nYou will then need to write your code to handle the slight variations, either by using try/catch or checking for specific attributes with hasattr.\nIf you post a link to one of the feeds in question I might be able to offer some more advice. \n" ]
[ 1 ]
[]
[]
[ "feedparser", "python" ]
stackoverflow_0003091476_feedparser_python.txt
Q: does google app engine display unicode differently in StringProperty v StringListProperty objs? I have a db.StringProperty() mRegion that is set to some Korean text. I see in my Dashboard that the value is visibly in Korean like this: 한국 : 충청남도 However, when I take this field and add it into a string list property (db.StringListProperty()) I end up with something like this: \ud55c\uad6d : \ucda9\uccad\ub0a8\ub3c4 I am having issues displaying this text on my client when I have this string list property value output to the client, so it makes me wonder if something is wrong on the server end when the value is stored (as I would expect it to be readable Korean like the StringProperty). Does anyone know where I might be going wrong with this or if this second display is simply normal in string list objects and the problem is likely on my client end? Thanks. Update with more detail of the issues: My client is an iphone app. Basically, I use the iPhone to get the user's gps location info using the reverse geocoder api. I send this to app engine and save it. This part appears to be working because for Korea, I see the Korean characters. The region name is obtained, in summary, like this: region = self.request.get('region') entry.init(region) ... self.mRegion = region pretty straightforward (and it works). Where it breaks down is when I retrieve that data and send it back to the client. To summarize: query = db.GqlQuery("SELECT * FROM RegionData WHERE mLatitudeCenter >= :1 and mLatitudeCenter <= :2", latmin, latmax) for entry in query: output += entry.mRegion + ',' self.response.out.write(output) When I take this and put it on a UILabel in the client, it's garbled. Also, when I take the garbled value in the client and send it back to the server to look up a region, it fails, so that suggests to me that instead of sending the Korean text maybe it's transmitting the repr() characters or something. If, as you say, it's just a matter of presentation and not the inherent data itself, then perhaps it's something to do with the system font I'm using to try to display this data? I had thought that somewhere I was missing the right call to encode() or decode(), but not sure. A: It's quite possible that the admin interface displays the two differently, yes. In the latter case it's clearly doing a repr(s), while in the former it's just printing the string. The admin interface's interface doesn't affect how your code works, though - both Strings and StringLists are stored the same way in the datastore, and will come back as Unicode strings for you to deal with as you wish. I highly recommend reading this Joel on Software post about unicode. In short, you're dealing with two kinds of things: Binary data, and unicode characters. To confuse you, Python exposes these both as strings - 'unicode strings' and 'raw strings', respectively, but you should only treat the former as actual strings. The datastore, with its StringListProperty and StringProperty, stores and returns Unicode strings. Your framework should also be giving you Unicode strings, and accepting Unicode strings back, but some poorly designed frameworks don't. What you need to do is check that you are using Unicode strings everywhere you deal with text, that you explicitly call .encode() to convert a Unicode string to a raw string, and .decode() to convert a raw string to a unicode string, and that the character encoding on the returned response is set correctly, and you're encoding your strings using the same encoding. How you do that will depend on your framework. Once you've done that, if you still have trouble, I would suggest writing some simple unit tests - storing data to the datastore and retrieving it and manipulating it, then checking it equals what you expect - to pin down where the issue is.
does google app engine display unicode differently in StringProperty v StringListProperty objs?
I have a db.StringProperty() mRegion that is set to some Korean text. I see in my Dashboard that the value is visibly in Korean like this: 한국 : 충청남도 However, when I take this field and add it into a string list property (db.StringListProperty()) I end up with something like this: \ud55c\uad6d : \ucda9\uccad\ub0a8\ub3c4 I am having issues displaying this text on my client when I have this string list property value output to the client, so it makes me wonder if something is wrong on the server end when the value is stored (as I would expect it to be readable Korean like the StringProperty). Does anyone know where I might be going wrong with this or if this second display is simply normal in string list objects and the problem is likely on my client end? Thanks. Update with more detail of the issues: My client is an iphone app. Basically, I use the iPhone to get the user's gps location info using the reverse geocoder api. I send this to app engine and save it. This part appears to be working because for Korea, I see the Korean characters. The region name is obtained, in summary, like this: region = self.request.get('region') entry.init(region) ... self.mRegion = region pretty straightforward (and it works). Where it breaks down is when I retrieve that data and send it back to the client. To summarize: query = db.GqlQuery("SELECT * FROM RegionData WHERE mLatitudeCenter >= :1 and mLatitudeCenter <= :2", latmin, latmax) for entry in query: output += entry.mRegion + ',' self.response.out.write(output) When I take this and put it on a UILabel in the client, it's garbled. Also, when I take the garbled value in the client and send it back to the server to look up a region, it fails, so that suggests to me that instead of sending the Korean text maybe it's transmitting the repr() characters or something. If, as you say, it's just a matter of presentation and not the inherent data itself, then perhaps it's something to do with the system font I'm using to try to display this data? I had thought that somewhere I was missing the right call to encode() or decode(), but not sure.
[ "It's quite possible that the admin interface displays the two differently, yes. In the latter case it's clearly doing a repr(s), while in the former it's just printing the string.\nThe admin interface's interface doesn't affect how your code works, though - both Strings and StringLists are stored the same way in the datastore, and will come back as Unicode strings for you to deal with as you wish.\nI highly recommend reading this Joel on Software post about unicode. In short, you're dealing with two kinds of things: Binary data, and unicode characters. To confuse you, Python exposes these both as strings - 'unicode strings' and 'raw strings', respectively, but you should only treat the former as actual strings.\nThe datastore, with its StringListProperty and StringProperty, stores and returns Unicode strings. Your framework should also be giving you Unicode strings, and accepting Unicode strings back, but some poorly designed frameworks don't.\nWhat you need to do is check that you are using Unicode strings everywhere you deal with text, that you explicitly call .encode() to convert a Unicode string to a raw string, and .decode() to convert a raw string to a unicode string, and that the character encoding on the returned response is set correctly, and you're encoding your strings using the same encoding. How you do that will depend on your framework.\nOnce you've done that, if you still have trouble, I would suggest writing some simple unit tests - storing data to the datastore and retrieving it and manipulating it, then checking it equals what you expect - to pin down where the issue is.\n" ]
[ 2 ]
[]
[]
[ "google_app_engine", "python", "string" ]
stackoverflow_0003091034_google_app_engine_python_string.txt
Q: Python script to read from a file and get values If in a file the values present are in either " or , separated values "Name" "Tom" "CODE 041" "Has" "Address" "NSYSTEMS c/o" "First Term" "123" 18 "Occ" "Engineer" "Level1" "JT" 18 How should the python script be written so as to get all the above values individually A: Your question is a little vague, and there are no commas in your example, so it's a bit hard to provide a good answer. On your example file containing "Name" "Tom" "CODE 041" "Has" "Address" "NSYSTEMS c/o" "First Term" "123" 18 "Occ" "Engineer" "Level1" "JT" 18 this script import csv reader = csv.reader(open('test.txt'), delimiter=' ', quotechar='"') for row in reader: print(row) produces ['Name', 'Tom', 'CODE 041', 'Has'] ['Address', 'NSYSTEMS c/o', 'First Term', '123', '18'] ['Occ', 'Engineer', 'Level1', 'JT', '18'] This assumes that the delimiter between values is a space. If it's a tab, use delimiter='\t' instead. You're out of luck with this approach if delimiters change throughout the file - in this case they are not valid CSV/TSV files anymore. But all this is just speculation until you can provide some actual and relevant examples of the data you want to analyse. A: An alternative approach to using the csv reader. in.txt "Name" "Tom" "CODE 041" "Has" "Address" "NSYSTEMS c/o" "First Term" "123" 18 "Occ" "Engineer" "Level1" "JT" 18 parse.py for i in [line.split('"') for line in open("in.txt")]: # split on the separator for j in i: # for each token in the split string if len(j.strip())>0: # ignore empty string, like the spaces between elements print j.strip() out.txt Name Tom CODE 041 Has Address NSYSTEMS c/o First Term 123 18 Occ Engineer Level1 JT 18 But I would call your values " enclosed. And I cant see any , separated. Could you expand your test data? Show some rows with , separated values and Ill expand my code. A: Use csv module it will handle all type of delimiters and quotes properly, writing such code using split etc isn't trivial import csv import StringIO data = '''"Name" "Tom" "CODE 041" "Has" "Address" "NSYSTEMS c/o" "First Term" "123" 18 "Occ" "Engineer" "Level1" "JT" 18" ''' reader = csv.reader(StringIO.StringIO(data), delimiter=' ') for row in reader: print row Output: ['Name', 'Tom', 'CODE 041', 'Has'] ['Address', 'NSYSTEMS c/o', 'First Term', '123', '18'] ['Occ', 'Engineer', 'Level1', 'JT', '18']
Python script to read from a file and get values
If in a file the values present are in either " or , separated values "Name" "Tom" "CODE 041" "Has" "Address" "NSYSTEMS c/o" "First Term" "123" 18 "Occ" "Engineer" "Level1" "JT" 18 How should the python script be written so as to get all the above values individually
[ "Your question is a little vague, and there are no commas in your example, so it's a bit hard to provide a good answer.\nOn your example file containing\n\"Name\" \"Tom\" \"CODE 041\" \"Has\"\n\"Address\" \"NSYSTEMS c/o\" \"First Term\" \"123\" 18 \n\"Occ\" \"Engineer\" \"Level1\" \"JT\" 18\n\nthis script\nimport csv\nreader = csv.reader(open('test.txt'), delimiter=' ', quotechar='\"')\nfor row in reader:\n print(row)\n\nproduces\n['Name', 'Tom', 'CODE 041', 'Has']\n['Address', 'NSYSTEMS c/o', 'First Term', '123', '18']\n['Occ', 'Engineer', 'Level1', 'JT', '18']\n\nThis assumes that the delimiter between values is a space. If it's a tab, use delimiter='\\t' instead.\nYou're out of luck with this approach if delimiters change throughout the file - in this case they are not valid CSV/TSV files anymore. But all this is just speculation until you can provide some actual and relevant examples of the data you want to analyse.\n", "An alternative approach to using the csv reader.\nin.txt\n\"Name\" \"Tom\" \"CODE 041\" \"Has\"\n\"Address\" \"NSYSTEMS c/o\" \"First Term\" \"123\" 18 \n\"Occ\" \"Engineer\" \"Level1\" \"JT\" 18\n\nparse.py\nfor i in [line.split('\"') for line in open(\"in.txt\")]: # split on the separator\n for j in i: # for each token in the split string\n if len(j.strip())>0: # ignore empty string, like the spaces between elements\n print j.strip()\n\nout.txt\nName\nTom\nCODE 041\nHas\nAddress\nNSYSTEMS c/o\nFirst Term\n123\n18\nOcc\nEngineer\nLevel1\nJT\n18\n\nBut I would call your values \" enclosed. And I cant see any , separated. Could you expand your test data? Show some rows with , separated values and Ill expand my code.\n", "Use csv module it will handle all type of delimiters and quotes properly, writing such code using split etc isn't trivial\nimport csv\nimport StringIO\n\ndata = '''\"Name\" \"Tom\" \"CODE 041\" \"Has\"\n\"Address\" \"NSYSTEMS c/o\" \"First Term\" \"123\" 18 \n\"Occ\" \"Engineer\" \"Level1\" \"JT\" 18\"\n'''\n\nreader = csv.reader(StringIO.StringIO(data), delimiter=' ')\nfor row in reader:\n print row\n\nOutput:\n['Name', 'Tom', 'CODE 041', 'Has']\n['Address', 'NSYSTEMS c/o', 'First Term', '123', '18']\n['Occ', 'Engineer', 'Level1', 'JT', '18']\n\n" ]
[ 3, 1, 0 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0003091976_file_io_python.txt
Q: Python time.gmtime() returning time that's 5 hours ahead of system time I have been scouring the google machine and have come up with nothing to answer this. When making calls to: time.gmtime() This ends up returning a time, as the subject line says, 5 hours ahead of my system time. I cannot figure out what is going on. time.tzname() returns the proper timezone. Aside from setting python to a timezone 5 hours earlier than mine, is there any way to correct this error? A: Have you tried moving to London? I think that will solve your problem. :) A: Are you looking for time.localtime? As docs say time.gmtime returns time struct in UTC. A: time.gmtime() returns Greenwich Mean Time. This is five hours ahead of Eastern Standard Time, for example; taking into account daylight savings time, it's five hours ahead of Central Standard Time.
Python time.gmtime() returning time that's 5 hours ahead of system time
I have been scouring the google machine and have come up with nothing to answer this. When making calls to: time.gmtime() This ends up returning a time, as the subject line says, 5 hours ahead of my system time. I cannot figure out what is going on. time.tzname() returns the proper timezone. Aside from setting python to a timezone 5 hours earlier than mine, is there any way to correct this error?
[ "Have you tried moving to London? I think that will solve your problem. :)\n", "Are you looking for time.localtime? As docs say time.gmtime returns time struct in UTC.\n", "time.gmtime() returns Greenwich Mean Time. This is five hours ahead of Eastern Standard Time, for example; taking into account daylight savings time, it's five hours ahead of Central Standard Time.\n" ]
[ 20, 6, 5 ]
[]
[]
[ "python", "time", "timezone" ]
stackoverflow_0003092479_python_time_timezone.txt
Q: Django: custom serialization options? I'm working on a Django-based web service and I'm trying to figure out what the best way to do my serialization will be. The tricky requirement, though, is that I'd like to have pretty much full control over format of, and fields contained in, the response. For example, the Django serializers (which, unfortunately, includes the wadofstuff serializer) automatically wrap the fields in { model: "app.Model", pk: 42, fields: { ... }}, which is great for creating fixtures, but isn't great for me — I'd like full control over the output. Additionally, I'd like a serializer that is aware of Django's objects so, for example, it will do the Right Thing with a QuerySet or ManyToManyField. Currently I'm thinking of using django-piston's emitters.py, but my experience with django-piston has only been mediocreª, so I'd like to see if there are other options. So, are there any other options for customizable Django serializers? ª: It's sparsely documented and tested, and I've had some problems with the serializer. A: Have you looked at django-piston? It should have a bunch of stuff to make this easier. (Not sure about serialization specifically, but Django RESTy web services.) A: When I need some custom serialization really fast and my case doesn't require deserialization I just write django template that can make any format I want from list/queryset/object. You can then call render_to_string with proper context and you have your data serialized. UPDATE: some short example Let's say you want to get json format accepted by datatables.net plugin. Since there are some special parameters required serializing queryset using simplejson or sth else is impossible here (or might be not so easy at least). We found that fastest way to provide such structure is to create simple template like this one: { "sEcho": {{sEcho}}, "iTotalRecords": {{iTotalRecords}}, "iTotalDisplayRecords": {{iTotalDisplayRecords}}, "aaData":[ {% for obj in querySet %} [ "{{obj.name}}", "{{obj.message|truncatewords:20}}", "<a href=\"{% url some_view obj.id %}\">{{obj.name}}</a>" ] {% if not forloop.last %} , {% endif %} {% endfor %} ] } which renders to beatiful json that we were looking for. It gives you full control over the format also. Other advantages is the abillity to modify objects fields by using built-in django filters which in our case was really usefull. I know this is not serialization as described in books but if f you want to convert some object to a custom format this solution might be the fastest one. For some reason django developers allowed to render template to any given format not only html, so why not to use it? Example shown above is very specific but you can generate any other format. Of course writing deserializer for that could restore object from this format might be painfull but if you don't need it... A: EDIT : Now out at https://bitbucket.org/sebpiq/any2any/ I am currently writing a full-featured serialization framework for Django. The aim is precisely to have full control over the serialization. It would probably fill-in your requirements pretty well ! However, it is not ready yet. I estimate that in 1 or 2 weeks I will be able to release a first version. You can still check the google code : http://code.google.com/p/django-serializable/ , even give some help if you are interested in it. There will be a featured download when the first release will be out !
Django: custom serialization options?
I'm working on a Django-based web service and I'm trying to figure out what the best way to do my serialization will be. The tricky requirement, though, is that I'd like to have pretty much full control over format of, and fields contained in, the response. For example, the Django serializers (which, unfortunately, includes the wadofstuff serializer) automatically wrap the fields in { model: "app.Model", pk: 42, fields: { ... }}, which is great for creating fixtures, but isn't great for me — I'd like full control over the output. Additionally, I'd like a serializer that is aware of Django's objects so, for example, it will do the Right Thing with a QuerySet or ManyToManyField. Currently I'm thinking of using django-piston's emitters.py, but my experience with django-piston has only been mediocreª, so I'd like to see if there are other options. So, are there any other options for customizable Django serializers? ª: It's sparsely documented and tested, and I've had some problems with the serializer.
[ "Have you looked at django-piston? It should have a bunch of stuff to make this easier.\n(Not sure about serialization specifically, but Django RESTy web services.)\n", "When I need some custom serialization really fast and my case doesn't require deserialization I just write django template that can make any format I want from list/queryset/object. You can then call render_to_string with proper context and you have your data serialized.\nUPDATE: some short example\nLet's say you want to get json format accepted by datatables.net plugin. Since there are some special parameters required serializing queryset using simplejson or sth else is impossible here (or might be not so easy at least). We found that fastest way to provide such structure is to create simple template like this one:\n{\n \"sEcho\": {{sEcho}},\n \"iTotalRecords\": {{iTotalRecords}},\n \"iTotalDisplayRecords\": {{iTotalDisplayRecords}},\n \"aaData\":[\n {% for obj in querySet %}\n [\n \"{{obj.name}}\",\n \"{{obj.message|truncatewords:20}}\",\n \"<a href=\\\"{% url some_view obj.id %}\\\">{{obj.name}}</a>\"\n ]\n {% if not forloop.last %}\n ,\n {% endif %}\n {% endfor %}\n ]\n}\n\nwhich renders to beatiful json that we were looking for. It gives you full control over the format also. Other advantages is the abillity to modify objects fields by using built-in django filters which in our case was really usefull.\nI know this is not serialization as described in books but if f you want to convert some object to a custom format this solution might be the fastest one. For some reason django developers allowed to render template to any given format not only html, so why not to use it?\nExample shown above is very specific but you can generate any other format. Of course writing deserializer for that could restore object from this format might be painfull but if you don't need it...\n", "EDIT :\nNow out at https://bitbucket.org/sebpiq/any2any/\n\nI am currently writing a full-featured serialization framework for Django. The aim is precisely to have full control over the serialization. It would probably fill-in your requirements pretty well ! However, it is not ready yet. I estimate that in 1 or 2 weeks I will be able to release a first version.\nYou can still check the google code : http://code.google.com/p/django-serializable/ , even give some help if you are interested in it.\nThere will be a featured download when the first release will be out !\n" ]
[ 1, 1, 1 ]
[]
[]
[ "django", "django_piston", "python", "serialization" ]
stackoverflow_0003055650_django_django_piston_python_serialization.txt
Q: Python dynamically importing a script, need to have its __name__ == "__main__" code to be called While importing a python script from another script I want the script code that is classically protected by if __name__ == "__main__": .... .... to be run, how can I get that code run? What I am trying to do is from a python script, dynamically change a module then import an existing script which should see the changes made and run its __main__ code like it was directly invoked by python? I need to execute the 2nd python script in the same namespace as the 1st python script and pass the 2nd script command line parameters. execfile() suggested below might work but that doesn't take any command line parameters. I would rather not edit the 2nd script (external code) as I want the 1st script to be a wrapper around it. A: If you can edit the file being imported, one option is to follow the basic principle of putting important code inside of functions. # Your script. import foo foo.main() # The file being imported. def main(): print "running foo.main()" if __name__ == "__main__": main() If you can't edit the code being imported, execfile does provide a mechanism for passing arguments to the imported code, but this approach would make me nervous. Use with caution. # Your script. import sys import foo bar = 999 sys.argv = ['blah', 'fubb'] execfile( 'foo.py', globals() ) # The file being exec'd. if __name__ == "__main__": print bar print sys.argv
Python dynamically importing a script, need to have its __name__ == "__main__" code to be called
While importing a python script from another script I want the script code that is classically protected by if __name__ == "__main__": .... .... to be run, how can I get that code run? What I am trying to do is from a python script, dynamically change a module then import an existing script which should see the changes made and run its __main__ code like it was directly invoked by python? I need to execute the 2nd python script in the same namespace as the 1st python script and pass the 2nd script command line parameters. execfile() suggested below might work but that doesn't take any command line parameters. I would rather not edit the 2nd script (external code) as I want the 1st script to be a wrapper around it.
[ "If you can edit the file being imported, one option is to follow the basic principle of putting important code inside of functions.\n# Your script.\nimport foo\n\nfoo.main()\n\n# The file being imported.\ndef main():\n print \"running foo.main()\"\n\nif __name__ == \"__main__\":\n main()\n\nIf you can't edit the code being imported, execfile does provide a mechanism for passing arguments to the imported code, but this approach would make me nervous. Use with caution.\n# Your script.\nimport sys\n\nimport foo\n\nbar = 999\nsys.argv = ['blah', 'fubb']\n\nexecfile( 'foo.py', globals() )\n\n# The file being exec'd.\nif __name__ == \"__main__\":\n print bar\n print sys.argv\n\n" ]
[ 6 ]
[]
[]
[ "import", "python" ]
stackoverflow_0003092319_import_python.txt
Q: Increasing throughput in a python script I'm processing a list of thousands of domain names from a DNSBL through dig, creating a CSV of URLs and IPs. This is a very time-consuming process that can take several hours. My server's DNSBL updates every fifteen minutes. Is there a way I can increase throughput in my Python script to keep pace with the server's updates? Edit: the script, as requested. import re import subprocess as sp text = open("domainslist", 'r') text = text.read() text = re.split("\n+", text) file = open('final.csv', 'w') for element in text: try: ip = sp.Popen(["dig", "+short", url], stdout = sp.PIPE) ip = re.split("\n+", ip.stdout.read()) file.write(url + "," + ip[0] + "\n") except: pass A: The vast majority of the time here is spent in the external calls to dig, so to improve that speed, you'll need to multithread. This will allow you to run multiple calls to dig at the same time. See for example: Python Subprocess.Popen from a thread . Or, you can use Twisted ( http://twistedmatrix.com/trac/ ). EDIT: You're correct, much of that was unnecessary. A: Well, it's probably the name resolution that's taking you so long. If you count that out (i.e., if somehow dig returned very quickly), Python should be able to deal with thousands of entries easily. That said, you should try a threaded approach. That would (theoretically) resolve several addresses at the same time, instead of sequentially. You could just as well continue to use dig for that, and it should be trivial to modify my example code below for that, but, to make things interesting (and hopefully more pythonic), let's use an existing module for that: dnspython So, install it with: sudo pip install -f http://www.dnspython.org/kits/1.8.0/ dnspython And then try something like the following: import threading from dns import resolver class Resolver(threading.Thread): def __init__(self, address, result_dict): threading.Thread.__init__(self) self.address = address self.result_dict = result_dict def run(self): try: result = resolver.query(self.address)[0].to_text() self.result_dict[self.address] = result except resolver.NXDOMAIN: pass def main(): infile = open("domainlist", "r") intext = infile.readlines() threads = [] results = {} for address in [address.strip() for address in intext if address.strip()]: resolver_thread = Resolver(address, results) threads.append(resolver_thread) resolver_thread.start() for thread in threads: thread.join() outfile = open('final.csv', 'w') outfile.write("\n".join("%s,%s" % (address, ip) for address, ip in results.iteritems())) outfile.close() if __name__ == '__main__': main() If that proves to start too many threads at the same time, you could try doing it in batches, or using a queue (see http://www.ibm.com/developerworks/aix/library/au-threadingpython/ for an example) A: I'd consider using a pure-Python library to do the DNS queries, rather than delegating to dig, because invoking another process can be relatively time-consuming. (Of course, looking up anything on the internet is also relatively time-consuming, so what gilesc said about multithreading still applies) A Google search for python dns will give you some options to get started with. A: In order to keep pace with the server updates, one must take less than 15 minutes to execute. Does your script take 15 minutes to run? If it doesn't take 15 minutes, you're done! I would investigate caching and diffs from previous runs in order to increase performance.
Increasing throughput in a python script
I'm processing a list of thousands of domain names from a DNSBL through dig, creating a CSV of URLs and IPs. This is a very time-consuming process that can take several hours. My server's DNSBL updates every fifteen minutes. Is there a way I can increase throughput in my Python script to keep pace with the server's updates? Edit: the script, as requested. import re import subprocess as sp text = open("domainslist", 'r') text = text.read() text = re.split("\n+", text) file = open('final.csv', 'w') for element in text: try: ip = sp.Popen(["dig", "+short", url], stdout = sp.PIPE) ip = re.split("\n+", ip.stdout.read()) file.write(url + "," + ip[0] + "\n") except: pass
[ "The vast majority of the time here is spent in the external calls to dig, so to improve that speed, you'll need to multithread. This will allow you to run multiple calls to dig at the same time. See for example: Python Subprocess.Popen from a thread . Or, you can use Twisted ( http://twistedmatrix.com/trac/ ).\nEDIT: You're correct, much of that was unnecessary.\n", "Well, it's probably the name resolution that's taking you so long. If you count that out (i.e., if somehow dig returned very quickly), Python should be able to deal with thousands of entries easily.\nThat said, you should try a threaded approach. That would (theoretically) resolve several addresses at the same time, instead of sequentially. You could just as well continue to use dig for that, and it should be trivial to modify my example code below for that, but, to make things interesting (and hopefully more pythonic), let's use an existing module for that: dnspython\nSo, install it with:\nsudo pip install -f http://www.dnspython.org/kits/1.8.0/ dnspython\n\nAnd then try something like the following:\nimport threading\nfrom dns import resolver\n\nclass Resolver(threading.Thread):\n def __init__(self, address, result_dict):\n threading.Thread.__init__(self)\n self.address = address\n self.result_dict = result_dict\n\n def run(self):\n try:\n result = resolver.query(self.address)[0].to_text()\n self.result_dict[self.address] = result\n except resolver.NXDOMAIN:\n pass\n\n\ndef main():\n infile = open(\"domainlist\", \"r\")\n intext = infile.readlines()\n threads = []\n results = {}\n for address in [address.strip() for address in intext if address.strip()]:\n resolver_thread = Resolver(address, results)\n threads.append(resolver_thread)\n resolver_thread.start()\n\n for thread in threads:\n thread.join()\n\n outfile = open('final.csv', 'w')\n outfile.write(\"\\n\".join(\"%s,%s\" % (address, ip) for address, ip in results.iteritems()))\n outfile.close()\n\nif __name__ == '__main__':\n main()\n\nIf that proves to start too many threads at the same time, you could try doing it in batches, or using a queue (see http://www.ibm.com/developerworks/aix/library/au-threadingpython/ for an example)\n", "I'd consider using a pure-Python library to do the DNS queries, rather than delegating to dig, because invoking another process can be relatively time-consuming. (Of course, looking up anything on the internet is also relatively time-consuming, so what gilesc said about multithreading still applies) A Google search for python dns will give you some options to get started with.\n", "In order to keep pace with the server updates, one must take less than 15 minutes to execute. Does your script take 15 minutes to run? If it doesn't take 15 minutes, you're done!\nI would investigate caching and diffs from previous runs in order to increase performance.\n" ]
[ 2, 2, 0, 0 ]
[]
[]
[ "python", "python_multithreading", "unix" ]
stackoverflow_0003089413_python_python_multithreading_unix.txt
Q: Python C API: Switch on PyObject type I have some code to interface Python to C++ which works fine but every time I look at it I think there must be a better way to do it. On the C++ side there is a 'variant' type that can deal with a fixed range of basic types - int, real, string, vector of variants, etc. I have some code using the Python API to convert from the equivalent Python types. It looks something like this: variant makeVariant(PyObject* value) { if (PyString_Check(value)) { return PyString_AsString(value); } else if (value == Py_None) { return variant(); } else if (PyBool_Check(value)) { return value == Py_True; } else if (PyInt_Check(value)) { return PyInt_AsLong(value); } else if (PyFloat_Check(value)) { return PyFloat_AsDouble(value); } // ... etc The problem is the chained if-else ifs. It seems to be calling out for a switch statement, or a table or map of creation functions which is keyed by a type identifier. In other words I want to be able to write something like: return createFunMap[typeID(value)](value); Based on a skim of the API docs it wasn't obvious what the best way is to get the 'typeID' here directly. I see I can do something like this: PyTypeObject* type = value->ob_type; This apparently gets me quickly to the type information but what is the cleanest way to use that to relate to the limited set of types I am interested in? A: In a way, I think you've answered your own question. Somewhere, you're going to have to select functionality based on data. The way to do this in C is to use function pointers. Create a map of object_type->function mappers... where each function has a clearly-defined interface. variant PyBoolToVariant(PyObject *value) { return value == Py_True; } Map<PyTypeObject*,variant* (PyObject*)> function_map; function_map.add(PyBool, PyBoolToVariant); Now your makeVariant can look like this. variant makeVariant(PyObject *value) { return (*function_map.get(value->ob_type))(value); } The hard part is going to be getting the syntax right for the Map object. Also, I'm assuming there is a Map object you can use that takes type parameters (<PyTypeObject*, variant*(PyObject*)). I probably have not quite gotten the syntax correct for the second type of the Map. It should be a pointer to a function which takes one pointer and returns a pointer to a variant. I hope this is helpful.
Python C API: Switch on PyObject type
I have some code to interface Python to C++ which works fine but every time I look at it I think there must be a better way to do it. On the C++ side there is a 'variant' type that can deal with a fixed range of basic types - int, real, string, vector of variants, etc. I have some code using the Python API to convert from the equivalent Python types. It looks something like this: variant makeVariant(PyObject* value) { if (PyString_Check(value)) { return PyString_AsString(value); } else if (value == Py_None) { return variant(); } else if (PyBool_Check(value)) { return value == Py_True; } else if (PyInt_Check(value)) { return PyInt_AsLong(value); } else if (PyFloat_Check(value)) { return PyFloat_AsDouble(value); } // ... etc The problem is the chained if-else ifs. It seems to be calling out for a switch statement, or a table or map of creation functions which is keyed by a type identifier. In other words I want to be able to write something like: return createFunMap[typeID(value)](value); Based on a skim of the API docs it wasn't obvious what the best way is to get the 'typeID' here directly. I see I can do something like this: PyTypeObject* type = value->ob_type; This apparently gets me quickly to the type information but what is the cleanest way to use that to relate to the limited set of types I am interested in?
[ "In a way, I think you've answered your own question.\nSomewhere, you're going to have to select functionality based on data. The way to do this in C is to use function pointers.\nCreate a map of object_type->function mappers... where each function has a clearly-defined interface.\nvariant PyBoolToVariant(PyObject *value) {\n return value == Py_True;\n}\n\nMap<PyTypeObject*,variant* (PyObject*)> function_map;\n\nfunction_map.add(PyBool, PyBoolToVariant);\n\nNow your makeVariant can look like this.\nvariant makeVariant(PyObject *value) {\n return (*function_map.get(value->ob_type))(value);\n}\n\nThe hard part is going to be getting the syntax right for the Map object. Also, I'm assuming there is a Map object you can use that takes type parameters (<PyTypeObject*, variant*(PyObject*)).\nI probably have not quite gotten the syntax correct for the second type of the Map. It should be a pointer to a function which takes one pointer and returns a pointer to a variant.\nI hope this is helpful.\n" ]
[ 3 ]
[]
[]
[ "c", "python", "python_c_api", "python_c_extension" ]
stackoverflow_0003092786_c_python_python_c_api_python_c_extension.txt
Q: python listen 2 port same file I would like to listen on 2 different UDP port with the same server. I use SocketServer lib for my server, and basicly it looks like that; SocketServer.UDPServer(('', 7878),CLASSNAME) I would like to listen on 7878 and 7879 with the same server and same file. Is that possible? If yes how? A: Sure you can, using threads. Here's a server: import SocketServer import threading class MyUDPHandler(SocketServer.BaseRequestHandler): def handle(self): data = self.request[0].strip() socket = self.request[1] print "%s wrote:" % self.client_address[0] print data socket.sendto(data.upper(), self.client_address) def serve_thread(host, port): server = SocketServer.UDPServer((host, port), MyUDPHandler) server.serve_forever() threading.Thread(target=serve_thread,args=('localhost', 9999)).start() threading.Thread(target=serve_thread,args=('localhost', 12345)).start() It creates a server to listen on 9999 and another to listen on 12345. Here's a sample client you can use for testing this: import socket import sys HOST, PORT = "localhost", 12345 data = 'da bomb' # SOCK_DGRAM is the socket type to use for UDP sockets sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # As you can see, there is no connect() call; UDP has no connections. # Instead, data is directly sent to the recipient via sendto(). sock.sendto(data + "\n", (HOST, PORT)) received = sock.recv(1024) print "Sent: %s" % data print "Received: %s" % received Note: this was taken from the docs of the SocketServer module, and modified with threads. A: Nope. Consider using Twisted. A: No need to use threads for something like this. Consider http://code.google.com/p/pyev/
python listen 2 port same file
I would like to listen on 2 different UDP port with the same server. I use SocketServer lib for my server, and basicly it looks like that; SocketServer.UDPServer(('', 7878),CLASSNAME) I would like to listen on 7878 and 7879 with the same server and same file. Is that possible? If yes how?
[ "Sure you can, using threads. Here's a server:\nimport SocketServer\nimport threading\n\n\nclass MyUDPHandler(SocketServer.BaseRequestHandler):\n def handle(self):\n data = self.request[0].strip()\n socket = self.request[1]\n print \"%s wrote:\" % self.client_address[0]\n print data\n socket.sendto(data.upper(), self.client_address)\n\n\ndef serve_thread(host, port):\n server = SocketServer.UDPServer((host, port), MyUDPHandler)\n server.serve_forever()\n\n\nthreading.Thread(target=serve_thread,args=('localhost', 9999)).start()\nthreading.Thread(target=serve_thread,args=('localhost', 12345)).start()\n\nIt creates a server to listen on 9999 and another to listen on 12345. \nHere's a sample client you can use for testing this:\nimport socket\nimport sys\n\nHOST, PORT = \"localhost\", 12345\ndata = 'da bomb'\n\n# SOCK_DGRAM is the socket type to use for UDP sockets\nsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\n# As you can see, there is no connect() call; UDP has no connections.\n# Instead, data is directly sent to the recipient via sendto().\nsock.sendto(data + \"\\n\", (HOST, PORT))\nreceived = sock.recv(1024)\n\nprint \"Sent: %s\" % data\nprint \"Received: %s\" % received\n\nNote: this was taken from the docs of the SocketServer module, and modified with threads.\n", "Nope. Consider using Twisted.\n", "No need to use threads for something like this. Consider http://code.google.com/p/pyev/\n" ]
[ 3, 1, 0 ]
[]
[]
[ "python", "socketserver", "udp" ]
stackoverflow_0002069566_python_socketserver_udp.txt
Q: How to use Python files spread out over many folders, or: how to organize a project I am looking to make my project fulfill the guidelines described here: http://infinitemonkeycorps.net/docs/pph/. I currently have the following directories: src/ test/ doc/ I would really like to organize my src/ file as follows: src/ similar_files/ other_files/ helpers/ etc However, I'm not familiar with how I could have my modules and classes interact the same way, i.e. if some module in one folder needs access to one in another folder. Is this a bad way to organize my project? If not, how can I accomplish what I want? Thanks! A: You'll want to read the tutorial.. here! :D Section 6.4.2 also contains the references that would assist you.
How to use Python files spread out over many folders, or: how to organize a project
I am looking to make my project fulfill the guidelines described here: http://infinitemonkeycorps.net/docs/pph/. I currently have the following directories: src/ test/ doc/ I would really like to organize my src/ file as follows: src/ similar_files/ other_files/ helpers/ etc However, I'm not familiar with how I could have my modules and classes interact the same way, i.e. if some module in one folder needs access to one in another folder. Is this a bad way to organize my project? If not, how can I accomplish what I want? Thanks!
[ "You'll want to read the tutorial.. here! :D\nSection 6.4.2 also contains the references that would assist you.\n" ]
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0003093249_python.txt
Q: Python: Object assignment with variable argument list Is there a method to pass a variable number of arguments to a function and have it change those arguments using the ( *args, **keywords ) style of argument passing? I've tried a few things but either see no change or have an error raised by the compiler: def foo( *args ): args[0] = 4 This gets me TypeError: object does not support assignment (they're tuples.) Or def foo( *args ): plusOne = [ item+1 for item in args ] args = plusOne which has no effect what so ever. If there is no mechanism nor work around I can admit defeat. Edit: To clarify why I'm trying to go this route, consider the case here: class bar(object): def __init__(self,obj): self.obj = obj def foo( input ): input.obj = "something else" If I pass my bar object into foo, I get a change in the state. To create a decorator which performs a deepcopy which resets all such state I'm currently customizing it for N arguments. I'd like to create one which accepts any number of arguments. Hence, the question. A: No - Python uses call by object-sharing, also known as call-by-value. To clarify the terminology: you are not receiving a deep copy of the object, but a copy of the object reference. Note: this is not the same as call-by-reference! You can think of it as call by value, and that the values are references to objects. So to answer your question, you receive a copy of the arguments (object references). You cannot modify the object references as if they were passed by reference. You can make a new modified copy of them if you want, but judging from your examples that isn't what you are looking for. The calling scope won't see your changes. If instead you mutate the objects you receive, the client can see those changes. A: The reason args[0] = 4 doesn't work is because, as the error message says, args a tuple, which is immutable. So, you'll need it convert it to the mutable object first, for example like this: >>> def foo( *args ): print(args) args = list(args) args[0] = 42 print(args) >>> foo(23) (23,) [42] If you give more information, it would be possible to provide more pythonic solution, because what you're doing seems strange. Also, second code seem to work just fine. For example the following works just fine and changes calling scope variable: >>> def spam(*a): a[0][0] = 42 >>> l = [23, 32] >>> spam(l) >>> l [42, 32] The reason being exactly the same: mutability of the l object. The same can be shown on your example: >>> def foo( *input ): input[0].obj = "something else" >>> b = bar('abc') >>> foo(b) >>> b.obj 'something else' A: If you want to change the arguments passed to the functions, so that you could do something like this: >>> x, y = (10, 17) >>> foo(x, y) >>> print (x, y) (11, 18) you're out of luck, for the reason stated in Mark's answer. However, if you're passing mutable objects to your function you can change these objects and see the results after calling foo: def foo(*args): for arg in args: arg['value'] += 1 >>> d1 = {'value': 1} >>> d2 = {'value': 2} >>> foo(d1, d2) >>> print (d1, d2) ({'value': 2}, {'value': 3})
Python: Object assignment with variable argument list
Is there a method to pass a variable number of arguments to a function and have it change those arguments using the ( *args, **keywords ) style of argument passing? I've tried a few things but either see no change or have an error raised by the compiler: def foo( *args ): args[0] = 4 This gets me TypeError: object does not support assignment (they're tuples.) Or def foo( *args ): plusOne = [ item+1 for item in args ] args = plusOne which has no effect what so ever. If there is no mechanism nor work around I can admit defeat. Edit: To clarify why I'm trying to go this route, consider the case here: class bar(object): def __init__(self,obj): self.obj = obj def foo( input ): input.obj = "something else" If I pass my bar object into foo, I get a change in the state. To create a decorator which performs a deepcopy which resets all such state I'm currently customizing it for N arguments. I'd like to create one which accepts any number of arguments. Hence, the question.
[ "No - Python uses call by object-sharing, also known as call-by-value.\nTo clarify the terminology: you are not receiving a deep copy of the object, but a copy of the object reference. Note: this is not the same as call-by-reference! You can think of it as call by value, and that the values are references to objects.\nSo to answer your question, you receive a copy of the arguments (object references). You cannot modify the object references as if they were passed by reference. You can make a new modified copy of them if you want, but judging from your examples that isn't what you are looking for. The calling scope won't see your changes.\nIf instead you mutate the objects you receive, the client can see those changes.\n", "The reason \nargs[0] = 4\n\ndoesn't work is because, as the error message says, args a tuple, which is immutable. So, you'll need it convert it to the mutable object first, for example like this:\n>>> def foo( *args ):\n print(args)\n args = list(args)\n args[0] = 42\n print(args)\n\n\n>>> foo(23)\n(23,)\n[42]\n\nIf you give more information, it would be possible to provide more pythonic solution, because what you're doing seems strange. Also, second code seem to work just fine.\nFor example the following works just fine and changes calling scope variable:\n>>> def spam(*a):\n a[0][0] = 42\n\n\n>>> l = [23, 32]\n>>> spam(l)\n>>> l\n[42, 32]\n\nThe reason being exactly the same: mutability of the l object. The same can be shown on your example:\n>>> def foo( *input ):\n input[0].obj = \"something else\"\n\n\n>>> b = bar('abc')\n>>> foo(b)\n>>> b.obj\n'something else'\n\n", "If you want to change the arguments passed to the functions, so that you could do something like this:\n>>> x, y = (10, 17)\n>>> foo(x, y)\n>>> print (x, y)\n(11, 18)\n\nyou're out of luck, for the reason stated in Mark's answer.\nHowever, if you're passing mutable objects to your function you can change these objects and see the results after calling foo:\ndef foo(*args):\n for arg in args:\n arg['value'] += 1\n\n>>> d1 = {'value': 1}\n>>> d2 = {'value': 2}\n>>> foo(d1, d2)\n>>> print (d1, d2)\n({'value': 2}, {'value': 3})\n\n" ]
[ 4, 3, 1 ]
[]
[]
[ "arguments", "python", "variadic_functions" ]
stackoverflow_0003093352_arguments_python_variadic_functions.txt
Q: What is affected by ReferenceProperty? In reference to these two questions (see links below) and the Google AppEngine doc, I got a little bit confused: class Author(db.Model): name = db.StringProperty() class Story(db.Model): author = db.ReferenceProperty(Author) story = db.get(story_key) author_name = story.author.name Source: Google The doc example indicates that the object which has the ReferenceProperty is the "owner" object, which (can have) has such an object as relational item. The links below show it vice-versa: The object which has the ReferenceProperty is the "owned" object. Now my question is, what is right, or what aspect of the ReferenceProperty am I missing/misunderstanding? GQL with two tables Google app engine ReferenceProperty relationships A: The notion of ownership here is purely semantic, ReferenceProperty fields are only used for navigability. A: References imply only referentiality - a "has a" relationship, if you like - not ownership. In your example, a Story "has an" Author. Another way to think about it is in the same way you would use a variable to refer to an object in OO.
What is affected by ReferenceProperty?
In reference to these two questions (see links below) and the Google AppEngine doc, I got a little bit confused: class Author(db.Model): name = db.StringProperty() class Story(db.Model): author = db.ReferenceProperty(Author) story = db.get(story_key) author_name = story.author.name Source: Google The doc example indicates that the object which has the ReferenceProperty is the "owner" object, which (can have) has such an object as relational item. The links below show it vice-versa: The object which has the ReferenceProperty is the "owned" object. Now my question is, what is right, or what aspect of the ReferenceProperty am I missing/misunderstanding? GQL with two tables Google app engine ReferenceProperty relationships
[ "The notion of ownership here is purely semantic, ReferenceProperty fields are only used for navigability.\n", "References imply only referentiality - a \"has a\" relationship, if you like - not ownership. In your example, a Story \"has an\" Author. Another way to think about it is in the same way you would use a variable to refer to an object in OO.\n" ]
[ 1, 1 ]
[]
[]
[ "google_app_engine", "gql", "python" ]
stackoverflow_0003093288_google_app_engine_gql_python.txt
Q: Removing spaces and newlines between tags in html (aka unformatting) in python An example: <p> Hello</p> <div>hgello</div> <pre> code code <pre> turns in something like: <p> Hello</p><div>hgello</div><pre> code code <pre> How to do this in python? I make also intensive use of < pre> tags so substituting all '\n' with '' is not an option. What's the best way to do that? A: You could use re.sub(">\s*<","><","[here your html string]"). Maybe string.replace(">\n",">"), i.e. look for an enclosing bracket and a newline and remove the newline. A: I would choose to use the python regex: string.replace(">\s+<","><") Where the '\s' finds any whitespace character and the '+' after it shows it matches one or more whitespace characters. This removes the possibility of the replace replacing <pre> code code <pre> with <pre><pre> More information about regular expressions can be found here, here and here.
Removing spaces and newlines between tags in html (aka unformatting) in python
An example: <p> Hello</p> <div>hgello</div> <pre> code code <pre> turns in something like: <p> Hello</p><div>hgello</div><pre> code code <pre> How to do this in python? I make also intensive use of < pre> tags so substituting all '\n' with '' is not an option. What's the best way to do that?
[ "You could use re.sub(\">\\s*<\",\"><\",\"[here your html string]\").\nMaybe string.replace(\">\\n\",\">\"), i.e. look for an enclosing bracket and a newline and remove the newline.\n", "I would choose to use the python regex:\nstring.replace(\">\\s+<\",\"><\")\n\nWhere the '\\s' finds any whitespace character and the '+' after it shows it matches one or more whitespace characters. This removes the possibility of the replace replacing\n<pre>\n code\n code\n<pre>\n\nwith \n<pre><pre>\n\nMore information about regular expressions can be found here, here and here. \n" ]
[ 6, 2 ]
[]
[]
[ "html", "python", "regex" ]
stackoverflow_0003093802_html_python_regex.txt
Q: is ready made vmware images good for python website development I tried a lot and was not able to set python with django and wastd full day. I just found this http://bitnami.org/stack/djangostack Is that good for development and alos does it has mod_wsgi enabled on apache. I want to make sure that , everything is ok , so that i can start building app on this IF there are any other alternatives A: http://www.instantdjango.com is a good click-and-go dev stack for Windows users. It bundles Python which is otherwise 80% of the hassle. I suggest you be cautious when you deploy to a server though as a Django install on Linux may differ... But that's a problem you've got some time to think about.
is ready made vmware images good for python website development
I tried a lot and was not able to set python with django and wastd full day. I just found this http://bitnami.org/stack/djangostack Is that good for development and alos does it has mod_wsgi enabled on apache. I want to make sure that , everything is ok , so that i can start building app on this IF there are any other alternatives
[ "http://www.instantdjango.com is a good click-and-go dev stack for Windows users. It bundles Python which is otherwise 80% of the hassle.\nI suggest you be cautious when you deploy to a server though as a Django install on Linux may differ... But that's a problem you've got some time to think about.\n" ]
[ 0 ]
[]
[]
[ "python", "vmware" ]
stackoverflow_0003092907_python_vmware.txt
Q: How to run a clean up when terminating Python script I have a python script that does some jobs. I use multiprocessing.Pool to have a few workers do some commands for me. My problem is when I try to terminate the script. When I press Ctrl-C, I would like, that every worker immediately cleans up its experiment (which is some custom code, or actually even a subprocess command, not just releasing locks or memory) and stops. I know that I can catch Ctrl-C with the signal handler. How can I make all current running workers of a multiprocessing.Pool to terminate, still doing their cleanup command? Pool.terminate() will not be useful, because the processes will be terminated without cleaning up. A: How about trying the atexit standard module? It allows you to register a function that will be executed upon termination. A: Are you working with Unix? If yes, why not catch SIGTERM in the subprocesses? In fact, the documentation of Process.terminate() reads: Terminate the process. On Unix this is done using the SIGTERM signal (I have not tested this.)
How to run a clean up when terminating Python script
I have a python script that does some jobs. I use multiprocessing.Pool to have a few workers do some commands for me. My problem is when I try to terminate the script. When I press Ctrl-C, I would like, that every worker immediately cleans up its experiment (which is some custom code, or actually even a subprocess command, not just releasing locks or memory) and stops. I know that I can catch Ctrl-C with the signal handler. How can I make all current running workers of a multiprocessing.Pool to terminate, still doing their cleanup command? Pool.terminate() will not be useful, because the processes will be terminated without cleaning up.
[ "How about trying the atexit standard module?\nIt allows you to register a function that will be executed upon termination.\n", "Are you working with Unix? If yes, why not catch SIGTERM in the subprocesses? In fact, the documentation of Process.terminate() reads:\nTerminate the process. On Unix this is done using the SIGTERM signal\n\n(I have not tested this.)\n" ]
[ 2, 0 ]
[]
[]
[ "multiprocessing", "python", "terminate" ]
stackoverflow_0003090661_multiprocessing_python_terminate.txt
Q: Dynamically set inheritance in Python I have class A that is supposed to inherit class B whose name is not yet known at the time of A being written. Is it possible to declare A not inheriting anything, and add B as the base class during A's instantiation? Example: First file class B: def __init__(self): self.__name = "Class B" def name(self): return self.__name Second file class A: def __init__(self): self.__name = "Class A" # At some point here, the appropriate module name and location is discovered import sys sys.path.append(CustomModulePath) B = __import__(CustomModuleName) magic(A, B) # TODO What should magic() do? a = A() print a.name() # This will now print "Class A", since name() is defined in B. A: Yeah, you can accomplish this with metaclasses. It's not the easiest topic to wrap your head around but it'll do the job. There's a Stack Overflow question about them that looks like it has some good information and I also found an IBM article that might help as well. Somewhere in the official Python documentation, there's a section about them but I can't recall exactly where offhand.
Dynamically set inheritance in Python
I have class A that is supposed to inherit class B whose name is not yet known at the time of A being written. Is it possible to declare A not inheriting anything, and add B as the base class during A's instantiation? Example: First file class B: def __init__(self): self.__name = "Class B" def name(self): return self.__name Second file class A: def __init__(self): self.__name = "Class A" # At some point here, the appropriate module name and location is discovered import sys sys.path.append(CustomModulePath) B = __import__(CustomModuleName) magic(A, B) # TODO What should magic() do? a = A() print a.name() # This will now print "Class A", since name() is defined in B.
[ "Yeah, you can accomplish this with metaclasses. It's not the easiest topic to wrap your head around but it'll do the job. There's a Stack Overflow question about them that looks like it has some good information and I also found an IBM article that might help as well. Somewhere in the official Python documentation, there's a section about them but I can't recall exactly where offhand. \n" ]
[ 2 ]
[]
[]
[ "inheritance", "python" ]
stackoverflow_0003094265_inheritance_python.txt
Q: determining if process has terminated successfully I have some code to execute the unix shell command in background in python import subprocess process = subprocess.Popen('find / > tmp.txt &',shell=True) I need to capture the scenario where i come to know that process has finished successful completion . Please explain with sample code Tazim A: There is no need for the &: the command is launched in a separate process, and runs independently. If you want to wait until the process terminates, use wait(): process = subprocess.Popen('find / > tmp.txt', shell = True) exitcode = process.wait() if exitcode == 0: # successful completion else: # error happened If your program can do something meaningful in the meantime, you can use poll() to determine if the process has finished. Furthermore, instead of writing the output to a temporary file and then reading it from your Python program, you can read from the pipe directly. See the subprocess documentation for details. A: Don't use shell=True. It is bad for your health. proc = subprocess.Popen(['find', '/'], stdout=open('tmp.txt', 'w')) if proc.wait() == 0: pass If you really need a file, use import tempfile instead of a hard-coded temporary file name. If you don't need the file, use a pipe (see the subprocess docs as Thomas suggests). Also, don't write shell scripts in Python. Use the os.walk function instead.
determining if process has terminated successfully
I have some code to execute the unix shell command in background in python import subprocess process = subprocess.Popen('find / > tmp.txt &',shell=True) I need to capture the scenario where i come to know that process has finished successful completion . Please explain with sample code Tazim
[ "There is no need for the &: the command is launched in a separate process, and runs independently.\nIf you want to wait until the process terminates, use wait():\nprocess = subprocess.Popen('find / > tmp.txt', shell = True)\nexitcode = process.wait()\nif exitcode == 0:\n # successful completion\nelse:\n # error happened\n\nIf your program can do something meaningful in the meantime, you can use poll() to determine if the process has finished.\nFurthermore, instead of writing the output to a temporary file and then reading it from your Python program, you can read from the pipe directly. See the subprocess documentation for details.\n", "Don't use shell=True. It is bad for your health.\nproc = subprocess.Popen(['find', '/'], stdout=open('tmp.txt', 'w'))\nif proc.wait() == 0:\n pass\n\nIf you really need a file, use import tempfile instead of a hard-coded temporary file name. If you don't need the file, use a pipe (see the subprocess docs as Thomas suggests).\nAlso, don't write shell scripts in Python. Use the os.walk function instead.\n" ]
[ 4, 2 ]
[]
[]
[ "bash", "python", "unix" ]
stackoverflow_0003084214_bash_python_unix.txt
Q: Quickest language to make a little 'Connect to a SSL webpage' script I just need some advice. I already know how to play with bash, ruby, python and perl and I'd like to know: with which of them would it be faster to make a little script that would connect to a website with SSL and login. I just need to do this script and make a cron job with it. So it must be executable from the console. Thanks. NB: If you have any example script, it'd be awesome :) A: I don't know about the others so can't compare, but in Perl, it's quick and easy with WWW::Mechanize or LWP A: You could look at Scrubyt if you are familiar with ruby. an example from http://github.com/scrubber/scrubyt_examples/blob/master/ebay.rb #simple ebay example require 'rubygems' require 'scrubyt' ebay_data = Scrubyt::Extractor.define do fetch 'http://www.ebay.com/' fill_textfield 'satitle', 'ipod' submit record "//table[@class='nol']" do name "//td[@class='details']/div/a" end end puts ebay_data.to_xml
Quickest language to make a little 'Connect to a SSL webpage' script
I just need some advice. I already know how to play with bash, ruby, python and perl and I'd like to know: with which of them would it be faster to make a little script that would connect to a website with SSL and login. I just need to do this script and make a cron job with it. So it must be executable from the console. Thanks. NB: If you have any example script, it'd be awesome :)
[ "I don't know about the others so can't compare, but in Perl, it's quick and easy with WWW::Mechanize or LWP\n", "You could look at Scrubyt if you are familiar with ruby.\nan example from http://github.com/scrubber/scrubyt_examples/blob/master/ebay.rb\n#simple ebay example\n\nrequire 'rubygems'\nrequire 'scrubyt'\n\nebay_data = Scrubyt::Extractor.define do\n\n fetch 'http://www.ebay.com/'\n fill_textfield 'satitle', 'ipod'\n submit\n\n record \"//table[@class='nol']\" do\n name \"//td[@class='details']/div/a\"\n end\nend\n\nputs ebay_data.to_xml\n\n" ]
[ 5, 2 ]
[]
[]
[ "bash", "perl", "python", "ruby", "ssl" ]
stackoverflow_0003094138_bash_perl_python_ruby_ssl.txt
Q: Google App Engine django model form does not pick up BlobProperty I have the following model: class Image(db.Model): auction = db.ReferenceProperty(Auction) image = db.BlobProperty() thumb = db.BlobProperty() caption = db.StringProperty() item_to_tag = db.StringProperty() And the following form: class ImageForm(djangoforms.ModelForm): class Meta: model = Image When I call ImageForm(), only the non-Blob fields are created, like this: <tr><th><label for="id_auction">Auction:</label></th><td><select name="auction" id="id_auction"> <option value="" selected="selected">---------</option> <option value="ahRoYXJ0bWFuYXVjdGlvbmVlcmluZ3INCxIHQXVjdGlvbhgKDA">2010-06-19 11:00:00</option> </select></td></tr> <tr><th><label for="id_caption">Caption:</label></th><td><input type="text" name="caption" id="id_caption" /></td></tr> <tr><th><label for="id_item_to_tag">Item to tag:</label></th><td><input type="text" name="item_to_tag" id="id_item_to_tag" /></td></tr> I expect the Blob fields to be included in the form as well (as file inputs). What am I doing wrong? A: I think my problem hinges on the fact that Django does not support blobs, so the BlobProperty is simply ignored when generating Django forms. A: You can use the widgets attribute to define the field type used for your blob properties: class ImageForm(djangoforms.ModelForm): class Meta: model = Image widgets = { 'image': djangoforms.FileInput(), 'thumb': djangoforms.FileInput(), }
Google App Engine django model form does not pick up BlobProperty
I have the following model: class Image(db.Model): auction = db.ReferenceProperty(Auction) image = db.BlobProperty() thumb = db.BlobProperty() caption = db.StringProperty() item_to_tag = db.StringProperty() And the following form: class ImageForm(djangoforms.ModelForm): class Meta: model = Image When I call ImageForm(), only the non-Blob fields are created, like this: <tr><th><label for="id_auction">Auction:</label></th><td><select name="auction" id="id_auction"> <option value="" selected="selected">---------</option> <option value="ahRoYXJ0bWFuYXVjdGlvbmVlcmluZ3INCxIHQXVjdGlvbhgKDA">2010-06-19 11:00:00</option> </select></td></tr> <tr><th><label for="id_caption">Caption:</label></th><td><input type="text" name="caption" id="id_caption" /></td></tr> <tr><th><label for="id_item_to_tag">Item to tag:</label></th><td><input type="text" name="item_to_tag" id="id_item_to_tag" /></td></tr> I expect the Blob fields to be included in the form as well (as file inputs). What am I doing wrong?
[ "I think my problem hinges on the fact that Django does not support blobs, so the BlobProperty is simply ignored when generating Django forms.\n", "You can use the widgets attribute to define the field type used for your blob properties:\nclass ImageForm(djangoforms.ModelForm):\nclass Meta:\n model = Image\n widgets = { \n 'image': djangoforms.FileInput(),\n 'thumb': djangoforms.FileInput(),\n } \n\n" ]
[ 1, 0 ]
[]
[]
[ "django_forms", "google_app_engine", "python" ]
stackoverflow_0003033945_django_forms_google_app_engine_python.txt
Q: Python Glade could not create GladeXML Object I've created a simple window GUI in Glade 3.6.7 and I am trying to import it into Python. Every time I try to do so I get the following error: (queryrelevanceevaluation.py:8804): libglade-WARNING **: Expected <glade-interface>. Got <interface>. (queryrelevanceevaluation.py:8804): libglade-WARNING **: did not finish in PARSER_FINISH state Traceback (most recent call last): File "queryrelevanceevaluation.py", line 17, in <module> app = QueryRelevanceEvaluationApp() File "queryrelevanceevaluation.py", line 10, in __init__ self.widgets = gtk.glade.XML(gladefile) RuntimeError: could not create GladeXML object My Python Code: #!/usr/bin/env python import gtk import gtk.glade class QueryRelevanceEvaluationApp: def __init__(self): gladefile = "foo.glade" self.widgets = gtk.glade.XML(gladefile) dic = {"on_buttonGenerate_clicked" : self.on_buttonGenerate_clicked} self.widgets.signal_autoconnect(dic) def on_buttonGenerate_clicked(self, widget): print "You clicked the button" app = QueryRelevanceEvaluationApp() gtk.main() And the foo.glade file: <?xml version="1.0"?> <interface> <requires lib="gtk+" version="2.16"/> <!-- interface-naming-policy project-wide --> <object class="GtkWindow" id="windowRelevanceEvaluation"> <property name="visible">True</property> <property name="title" translatable="yes">Query Result Relevance Evaluation</property> <child> <object class="GtkVBox" id="vbox1"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkHBox" id="hbox2"> <property name="visible">True</property> <child> <object class="GtkLabel" id="labelQuery"> <property name="visible">True</property> <property name="label" translatable="yes">Query:</property> </object> <packing> <property name="expand">False</property> <property name="padding">4</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkEntry" id="entry1"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="invisible_char">&#x25CF;</property> </object> <packing> <property name="padding">4</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkFrame" id="frameSource"> <property name="visible">True</property> <property name="label_xalign">0</property> <child> <object class="GtkAlignment" id="alignment1"> <property name="visible">True</property> <property name="left_padding">12</property> <child> <object class="GtkHButtonBox" id="hbuttonbox1"> <property name="visible">True</property> <child> <object class="GtkRadioButton" id="radiobuttonGoogle"> <property name="label" translatable="yes">Google</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="active">True</property> <property name="draw_indicator">True</property> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkRadioButton" id="radiobuttonBing"> <property name="label" translatable="yes">Bing</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="active">True</property> <property name="draw_indicator">True</property> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">1</property> </packing> </child> <child> <object class="GtkRadioButton" id="radiobuttonBoden"> <property name="label" translatable="yes">Boden</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="active">True</property> <property name="draw_indicator">True</property> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">2</property> </packing> </child> <child> <object class="GtkRadioButton" id="radiobuttonCSV"> <property name="label" translatable="yes">CSV</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="active">True</property> <property name="draw_indicator">True</property> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">3</property> </packing> </child> </object> </child> </object> </child> <child type="label"> <object class="GtkLabel" id="labelFrameSource"> <property name="visible">True</property> <property name="label" translatable="yes">&lt;b&gt;Source&lt;/b&gt;</property> <property name="use_markup">True</property> </object> </child> </object> <packing> <property name="position">1</property> </packing> </child> <child> <object class="GtkFrame" id="frame1"> <property name="visible">True</property> <property name="label_xalign">0</property> <child> <object class="GtkHBox" id="hbox3"> <property name="visible">True</property> <child> <object class="GtkLabel" id="labelResults"> <property name="visible">True</property> <property name="label" translatable="yes">Number Results:</property> </object> <packing> <property name="expand">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkSpinButton" id="spinbuttonResults"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="invisible_char">&#x25CF;</property> </object> <packing> <property name="padding">4</property> <property name="position">1</property> </packing> </child> </object> </child> <child type="label"> <object class="GtkLabel" id="labelFrameResults"> <property name="visible">True</property> <property name="label" translatable="yes">&lt;b&gt;Results&lt;/b&gt;</property> <property name="use_markup">True</property> </object> </child> </object> <packing> <property name="padding">2</property> <property name="position">2</property> </packing> </child> <child> <object class="GtkButton" id="buttonGenerateResults"> <property name="label" translatable="yes">Generate!</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> </object> <packing> <property name="position">3</property> </packing> </child> </object> </child> </object> </interface> foo.glade and the above python script are in the same directory, and I have tried using a fully-qualified path but still get the same error (I am certain that the path is correct!). Any ideas? Cheers, Pete A: You have created a GtkBuilder file instead of Glade file. You can use GtkBuilder as follow: builder = gtk.Builder() builder.add_from_string(string, len(string)) builder.connect_signals(anobject) builder.get_object(name) EDIT: When you start a new project in glade it asks you if you want create a glade file or a GtkBuilder file, which is new and more flexible. Try the builder file with the following code: #!/usr/bin/env python import gtk class QueryRelevanceEvaluationApp: def __init__(self): filename = "foo.glade" builder = gtk.Builder() builder.add_from_file(filename) builder.connect_signals(self) def on_buttonGenerate_clicked(self, widget): print "You clicked the button" app = QueryRelevanceEvaluationApp() gtk.main() EDIT2: Beware that i cannot see any handler in your GtkBuilder file A: I had the same problem Pete mentioned. After the answer that mg gave, what I did is to save the .glade file in a liblgade format instead of GTKBuilder. On the Save As.. dialog box, at the bottom you have the option "File Format" click on "liblglade" and voila!!!!
Python Glade could not create GladeXML Object
I've created a simple window GUI in Glade 3.6.7 and I am trying to import it into Python. Every time I try to do so I get the following error: (queryrelevanceevaluation.py:8804): libglade-WARNING **: Expected <glade-interface>. Got <interface>. (queryrelevanceevaluation.py:8804): libglade-WARNING **: did not finish in PARSER_FINISH state Traceback (most recent call last): File "queryrelevanceevaluation.py", line 17, in <module> app = QueryRelevanceEvaluationApp() File "queryrelevanceevaluation.py", line 10, in __init__ self.widgets = gtk.glade.XML(gladefile) RuntimeError: could not create GladeXML object My Python Code: #!/usr/bin/env python import gtk import gtk.glade class QueryRelevanceEvaluationApp: def __init__(self): gladefile = "foo.glade" self.widgets = gtk.glade.XML(gladefile) dic = {"on_buttonGenerate_clicked" : self.on_buttonGenerate_clicked} self.widgets.signal_autoconnect(dic) def on_buttonGenerate_clicked(self, widget): print "You clicked the button" app = QueryRelevanceEvaluationApp() gtk.main() And the foo.glade file: <?xml version="1.0"?> <interface> <requires lib="gtk+" version="2.16"/> <!-- interface-naming-policy project-wide --> <object class="GtkWindow" id="windowRelevanceEvaluation"> <property name="visible">True</property> <property name="title" translatable="yes">Query Result Relevance Evaluation</property> <child> <object class="GtkVBox" id="vbox1"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkHBox" id="hbox2"> <property name="visible">True</property> <child> <object class="GtkLabel" id="labelQuery"> <property name="visible">True</property> <property name="label" translatable="yes">Query:</property> </object> <packing> <property name="expand">False</property> <property name="padding">4</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkEntry" id="entry1"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="invisible_char">&#x25CF;</property> </object> <packing> <property name="padding">4</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkFrame" id="frameSource"> <property name="visible">True</property> <property name="label_xalign">0</property> <child> <object class="GtkAlignment" id="alignment1"> <property name="visible">True</property> <property name="left_padding">12</property> <child> <object class="GtkHButtonBox" id="hbuttonbox1"> <property name="visible">True</property> <child> <object class="GtkRadioButton" id="radiobuttonGoogle"> <property name="label" translatable="yes">Google</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="active">True</property> <property name="draw_indicator">True</property> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkRadioButton" id="radiobuttonBing"> <property name="label" translatable="yes">Bing</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="active">True</property> <property name="draw_indicator">True</property> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">1</property> </packing> </child> <child> <object class="GtkRadioButton" id="radiobuttonBoden"> <property name="label" translatable="yes">Boden</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="active">True</property> <property name="draw_indicator">True</property> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">2</property> </packing> </child> <child> <object class="GtkRadioButton" id="radiobuttonCSV"> <property name="label" translatable="yes">CSV</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="active">True</property> <property name="draw_indicator">True</property> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">3</property> </packing> </child> </object> </child> </object> </child> <child type="label"> <object class="GtkLabel" id="labelFrameSource"> <property name="visible">True</property> <property name="label" translatable="yes">&lt;b&gt;Source&lt;/b&gt;</property> <property name="use_markup">True</property> </object> </child> </object> <packing> <property name="position">1</property> </packing> </child> <child> <object class="GtkFrame" id="frame1"> <property name="visible">True</property> <property name="label_xalign">0</property> <child> <object class="GtkHBox" id="hbox3"> <property name="visible">True</property> <child> <object class="GtkLabel" id="labelResults"> <property name="visible">True</property> <property name="label" translatable="yes">Number Results:</property> </object> <packing> <property name="expand">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkSpinButton" id="spinbuttonResults"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="invisible_char">&#x25CF;</property> </object> <packing> <property name="padding">4</property> <property name="position">1</property> </packing> </child> </object> </child> <child type="label"> <object class="GtkLabel" id="labelFrameResults"> <property name="visible">True</property> <property name="label" translatable="yes">&lt;b&gt;Results&lt;/b&gt;</property> <property name="use_markup">True</property> </object> </child> </object> <packing> <property name="padding">2</property> <property name="position">2</property> </packing> </child> <child> <object class="GtkButton" id="buttonGenerateResults"> <property name="label" translatable="yes">Generate!</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> </object> <packing> <property name="position">3</property> </packing> </child> </object> </child> </object> </interface> foo.glade and the above python script are in the same directory, and I have tried using a fully-qualified path but still get the same error (I am certain that the path is correct!). Any ideas? Cheers, Pete
[ "You have created a GtkBuilder file instead of Glade file.\nYou can use GtkBuilder as follow:\nbuilder = gtk.Builder()\nbuilder.add_from_string(string, len(string))\nbuilder.connect_signals(anobject)\nbuilder.get_object(name)\n\nEDIT:\nWhen you start a new project in glade it asks you if you want create a glade file or a GtkBuilder file, which is new and more flexible.\nTry the builder file with the following code:\n#!/usr/bin/env python\n\nimport gtk\n\nclass QueryRelevanceEvaluationApp:\n\n def __init__(self):\n filename = \"foo.glade\"\n builder = gtk.Builder()\n builder.add_from_file(filename)\n builder.connect_signals(self)\n\n def on_buttonGenerate_clicked(self, widget):\n print \"You clicked the button\"\n\napp = QueryRelevanceEvaluationApp()\ngtk.main()\n\nEDIT2:\nBeware that i cannot see any handler in your GtkBuilder file\n", "I had the same problem Pete mentioned. After the answer that mg gave, what I did is to save the .glade file in a liblgade format instead of GTKBuilder. On the Save As.. dialog box, at the bottom you have the option \"File Format\" click on \"liblglade\" and voila!!!!\n" ]
[ 23, 5 ]
[]
[]
[ "exception", "glade", "python", "user_interface" ]
stackoverflow_0002668618_exception_glade_python_user_interface.txt
Q: Segmentation fault while embedding python in ubuntu I have an application where I'm embedding python. It was developed on windows where it works fine, but now I'm porting it to linux with less success where it crashes in Py_Initialize(). From gdb, it seems to happen when loading the os module. gdb reports this callstack on seg fault: #0 0x002384fc in import_submodule (mod=None, subname=0xb7d8a9bb "os", fullname=0xb7d8a9bb "os") at ../Python/import.c:2551 #1 0x0023893c in load_next (mod=<value optimized out>, altmod=<value optimized out>, p_name=0xb7d8a9ac, buf=0xb7d8a9bb "os", p_buflen=0xb7d8a9b4) at ../Python/import.c:2411 //.... etc...: #65 0x002439de in Py_Initialize () at ../Python/pythonrun.c:361 source code of import_submodule in Python/import.c (downloaded from 2.6.5 python): static PyObject * import_submodule(PyObject *mod, char *subname, char *fullname) { //***************** THIS IS LINE 2551*************************** PyObject *modules = PyImport_GetModuleDict(); PyObject *m = NULL; /* Require: if mod == None: subname == fullname else: mod.__name__ + "." + subname == fullname */ if ((m = PyDict_GetItemString(modules, fullname)) != NULL) { Py_INCREF(m); } else { PyObject *path, *loader = NULL; char buf[MAXPATHLEN+1]; struct filedescr *fdp; FILE *fp = NULL; if (mod == Py_None) path = NULL; else { path = PyObject_GetAttrString(mod, "__path__"); if (path == NULL) { PyErr_Clear(); Py_INCREF(Py_None); return Py_None; } } buf[0] = '\0'; fdp = find_module(fullname, subname, path, buf, MAXPATHLEN+1, &fp, &loader); Py_XDECREF(path); if (fdp == NULL) { if (!PyErr_ExceptionMatches(PyExc_ImportError)) return NULL; PyErr_Clear(); Py_INCREF(Py_None); return Py_None; } m = load_module(fullname, fp, buf, fdp->type, loader); Py_XDECREF(loader); if (fp) fclose(fp); if (!add_submodule(mod, m, fullname, subname, modules)) { Py_XDECREF(m); m = NULL; } } return m; } Disassembly + part source + breakpoint: 2550 import_submodule(PyObject *mod, char *subname, char *fullname) 2551 { 0x002384f0 <+0>: push %ebp 0x002384f1 <+1>: mov %esp,%ebp 0x002384f3 <+3>: sub $0x1058,%esp 0x002384f9 <+9>: mov %ebx,-0xc(%ebp) => 0x002384fc <+12>: call 0x174787 <__i686.get_pc_thunk.bx> 0x00238501 <+17>: add $0x112af3,%ebx 0x00238507 <+23>: mov %esi,-0x8(%ebp) 0x0023850a <+26>: mov 0x8(%ebp),%esi 0x0023850d <+29>: mov %edi,-0x4(%ebp) 0x00238510 <+32>: mov %eax,-0x102c(%ebp) 0x00238516 <+38>: mov %edx,-0x1030(%ebp) 0x0023851c <+44>: mov %gs:0x14,%eax What's happening here? Apparently some code from libpython2.6.so is loaded and run. A: Try setting the Python home with Py_SetPythonHome before calling Py_Initialize. Start with hardcoded complete path to the python directory. Also make sure you are not mixing debug & release versions. Py_GetPath is a good API to see where all python is looking for modules - but dont know if it can be called before Py_Initialize. char pySearchPath[] = "/users/abc/Python26"; Py_SetPythonHome(pySearchPath); Py_Initialize(); PyRun_SimpleString("from time import time,ctime\n" "print 'Today is',ctime(time())\n"); cerr << Py_GetPath() << endl;
Segmentation fault while embedding python in ubuntu
I have an application where I'm embedding python. It was developed on windows where it works fine, but now I'm porting it to linux with less success where it crashes in Py_Initialize(). From gdb, it seems to happen when loading the os module. gdb reports this callstack on seg fault: #0 0x002384fc in import_submodule (mod=None, subname=0xb7d8a9bb "os", fullname=0xb7d8a9bb "os") at ../Python/import.c:2551 #1 0x0023893c in load_next (mod=<value optimized out>, altmod=<value optimized out>, p_name=0xb7d8a9ac, buf=0xb7d8a9bb "os", p_buflen=0xb7d8a9b4) at ../Python/import.c:2411 //.... etc...: #65 0x002439de in Py_Initialize () at ../Python/pythonrun.c:361 source code of import_submodule in Python/import.c (downloaded from 2.6.5 python): static PyObject * import_submodule(PyObject *mod, char *subname, char *fullname) { //***************** THIS IS LINE 2551*************************** PyObject *modules = PyImport_GetModuleDict(); PyObject *m = NULL; /* Require: if mod == None: subname == fullname else: mod.__name__ + "." + subname == fullname */ if ((m = PyDict_GetItemString(modules, fullname)) != NULL) { Py_INCREF(m); } else { PyObject *path, *loader = NULL; char buf[MAXPATHLEN+1]; struct filedescr *fdp; FILE *fp = NULL; if (mod == Py_None) path = NULL; else { path = PyObject_GetAttrString(mod, "__path__"); if (path == NULL) { PyErr_Clear(); Py_INCREF(Py_None); return Py_None; } } buf[0] = '\0'; fdp = find_module(fullname, subname, path, buf, MAXPATHLEN+1, &fp, &loader); Py_XDECREF(path); if (fdp == NULL) { if (!PyErr_ExceptionMatches(PyExc_ImportError)) return NULL; PyErr_Clear(); Py_INCREF(Py_None); return Py_None; } m = load_module(fullname, fp, buf, fdp->type, loader); Py_XDECREF(loader); if (fp) fclose(fp); if (!add_submodule(mod, m, fullname, subname, modules)) { Py_XDECREF(m); m = NULL; } } return m; } Disassembly + part source + breakpoint: 2550 import_submodule(PyObject *mod, char *subname, char *fullname) 2551 { 0x002384f0 <+0>: push %ebp 0x002384f1 <+1>: mov %esp,%ebp 0x002384f3 <+3>: sub $0x1058,%esp 0x002384f9 <+9>: mov %ebx,-0xc(%ebp) => 0x002384fc <+12>: call 0x174787 <__i686.get_pc_thunk.bx> 0x00238501 <+17>: add $0x112af3,%ebx 0x00238507 <+23>: mov %esi,-0x8(%ebp) 0x0023850a <+26>: mov 0x8(%ebp),%esi 0x0023850d <+29>: mov %edi,-0x4(%ebp) 0x00238510 <+32>: mov %eax,-0x102c(%ebp) 0x00238516 <+38>: mov %edx,-0x1030(%ebp) 0x0023851c <+44>: mov %gs:0x14,%eax What's happening here? Apparently some code from libpython2.6.so is loaded and run.
[ "Try setting the Python home with Py_SetPythonHome before calling Py_Initialize. Start with hardcoded complete path to the python directory. Also make sure you are not mixing debug & release versions. Py_GetPath is a good API to see where all python is looking for modules - but dont know if it can be called before Py_Initialize. \n char pySearchPath[] = \"/users/abc/Python26\";\n Py_SetPythonHome(pySearchPath);\n Py_Initialize();\n PyRun_SimpleString(\"from time import time,ctime\\n\"\n \"print 'Today is',ctime(time())\\n\");\n cerr << Py_GetPath() << endl;\n\n" ]
[ 2 ]
[]
[]
[ "debugging", "linux", "python", "shared_libraries" ]
stackoverflow_0003094166_debugging_linux_python_shared_libraries.txt
Q: How does import keyword in python actually work? Let's say I have 3 files: a.py from d import d class a: def type(self): return "a" def test(self): try: x = b() except: print "EXCEPT IN A" from b import b x = b() return x.type() b.py import sys class b: def __init__(self): if "a" not in sys.modules: print "Importing a!" from a import a pass def type(self): return "b" def test(self): for modules in sys.modules: print modules x = a() return x.type() c.py from b import b import sys x = b() print x.test() and run python c.py Python comes back complaining: NameError: global name 'a' is not defined But, a IS in sys.modules: copy_reg sre_compile locale _sre functools encodings site __builtin__ operator __main__ types encodings.encodings abc errno encodings.codecs sre_constants re _abcoll ntpath _codecs nt _warnings genericpath stat zipimport encodings.__builtin__ warnings UserDict encodings.cp1252 sys a codecs os.path _functools _locale b d signal linecache encodings.aliases exceptions sre_parse os And I can alter b.py such that: x = a() changes to x = sys.modules["a"].a() And python will happily run that. A couple questions arise from this: Why does python say it doesn't know what a is, when it is in sys.modules? Is using sys.modules a "proper" way to access class and function definitions? What is the "right" way to import modules? ie from module import x or import module A: I guess it's a problem of scoping, if you import a module in your constructor you can only use it in your constructor, after the import statement. A: According to the Python documentation, Import statements are executed in two steps: (1) find a module, and initialize it if necessary; (2) define a name or names in the local namespace (of the scope where the import statement occurs). So the problem is that even though module a has been imported, the name a has only been bound in the scope of the b.__init__ method, not the entire scope of b.py. So in the b.test method, there is no such name a, and so you get a NameError. You might want to read this article on importing Python modules, as it helps to explain best practices for working with imports. A: In your case, a is in sys.modules.. but not everything in sys.modules is in b's scope. If you want to use re, you'd have to import that as well. Conditional importing is occasionally acceptable, but this isn't one of those occasions. For one thing, the circular dependency between a and b in this case is unfortunate, and should be avoided (lots of patterns for doing so in Fowler's Refactoring).. That said, there's no need to conditionally import here. b ought to simply import a. What were you trying to avoid by not importing it directly at the top of the file? A: It is bad style to conditionally import code modules based on program logic. A name should always mean the same thing everywhere in your code. Think about how confusing this would be to debug: if (something) from office import desk else from home import desk ... somewhere later in the code... desk() Even if you don't have scoping issues (which you most likely will have), it's still confusing. Put all your import statements at the top of your file. That's where other coders will look for them. As far as whether to use "from foo import bar" verses just "import foo", the tradeoff is more typing (having to type "foo.bar()" or just type "bar()") verses clearness and specificity. If you want your code to be really readable and unambiguous, just say "import foo" and fully specify the call everywhere. Remember, it's much harder to read code than it is to write it.
How does import keyword in python actually work?
Let's say I have 3 files: a.py from d import d class a: def type(self): return "a" def test(self): try: x = b() except: print "EXCEPT IN A" from b import b x = b() return x.type() b.py import sys class b: def __init__(self): if "a" not in sys.modules: print "Importing a!" from a import a pass def type(self): return "b" def test(self): for modules in sys.modules: print modules x = a() return x.type() c.py from b import b import sys x = b() print x.test() and run python c.py Python comes back complaining: NameError: global name 'a' is not defined But, a IS in sys.modules: copy_reg sre_compile locale _sre functools encodings site __builtin__ operator __main__ types encodings.encodings abc errno encodings.codecs sre_constants re _abcoll ntpath _codecs nt _warnings genericpath stat zipimport encodings.__builtin__ warnings UserDict encodings.cp1252 sys a codecs os.path _functools _locale b d signal linecache encodings.aliases exceptions sre_parse os And I can alter b.py such that: x = a() changes to x = sys.modules["a"].a() And python will happily run that. A couple questions arise from this: Why does python say it doesn't know what a is, when it is in sys.modules? Is using sys.modules a "proper" way to access class and function definitions? What is the "right" way to import modules? ie from module import x or import module
[ "I guess it's a problem of scoping, if you import a module in your constructor you can only use it in your constructor, after the import statement.\n", "According to the Python documentation,\n\nImport statements are executed in two steps: (1) find a module, and initialize it if necessary; (2) define a name or names in the local namespace (of the scope where the import statement occurs). \n\nSo the problem is that even though module a has been imported, the name a has only been bound in the scope of the b.__init__ method, not the entire scope of b.py. So in the b.test method, there is no such name a, and so you get a NameError.\nYou might want to read this article on importing Python modules, as it helps to explain best practices for working with imports.\n", "In your case, a is in sys.modules.. but not everything in sys.modules is in b's scope. If you want to use re, you'd have to import that as well.\nConditional importing is occasionally acceptable, but this isn't one of those occasions. For one thing, the circular dependency between a and b in this case is unfortunate, and should be avoided (lots of patterns for doing so in Fowler's Refactoring).. That said, there's no need to conditionally import here.\nb ought to simply import a. What were you trying to avoid by not importing it directly at the top of the file?\n", "It is bad style to conditionally import code modules based on program logic. A name should always mean the same thing everywhere in your code. Think about how confusing this would be to debug:\nif (something)\n from office import desk\nelse\n from home import desk\n\n... somewhere later in the code...\ndesk()\n\nEven if you don't have scoping issues (which you most likely will have), it's still confusing.\nPut all your import statements at the top of your file. That's where other coders will look for them.\nAs far as whether to use \"from foo import bar\" verses just \"import foo\", the tradeoff is more typing (having to type \"foo.bar()\" or just type \"bar()\") verses clearness and specificity. If you want your code to be really readable and unambiguous, just say \"import foo\" and fully specify the call everywhere. Remember, it's much harder to read code than it is to write it.\n" ]
[ 3, 2, 1, 0 ]
[]
[]
[ "import", "module", "python" ]
stackoverflow_0003094506_import_module_python.txt
Q: how to load a big file and cut it into smaller files? I have file about 4MB (which i called as big one)...this file has about 160000 lines..in a specific format...and i need to cut them at regular interval(not at equal intervals) i.e at the end of a certain format and write the part into another file.. Basically,what i wanted is to copy the information for the big file into the many smaller files ...as i read the big file keep writing the information into one file and after the a certain pattern occurs then end this and starting writing for that line into another file... Normally, if it is a small file i guess it can be done dont know if i can perform file.readline() to read each line check if pattern end if not then write it to a file if patter end then change the file name open new file..so on but how to do it for this big file.. thanks in advance.. didnt mention the file format as i felt it is not neccesary will mention if required.. A: I would first read all of the allegedly-big file in memory as a list of lines: with open('socalledbig.txt', 'rt') as f: lines = f.readlines() should take little more than 4MB -- tiny even by the standard of today's phones, much less ordinary computers. Then, perform whatever processing you need to determine the beginning and ending of each group of lines you want to write out to a smaller files (I'm not sure by your question's text whether such groups can overlap or leave gaps, so I'm offering the most general solution where they're fully allowed to -- this will also cover more constrained use cases, with no real performance penalty, though code might be a tad simpler if the constraints were very rigid). Say that you put these numbers in lists starts (index from 0 of first line to write, included), ends (index from 0 of first line to NOT write -- may legitimately and innocuosly be len(lines) or more), names (filenames to which you want to write), all lists having the same length of course. Then, lastly: assert len(starts) == len(ends) == len(names) for s, e, n in zip(starts, ends, names): with open(n, 'wt') as f: f.writelines(lines[s:e]) ...and that's all you need to do! Edit: the OP seems to be confused by the concept of having these lists, so let me try to give an example: each block written out to a file starts at a line containing 'begin' (included) and ends at the first immediately succeeding line containing 'end' (also included), and the names of the files to be written are to be result0.txt, result1.txt, and so on. It's an error if the number of "closing ends" differ from that of "opening begins" (and remember, the first immediately succeeding "end" terminates all pending "begins"); no line is allowed to contain both 'begin' and 'end'. A very arbitrary set of conditions, to be sure, but then, the OP leaves us totally in the dark about the actual specifics of the problem, so what else can we do but guess most wildly?-) outfile = 0 starts = [] ends = [] names = [] for i, line in enumerate(lines): if 'begin' in line: if 'end' in line: raise ValueError('Both begin and end: %r' % line) starts.append(i) names.append('result%d.txt' % outfile) outfile += 1 elif 'end' in line: ends.append(i + 1) # remember ends are EXCLUDED, hence the +1 That's it -- the assert about the three lists having identical lengths will take care of checking that the constraints are respected. As the constraints and specs are changed, so of course will this snippet of code change accordingly -- as long as it fills the three equal-length lists starts, ends, and names, exactly how it does so matters not in the least to the rest of the code. A: A 4MB file is very small, it fits in memory for sure. The fastest approach would be to read it all and then iterate over each line searching for the pattern, writing out the line to the appropriate file depending on the pattern (your approach for small files.) A: I'm not going to get into the actual code, but pseudo code would do this. BIGFILE="filename" SMALLFILE="smallfile1" while(readline(bigfile)) { write(SMALLFILE, line) if(line matches pattern) { SMALLFILE="smallfile++" } } Which is really bad code, but maybe you get the point. I should also have said that it doesn't matter how big your file is since you have to read the file anyway.
how to load a big file and cut it into smaller files?
I have file about 4MB (which i called as big one)...this file has about 160000 lines..in a specific format...and i need to cut them at regular interval(not at equal intervals) i.e at the end of a certain format and write the part into another file.. Basically,what i wanted is to copy the information for the big file into the many smaller files ...as i read the big file keep writing the information into one file and after the a certain pattern occurs then end this and starting writing for that line into another file... Normally, if it is a small file i guess it can be done dont know if i can perform file.readline() to read each line check if pattern end if not then write it to a file if patter end then change the file name open new file..so on but how to do it for this big file.. thanks in advance.. didnt mention the file format as i felt it is not neccesary will mention if required..
[ "I would first read all of the allegedly-big file in memory as a list of lines:\nwith open('socalledbig.txt', 'rt') as f:\n lines = f.readlines()\n\nshould take little more than 4MB -- tiny even by the standard of today's phones, much less ordinary computers.\nThen, perform whatever processing you need to determine the beginning and ending of each group of lines you want to write out to a smaller files (I'm not sure by your question's text whether such groups can overlap or leave gaps, so I'm offering the most general solution where they're fully allowed to -- this will also cover more constrained use cases, with no real performance penalty, though code might be a tad simpler if the constraints were very rigid).\nSay that you put these numbers in lists starts (index from 0 of first line to write, included), ends (index from 0 of first line to NOT write -- may legitimately and innocuosly be len(lines) or more), names (filenames to which you want to write), all lists having the same length of course.\nThen, lastly:\nassert len(starts) == len(ends) == len(names)\n\nfor s, e, n in zip(starts, ends, names):\n with open(n, 'wt') as f:\n f.writelines(lines[s:e])\n\n...and that's all you need to do!\nEdit: the OP seems to be confused by the concept of having these lists, so let me try to give an example: each block written out to a file starts at a line containing 'begin' (included) and ends at the first immediately succeeding line containing 'end' (also included), and the names of the files to be written are to be result0.txt, result1.txt, and so on.\nIt's an error if the number of \"closing ends\" differ from that of \"opening begins\" (and remember, the first immediately succeeding \"end\" terminates all pending \"begins\"); no line is allowed to contain both 'begin' and 'end'.\nA very arbitrary set of conditions, to be sure, but then, the OP leaves us totally in the dark about the actual specifics of the problem, so what else can we do but guess most wildly?-)\noutfile = 0\nstarts = []\nends = []\nnames = []\nfor i, line in enumerate(lines):\n if 'begin' in line:\n if 'end' in line:\n raise ValueError('Both begin and end: %r' % line)\n starts.append(i)\n names.append('result%d.txt' % outfile)\n outfile += 1\n elif 'end' in line:\n ends.append(i + 1) # remember ends are EXCLUDED, hence the +1\n\nThat's it -- the assert about the three lists having identical lengths will take care of checking that the constraints are respected.\nAs the constraints and specs are changed, so of course will this snippet of code change accordingly -- as long as it fills the three equal-length lists starts, ends, and names, exactly how it does so matters not in the least to the rest of the code.\n", "A 4MB file is very small, it fits in memory for sure. The fastest approach would be to read it all and then iterate over each line searching for the pattern, writing out the line to the appropriate file depending on the pattern (your approach for small files.)\n", "I'm not going to get into the actual code, but pseudo code would do this.\nBIGFILE=\"filename\"\nSMALLFILE=\"smallfile1\"\nwhile(readline(bigfile)) {\n write(SMALLFILE, line)\n if(line matches pattern) {\n SMALLFILE=\"smallfile++\"\n }\n}\n\nWhich is really bad code, but maybe you get the point. I should also have said that it doesn't matter how big your file is since you have to read the file anyway.\n" ]
[ 2, 1, 0 ]
[]
[]
[ "file", "python" ]
stackoverflow_0003094618_file_python.txt
Q: does write mode create a new file if not existing? I'm trying to write to a file that does not already exist using a file context manager. a=open ('C:/c.txt' , 'w') The above does not succeed. How would I create a file for writing if it does already exist? A: Yes, 'w' is specified as creating a new file -- as the docs put it, 'w' for writing (truncating the file if it already exists), (clearly inferring it's allowed to not already exist). Please show the exact traceback, not just your own summary of it, as details matters -- e.g. if the actual path you're using is different, what's missing might be the drive, or some intermediate directory; or there might be permission problems. A: [Edited to reflect that the problem is likely not forward vs. back slash] If I understood correctly, you want the file to be automatically created for you, right? open in write mode does create the file for you. It would be more clear if you told us the exact error you're getting. It might be something like you not having permission to write in C:. I had previously suggested that it might be because of the forward slash, and indicated that the OP could try: a = open(r'C:\c.txt', 'w') Note the r before the file path, indicating raw mode (that is, the backslash won't be interpreted as special). However, as Brian Neal pointed out (as well as others, commenting elsewhere), that's likely not the reason for the error. I'm keeping it here simply for historical purposes. A: You most probably are trying to write to a directory that doesn't exist or one that you don't have permission writing to. If you want to write to C:\foo\bar\foobar.txt then make sure that you've got a C:\foo\bar\ that exists (and in case permissions work on Windows, make sure you've got the permission to write there). Now when you open the file in write mode, a file should be created. A: If you're asking how to be warned when the file doesn't exist, then you need to explicitly check for that. See here
does write mode create a new file if not existing?
I'm trying to write to a file that does not already exist using a file context manager. a=open ('C:/c.txt' , 'w') The above does not succeed. How would I create a file for writing if it does already exist?
[ "Yes, 'w' is specified as creating a new file -- as the docs put it,\n\n'w' for writing (truncating the file\n if it already exists),\n\n(clearly inferring it's allowed to not already exist). Please show the exact traceback, not just your own summary of it, as details matters -- e.g. if the actual path you're using is different, what's missing might be the drive, or some intermediate directory; or there might be permission problems.\n", "[Edited to reflect that the problem is likely not forward vs. back slash]\nIf I understood correctly, you want the file to be automatically created for you, right?\nopen in write mode does create the file for you. It would be more clear if you told us the exact error you're getting. It might be something like you not having permission to write in C:.\nI had previously suggested that it might be because of the forward slash, and indicated that the OP could try:\na = open(r'C:\\c.txt', 'w')\n\nNote the r before the file path, indicating raw mode (that is, the backslash won't be interpreted as special).\nHowever, as Brian Neal pointed out (as well as others, commenting elsewhere), that's likely not the reason for the error. I'm keeping it here simply for historical purposes.\n", "You most probably are trying to write to a directory that doesn't exist or one that you don't have permission writing to.\nIf you want to write to C:\\foo\\bar\\foobar.txt then make sure that you've got a C:\\foo\\bar\\ that exists (and in case permissions work on Windows, make sure you've got the permission to write there). \nNow when you open the file in write mode, a file should be created.\n", "If you're asking how to be warned when the file doesn't exist, then you need to explicitly check for that. \nSee here\n" ]
[ 30, 4, 3, 0 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0003094986_file_io_python.txt
Q: Potential Multiple installations of Python on Windows I ran into the following problem: I need to supply the installation package to the client. Part of the code is python, so I have to make sure that it is installed. I am using NSIS for the installation ans would like to install python into a predefined by me folder (let it be c:\Program Files\Project\Python26). For that I downloaded the python's msi and trying to execute the following to install it msiexec /package "$INSTDIR\packages\python-2.6.5.msi" /quiet TARGETDIR=c:\Program Files\Project\Python26 This works the first time (when python is not already installed), but if the python is already installed, I have to choose between reinstalling/repairing/changing. Does anybody know how to make sure that I can install python in the my directory without affecting potentially installed python? A: Per the docs, options such as /p (or maybe /o or /c, depending on your exact intent) should serve your purposes.
Potential Multiple installations of Python on Windows
I ran into the following problem: I need to supply the installation package to the client. Part of the code is python, so I have to make sure that it is installed. I am using NSIS for the installation ans would like to install python into a predefined by me folder (let it be c:\Program Files\Project\Python26). For that I downloaded the python's msi and trying to execute the following to install it msiexec /package "$INSTDIR\packages\python-2.6.5.msi" /quiet TARGETDIR=c:\Program Files\Project\Python26 This works the first time (when python is not already installed), but if the python is already installed, I have to choose between reinstalling/repairing/changing. Does anybody know how to make sure that I can install python in the my directory without affecting potentially installed python?
[ "Per the docs, options such as /p (or maybe /o or /c, depending on your exact intent) should serve your purposes.\n" ]
[ 0 ]
[]
[]
[ "python", "windows", "windows_installer" ]
stackoverflow_0003095262_python_windows_windows_installer.txt
Q: Is there a minimal style for unittests in Python? I'm wondering what techniques people use for simplifying the 'size' of code used for unit testing. For example I was trying to marshal an object of the class and testing the marshal'ed object (but this presumes marshal is working correctly). Consider the class import unittest class Nums(object): def __init__(self, n1_, n2_, n3_): self.n1, self.n2, self.n3 = n1_, n2_, n3_ def marshal(self): return "n1 %g, n2 %g, n3 %g"%(self.n1,self.n2,self.n3) and then the marshaling based, list based, and normal tests class NumsTests(unittest.TestCase): def setUp(self): self.nu = Nums(10,20,30) def test_init1(self): self.assertEquals(self.nu.marshal(),"n1 %g, n2 %g, n3 %g"%(10,20,30)) def test_init2(self): self.assertEquals([self.nu.n1,self.nu.n2,self.nu.n3],[10,21,31]) def test_init3(self): self.assertEquals(self.nu.n1,10) self.assertEquals(self.nu.n2,21) self.assertEquals(self.nu.n3,31) which give the following errors (since, 20!=21 and 30!=31, my test has a bad initialization or the test conditions are wrong) AssertionError: 'n1 10, n2 20, n3 30' != 'n1 10, n2 21, n3 31' AssertionError: [10, 20, 30] != [10, 21, 31] AssertionError: 20 != 21 The first and second error messages are difficult to understand (since you have to parse the string or list). However, the 3rd technique rapidly explodes in the amount of code used to test complex objects. Is there a better way to simplify unit tests without creating difficult error messages? And, without depending on the veracity of a marshal function? [changed test_marshal to marshal] A: I echo the comments above that you should not have test methods on the actual class you are testing. Functions like test_marshal should be placed elsewhere (assuming that they do exist for testing and not for general usage), typically in your unit test files. However, setting that aside for the moment, I'd do something like this import unittest class Nums(object): FORMAT = "n1 %g, n2 %g, n3 %g" # make this a variable for easy testing def __init__(self, n1, n2, n3): self.n1, self.n2, self.n3 = n1, n2, n3 # no underscores necessary def test_marshal(self): return self.FORMAT % (self.n1, self.n2, self.n3) class NumsTests(unittest.TestCase): def setUp(self): self.nums = [10, 20, 30] # make a param list variable to avoid duplication self.nu = Nums(*self.nums) # Python "apply" syntax self.nu_nums = [self.nu.n1, self.nu.n2, self.nu.n3] # we'll use this repeatedly def test_init1(self): self.assertEquals(self.nu.test_marshal(), self.nu.FORMAT % self.nums ) def test_init2(self): self.assertEquals(self.nums, self.nu_nums) def test_init3(self): for reference, test in zip(self.nums, self.nu_nums): self.assertEquals(reference, test) See http://docs.python.org/library/functions.html#apply for an explanation of the apply syntax used above. By putting the things you're testing into variables, you can avoid duplication of code, which seems to be your primary concern. As for the error messages being confusing, I guess it depends on how much detail you feel you need. Personally, the fact that my unit tests give me the line of code and values that were expected and not present tends to make it fairly clear what went wrong. However, if you REALLY wanted something that told you specifically which field was incorrect, rather that just the values that didn't match AND you wanted to avoid code duplication, you could write something like this: class NumsTests(unittest.TestCase): def setUp(self): self.nums = {"n1": 10, "n2": 20, "n3": 30} # use a dict, not a list self.nu = Nums(**self.nums) # same Python "apply" syntax # test_init1 and test_init2 omitted for space def test_init3(self): for attr,val in self.nums.items(): self.assertEqual([attr, val], [attr, getattr(self.nu, val)]) If you ever did have non-matching values, you'd now get errors that look like AssertionError: ["n1", 10] != ["n1", 11] and thus you'd know at a glance which field didn't match, instead of having to reason it out based on what the values were. This approach still preserves the code expansion problem, since test_init3 will stay the same size no matter how many parameters you add to your Nums class. Note that this use of getattr requires that your __init__ parameters have the same name as the fields in the num class, e.g. they must be named n1 rather than n1_, etc. An alternative approach would be to use the __dict__ attribute, as described here. A: For testing initialization, I recommend not testing via calling the marshal() function. Not only do you then have to parse out which initializer failed, you also have to figure out whether it's your initialization that's failing or the marshal function itself. The "minimal style" for unit tests I would recommend is to narrow down the focus of what you're testing at any test point as much as is feasible. If I really had to test the initialization of a whole bunch of fields, I might refactor much the same way as Eli: class MyTestCase(unittest.TestCase): def assertFieldsEqual(self, obj, expectedFieldValDict): for fieldName, fieldVal in expectedFieldValDict.items(): self.assertFieldEqual(obj, fieldName, fieldVal) def assertFieldEqual(self, obj, fieldName, expectedFieldVal): actualFieldVal = getattr(obj, fieldName) if expectedFieldVal != actualFieldVal: msg = "Field %r doesn't match: expected %r, actual %r" % \ (fieldName, expectedFieldVal, actualFieldVal) self.fail(msg) class NumsTests(MyTestCase): def setUp(self): self.initFields = {'n1': 10, 'n2': 20, 'n3': 30} self.nums = Nums(**initFields) def test_init(self): self.assertFieldsEqual(self.nums, self.initFields) "Good grief," I can hear you say, "that's a lot of code!" Well yeah, but the differences are: assertFieldsEqual and assertFieldEqual are reusable functions that have been abstracted to a common test case class which your other test cases can reuse. The failure message describes exactly what's going on. When it comes time to test your marshal function, you can simply do this: def test_marshal(self): expected = '...' self.assertEqual(expected, self.nums.marshal()) When comparing strings, though, I prefer a method that tells me exactly where the strings diverge. For multiline strings, there's now a method for that in Python 2.7, but I've rolled or cribbed my own methods for this purpose in the past.
Is there a minimal style for unittests in Python?
I'm wondering what techniques people use for simplifying the 'size' of code used for unit testing. For example I was trying to marshal an object of the class and testing the marshal'ed object (but this presumes marshal is working correctly). Consider the class import unittest class Nums(object): def __init__(self, n1_, n2_, n3_): self.n1, self.n2, self.n3 = n1_, n2_, n3_ def marshal(self): return "n1 %g, n2 %g, n3 %g"%(self.n1,self.n2,self.n3) and then the marshaling based, list based, and normal tests class NumsTests(unittest.TestCase): def setUp(self): self.nu = Nums(10,20,30) def test_init1(self): self.assertEquals(self.nu.marshal(),"n1 %g, n2 %g, n3 %g"%(10,20,30)) def test_init2(self): self.assertEquals([self.nu.n1,self.nu.n2,self.nu.n3],[10,21,31]) def test_init3(self): self.assertEquals(self.nu.n1,10) self.assertEquals(self.nu.n2,21) self.assertEquals(self.nu.n3,31) which give the following errors (since, 20!=21 and 30!=31, my test has a bad initialization or the test conditions are wrong) AssertionError: 'n1 10, n2 20, n3 30' != 'n1 10, n2 21, n3 31' AssertionError: [10, 20, 30] != [10, 21, 31] AssertionError: 20 != 21 The first and second error messages are difficult to understand (since you have to parse the string or list). However, the 3rd technique rapidly explodes in the amount of code used to test complex objects. Is there a better way to simplify unit tests without creating difficult error messages? And, without depending on the veracity of a marshal function? [changed test_marshal to marshal]
[ "I echo the comments above that you should not have test methods on the actual class you are testing. Functions like test_marshal should be placed elsewhere (assuming that they do exist for testing and not for general usage), typically in your unit test files. However, setting that aside for the moment, I'd do something like this\nimport unittest\n\nclass Nums(object):\n FORMAT = \"n1 %g, n2 %g, n3 %g\" # make this a variable for easy testing\n\n def __init__(self, n1, n2, n3):\n self.n1, self.n2, self.n3 = n1, n2, n3 # no underscores necessary\n\n def test_marshal(self):\n return self.FORMAT % (self.n1, self.n2, self.n3)\n\n\nclass NumsTests(unittest.TestCase):\n def setUp(self):\n self.nums = [10, 20, 30] # make a param list variable to avoid duplication\n self.nu = Nums(*self.nums) # Python \"apply\" syntax\n self.nu_nums = [self.nu.n1, self.nu.n2, self.nu.n3] # we'll use this repeatedly\n\n def test_init1(self):\n self.assertEquals(self.nu.test_marshal(), self.nu.FORMAT % self.nums )\n\n def test_init2(self):\n self.assertEquals(self.nums, self.nu_nums)\n\n def test_init3(self):\n for reference, test in zip(self.nums, self.nu_nums):\n self.assertEquals(reference, test)\n\nSee http://docs.python.org/library/functions.html#apply for an explanation of the apply syntax used above.\nBy putting the things you're testing into variables, you can avoid duplication of code, which seems to be your primary concern.\nAs for the error messages being confusing, I guess it depends on how much detail you feel you need. Personally, the fact that my unit tests give me the line of code and values that were expected and not present tends to make it fairly clear what went wrong. However, if you REALLY wanted something that told you specifically which field was incorrect, rather that just the values that didn't match AND you wanted to avoid code duplication, you could write something like this:\nclass NumsTests(unittest.TestCase):\n def setUp(self):\n self.nums = {\"n1\": 10, \"n2\": 20, \"n3\": 30} # use a dict, not a list\n self.nu = Nums(**self.nums) # same Python \"apply\" syntax\n\n # test_init1 and test_init2 omitted for space\n\n def test_init3(self):\n for attr,val in self.nums.items():\n self.assertEqual([attr, val], [attr, getattr(self.nu, val)])\n\nIf you ever did have non-matching values, you'd now get errors that look like\nAssertionError: [\"n1\", 10] != [\"n1\", 11]\n\nand thus you'd know at a glance which field didn't match, instead of having to reason it out based on what the values were. This approach still preserves the code expansion problem, since test_init3 will stay the same size no matter how many parameters you add to your Nums class.\nNote that this use of getattr requires that your __init__ parameters have the same name as the fields in the num class, e.g. they must be named n1 rather than n1_, etc. An alternative approach would be to use the __dict__ attribute, as described here.\n", "For testing initialization, I recommend not testing via calling the marshal() function. Not only do you then have to parse out which initializer failed, you also have to figure out whether it's your initialization that's failing or the marshal function itself. The \"minimal style\" for unit tests I would recommend is to narrow down the focus of what you're testing at any test point as much as is feasible.\nIf I really had to test the initialization of a whole bunch of fields, I might refactor much the same way as Eli:\nclass MyTestCase(unittest.TestCase):\n def assertFieldsEqual(self, obj, expectedFieldValDict):\n for fieldName, fieldVal in expectedFieldValDict.items():\n self.assertFieldEqual(obj, fieldName, fieldVal)\n def assertFieldEqual(self, obj, fieldName, expectedFieldVal):\n actualFieldVal = getattr(obj, fieldName)\n if expectedFieldVal != actualFieldVal:\n msg = \"Field %r doesn't match: expected %r, actual %r\" % \\\n (fieldName, expectedFieldVal, actualFieldVal)\n self.fail(msg)\n\nclass NumsTests(MyTestCase):\n def setUp(self):\n self.initFields = {'n1': 10, 'n2': 20, 'n3': 30}\n self.nums = Nums(**initFields)\n def test_init(self):\n self.assertFieldsEqual(self.nums, self.initFields)\n\n\"Good grief,\" I can hear you say, \"that's a lot of code!\" Well yeah, but the differences are:\n\nassertFieldsEqual and assertFieldEqual are reusable functions that have been abstracted to a common test case class which your other test cases can reuse.\nThe failure message describes exactly what's going on.\n\nWhen it comes time to test your marshal function, you can simply do this:\ndef test_marshal(self):\n expected = '...'\n self.assertEqual(expected, self.nums.marshal())\n\nWhen comparing strings, though, I prefer a method that tells me exactly where the strings diverge. For multiline strings, there's now a method for that in Python 2.7, but I've rolled or cribbed my own methods for this purpose in the past.\n" ]
[ 3, 2 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0003094273_python_unit_testing.txt
Q: How do I extract text between two different matches? I have a text file that has sets of text I need to extract that looks something like as follows: ITEM A blah blah blah ITEM B bloo bloo bloo ITEM A blee blee blee ITEM B Here is the working code I have so far: finda = r'(Item\sA)' findb = r'(Item\sB)' match_a = re.finditer(finda, usefile, 2) # the "2" is a flag to say ignore case match_b = re.finditer(findb, usefile, 2) I know that I can use commands like span, start, and end to find the text positions of my matches. But I need to do this many times so what I need is: start writing at ITEM A and stop writing at ITEM B. if that first iteration is less than 50 characters long then discard and move to the next one once you find a set that starts with ITEM A and ends with ITEM B and is larger than 50 characters write it to a file Thanks a ton in advance! I have been spinning my wheels for a while. A: why not just: with open(fname, 'w') as file: for match in re.finditer(r'Item A(.+?)Item B', subject, re.I): s = match.group(1) if len(s) > 50: file.write(s) Note: using actual numerical values of flags is rather oblique, use provided in re flags. A: This can be done in a single regex: with open("output.txt", "w") as f: for match in re.finditer(r"(?<=Item\sA)(?:(?!Item\sB).){50,}(?=Item\sB)", subject, re.I): f.write(match.group()+"\n") This matches what is between Item A and Item B. Or did you want to match the delimiters, too? The regex explained: (?<=Item\sA) # assert that we start our match right after "Item A" (?: # start repeated group (non-capturing) (?!Item\sB) # assert that we're not running into "Item B" . # then match any character ){50,} # repeat this at least 50 times (?=Item\sB) # then assert that "Item B" follows next (without making it part of the match)
How do I extract text between two different matches?
I have a text file that has sets of text I need to extract that looks something like as follows: ITEM A blah blah blah ITEM B bloo bloo bloo ITEM A blee blee blee ITEM B Here is the working code I have so far: finda = r'(Item\sA)' findb = r'(Item\sB)' match_a = re.finditer(finda, usefile, 2) # the "2" is a flag to say ignore case match_b = re.finditer(findb, usefile, 2) I know that I can use commands like span, start, and end to find the text positions of my matches. But I need to do this many times so what I need is: start writing at ITEM A and stop writing at ITEM B. if that first iteration is less than 50 characters long then discard and move to the next one once you find a set that starts with ITEM A and ends with ITEM B and is larger than 50 characters write it to a file Thanks a ton in advance! I have been spinning my wheels for a while.
[ "why not just:\nwith open(fname, 'w') as file:\n for match in re.finditer(r'Item A(.+?)Item B', subject, re.I):\n s = match.group(1)\n if len(s) > 50:\n file.write(s)\n\nNote: using actual numerical values of flags is rather oblique, use provided in re flags.\n", "This can be done in a single regex:\nwith open(\"output.txt\", \"w\") as f:\n for match in re.finditer(r\"(?<=Item\\sA)(?:(?!Item\\sB).){50,}(?=Item\\sB)\", subject, re.I):\n f.write(match.group()+\"\\n\")\n\nThis matches what is between Item A and Item B. Or did you want to match the delimiters, too?\nThe regex explained:\n(?<=Item\\sA) # assert that we start our match right after \"Item A\"\n(?: # start repeated group (non-capturing)\n (?!Item\\sB) # assert that we're not running into \"Item B\"\n . # then match any character\n){50,} # repeat this at least 50 times\n(?=Item\\sB) # then assert that \"Item B\" follows next (without making it part of the match)\n\n" ]
[ 2, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003095574_python_regex.txt
Q: Django blog generate next/previous entries In a blog application (which I have mostly built following a tutorial), I would like to have a next and previous post link on the single page views of the posts. The blog app's urls.py file looks like this: from django.conf.urls.defaults import * from django.views.generic import list_detail from sandy.blog.models import Post urlpatterns = patterns('', url(r'^post/(?P<slug>.*)/$', list_detail.object_detail, {'queryset': Post.objects.all(), 'template_object_name': 'post',}, name="single_post"), url(r'^$', list_detail.object_list, {'queryset': Post.objects.order_by('-published'), 'template_object_name': 'post',}, name="blog_home"), ) In the single page template I would like to do something like this: <p><a href="{% url single_post slug=[how would I derive it???] %}">Previous Post</a></p> I have the Post object as post available in the template, so I can do something like {% url single_post slug=post.slug %} for the current page, but would like to be able to do something like slug=post[-1].slug or whatever. Is there a simple batteries included way to do this? Of course there would need to be some checking (to see if there is a previous post or not), and I would need to repeat it for the 'next post' link as well. I have been going around in circles to get this to work. Is there a way, or am I forced to write out a full view for the page. A: You want the get_next_by_FOO() and get_previous_by_FOO() model methods.
Django blog generate next/previous entries
In a blog application (which I have mostly built following a tutorial), I would like to have a next and previous post link on the single page views of the posts. The blog app's urls.py file looks like this: from django.conf.urls.defaults import * from django.views.generic import list_detail from sandy.blog.models import Post urlpatterns = patterns('', url(r'^post/(?P<slug>.*)/$', list_detail.object_detail, {'queryset': Post.objects.all(), 'template_object_name': 'post',}, name="single_post"), url(r'^$', list_detail.object_list, {'queryset': Post.objects.order_by('-published'), 'template_object_name': 'post',}, name="blog_home"), ) In the single page template I would like to do something like this: <p><a href="{% url single_post slug=[how would I derive it???] %}">Previous Post</a></p> I have the Post object as post available in the template, so I can do something like {% url single_post slug=post.slug %} for the current page, but would like to be able to do something like slug=post[-1].slug or whatever. Is there a simple batteries included way to do this? Of course there would need to be some checking (to see if there is a previous post or not), and I would need to repeat it for the 'next post' link as well. I have been going around in circles to get this to work. Is there a way, or am I forced to write out a full view for the page.
[ "You want the get_next_by_FOO() and get_previous_by_FOO() model methods.\n" ]
[ 4 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003095725_django_python.txt
Q: Django models.Model class member not appearing in model_instance._meta.fields I have a django.contrib.contenttypes.generic.genericForeignKeyField as a member of my model, however, it is not appearing when I instantiate the model and then try to get the fields out of the _meta of the object. e.g: class A(models.Model): field2 = models.IntegerField(...) field1 = generic.genericForeignKeyField() a = A() a._meta.fields ---> this does not show field1, but shows field2. Can someone please tell me why ? Thanks ! A: Your are not setting up the generic relation correctly. Read the documentation: There are three parts to setting up a GenericForeignKey: Give your model a ForeignKey to ContentType. Give your model a field that can store a primary-key value from the models you'll be relating to. (For most models, this means an IntegerField or PositiveIntegerField.) This field must be of the same type as the primary key of the models that will be involved in the generic relation. For example, if you use IntegerField, you won't be able to form a generic relation with a model that uses a CharField as a primary key. Give your model a GenericForeignKey, and pass it the names of the two fields described above. If these fields are named "content_type" and "object_id", you can omit this -- those are the default field names GenericForeignKey will look for. In the end, it must be something like: content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') A: Why would you expect it to? It's not a real field. It's a virtual field that's calculated using the (real) content_type and object_id fields on the model. You can however see it in a._meta.virtual_fields.
Django models.Model class member not appearing in model_instance._meta.fields
I have a django.contrib.contenttypes.generic.genericForeignKeyField as a member of my model, however, it is not appearing when I instantiate the model and then try to get the fields out of the _meta of the object. e.g: class A(models.Model): field2 = models.IntegerField(...) field1 = generic.genericForeignKeyField() a = A() a._meta.fields ---> this does not show field1, but shows field2. Can someone please tell me why ? Thanks !
[ "Your are not setting up the generic relation correctly. Read the documentation:\n\nThere are three parts to setting up a GenericForeignKey:\n\nGive your model a ForeignKey to ContentType. \nGive your model a field that can store a primary-key value from the models you'll be relating to. (For most models, this means an IntegerField or PositiveIntegerField.)\n This field must be of the same type as the primary key of the models that will be involved in the generic relation. For example, if you use IntegerField, you won't be able to form a generic relation with a model that uses a CharField as a primary key.\nGive your model a GenericForeignKey, and pass it the names of the two fields described above. If these fields are named \"content_type\" and \"object_id\", you can omit this -- those are the default field names GenericForeignKey will look for.\n\n\nIn the end, it must be something like:\ncontent_type = models.ForeignKey(ContentType)\nobject_id = models.PositiveIntegerField()\ncontent_object = generic.GenericForeignKey('content_type', 'object_id')\n\n", "Why would you expect it to? It's not a real field. It's a virtual field that's calculated using the (real) content_type and object_id fields on the model.\nYou can however see it in a._meta.virtual_fields.\n" ]
[ 1, 1 ]
[]
[]
[ "django", "generics", "metadata", "models", "python" ]
stackoverflow_0003096040_django_generics_metadata_models_python.txt
Q: In Python, what happens when you import inside of a function? What are the pros and cons of importing a Python module and/or function inside of a function, with respect to efficiency of speed and of memory? Does it re-import every time the function is run, or perhaps just once at the beginning whether or not the function is run? A: Does it re-import every time the function is run? No; or rather, Python modules are essentially cached every time they are imported, so importing a second (or third, or fourth...) time doesn't actually force them to go through the whole import process again. 1 Does it import once at the beginning whether or not the function is run? No, it is only imported if and when the function is executed. 2, 3 As for the benefits: it depends, I guess. If you may only run a function very rarely and don't need the module imported anywhere else, it may be beneficial to only import it in that function. Or if there is a name clash or other reason you don't want the module or symbols from the module available everywhere, you may only want to import it in a specific function. (Of course, there's always from my_module import my_function as f for those cases.) In general practice, it's probably not that beneficial. In fact, most Python style guides encourage programmers to place all imports at the beginning of the module file. A: The very first time you import goo from anywhere (inside or outside a function), goo.py (or other importable form) is loaded and sys.modules['goo'] is set to the module object thus built. Any future import within the same run of the program (again, whether inside or outside a function) just look up sys.modules['goo'] and bind it to barename goo in the appropriate scope. The dict lookup and name binding are very fast operations. Assuming the very first import gets totally amortized over the program's run anyway, having the "appropriate scope" be module-level means each use of goo.this, goo.that, etc, is two dict lookups -- one for goo and one for the attribute name. Having it be "function level" pays one extra local-variable setting per run of the function (even faster than the dictionary lookup part!) but saves one dict lookup (exchanging it for a local-variable lookup, blazingly fast) for each goo.this (etc) access, basically halving the time such lookups take. We're talking about a few nanoseconds one way or another, so it's hardly a worthwhile optimization. The one potentially substantial advantage of having the import within a function is when that function may well not be needed at all in a given run of the program, e.g., that function deals with errors, anomalies, and rare situations in general; if that's the case, any run that does not need the functionality will not even perform the import (and that's a saving of microseconds, not just nanoseconds), only runs that do need the functionality will pay the (modest but measurable) price. It's still an optimization that's only worthwhile in pretty extreme situations, and there are many others I would consider before trying to squeeze out microseconds in this way. A: It imports once when the function executes first time. Pros: imports related to the function they're used in easy to move functions around the package Cons: couldn't see what modules this module might depend on A: Might I suggest in general that instead of asking, "Will X improve my performance?" you use profiling to determine where your program is actually spending its time and then apply optimizations according to where you'll get the most benefit? And then you can use profiling to assure that your optimizations have actually benefited you, too. A: Importing inside a function will effectively import the module once.. the first time the function is run. It ought to import just as fast whether you import it at the top, or when the function is run. This isn't generally a good reason to import in a def. Pros? It won't be imported if the function isn't called.. This is actually a reasonable reason if your module only requires the user to have a certain module installed if they use specific functions of yours... If that's not he reason you're doing this, it's almost certainly a yucky idea. A: It imports once when the function is called for the first time. I could imagine doing it this way if I had a function in an imported module that is used very seldomly and is the only one requiring the import. Looks rather far-fetched, though...
In Python, what happens when you import inside of a function?
What are the pros and cons of importing a Python module and/or function inside of a function, with respect to efficiency of speed and of memory? Does it re-import every time the function is run, or perhaps just once at the beginning whether or not the function is run?
[ "\nDoes it re-import every time the function is run?\n\nNo; or rather, Python modules are essentially cached every time they are imported, so importing a second (or third, or fourth...) time doesn't actually force them to go through the whole import process again. 1\n\nDoes it import once at the beginning whether or not the function is run?\n\nNo, it is only imported if and when the function is executed. 2, 3\nAs for the benefits: it depends, I guess. If you may only run a function very rarely and don't need the module imported anywhere else, it may be beneficial to only import it in that function. Or if there is a name clash or other reason you don't want the module or symbols from the module available everywhere, you may only want to import it in a specific function. (Of course, there's always from my_module import my_function as f for those cases.)\nIn general practice, it's probably not that beneficial. In fact, most Python style guides encourage programmers to place all imports at the beginning of the module file.\n", "The very first time you import goo from anywhere (inside or outside a function), goo.py (or other importable form) is loaded and sys.modules['goo'] is set to the module object thus built. Any future import within the same run of the program (again, whether inside or outside a function) just look up sys.modules['goo'] and bind it to barename goo in the appropriate scope. The dict lookup and name binding are very fast operations.\nAssuming the very first import gets totally amortized over the program's run anyway, having the \"appropriate scope\" be module-level means each use of goo.this, goo.that, etc, is two dict lookups -- one for goo and one for the attribute name. Having it be \"function level\" pays one extra local-variable setting per run of the function (even faster than the dictionary lookup part!) but saves one dict lookup (exchanging it for a local-variable lookup, blazingly fast) for each goo.this (etc) access, basically halving the time such lookups take.\nWe're talking about a few nanoseconds one way or another, so it's hardly a worthwhile optimization. The one potentially substantial advantage of having the import within a function is when that function may well not be needed at all in a given run of the program, e.g., that function deals with errors, anomalies, and rare situations in general; if that's the case, any run that does not need the functionality will not even perform the import (and that's a saving of microseconds, not just nanoseconds), only runs that do need the functionality will pay the (modest but measurable) price.\nIt's still an optimization that's only worthwhile in pretty extreme situations, and there are many others I would consider before trying to squeeze out microseconds in this way.\n", "It imports once when the function executes first time.\nPros:\n\nimports related to the function they're used in\neasy to move functions around the package\n\nCons:\n\ncouldn't see what modules this module might depend on\n\n", "Might I suggest in general that instead of asking, \"Will X improve my performance?\" you use profiling to determine where your program is actually spending its time and then apply optimizations according to where you'll get the most benefit?\nAnd then you can use profiling to assure that your optimizations have actually benefited you, too.\n", "Importing inside a function will effectively import the module once.. the first time the function is run.\nIt ought to import just as fast whether you import it at the top, or when the function is run. This isn't generally a good reason to import in a def. Pros? It won't be imported if the function isn't called.. This is actually a reasonable reason if your module only requires the user to have a certain module installed if they use specific functions of yours...\nIf that's not he reason you're doing this, it's almost certainly a yucky idea.\n", "It imports once when the function is called for the first time.\nI could imagine doing it this way if I had a function in an imported module that is used very seldomly and is the only one requiring the import. Looks rather far-fetched, though...\n" ]
[ 222, 58, 22, 10, 7, 3 ]
[]
[]
[ "python", "python_import" ]
stackoverflow_0003095071_python_python_import.txt
Q: Python xmlrpc server in windows I'm looking for a library that can help me build a good XMLRPC server in Python that could run on Windows. The SimpleXMLRPCServer class looks fine but I don't know if it will suit all my needs, since I'd like to be able to connect from multiple clients at the same time. I found this on GitHub, but I don't know if it'll work. Any suggestions/ideas? A: I like CherryPy for XMLRPC using the built-in tool/dispatcher, and it runs on Windows as far as I know. But you really need to ask yourself why you want to do RPC vs. a RESTful service in 2010. XMLRPC is very limited in the variable types allowed, and adds significant encapsulation overhead, and requires a client that can talk XMLRPC. A: I also like CheeyPy, but have also used Twisted for such needs. Pretty simple to use and Twisted has defereds and helper functions like deferToThread and callLater to allow for blocking code to act in a non-blocking fashion. Take a look at http://twistedmatrix.com/documents/current/web/howto/xmlrpc.html for a simple example. A: I like to use circuits for stuff like this (but it's not for everyone). There's a simple example in the examples/web/ directory in the source repository.
Python xmlrpc server in windows
I'm looking for a library that can help me build a good XMLRPC server in Python that could run on Windows. The SimpleXMLRPCServer class looks fine but I don't know if it will suit all my needs, since I'd like to be able to connect from multiple clients at the same time. I found this on GitHub, but I don't know if it'll work. Any suggestions/ideas?
[ "I like CherryPy for XMLRPC using the built-in tool/dispatcher, and it runs on Windows as far as I know.\nBut you really need to ask yourself why you want to do RPC vs. a RESTful service in 2010. XMLRPC is very limited in the variable types allowed, and adds significant encapsulation overhead, and requires a client that can talk XMLRPC.\n", "I also like CheeyPy, but have also used Twisted for such needs. Pretty simple to use and Twisted has defereds and helper functions like deferToThread and callLater to allow for blocking code to act in a non-blocking fashion.\nTake a look at http://twistedmatrix.com/documents/current/web/howto/xmlrpc.html for a simple example.\n", "I like to use circuits for stuff like this (but it's not for everyone). There's a simple example in the examples/web/ directory in the source repository.\n" ]
[ 1, 1, 1 ]
[]
[]
[ "python", "xml_rpc" ]
stackoverflow_0003087944_python_xml_rpc.txt
Q: python and xml integration How do I produce XML from Python? I built a program for keystroke detection integrated with open office and other softwares and i want the output of the program to be stored in an XML file? my program detects the keys stroked in an open office, ms office software. i want the outpu to be directly stored in an XML file A: You should use lxml Python library. from lxml import etree root = etree.Element("root") root.set("foo", "bar") child1 = etree.SubElement(root, "spam") et = etree.ElementTree(root) et.write('output_file.xml', xml_declaration=True, encoding='utf-8') A: Look into xml.dom.minidom, particulary the toXml method. A: If you're looking to be able to run a python function from within an xml file, take a look at this: lxml extension functions With these, you can define a function namespace and then, with the proper editing of your xml/xsl file, you'll be able to put the value of your code into the xml file. The other option would be to do as systempuntoout suggested and parse your xml into a python object using the lxml library, and then place the output of running your code in the proper place. Either way, more specificity in your question will help us answer you quickly and correctly. Edit: If you're just looking to write the keystrokes to some file.xml, you can use: with open('file.xml', 'w') as f: f.write(keystroke_data)
python and xml integration
How do I produce XML from Python? I built a program for keystroke detection integrated with open office and other softwares and i want the output of the program to be stored in an XML file? my program detects the keys stroked in an open office, ms office software. i want the outpu to be directly stored in an XML file
[ "You should use lxml Python library.\nfrom lxml import etree\n\nroot = etree.Element(\"root\")\nroot.set(\"foo\", \"bar\")\nchild1 = etree.SubElement(root, \"spam\")\net = etree.ElementTree(root)\net.write('output_file.xml', xml_declaration=True, encoding='utf-8')\n\n", "Look into xml.dom.minidom, particulary the toXml method.\n", "If you're looking to be able to run a python function from within an xml file, take a look at this: lxml extension functions\nWith these, you can define a function namespace and then, with the proper editing of your xml/xsl file, you'll be able to put the value of your code into the xml file.\nThe other option would be to do as systempuntoout suggested and parse your xml into a python object using the lxml library, and then place the output of running your code in the proper place.\nEither way, more specificity in your question will help us answer you quickly and correctly.\nEdit:\nIf you're just looking to write the keystrokes to some file.xml, you can use:\nwith open('file.xml', 'w') as f:\n f.write(keystroke_data)\n\n" ]
[ 3, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003096096_python.txt
Q: Load a .so library into ctypes I have compiled a library using cmake add_library(object3d SHARED some_file.h some_file.cpp). After compilation, I get a file: libobject3d.so I would like to call a function in this library. This function definition in some_file.h is: void ComputeGeometryImage(char * input_image, int geometry_image_size, float * output); I did check that this method exists in my library by doing: nm libobject3d.so 0000000000202058 d DW.ref.__gxx_personality_v0 0000000000201d40 a _DYNAMIC 0000000000201fe8 a _GLOBAL_OFFSET_TABLE_ 0000000000000cbd t _GLOBAL__I_export_object3d_lib.cpp w _Jv_RegisterClasses 0000000000000bdc T _Z20ComputeGeometryImagePciPf 0000000000000c75 t _Z41__static_initialization_and_destruction_0ii U _Z7load_3dPKci 0000000000000cd2 W _ZN7Image2DIfE10get_accessEv 0000000000000ce8 W _ZN7Image2DIfED1Ev U _ZNK8Object3D18convert_to_Image2DEi U _ZNSt8ios_base4InitC1Ev@@GLIBCXX_3.4 U _ZNSt8ios_base4InitD1Ev@@GLIBCXX_3.4 0000000000202070 b _ZStL8__ioinit U _ZdaPv@@GLIBCXX_3.4 U _ZdlPv@@GLIBCXX_3.4 0000000000201d20 d __CTOR_END__ 0000000000201d10 d __CTOR_LIST__ 0000000000201d30 d __DTOR_END__ 0000000000201d28 d __DTOR_LIST__ 0000000000000e70 r __FRAME_END__ 0000000000201d38 d __JCR_END__ 0000000000201d38 d __JCR_LIST__ 0000000000202060 A __bss_start U __cxa_atexit@@GLIBC_2.2.5 w __cxa_finalize@@GLIBC_2.2.5 0000000000000d30 t __do_global_ctors_aux 0000000000000b30 t __do_global_dtors_aux 0000000000202050 d __dso_handle w __gmon_start__ U __gxx_personality_v0@@CXXABI_1.3 0000000000202060 A _edata 0000000000202078 A _end 0000000000000d68 T _fini 0000000000000a40 T _init 0000000000000b10 t call_gmon_start 0000000000202060 b completed.7382 0000000000202068 b dtor_idx.7384 0000000000000bb0 t frame_dummy U memcpy@@GLIBC_2.2.5 However, when I try to load this library into ctypes: lib = np.ctypeslib.load_library('libobject3d.so', '.') This lib object does not have the object ComputeGeometryImage. That is lib.ComputeGeometryImage does not exist. Is this a problem of compiling my library? How do I expose this method from C++ into ctypes? A: Your C++ compiler mangles the function name to _Z20ComputeGeometryImagePciPf. You need to tell your compiler to stop mangling the function name. In some_file.h: extern "C" void ComputeGeometryImage(char * input_image, int geometry_image_size, float * output); You can also declare multiple functions to have none mangled names with a block: extern "C" { void foo(int i); void bar(char c); } If you need to expose classes from C++ I would recomend Boost.Python.
Load a .so library into ctypes
I have compiled a library using cmake add_library(object3d SHARED some_file.h some_file.cpp). After compilation, I get a file: libobject3d.so I would like to call a function in this library. This function definition in some_file.h is: void ComputeGeometryImage(char * input_image, int geometry_image_size, float * output); I did check that this method exists in my library by doing: nm libobject3d.so 0000000000202058 d DW.ref.__gxx_personality_v0 0000000000201d40 a _DYNAMIC 0000000000201fe8 a _GLOBAL_OFFSET_TABLE_ 0000000000000cbd t _GLOBAL__I_export_object3d_lib.cpp w _Jv_RegisterClasses 0000000000000bdc T _Z20ComputeGeometryImagePciPf 0000000000000c75 t _Z41__static_initialization_and_destruction_0ii U _Z7load_3dPKci 0000000000000cd2 W _ZN7Image2DIfE10get_accessEv 0000000000000ce8 W _ZN7Image2DIfED1Ev U _ZNK8Object3D18convert_to_Image2DEi U _ZNSt8ios_base4InitC1Ev@@GLIBCXX_3.4 U _ZNSt8ios_base4InitD1Ev@@GLIBCXX_3.4 0000000000202070 b _ZStL8__ioinit U _ZdaPv@@GLIBCXX_3.4 U _ZdlPv@@GLIBCXX_3.4 0000000000201d20 d __CTOR_END__ 0000000000201d10 d __CTOR_LIST__ 0000000000201d30 d __DTOR_END__ 0000000000201d28 d __DTOR_LIST__ 0000000000000e70 r __FRAME_END__ 0000000000201d38 d __JCR_END__ 0000000000201d38 d __JCR_LIST__ 0000000000202060 A __bss_start U __cxa_atexit@@GLIBC_2.2.5 w __cxa_finalize@@GLIBC_2.2.5 0000000000000d30 t __do_global_ctors_aux 0000000000000b30 t __do_global_dtors_aux 0000000000202050 d __dso_handle w __gmon_start__ U __gxx_personality_v0@@CXXABI_1.3 0000000000202060 A _edata 0000000000202078 A _end 0000000000000d68 T _fini 0000000000000a40 T _init 0000000000000b10 t call_gmon_start 0000000000202060 b completed.7382 0000000000202068 b dtor_idx.7384 0000000000000bb0 t frame_dummy U memcpy@@GLIBC_2.2.5 However, when I try to load this library into ctypes: lib = np.ctypeslib.load_library('libobject3d.so', '.') This lib object does not have the object ComputeGeometryImage. That is lib.ComputeGeometryImage does not exist. Is this a problem of compiling my library? How do I expose this method from C++ into ctypes?
[ "Your C++ compiler mangles the function name to _Z20ComputeGeometryImagePciPf. You need to tell your compiler to stop mangling the function name. In some_file.h:\nextern \"C\" void ComputeGeometryImage(char * input_image, \n int geometry_image_size, \n float * output);\n\nYou can also declare multiple functions to have none mangled names with a block:\nextern \"C\"\n{\n void foo(int i);\n void bar(char c);\n}\n\nIf you need to expose classes from C++ I would recomend Boost.Python.\n" ]
[ 4 ]
[]
[]
[ "ctypes", "linux", "python" ]
stackoverflow_0003095923_ctypes_linux_python.txt
Q: Python string formatter for paragraphs I'm trying to format some strings for output on the command-line, report style, and am looking for the easiest method to format a string such that I can get automatic paragraph formatting. In perlform formatting is done through the "format" function format Something = Test: @<<<<<<<< @||||| @>>>>> $str, $%, '$' . int($num) . $str = "widget"; $num = $cost/$quantity; $~ = 'Something'; write; Variations of the perlform allow texts to be wrapped cleanly, useful for help screens, log reports and such. Is there a python equivalent? Or a reasonable hack that I could write using Python's new string format function? Example output I'd like: Foobar-Title Blob 0123 This is some long text which would wrap past the 80 column mark and go onto the next line number of times blah blah blah. hi there dito something more text here. more text here. more text here. A: There isn't automatic formatting like this built into Python. (The .format function syntax is borrowed from C#.) After all, Perl was "Practical Extraction and Report Language" and Python isn't designed for formatting reports. Your output could be done with the textwrap module, e.g. from textwrap import fill def formatItem(left, right): wrapped = fill(right, width=41, subsequent_indent=' '*15) return ' {0:<13}{1}'.format(left, wrapped) ... >>> print(formatItem('0123', 'This is some long text which would wrap past the 80 column mark and go onto the next line number of times blah blah blah.')) 0123 This is some long text which would wrap past the 80 column mark and go onto the next line number of times blah blah blah. Note that this assumes the "left" does not span over 1 line. A more general solution would be from textwrap import wrap from itertools import zip_longest def twoColumn(left, right, leftWidth=13, rightWidth=41, indent=2, separation=2): lefts = wrap(left, width=leftWidth) rights = wrap(right, width=rightWidth) results = [] for l, r in zip_longest(lefts, rights, fillvalue=''): results.append('{0:{1}}{2:{5}}{0:{3}}{4}'.format('', indent, l, separation, r, leftWidth)) return "\n".join(results) >>> print(twoColumn("I'm trying to format some strings for output on the command-line", "report style, and am looking for the easiest method to format a string such that I can get automatic paragraph formatting.")) I'm trying to report style, and am looking for the format some easiest method to format a string such strings for that I can get automatic paragraph output on the formatting. command-line A: import textwrap import itertools def formatter(format_str,widths,*columns): ''' format_str describes the format of the report. {row[i]} is replaced by data from the ith element of columns. widths is expected to be a list of integers. {width[i]} is replaced by the ith element of the list widths. All the power of Python's string format spec is available for you to use in format_str. You can use it to define fill characters, alignment, width, type, etc. formatter takes an arbitrary number of arguments. Every argument after format_str and widths should be a list of strings. Each list contains the data for one column of the report. formatter returns the report as one big string. ''' result=[] for row in zip(*columns): lines=[textwrap.wrap(elt, width=num) for elt,num in zip(row,widths)] for line in itertools.izip_longest(*lines,fillvalue=''): result.append(format_str.format(width=widths,row=line)) return '\n'.join(result) For example: widths=[17,41] form='{row[0]:<{width[0]}} {row[1]:<{width[1]}}' titles=['Foobar-Title','0123','hi there','something'] blobs=['Blob','This is some long text which would wrap past the 80 column mark and go onto the next line number of times blah blah blah.','dito','more text here. more text here. more text here.'] print(formatter(form,widths,titles,blobs)) yields # Foobar-Title Blob # 0123 This is some long text which would wrap # past the 80 column mark and go onto the # next line number of times blah blah blah. # hi there dito # something more text here. more text here. more text # here. formatter can take an arbitrary number of columns. A: There is this from python documents and this that might help.
Python string formatter for paragraphs
I'm trying to format some strings for output on the command-line, report style, and am looking for the easiest method to format a string such that I can get automatic paragraph formatting. In perlform formatting is done through the "format" function format Something = Test: @<<<<<<<< @||||| @>>>>> $str, $%, '$' . int($num) . $str = "widget"; $num = $cost/$quantity; $~ = 'Something'; write; Variations of the perlform allow texts to be wrapped cleanly, useful for help screens, log reports and such. Is there a python equivalent? Or a reasonable hack that I could write using Python's new string format function? Example output I'd like: Foobar-Title Blob 0123 This is some long text which would wrap past the 80 column mark and go onto the next line number of times blah blah blah. hi there dito something more text here. more text here. more text here.
[ "There isn't automatic formatting like this built into Python. (The .format function syntax is borrowed from C#.) After all, Perl was \"Practical Extraction and Report Language\" and Python isn't designed for formatting reports.\nYour output could be done with the textwrap module, e.g.\nfrom textwrap import fill\ndef formatItem(left, right):\n wrapped = fill(right, width=41, subsequent_indent=' '*15)\n return ' {0:<13}{1}'.format(left, wrapped)\n\n...\n\n>>> print(formatItem('0123', 'This is some long text which would wrap past the 80 column mark and go onto the next line number of times blah blah blah.'))\n 0123 This is some long text which would wrap\n past the 80 column mark\n and go onto the next line\n number of times blah blah\n blah.\n\nNote that this assumes the \"left\" does not span over 1 line. A more general solution would be\nfrom textwrap import wrap\nfrom itertools import zip_longest\ndef twoColumn(left, right, leftWidth=13, rightWidth=41, indent=2, separation=2):\n lefts = wrap(left, width=leftWidth)\n rights = wrap(right, width=rightWidth)\n results = []\n for l, r in zip_longest(lefts, rights, fillvalue=''):\n results.append('{0:{1}}{2:{5}}{0:{3}}{4}'.format('', indent, l, separation, r, leftWidth))\n return \"\\n\".join(results)\n\n>>> print(twoColumn(\"I'm trying to format some strings for output on the command-line\", \"report style, and am looking for the easiest method to format a string such that I can get automatic paragraph formatting.\"))\n I'm trying to report style, and am looking for the\n format some easiest method to format a string such\n strings for that I can get automatic paragraph\n output on the formatting.\n command-line \n\n", "import textwrap\nimport itertools\n\ndef formatter(format_str,widths,*columns):\n '''\n format_str describes the format of the report.\n {row[i]} is replaced by data from the ith element of columns.\n\n widths is expected to be a list of integers.\n {width[i]} is replaced by the ith element of the list widths.\n\n All the power of Python's string format spec is available for you to use\n in format_str. You can use it to define fill characters, alignment, width, type, etc.\n\n formatter takes an arbitrary number of arguments.\n Every argument after format_str and widths should be a list of strings.\n Each list contains the data for one column of the report.\n\n formatter returns the report as one big string.\n '''\n result=[]\n for row in zip(*columns):\n lines=[textwrap.wrap(elt, width=num) for elt,num in zip(row,widths)]\n for line in itertools.izip_longest(*lines,fillvalue=''):\n result.append(format_str.format(width=widths,row=line))\n return '\\n'.join(result)\n\nFor example:\nwidths=[17,41]\nform='{row[0]:<{width[0]}} {row[1]:<{width[1]}}'\n\ntitles=['Foobar-Title','0123','hi there','something']\nblobs=['Blob','This is some long text which would wrap past the 80 column mark and go onto the next line number of times blah blah blah.','dito','more text here. more text here. more text here.']\n\nprint(formatter(form,widths,titles,blobs))\n\nyields\n# Foobar-Title Blob \n# 0123 This is some long text which would wrap \n# past the 80 column mark and go onto the \n# next line number of times blah blah blah.\n# hi there dito \n# something more text here. more text here. more text\n# here. \n\nformatter can take an arbitrary number of columns.\n", "There is this from python documents and this that might help.\n" ]
[ 6, 4, 1 ]
[]
[]
[ "formatting", "python", "string" ]
stackoverflow_0003096402_formatting_python_string.txt
Q: Fibonacci numbers not getting printed beyond F(996) I wrote this small snippet to calculate Fibonacci numbers. It works well for numbers up to 996 and from 997 a trace back is being printed. I can't figure out what the problem is. Does it has something to do with maximum_recursion_count? def fib(n): if n==0: return 0 elif n==1: return 1 else: return fib(n-1)+n A: Probably. Take a look at sys.getrecursionlimit(). The default value is 1000, which sounds like it just might be causing the problem you're seeing: once there are 1000 frames on the stack (i.e. slightly less than 1000 recursive function calls), you'll get an error on the next function call. You can set the recursion limit to a larger value using sys.setrecursionlimit, but there is a maximum value which is platform-dependent (which means you might have to figure out what it is by trial and error). A: There is a wonderful Fibonnaci function implementation here that doesn't use recursion. A: Your code may come up against stack call limits. A: You say "It works well for numbers up to 996" ... No, it doesn't, it generates the wrong results. The last line should be: return fib(n - 1) + fib(n - 2) A: You have reached the maxmimum recursion depth limit. As far as I know its default value is about 1000. You can change it sys.setrecursionlimit() and see it using sys.getrecursionlimit()
Fibonacci numbers not getting printed beyond F(996)
I wrote this small snippet to calculate Fibonacci numbers. It works well for numbers up to 996 and from 997 a trace back is being printed. I can't figure out what the problem is. Does it has something to do with maximum_recursion_count? def fib(n): if n==0: return 0 elif n==1: return 1 else: return fib(n-1)+n
[ "Probably. Take a look at sys.getrecursionlimit(). The default value is 1000, which sounds like it just might be causing the problem you're seeing: once there are 1000 frames on the stack (i.e. slightly less than 1000 recursive function calls), you'll get an error on the next function call.\nYou can set the recursion limit to a larger value using sys.setrecursionlimit, but there is a maximum value which is platform-dependent (which means you might have to figure out what it is by trial and error).\n", "There is a wonderful Fibonnaci function implementation here that doesn't use recursion.\n", "Your code may come up against stack call limits.\n", "You say \"It works well for numbers up to 996\" ... No, it doesn't, it generates the wrong results. The last line should be:\nreturn fib(n - 1) + fib(n - 2)\n\n", "You have reached the maxmimum recursion depth limit. As far as I know its default value is about 1000. You can change it sys.setrecursionlimit() and see it using sys.getrecursionlimit()\n" ]
[ 5, 3, 3, 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003095987_python.txt
Q: U combinator on a fibonacci : how would you translate this code to python? I am trying to learn about combinators and I am having trouble understand the example given at (Y overriding self-application). I think I am beginning to grasp the concept but I am still far from understanding. I would like to translate the following code to Python: (define (U f) (f f)) (define (fib-nr f) (lambda (n) (if (< n 2) 1 (+ ((f f) (- n 1)) ((f f) (- n 2)))))) # Usage: ((U fib-nr) 35) ;==> 14930352 I tried a 'literal' translation by writing: U = lambda u: u(u) def fibnr(f): return lambda n: 1 if (n<2) else (f (f (n-1))) + (f (f (n-2))) But this doesnt work (I think it has to do with the order the functions are evaluated inside the lambda). So I tried to use function composition as: # http://code.activestate.com/recipes/52902-function-composition/ class compose: '''compose functions. compose(f,g,x...)(y...) = f(g(y...),x...))''' def __init__(self, f, g, *args, **kwargs): self.f = f self.g = g self.pending = args[:] self.kwargs = kwargs.copy() def __call__(self, *args, **kwargs): return self.f(self.g(*args, **kwargs), *self.pending, **self.kwargs) U = lambda u: compose(u, u) def fibnr(f): ff = compose(f, f) return lambda n: 1 if (n<2) else (ff (n-1)) + (ff (n-2)) But still didn't work, when calling my last snippet of code I get a lambda back: >>> U(fibnr)(35) <function <lambda> at 0x01A1B6B0> So, is it possible to write a 'literal' translation of the given example in Python? How could I do it? A: I wrote a simple translation that seems to produce correct results: def U(f): return f(f) def fibnr(f): def lam(n): if (n < 2): return 1 return f(f)(n-1) + f(f)(n-2) return lam Or if you really like lambdas: def fibnr(f): return lambda n: 1 if (n < 2) else f(f)(n-1) + f(f)(n-2) I think your initial problem was translating Lisp ((f f) x) into Python f(f(x)) instead of f(f)(x). Good luck understanding combinators :)
U combinator on a fibonacci : how would you translate this code to python?
I am trying to learn about combinators and I am having trouble understand the example given at (Y overriding self-application). I think I am beginning to grasp the concept but I am still far from understanding. I would like to translate the following code to Python: (define (U f) (f f)) (define (fib-nr f) (lambda (n) (if (< n 2) 1 (+ ((f f) (- n 1)) ((f f) (- n 2)))))) # Usage: ((U fib-nr) 35) ;==> 14930352 I tried a 'literal' translation by writing: U = lambda u: u(u) def fibnr(f): return lambda n: 1 if (n<2) else (f (f (n-1))) + (f (f (n-2))) But this doesnt work (I think it has to do with the order the functions are evaluated inside the lambda). So I tried to use function composition as: # http://code.activestate.com/recipes/52902-function-composition/ class compose: '''compose functions. compose(f,g,x...)(y...) = f(g(y...),x...))''' def __init__(self, f, g, *args, **kwargs): self.f = f self.g = g self.pending = args[:] self.kwargs = kwargs.copy() def __call__(self, *args, **kwargs): return self.f(self.g(*args, **kwargs), *self.pending, **self.kwargs) U = lambda u: compose(u, u) def fibnr(f): ff = compose(f, f) return lambda n: 1 if (n<2) else (ff (n-1)) + (ff (n-2)) But still didn't work, when calling my last snippet of code I get a lambda back: >>> U(fibnr)(35) <function <lambda> at 0x01A1B6B0> So, is it possible to write a 'literal' translation of the given example in Python? How could I do it?
[ "I wrote a simple translation that seems to produce correct results:\ndef U(f): return f(f)\n\ndef fibnr(f):\n def lam(n):\n if (n < 2): return 1\n return f(f)(n-1) + f(f)(n-2)\n return lam\n\nOr if you really like lambdas:\ndef fibnr(f): return lambda n: 1 if (n < 2) else f(f)(n-1) + f(f)(n-2)\n\nI think your initial problem was translating Lisp ((f f) x) into Python f(f(x)) instead of f(f)(x).\nGood luck understanding combinators :)\n" ]
[ 4 ]
[]
[]
[ "code_translation", "fixpoint_combinators", "python" ]
stackoverflow_0003097142_code_translation_fixpoint_combinators_python.txt
Q: How to put a Windows UAC Shield overlay on a button using wxPython? I have a button that will launch a process that requires UAC elevation. I want to display the Windows UAC shield overlay on the button, how do I do this in wxPython? The application is only going to run on Windows, so I don't need to worry about it not working on other systems. edit 2: Got it: BCM_SETSHIELD = 0x0000160C btn_apply = wx.Button(self, wx.ID_APPLY, "Apply", wx.DefaultPosition, wx.DefaultSize, 0) response = win32gui.SendMessage(btn_apply.GetHandle(), BCM_SETSHIELD, None, True) I put true in the wparam, not lparam of SendMessage, this works now. Now I'm just wondering if BCM_SETSHIELD is declared in some library somewhere in pywin32, but I'm fine with declaring the constant myself if I have to. A: I don't know how to send a Windows message in Python, but I assume you do. You need to send BCM_SETSHIELD with true as the parameter. It will be ignored on XP and earlier. Also make sure the button style is set to FlatStyle.System. The numerical value of BCM_SETSHIELD is 0x0000160C.
How to put a Windows UAC Shield overlay on a button using wxPython?
I have a button that will launch a process that requires UAC elevation. I want to display the Windows UAC shield overlay on the button, how do I do this in wxPython? The application is only going to run on Windows, so I don't need to worry about it not working on other systems. edit 2: Got it: BCM_SETSHIELD = 0x0000160C btn_apply = wx.Button(self, wx.ID_APPLY, "Apply", wx.DefaultPosition, wx.DefaultSize, 0) response = win32gui.SendMessage(btn_apply.GetHandle(), BCM_SETSHIELD, None, True) I put true in the wparam, not lparam of SendMessage, this works now. Now I'm just wondering if BCM_SETSHIELD is declared in some library somewhere in pywin32, but I'm fine with declaring the constant myself if I have to.
[ "I don't know how to send a Windows message in Python, but I assume you do. You need to send BCM_SETSHIELD with true as the parameter. It will be ignored on XP and earlier. Also make sure the button style is set to FlatStyle.System. The numerical value of BCM_SETSHIELD is 0x0000160C.\n" ]
[ 2 ]
[]
[]
[ "button", "icons", "python", "uac", "wxpython" ]
stackoverflow_0003097124_button_icons_python_uac_wxpython.txt
Q: Need a better way to execute console commands from python and log the results I have a python script which needs to execute several command line utilities. The stdout output is sometimes used for further processing. In all cases, I want to log the results and raise an exception if an error is detected. I use the following function to achieve this: def execute(cmd, logsink): logsink.log("executing: %s\n" % cmd) popen_obj = subprocess.Popen(\ cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (stdout, stderr) = popen_obj.communicate() returncode = popen_obj.returncode if (returncode <> 0): logsink.log(" RETURN CODE: %s\n" % str(returncode)) if (len(stdout.strip()) > 0): logsink.log(" STDOUT:\n%s\n" % stdout) if (len(stderr.strip()) > 0): logsink.log(" STDERR:\n%s\n" % stderr) if (returncode <> 0): raise Exception, "execute failed with error output:\n%s" % stderr return stdout "logsink" can be any python object with a log method. I typically use this to forward the logging data to a specific file, or echo it to the console, or both, or something else... This works pretty good, except for three problems where I need more fine-grained control than the communicate() method provides: stdout and stderr output can be interleaved on the console, but the above function logs them separately. This can complicate the interpretation of the log. How do I log stdout and stderr lines interleaved, in the same order as they were output? The above function will only log the command output once the command has completed. This complicates diagnosis of issues when commands get stuck in an infinite loop or take a very long time for some other reason. How do I get the log in real-time, while the command is still executing? If the logs are large, it can get hard to interpret which command generated which output. Is there a way to prefix each line with something (e.g. the first word of the cmd string followed by :). A: You can redirect to a file if you just want the output in a file for later evaluation. Your already defining the stdout/stderr of the processes your executuing by the stdout=/stderr= methods. In your example code your just redirecting to the scripts current out/err assigments. subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) sys.stdout and sys.stderr are just file-like objects. As the documentation documentation on sys.stdout mentions, "Any object is acceptable as long as it has a write() method that takes a string argument." f = open('cmd_fileoutput.txt', 'w') subprocess.Popen(cmd, shell=True, stdout=f, stderr=f) So you only need to given it a class with a write method in order to re-direct output. If you want both console output and file output may be making a class to manage the output. General redirection: # Redirecting stdout and stderr to a file f = open('log.txt', 'w') sys.stdout = f sys.stderr = f Making a redirection class: # redirecting to both class OutputManager: def __init__(self, filename, console): self.f = open(filename, 'w') self.con = console def write(self, data): self.con.write(data) self.f.write(data) new_stdout = OutputManager("log.txt", sys.stdout) Interleaving is dependant on buffering, so you may or may not get the output you expect. (You can probably turn off or reduce the buffering used, but I don't remember how at the moment) A: You can look into pexpect (http://www.noah.org/wiki/Pexpect) It solves 1) and 2) out of the box, prefixing the output might be a little trickier. A: One other option: def run_test(test_cmd): with tempfile.TemporaryFile() as cmd_out: proc = subprocess.Popen(test_cmd, stdout=cmd_out, stderr=cmd_out) proc.wait() cmd_out.seek(0) output = "".join(cmd_out.readlines()) return (proc.returncode, output) This will interleave stdout and stderr as desired, in a real file that is conveniently open for you. A: This is by no means a complete or exhaustive answer, but perhaps you should look into the Fabric module. http://docs.fabfile.org/0.9.1/ Makes parallel execution of shell commands and error handling rather easy.
Need a better way to execute console commands from python and log the results
I have a python script which needs to execute several command line utilities. The stdout output is sometimes used for further processing. In all cases, I want to log the results and raise an exception if an error is detected. I use the following function to achieve this: def execute(cmd, logsink): logsink.log("executing: %s\n" % cmd) popen_obj = subprocess.Popen(\ cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (stdout, stderr) = popen_obj.communicate() returncode = popen_obj.returncode if (returncode <> 0): logsink.log(" RETURN CODE: %s\n" % str(returncode)) if (len(stdout.strip()) > 0): logsink.log(" STDOUT:\n%s\n" % stdout) if (len(stderr.strip()) > 0): logsink.log(" STDERR:\n%s\n" % stderr) if (returncode <> 0): raise Exception, "execute failed with error output:\n%s" % stderr return stdout "logsink" can be any python object with a log method. I typically use this to forward the logging data to a specific file, or echo it to the console, or both, or something else... This works pretty good, except for three problems where I need more fine-grained control than the communicate() method provides: stdout and stderr output can be interleaved on the console, but the above function logs them separately. This can complicate the interpretation of the log. How do I log stdout and stderr lines interleaved, in the same order as they were output? The above function will only log the command output once the command has completed. This complicates diagnosis of issues when commands get stuck in an infinite loop or take a very long time for some other reason. How do I get the log in real-time, while the command is still executing? If the logs are large, it can get hard to interpret which command generated which output. Is there a way to prefix each line with something (e.g. the first word of the cmd string followed by :).
[ "You can redirect to a file if you just want the output in a file for later evaluation.\nYour already defining the stdout/stderr of the processes your executuing by the stdout=/stderr= methods.\nIn your example code your just redirecting to the scripts current out/err assigments.\nsubprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\nsys.stdout and sys.stderr are just file-like objects.\nAs the documentation documentation on sys.stdout mentions, \"Any object is acceptable as long as it has a write() method that takes a string argument.\"\nf = open('cmd_fileoutput.txt', 'w')\nsubprocess.Popen(cmd, shell=True, stdout=f, stderr=f)\n\nSo you only need to given it a class with a write method in order to re-direct output.\nIf you want both console output and file output may be making a class to manage the output.\nGeneral redirection:\n# Redirecting stdout and stderr to a file\nf = open('log.txt', 'w')\nsys.stdout = f\nsys.stderr = f\n\nMaking a redirection class:\n# redirecting to both\nclass OutputManager:\n def __init__(self, filename, console):\n self.f = open(filename, 'w')\n self.con = console\n\n def write(self, data):\n self.con.write(data)\n self.f.write(data)\n\nnew_stdout = OutputManager(\"log.txt\", sys.stdout)\n\nInterleaving is dependant on buffering, so you may or may not get the output you expect.\n(You can probably turn off or reduce the buffering used, but I don't remember how at the moment)\n", "You can look into pexpect (http://www.noah.org/wiki/Pexpect)\nIt solves 1) and 2) out of the box, prefixing the output might be a little trickier.\n", "One other option:\ndef run_test(test_cmd):\n with tempfile.TemporaryFile() as cmd_out:\n proc = subprocess.Popen(test_cmd, stdout=cmd_out, stderr=cmd_out)\n proc.wait()\n cmd_out.seek(0)\n output = \"\".join(cmd_out.readlines())\n return (proc.returncode, output)\n\nThis will interleave stdout and stderr as desired, in a real file that is conveniently open for you.\n", "This is by no means a complete or exhaustive answer, but perhaps you should look into the Fabric module. \nhttp://docs.fabfile.org/0.9.1/\nMakes parallel execution of shell commands and error handling rather easy. \n" ]
[ 5, 2, 1, 1 ]
[]
[]
[ "command_line", "logging", "python" ]
stackoverflow_0000559578_command_line_logging_python.txt
Q: GUI tools and APIs for small/medium hierarchical data structures I'm trying to find a tool and library to edit, write and read data in a hierarchical structure, similar to an LDAP tree, a Windows registry or a Berkeley DB structure. The keys should represent some hierarchy, and the values should have a relatively flexible format (typing is optional, but could be useful). Here is an example: Items/item_1/shape = "rectangle" Items/item_1/top = 10 Items/item_1/left = 10 Items/item_1/width = 30 Items/item_1/height = 40 Items/item_2/shape = "square" Items/item_2/top = 10 Items/item_2/left = 10 Items/item_2/width = 30 Items/item_3/shape = "circle" Items/item_3/centre_x = 40 Items/item_3/centre_y = 50 Items/item_3/radius = 20 Items/item_3/colour = blue The use-case would be: Edit the data store via a convenient GUI. This could look like Windows Regedit or Apache Directory Studio (LDAP Browser). Save that data into some store (e.g. a file). Load this store from another application, which would be able to query it from an API. The library for this would ideally be callable from Python. I'd like these operations to be reasonably fast for reading, but not have it all loaded in memory in advance. The data store would be updated into the application more or less manually, much less often than the data is read. Being able to write to that data from the API would be a plus, but it's not a strict requirement. Queries would be good. For example (in pseudo query), "List Items/* where top == 10" would return: Items/item_1 Items/item_2 Ease of edition (via a good GUI) is one of the most important features. I've considered a few options: An LDAP server answers most requirements (especially with the help of Apache Directory Studio). However, deploying an LDAP server just for that is too heavy. However good Apache Directory Studio is, the user still needs a reasonable understanding of LDAP (more than just explaining the tree hierachy). I'd also like some flexibility in the creation of schemas (or no schemas at all) rather than having to rely on an administrator to do this. Windows Regedit. I'm not sure if it's possible, but I guess it's conceivable to have a registry-like file that has nothing to do with the actual windows registry, editable with custom content via Regedit. I would however like this GUI application to be available on non-Windows platforms and I'm not even sure there's a Python API to read a Windows registry file. RDF. That could work. I'm sure there are fairly good Python libraries for semantic web. However, I don't need any reasoning capabilities. I'd rather have something fast and that doesn't use much memory. I'm not sure there are any good GUI tools to view and edit the tree (since it's geared towards webs and graphs). There are certainly ways to build this sort of data structures on top of existing systems like SQLite (for example), and this would be fine but I'm not sure whether there's a good GUI that would come with it. I'd appreciate comments and suggestions, thank you. A: Forgive my densitosity, but if your hierarchy is anything but the roughest kind of example, there must be hugely compelling, overpowering reasons for your choosing that over, say, JSON or even (gulp!) XML: <items> <item> <number>1</number> <shape>rectangle</shape> <top>10</top> <left>10</left> <width>30</width> <height>40</height> </item> <item> <number>2</number> <shape>triangle</shape> <top>20</top> <left>50</left> <width>30></width> <height>40</height> </item> </items> For XML, you know there are tons of editors that answer your needs. Same with JSON. And I think there are also XML-> MySQL -> XML libraries. Why not take that kind of approach?
GUI tools and APIs for small/medium hierarchical data structures
I'm trying to find a tool and library to edit, write and read data in a hierarchical structure, similar to an LDAP tree, a Windows registry or a Berkeley DB structure. The keys should represent some hierarchy, and the values should have a relatively flexible format (typing is optional, but could be useful). Here is an example: Items/item_1/shape = "rectangle" Items/item_1/top = 10 Items/item_1/left = 10 Items/item_1/width = 30 Items/item_1/height = 40 Items/item_2/shape = "square" Items/item_2/top = 10 Items/item_2/left = 10 Items/item_2/width = 30 Items/item_3/shape = "circle" Items/item_3/centre_x = 40 Items/item_3/centre_y = 50 Items/item_3/radius = 20 Items/item_3/colour = blue The use-case would be: Edit the data store via a convenient GUI. This could look like Windows Regedit or Apache Directory Studio (LDAP Browser). Save that data into some store (e.g. a file). Load this store from another application, which would be able to query it from an API. The library for this would ideally be callable from Python. I'd like these operations to be reasonably fast for reading, but not have it all loaded in memory in advance. The data store would be updated into the application more or less manually, much less often than the data is read. Being able to write to that data from the API would be a plus, but it's not a strict requirement. Queries would be good. For example (in pseudo query), "List Items/* where top == 10" would return: Items/item_1 Items/item_2 Ease of edition (via a good GUI) is one of the most important features. I've considered a few options: An LDAP server answers most requirements (especially with the help of Apache Directory Studio). However, deploying an LDAP server just for that is too heavy. However good Apache Directory Studio is, the user still needs a reasonable understanding of LDAP (more than just explaining the tree hierachy). I'd also like some flexibility in the creation of schemas (or no schemas at all) rather than having to rely on an administrator to do this. Windows Regedit. I'm not sure if it's possible, but I guess it's conceivable to have a registry-like file that has nothing to do with the actual windows registry, editable with custom content via Regedit. I would however like this GUI application to be available on non-Windows platforms and I'm not even sure there's a Python API to read a Windows registry file. RDF. That could work. I'm sure there are fairly good Python libraries for semantic web. However, I don't need any reasoning capabilities. I'd rather have something fast and that doesn't use much memory. I'm not sure there are any good GUI tools to view and edit the tree (since it's geared towards webs and graphs). There are certainly ways to build this sort of data structures on top of existing systems like SQLite (for example), and this would be fine but I'm not sure whether there's a good GUI that would come with it. I'd appreciate comments and suggestions, thank you.
[ "Forgive my densitosity, but if your hierarchy is anything but the roughest kind of example, there must be hugely compelling, overpowering reasons for your choosing that over, say, JSON or even (gulp!) XML:\n\n<items>\n <item>\n <number>1</number>\n <shape>rectangle</shape>\n <top>10</top>\n <left>10</left>\n <width>30</width>\n <height>40</height>\n </item>\n <item>\n <number>2</number>\n <shape>triangle</shape>\n <top>20</top>\n <left>50</left>\n <width>30></width>\n <height>40</height>\n </item>\n</items>\n\nFor XML, you know there are tons of editors that answer your needs. Same with JSON. And I think there are also XML-> MySQL -> XML libraries.\nWhy not take that kind of approach?\n" ]
[ 0 ]
[]
[]
[ "data_structures", "hierarchical_data", "python", "user_interface" ]
stackoverflow_0003097090_data_structures_hierarchical_data_python_user_interface.txt
Q: Most minimal Apache2 configuration for a python script that wgets, combines with local files and provides zip? I have a PHP site setup on my server that also has mod_wsgi + Python 2.5 on it. Occasionally I'm going to be asked to provide a zip of the entire site, and I'd like to use Python instead of PHP to do this. What's the most minimal configuration I could make so that my python script is web accessible in order such that it can wget and grab static files of my site, add my media ( css, js ) directories to a zip and provide that zip to download? A: The mod_wsgi site has very good documenation, including a "QuickStart" guide. It comes complete with a very minimal python script to get you going. If you want to use Python and go even simpler (and performace/load is not an issue), there's always the cgi module.
Most minimal Apache2 configuration for a python script that wgets, combines with local files and provides zip?
I have a PHP site setup on my server that also has mod_wsgi + Python 2.5 on it. Occasionally I'm going to be asked to provide a zip of the entire site, and I'd like to use Python instead of PHP to do this. What's the most minimal configuration I could make so that my python script is web accessible in order such that it can wget and grab static files of my site, add my media ( css, js ) directories to a zip and provide that zip to download?
[ "The mod_wsgi site has very good documenation, including a \"QuickStart\" guide. It comes complete with a very minimal python script to get you going.\nIf you want to use Python and go even simpler (and performace/load is not an issue), there's always the cgi module.\n" ]
[ 1 ]
[]
[]
[ "apache2", "python" ]
stackoverflow_0003097682_apache2_python.txt