content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: How to deploy highly iterative updates I have a set of binary assets (swf files) each about 150Kb in size. I am developing them locally on my home computer and I want to periodically deploy them for review. My current strategy is: Copy the .swf's into a transfer directory that is also a hg (mercurial) repo. hg pu...
How to deploy highly iterative updates
I have a set of binary assets (swf files) each about 150Kb in size. I am developing them locally on my home computer and I want to periodically deploy them for review. My current strategy is: Copy the .swf's into a transfer directory that is also a hg (mercurial) repo. hg push the changes to my slicehost VPN ssh onto ...
[ "to avoid su www I see two easy choices.\n\nmake a folder writable to you and readable by www's group in some path that the web-server will be able to serve, then you can rsync to that folder from somewhere on your local machine.\nput your public ssh key in www's authorized_keys and rsync to the www user (a bit les...
[ 1, 1 ]
[]
[]
[ "deployment", "macos", "python", "rsync", "ubuntu" ]
stackoverflow_0002084969_deployment_macos_python_rsync_ubuntu.txt
Q: Database password requested when running "manage.py test" When I try to run manage.py test a database password prompt shows. Previously, tests would run without me having to enter the db password manaually. I just updated my database to postgres 8.4. I assume it's some setting I'm forgetting. How can I configur...
Database password requested when running "manage.py test"
When I try to run manage.py test a database password prompt shows. Previously, tests would run without me having to enter the db password manaually. I just updated my database to postgres 8.4. I assume it's some setting I'm forgetting. How can I configure it to run tests without asking for the password? Additional I...
[ "Django tests use a different database; your DATABASE_NAME setting with \"_test\" appended. My first guess would be that somewhere in your Postgres authentication config (either in pg_hba.conf or in a ~/.pgpass file), you are allowing access to DATABASE_NAME with no password, but you don't have the same config for ...
[ 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002085002_django_python.txt
Q: How to find out whether a function defined for an instance of a class in Python? I want to know if a function is defined for an instance of a class class c(object): def func(self): pass cc = c() >>> is_function_defined_for_instance(cc,'func') True >>> is_function_defined_for_instance(cc,'cnuf') False my cleane...
How to find out whether a function defined for an instance of a class in Python?
I want to know if a function is defined for an instance of a class class c(object): def func(self): pass cc = c() >>> is_function_defined_for_instance(cc,'func') True >>> is_function_defined_for_instance(cc,'cnuf') False my cleanest attempts at the function is: def is_function_defined_for_instance(instance,function...
[ "In Python 2.6 or better, the recommended approach is:\nimport collections\n\ndef is_func(instance, func):\n return isinstance(getattr(instance, func, None), collections.Callable)\n\nThe new ABCs (Abstract Base Classes) in the collections module are the correct way, in Python 2.6+ and 3.any, to perform this kind o...
[ 3, 2, 0 ]
[]
[]
[ "function", "python", "reflection" ]
stackoverflow_0002087911_function_python_reflection.txt
Q: Why is my Facebook application with error 104 ("invalid signature")? I am trying to develop a Facebook application using PyFacebook (hosted on Google App Engine). It's an FBML application (runs in a Facebook canvas instead of an iframe). I'm having problems getting any API calls to function. The sequence looks ...
Why is my Facebook application with error 104 ("invalid signature")?
I am trying to develop a Facebook application using PyFacebook (hosted on Google App Engine). It's an FBML application (runs in a Facebook canvas instead of an iframe). I'm having problems getting any API calls to function. The sequence looks like this: fb = facebook.Faceboook(api_key, secret_key) fb.session_key = c...
[ "Deleting the Facebook application and re-creating it, then configuring my code with the new API key and secret key, resolved this problem.\n" ]
[ 1 ]
[]
[]
[ "authentication", "cherrypy", "facebook", "pyfacebook", "python" ]
stackoverflow_0002087672_authentication_cherrypy_facebook_pyfacebook_python.txt
Q: Java equivalent of Pythons urllib.urlencode(HashMap based UrlEncode) From Whats the java equivalent of Python’s urllib.urlencode? Like >>> urllib.urlencode({'abc':'d f', 'def': '-!2'}) 'abc=d+f&def=-%212' Where I can pass a HashMap of key values and it encodes and gives me the url string .. Edit: I wanted to avo...
Java equivalent of Pythons urllib.urlencode(HashMap based UrlEncode)
From Whats the java equivalent of Python’s urllib.urlencode? Like >>> urllib.urlencode({'abc':'d f', 'def': '-!2'}) 'abc=d+f&def=-%212' Where I can pass a HashMap of key values and it encodes and gives me the url string .. Edit: I wanted to avoid this scenario String data = URLEncoder.encode("key1", "UTF-8") + "=" + ...
[ "java.net.URLEncoder should work for you - though you would have to extend it to accept the hashmap - but that is not very difficult. \n" ]
[ 2 ]
[]
[]
[ "encoding", "java", "python", "url", "urlencode" ]
stackoverflow_0002088502_encoding_java_python_url_urlencode.txt
Q: Storing system-wide DB connection password for a Python module I have a written a Python module which due to its specifics needs to have a MySQL database connection. Right now, details of this connection (host, database, username and password to connect with) are stored in /etc/mymodule.conf in plaintext, which is...
Storing system-wide DB connection password for a Python module
I have a written a Python module which due to its specifics needs to have a MySQL database connection. Right now, details of this connection (host, database, username and password to connect with) are stored in /etc/mymodule.conf in plaintext, which is obviously not a good idea. Supposedly, the /etc/mymodule.conf file ...
[ "Your constraints set a very difficult problem: every user on the system must be able to access that password (since that's the only way for users to access that database)... yet they must not (except when running that script, and presumably only when running it without e.g. a python -i session that would let them ...
[ 4, 1 ]
[]
[]
[ "python", "security" ]
stackoverflow_0002087920_python_security.txt
Q: Local installation of python I want to install python to my local direcotory: ./configure --prefix=/home/alex/local-install && make && make install When i import sqlite3 i get the following: ImportError: No module named _sqlite3 the reason: there is no _sqlite3.so in /home/alex/local-install/lib/python2.6/lib-dy...
Local installation of python
I want to install python to my local direcotory: ./configure --prefix=/home/alex/local-install && make && make install When i import sqlite3 i get the following: ImportError: No module named _sqlite3 the reason: there is no _sqlite3.so in /home/alex/local-install/lib/python2.6/lib-dynload. How can i force python to b...
[ "You need to install the development headers and libraries for sqlite somewhere where the Python build can find them. You didn't say what OS you have. On Linux you usually have to install additional -dev[el] packages to be able to build against a library.\n" ]
[ 3 ]
[]
[]
[ "installation", "makefile", "python", "sqlite" ]
stackoverflow_0002089054_installation_makefile_python_sqlite.txt
Q: How to get more search results than the server's sizelimit with Python LDAP? I am using the python-ldap module to (amongst other things) search for groups, and am running into the server's size limit and getting a SIZELIMIT_EXCEEDED exception. I have tried both synchronous and asynchronous searches and hit the pr...
How to get more search results than the server's sizelimit with Python LDAP?
I am using the python-ldap module to (amongst other things) search for groups, and am running into the server's size limit and getting a SIZELIMIT_EXCEEDED exception. I have tried both synchronous and asynchronous searches and hit the problem both ways. You are supposed to be able to work round this by setting a pagin...
[ "Here are some links related to paging in python-ldap.\n\nDocumentation: http://www.python-ldap.org/doc/html/ldap-controls.html#ldap.controls.SimplePagedResultsControl\nExample code using paging: http://www.novell.com/coolsolutions/tip/18274.html\nMore example code: http://google-apps-for-your-domain-ldap-sync.goog...
[ 17, 8 ]
[]
[]
[ "ldap", "python" ]
stackoverflow_0002073574_ldap_python.txt
Q: How do I get cx_Oracle to work on 64-bit Itanium Windows? I'm running Windows Server 2003 on a 64-bit Itanium server which is also running 64-bit Oracle 10.2, and I'd like to install cx_Oracle for Python 2.5. I've used cx_Oracle before many times on both Windows and Linux, and I've also compiled it before on 32 b...
How do I get cx_Oracle to work on 64-bit Itanium Windows?
I'm running Windows Server 2003 on a 64-bit Itanium server which is also running 64-bit Oracle 10.2, and I'd like to install cx_Oracle for Python 2.5. I've used cx_Oracle before many times on both Windows and Linux, and I've also compiled it before on 32 bit versions of those platforms, but I've never tried an IA64 co...
[ "I ended up going with Option #2: I downloaded the 32-bit Oracle Instant Client, then compiled cx_Oracle for 32-bit Python with the instant client. So everything involved is 32-bit, and I'm just not using any IA64-bit executables, and this works just fine.\nIf I had an IA64 compiler, I'd try Option #3, but it turn...
[ 1, 0 ]
[]
[]
[ "64_bit", "cx_oracle", "itanium", "python", "windows" ]
stackoverflow_0002024016_64_bit_cx_oracle_itanium_python_windows.txt
Q: How do I resolve a "Too many open files" error in Bazaar? I am using Bazaar v2.0.1 on Max OS X 10.6.2 When I perform a commit after moving a large number of files/directories (over 10,000) I get the following error message: bzr: ERROR: [Errno 24] open: Too many open files: '.' My first work-around was to break...
How do I resolve a "Too many open files" error in Bazaar?
I am using Bazaar v2.0.1 on Max OS X 10.6.2 When I perform a commit after moving a large number of files/directories (over 10,000) I get the following error message: bzr: ERROR: [Errno 24] open: Too many open files: '.' My first work-around was to break the commit up into several sub-sets. However, this is not ide...
[ "You can use lsof to see all open files. You might try grepping for the pid of the bazaar process, or monitoring the number of open files.\nNote that you may or may not need to be root to see all files / processes relevant for your situation.\n", "Try ulimit -n 1024 (or more) before running bazaar, if your shell...
[ 3, 2 ]
[]
[]
[ "bazaar", "python" ]
stackoverflow_0002089353_bazaar_python.txt
Q: attribute 'tzinfo' of 'datetime.datetime' objects is not writable How do I set the timezone of a datetime instance that just came out of the datastore? When it first comes out it is in UTC. I want to change it to EST. I'm trying, for example: class Book( db.Model ): creationTime = db.DateTimeProperty() When ...
attribute 'tzinfo' of 'datetime.datetime' objects is not writable
How do I set the timezone of a datetime instance that just came out of the datastore? When it first comes out it is in UTC. I want to change it to EST. I'm trying, for example: class Book( db.Model ): creationTime = db.DateTimeProperty() When a Book is retrieved, I want to set its tzinfo immediately: book.creatio...
[ "datetime's objects are immutable, so you never change any of their attributes -- you make a new object with some attributes the same, and some different, and assign it to whatever you need to assign it to.\nI.e., in your case, instead of\nbook.creationTime.tzinfo = EST\n\nyou have to code\nbook.creationTime = book...
[ 64, 7, 0 ]
[]
[]
[ "datetime", "google_app_engine", "python", "tzinfo" ]
stackoverflow_0002089419_datetime_google_app_engine_python_tzinfo.txt
Q: Python NameError list1 = [a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z] for item in list1: print item Not sure why the above code is throwing this error: NameError: "name 'a' is not defined" A: In addition to using quotes properly, don't retype the alphabet. >>> import string >>> string.ascii_lowerc...
Python NameError
list1 = [a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z] for item in list1: print item Not sure why the above code is throwing this error: NameError: "name 'a' is not defined"
[ "In addition to using quotes properly, don't retype the alphabet.\n>>> import string\n>>> string.ascii_lowercase\n'abcdefghijklmnopqrstuvwxyz'\n>>> L = list(string.ascii_lowercase)\n>>> print L\n['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', ...\n>>> help(string)\n\n", "You have to put strings into (double) q...
[ 12, 7, 2, 1, 1, 1, 0 ]
[]
[]
[ "python", "syntax" ]
stackoverflow_0002081168_python_syntax.txt
Q: Server Setup for iPhone Push Notifications I'm new to the whole push notifications thing, and was wondering if somebody could walk me through the process of getting a simple application up and running. I currently rent a server that I use to serve my website that runs cPanel X. How would I go about setting up the...
Server Setup for iPhone Push Notifications
I'm new to the whole push notifications thing, and was wondering if somebody could walk me through the process of getting a simple application up and running. I currently rent a server that I use to serve my website that runs cPanel X. How would I go about setting up the service? What software do I need to install on ...
[ "I would go to the Apple Developer Forums. They have many questions and answers regarding this. For my apps, I use a Ruby On Rails plugin called apn_on_rails, but this is probably not an option for you on a shared host with some sort of admin gui. Your shared host probably runs php so I would look for a php impl...
[ 3 ]
[]
[]
[ "iphone", "push_notification", "python", "ruby_on_rails" ]
stackoverflow_0002089701_iphone_push_notification_python_ruby_on_rails.txt
Q: Rotate a quad around a centre point in OpenGL I'm making a 2D game. I want to be able to render a texture on the screen after rotating it a certain amount around a centre point. Basically this is for a level rotation around a player. The player position being the rotation point and the direction of the player as t...
Rotate a quad around a centre point in OpenGL
I'm making a 2D game. I want to be able to render a texture on the screen after rotating it a certain amount around a centre point. Basically this is for a level rotation around a player. The player position being the rotation point and the direction of the player as the angle. This code wont work: def draw_texture(tex...
[ "try reversing\nglTranslatef(point[0],point[1],0)\n\nand\nglRotatef(rotation,0,0,1)\n\nyou're translating to the player, but then rotating about the origin (not the player)\nIllustration from the red book: \n", "Unless you have a good reason to do otherwise, I'd leave the drawing code alone, and just change the c...
[ 2, 0 ]
[]
[]
[ "opengl", "primitive", "python", "rotation", "textures" ]
stackoverflow_0002089849_opengl_primitive_python_rotation_textures.txt
Q: Interpreter that ignores leading >>> characters and ellipsis I am studying some examples in a tutorial where there are a lot of leading >>> characters and ellipsis in the text. This makes it hard to cut and paste into the IPython interpreter since it doesn't like these strings. Is there another interpreter I could...
Interpreter that ignores leading >>> characters and ellipsis
I am studying some examples in a tutorial where there are a lot of leading >>> characters and ellipsis in the text. This makes it hard to cut and paste into the IPython interpreter since it doesn't like these strings. Is there another interpreter I could use that will appropriately ignore and interpret these leading te...
[ "IPython can do this (look at the %paste magic command)\n", "In any case, a way to clean up such stuff by python code:\nimport re\nmatcher= re.compile(\"(?m)^[.>]{3} \")\ndef cleanup(text):\n return matcher.sub('', text)\n\nExample use:\n>>> print (cleanup(\"\"\">>> d = dict(x.__array_interface__)\n>>> d['shap...
[ 4, 0 ]
[]
[]
[ "ide", "interpreter", "python" ]
stackoverflow_0002066061_ide_interpreter_python.txt
Q: Python 3 Library for Realtime Midi Communication Can anyone suggest a good Python 3 Library for sending / receiving reatime MIDI? A: Why Python 3? It generally doesn't have many libraries yet. Generally you want to look into high-level C-libraries with Python wrappers. I doubt many of these work under Python 3 a...
Python 3 Library for Realtime Midi Communication
Can anyone suggest a good Python 3 Library for sending / receiving reatime MIDI?
[ "Why Python 3? It generally doesn't have many libraries yet. Generally you want to look into high-level C-libraries with Python wrappers. I doubt many of these work under Python 3 at the moment. \n" ]
[ 1 ]
[]
[]
[ "midi", "python", "python_3.x" ]
stackoverflow_0001742382_midi_python_python_3.x.txt
Q: How to format search autocompletion part lists? I'm currently working on an AppEngine project, and I'd like to implement autocompletion of search terms. The items that can be searched for are reasonably unambiguous and short, so I was thinking of implementing it by giving each item a list of incomplete typings. So...
How to format search autocompletion part lists?
I'm currently working on an AppEngine project, and I'd like to implement autocompletion of search terms. The items that can be searched for are reasonably unambiguous and short, so I was thinking of implementing it by giving each item a list of incomplete typings. So foobar would get a list like [f, fo, foo, foob, foob...
[ "I have already run into the same problem and the solution that I adopted was very similar to your idea. I split the items into words, convert them to lowercase, remove accents, and create a list of startings. For instance, \"Báz Bar\" would become ['b', 'ba', 'bar', 'baz']. \nI have posted the code in this thread....
[ 2 ]
[]
[]
[ "autocomplete", "autosuggest", "google_app_engine", "python", "search" ]
stackoverflow_0002089917_autocomplete_autosuggest_google_app_engine_python_search.txt
Q: How to send a string from a python script at Google App Engine to the browser client as a file I have a python web-application running inside the Google App Engine. The application creates on user-demand a string and I want the string to be send to the browser client (application/octet-stream?) as a file. How can ...
How to send a string from a python script at Google App Engine to the browser client as a file
I have a python web-application running inside the Google App Engine. The application creates on user-demand a string and I want the string to be send to the browser client (application/octet-stream?) as a file. How can i realize this?
[ "If you're using App Engine's own, simple webapp framework, the simplest approach is to have as the get method of your request handler object something like:\ndef get(self):\n thestring = 'helloworld' # or however else it's synthesized;-)\n self.response.headers.add_header(\n 'content-disposition', 'attachm...
[ 3, 0 ]
[]
[]
[ "google_app_engine", "html", "mime_types", "python" ]
stackoverflow_0002089635_google_app_engine_html_mime_types_python.txt
Q: Printing correct time using timezones, Python Extends Ok, we are not having a good day today. When you attach the correct tzinfo object to a datetime instance, and then you strftime() it, it STILL comes out in UTC, seemingly ignoring the beautiful tzinfo object I attached to it. # python 2.5.4 now = datet...
Printing correct time using timezones, Python
Extends Ok, we are not having a good day today. When you attach the correct tzinfo object to a datetime instance, and then you strftime() it, it STILL comes out in UTC, seemingly ignoring the beautiful tzinfo object I attached to it. # python 2.5.4 now = datetime.now() print now.strftime( "%a %b %d %X" ) #...
[ ".replace does no computation: it simply replaces one or more field in the new returned object, while copying all others from the object it's called on.\nIf I understand your situation correctly, you start with a datetime object which you know (through other means) is UTC, but doesn't know that itself (is has a tzi...
[ 15, 5, 2 ]
[]
[]
[ "datetime", "python", "tzinfo" ]
stackoverflow_0002089706_datetime_python_tzinfo.txt
Q: Google app engine after refresh from datastore I want to set the .tzinfo of every datetime instance automatically as soon as it comes out of the datastore. So if I have class Message( db.Model ): creationTime = db.DateTimeProperty() someOtherTime = db.DateTimeProperty() ## I really want to define a me...
Google app engine after refresh from datastore
I want to set the .tzinfo of every datetime instance automatically as soon as it comes out of the datastore. So if I have class Message( db.Model ): creationTime = db.DateTimeProperty() someOtherTime = db.DateTimeProperty() ## I really want to define a method like this, ## that runs immediately AFTER a...
[ "I think the best approach is for you to subclass the DateTimeProperty class and override its method make_value_from_datastore:\nclass EstDateTimeProperty(db.DateTimeProperty):\n def make_value_from_datastore(self, value):\n naive_utc = db.DateTimeProperty(self, value)\n aware_utc = naive_utc.replace(tzinfo=...
[ 2, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002089746_google_app_engine_python.txt
Q: How can I process xml asynchronously in python? I have a large XML data file (>160M) to process, and it seems like SAX/expat/pulldom parsing is the way to go. I'd like to have a thread that sifts through the nodes and pushes nodes to be processed onto a queue, and then other worker threads pull the next available ...
How can I process xml asynchronously in python?
I have a large XML data file (>160M) to process, and it seems like SAX/expat/pulldom parsing is the way to go. I'd like to have a thread that sifts through the nodes and pushes nodes to be processed onto a queue, and then other worker threads pull the next available node off the queue and process it. I have the followi...
[ "I'm not too sure about this problem. I'm guessing the call to ParseFile is blocking and only the parsing thread is being run because of the GIL. A way around this would be to use multiprocessing instead. It's designed to work with queues, anyway.\nYou make a Process and you can pass it a Queue:\nimport sys, time\n...
[ 8, 8, 1, 0 ]
[]
[]
[ "multithreading", "python", "sax", "xml" ]
stackoverflow_0002090096_multithreading_python_sax_xml.txt
Q: python search replace using wildcards somewhat confused.. but trying to do a search/repace using wildcards if i have something like: <blah.... ssf ff> <bl.... ssf dfggg ff> <b.... ssf ghhjj fhf> and i want to replace all of the above strings with say, <hh >t any thoughts/comments on how this ca...
python search replace using wildcards
somewhat confused.. but trying to do a search/repace using wildcards if i have something like: <blah.... ssf ff> <bl.... ssf dfggg ff> <b.... ssf ghhjj fhf> and i want to replace all of the above strings with say, <hh >t any thoughts/comments on how this can be accomplished? thanks update (thanks fo...
[ "How about like this, with regex\nimport re\n\nYOURTEXT=re.sub(\"<b[^>]*>\",\"<hh >t\",YOURTEXT)\n\n", "See the rather usable Python Regular Expression manual here, or for a more hands-on approach a Regular Expression HOWTO section 5.2 Search and Replace.\n", "don't have to use regex\nfor line in open(\"file\")...
[ 3, 1, 0, 0 ]
[]
[]
[ "python", "regex", "replace", "search", "wildcard" ]
stackoverflow_0002090100_python_regex_replace_search_wildcard.txt
Q: GObject.add_emission_hook usage I was kindly directed to use GObject's "add_emission_hook" following a recent question on SO but I can't seem to find a usage example. Does anyone have one to share, please? A: After a discussion with helpful folks on IRC #pygtk, here is what I came up with: import gobject clas...
GObject.add_emission_hook usage
I was kindly directed to use GObject's "add_emission_hook" following a recent question on SO but I can't seem to find a usage example. Does anyone have one to share, please?
[ "After a discussion with helpful folks on IRC #pygtk, here is what I came up with:\nimport gobject\n\nclass Signals(gobject.GObject):\n\n __gsignals__ = {\n \"lastfm_username_changed\": (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (gobject.TYPE_STRING,)) #@UndefinedVariable\n }\n\n def __init__(sel...
[ 0 ]
[]
[]
[ "gobject", "pygobject", "python" ]
stackoverflow_0002088451_gobject_pygobject_python.txt
Q: Problems enabling a quit function in Python I'm pretty new to programming in general and I'm creating a small game for my younger sister... I have a while loop in which I want to have an option to quit the game, but none of the quitting techniques I know of seem to work: #main game: while 1: input_event_1 = gu...
Problems enabling a quit function in Python
I'm pretty new to programming in general and I'm creating a small game for my younger sister... I have a while loop in which I want to have an option to quit the game, but none of the quitting techniques I know of seem to work: #main game: while 1: input_event_1 = gui.buttonbox( msg = 'Hello, what would you...
[ "I think this is your problem:\nif input_quit == 'Quit':\n input_quit = gui.ynbox(\n msg = 'Are you sure you want to quit?',\n\nshould be\nif input_event_1 == 'Quit':\n input_quit = gui.ynbox(\n msg = 'Are you sure you want to quit?',\n\nEdit: the reason it's still not working, according...
[ 2, 2, 0, 0 ]
[]
[]
[ "python", "quit" ]
stackoverflow_0002090582_python_quit.txt
Q: how to drag image in a wxpython frame what is the easiest way to drag an image ( or text) in a wx window ? i need steps or a small example on how to do that. thanx in advance A: Take a look at the PseudoDC example in the wxPython demo. The sample displays some random shapes within the window which you can grab ...
how to drag image in a wxpython frame
what is the easiest way to drag an image ( or text) in a wx window ? i need steps or a small example on how to do that. thanx in advance
[ "Take a look at the PseudoDC example in the wxPython demo. The sample displays some random shapes within the window which you can grab and move around, you should be able to apply the concepts for an image. \nYou can download the win32-docs-demos from here\n", "Install wxpython demos, there is DragImage demostrat...
[ 1, 0 ]
[]
[]
[ "drag_and_drop", "drawing", "gdi", "python", "wxpython" ]
stackoverflow_0002062864_drag_and_drop_drawing_gdi_python_wxpython.txt
Q: wxpython systray icon menu I'm designing an application that I want to run in the background. There isn't any user interaction necessary, so I want the app to run invisibly save for a systray icon. I want that icon to have a menu that just opens the config/help files in notepad. Could someone point me in the right...
wxpython systray icon menu
I'm designing an application that I want to run in the background. There isn't any user interaction necessary, so I want the app to run invisibly save for a systray icon. I want that icon to have a menu that just opens the config/help files in notepad. Could someone point me in the right direction or provide an example...
[ "You can probably do this more cleanly but I have using some samples a while back I was able to create myself a class to handle the basic contruction of a taskbar icon.\nTaskBarIcon.py\nimport wx\n\n\nID_SHOW_OPTION = wx.NewId()\nID_EDIT_OPTION = wx.NewId()\n\n\nclass Icon(wx.TaskBarIcon):\n\n def __init__(self,...
[ 5, 3, 2 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0002015969_python_wxpython.txt
Q: Symbolic Group Names (like in Python) in Ruby Regular Expression Came across this handy regular expression utility in Python (I am a beginner in Python). e.g. By using the regexp (?P<id>[a-zA-Z_]\w*) I can refer to the matched data as m.group('id') (Full documentation: look for "symbolic group name" here) In R...
Symbolic Group Names (like in Python) in Ruby Regular Expression
Came across this handy regular expression utility in Python (I am a beginner in Python). e.g. By using the regexp (?P<id>[a-zA-Z_]\w*) I can refer to the matched data as m.group('id') (Full documentation: look for "symbolic group name" here) In Ruby, we can access the matched references using $1, $2 or using the Ma...
[ "Older Ruby releases didn't have named groups (tx Alan for pointing this out in a comment!), but, if you're using Ruby 1.9...:\n(?<name>subexp) expresses a named group in Ruby expressions too; \\k<name> is the way you back-reference a named group in substitution, if that's what you're looking for!\n", "Ruby 1.9 i...
[ 12, 10 ]
[]
[]
[ "python", "regex", "ruby" ]
stackoverflow_0002090424_python_regex_ruby.txt
Q: Python dictionary key order when printing s={ 'userName': "4-12\u4e2a\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf", 'userNameMin': "\u4e0d\u80fd\u5c0f\u4e8e4\u4e2a\u5b57", 'userNameMax': "\u4e0d\u80fd\u8d85\u8fc712\u4e2a\u5b57", 'userNameExist': "\u8be5\u7528\u...
Python dictionary key order when printing
s={ 'userName': "4-12\u4e2a\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf", 'userNameMin': "\u4e0d\u80fd\u5c0f\u4e8e4\u4e2a\u5b57", 'userNameMax': "\u4e0d\u80fd\u8d85\u8fc712\u4e2a\u5b57", 'userNameExist': "\u8be5\u7528\u6237\u540d\u5df2\u88ab\u6ce8\u518c\u4e86\uff0c\...
[ "Use OrderedDict on python 2.7+\nOr change dict to tuple or list, something like this\n[\n ('userName', \"4-12\\u4e2a\\u82f1\\u6587\\u5b57\\u6bcd\\u3001\\u6570\\u5b57\\u548c\\u4e0b\\u5212\\u7ebf\"),\n ('userNameMin', \"\\u4e0d\\u80fd\\u5c0f\\u4e8e4\\u4e2a\\u5b57\"),\n ....\n]\n\nAnd use s instead of s.item...
[ 5, 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002090564_python.txt
Q: Change keyboard input method to unicode? I am going to create an application called 'khmer keyboard input method' the khmer just come in unicode standard (Range: 1780–17FF). reference http://www.unicode.org/charts/PDF/U1780.pdf this application it will allow cambodian to switch from English to Khmer by press the d...
Change keyboard input method to unicode?
I am going to create an application called 'khmer keyboard input method' the khmer just come in unicode standard (Range: 1780–17FF). reference http://www.unicode.org/charts/PDF/U1780.pdf this application it will allow cambodian to switch from English to Khmer by press the definded shortcut key (F10 for example). the ap...
[ "There is no single way. Each IME has its own way of picking a different engine/method.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0002090886_python.txt
Q: How to set value of current Numbers cell using Py-Appscript This seems like a straightforward operation but I am stumped. How do you set value of current Numbers cell using Py-Appscript? A: Pretty tediously, but working: >>> from appscript import * >>> app('Numbers').documents.first.sheets.first.tables.first.sel...
How to set value of current Numbers cell using Py-Appscript
This seems like a straightforward operation but I am stumped. How do you set value of current Numbers cell using Py-Appscript?
[ "Pretty tediously, but working:\n>>> from appscript import *\n>>> app('Numbers').documents.first.sheets.first.tables.first.selection_range.cells.first.value.set(to=42)\n\nThat's assuming a simple document. More generally, you can select items by name:\n>>> app('Numbers').documents['MyDocument.numbers'].sheets['MyS...
[ 2 ]
[]
[]
[ "iwork", "python", "sourceforge_appscript" ]
stackoverflow_0002090921_iwork_python_sourceforge_appscript.txt
Q: What is the maximum packet size a python socket can handle? i am new to network programming in python. I wanted to know that what is the maximum size packet we can transmit or receive on python socket? and how to find out it? A: The actual amount of data that can be sent in a single packet depends on what the Ma...
What is the maximum packet size a python socket can handle?
i am new to network programming in python. I wanted to know that what is the maximum size packet we can transmit or receive on python socket? and how to find out it?
[ "The actual amount of data that can be sent in a single packet depends on what the Maximum Transmission Unit (MTU) is for the protocol you're using. Read the Wikipedia article for more information.\nThis is generally something you don't have to worry about, though - if you send a TCP packet that's too big, the oper...
[ 5, 1, 0 ]
[]
[]
[ "network_programming", "python", "sockets" ]
stackoverflow_0002091097_network_programming_python_sockets.txt
Q: Weird pynotify behaviour in Ubuntu 9.10 I wrote a small app and I am using pynotify to show some messages to the user. It all works fine here in arch, but when I tested it in Ubuntu, the behaviour was very weird. Because of the way Ubuntu shows notifications (as what seems to be a rip of of growl), I can't click o...
Weird pynotify behaviour in Ubuntu 9.10
I wrote a small app and I am using pynotify to show some messages to the user. It all works fine here in arch, but when I tested it in Ubuntu, the behaviour was very weird. Because of the way Ubuntu shows notifications (as what seems to be a rip of of growl), I can't click on them, or interact with them in any way, for...
[ "Yes, Ubuntu 9.10 replaced upstream's notification-daemon with their own notify-osd, and generally made a mess of things.\nYou can ensure notification-daemon is installed (via whatever your favorite package manager front-end is) and use it in favor of notify-osd:\n\n$ sudo mv /usr/share/dbus-1/services/org.freedesk...
[ 3 ]
[]
[]
[ "linux", "pynotify", "python", "ubuntu", "ubuntu_9.10" ]
stackoverflow_0002090273_linux_pynotify_python_ubuntu_ubuntu_9.10.txt
Q: Regular expression for urlpattern I need a regexp for a URL like: /slug/#slug/slug/ I know it should be something like: r'^(?P<slug1>[-\w]+)/#(?P<slug2>[-\w]+)/(?P<slug3>[-\w]+)/$' But I am having problems with the character # A: Parameter after # character is not send to server, so cannot catch in server side...
Regular expression for urlpattern
I need a regexp for a URL like: /slug/#slug/slug/ I know it should be something like: r'^(?P<slug1>[-\w]+)/#(?P<slug2>[-\w]+)/(?P<slug3>[-\w]+)/$' But I am having problems with the character #
[ "Parameter after # character is not send to server, so cannot catch in server side script like django.\n", "The URL fragment (everything after the #) is not sent to the server in a request.\n" ]
[ 5, 2 ]
[]
[]
[ "django", "django_urls", "python", "regex" ]
stackoverflow_0002091449_django_django_urls_python_regex.txt
Q: Sorting CSV in Python I assumed sorting a CSV file on multiple text/numeric fields using Python would be a problem that was already solved. But I can't find any example code anywhere, except for specific code focusing on sorting date fields. How would one go about sorting a relatively large CSV file (tens of thous...
Sorting CSV in Python
I assumed sorting a CSV file on multiple text/numeric fields using Python would be a problem that was already solved. But I can't find any example code anywhere, except for specific code focusing on sorting date fields. How would one go about sorting a relatively large CSV file (tens of thousand lines) on multiple fiel...
[ "Python's sort works in-memory only; however, tens of thousands of lines should fit in memory easily on a modern machine. So:\nimport csv\n\ndef sortcsvbymanyfields(csvfilename, themanyfieldscolumnnumbers):\n with open(csvfilename, 'rb') as f:\n readit = csv.reader(f)\n thedata = list(readit)\n thedata.sor...
[ 10, 4, 2 ]
[ "You bring up 3 issues:\n\nfile size\ncsv data\nsorting on multiple fields\n\nHere is a solution for the third part. You can handle csv data in a more sophisticated way.\n>>> data = 'a,b,c\\nb,b,a\\nb,c,a\\n'\n>>> lines = [e.split(',') for e in data.strip().split('\\n')]\n>>> lines\n[['a', 'b', 'c'], ['b', 'b', 'a...
[ -1 ]
[ "csv", "python", "sorting" ]
stackoverflow_0002089036_csv_python_sorting.txt
Q: unidentified com_error in python I've encountered the following error while scripting in Python. ERROR Tue 19. Jan 14:51:21 2010 C:\Python24\Lib\site-packages\win32com\client\util.py:0: Script Error com_error: (-2147217385, 'OLE error 0x80041017', None, None) Unfortunately, I don't know what it means, or even...
unidentified com_error in python
I've encountered the following error while scripting in Python. ERROR Tue 19. Jan 14:51:21 2010 C:\Python24\Lib\site-packages\win32com\client\util.py:0: Script Error com_error: (-2147217385, 'OLE error 0x80041017', None, None) Unfortunately, I don't know what it means, or even what other information I might need t...
[ "Here's a page at the Microsoft site which might shed some light:\n\nWBEM_E_INVALID_QUERY\n2147749911 (0x80041017)\nQuery was not syntactically valid.\n\n", "When doing python COM programming, I sometimes use VBA (in Excel) to test code that gives errors.\nThat way, I can see if the problem is in the Python-COM l...
[ 1, 0 ]
[]
[]
[ "com", "python" ]
stackoverflow_0002090950_com_python.txt
Q: How do I access an object's properties by name? class a(type): def __str__(self): return 'aaa' def __new__(cls, name, bases, attrs): attrs['cool']='cool!!!!' new_class = super(a,cls).__new__(cls, name, bases, attrs) #if 'media' not in attrs: #new_...
How do I access an object's properties by name?
class a(type): def __str__(self): return 'aaa' def __new__(cls, name, bases, attrs): attrs['cool']='cool!!!!' new_class = super(a,cls).__new__(cls, name, bases, attrs) #if 'media' not in attrs: #new_class.media ='media' return new_class class ...
[ "print b().cool\n\nattrs in your __new__ method becomes the object's dictionary. Properties of Python objects are referenced with the . syntax.\n", "print \"cool!!!\"\n\nOr did I miss something?\n" ]
[ 5, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002092002_python.txt
Q: Variables as a part of calling a method in python I'm pretty new to programming and I'm creating a python game for my little sister. I'm having trouble, because I want the variable value to be a part of the method name Is there any way this is possible? def play_with_toy(self): toy = gui.buttonbox( msg...
Variables as a part of calling a method in python
I'm pretty new to programming and I'm creating a python game for my little sister. I'm having trouble, because I want the variable value to be a part of the method name Is there any way this is possible? def play_with_toy(self): toy = gui.buttonbox( msg = 'Choose a toy for your potato head to play with:', ...
[ "method = getattr(myPotatoHead, 'play_' + toy)\nmethod()\n\n", "getattr(myPotatoHead,\"play_\"+toy)()\n\n", "Try this: \nmethod = getAttr(myPotatoHead, 'play_' + toy)\nmethod()\n\n(sorry about the semi-colons! I was programming in javascript all day). \n" ]
[ 3, 1, 1 ]
[]
[]
[ "function", "python" ]
stackoverflow_0002092059_function_python.txt
Q: Uploading files in RESTful way? I'm designing a RESTful API that should handle binary file uploads. Should this be done the same way as html form upload or is there a better way? A: Take a look at the Amazon api for an idea. It uses a PUT query and then through sendREST it sends the content. Uploading files to ...
Uploading files in RESTful way?
I'm designing a RESTful API that should handle binary file uploads. Should this be done the same way as html form upload or is there a better way?
[ "Take a look at the Amazon api for an idea. It uses a PUT query and then through sendREST it sends the content. \nUploading files to Amazon S3 with REST API\n", "A good way is to upload the binary information using streams. You could have a look at the JeCARS client project. To be exact the JC_RESTComm.java class...
[ 3, 1 ]
[]
[]
[ "file", "file_upload", "java", "python", "rest" ]
stackoverflow_0002092249_file_file_upload_java_python_rest.txt
Q: How do I get js and css to display in Django? I've got a template, a.html, which looks like this: <script type="text/javascript" src="jquery-1.4.min.js"></script> <script type="text/javascript" src="reg.js"></script> Why doesn't this work? A: Try: <script type="text/javascript" src="{{ MEDIA_URL }}jquery-1.4.mi...
How do I get js and css to display in Django?
I've got a template, a.html, which looks like this: <script type="text/javascript" src="jquery-1.4.min.js"></script> <script type="text/javascript" src="reg.js"></script> Why doesn't this work?
[ "Try:\n<script type=\"text/javascript\" src=\"{{ MEDIA_URL }}jquery-1.4.min.js\"></script>\n<script type=\"text/javascript\" src=\"{{ MEDIA_URL }}reg.js\"></script>\n\nYou'll need to make sure you're serving static files correctly, and you'll need \"django.core.context_processors.media\" in the TEMPLATE_CONTEXT_PRO...
[ 3, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002092346_django_python.txt
Q: Run a C++ Program from Django Framework I need to run a C++ Program from Django Framework. In a sense, I get inputs from UI in views.py . Once I have these inputs, I need to process the input using my C++ program and use those results. Is it possible ? A: Compile that C++ program to executable and call with subp...
Run a C++ Program from Django Framework
I need to run a C++ Program from Django Framework. In a sense, I get inputs from UI in views.py . Once I have these inputs, I need to process the input using my C++ program and use those results. Is it possible ?
[ "Compile that C++ program to executable and call with subprocess module from python\n", "You can use swig to create a C++ module that can be imported in python.\nAn alternative is boost::python (but personnaly, I prefer swig).\n", "One way of doing this would be to use os.popen. Assuming your C++ executable is ...
[ 10, 1, 0, 0 ]
[]
[]
[ "c++", "django", "python" ]
stackoverflow_0002091294_c++_django_python.txt
Q: Equivalent to django Form to show object contents Is there any Django class used to show the contents of an object model in a non-modifiable way? Something like this for forms to edit the objects from a model: class TestForm(forms.ModelForm): class Meta: model = models.Test using it as: def generic_vi...
Equivalent to django Form to show object contents
Is there any Django class used to show the contents of an object model in a non-modifiable way? Something like this for forms to edit the objects from a model: class TestForm(forms.ModelForm): class Meta: model = models.Test using it as: def generic_view(request): form = TestForm() return render_to...
[ "Calling repr() against the model instance will get you a (admittedly ugly) representation of the instance fields.\n", "I would take a look at the source of Databrowse to see how it does it. It introspects models and displays the data of objects with minimal configuration, so it probably has a component that does...
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002092242_django_python.txt
Q: Categorize a list of lists by 1 element in python An example list of lists: [ ["url","name","date","category"] ["hello","world","2010","one category"] ["foo","bar","2010","another category"] ["asdfasdf","adfasdf","2010","one category"] ["qwer","req","2010","another category"] ] What I wish do to is create a dicti...
Categorize a list of lists by 1 element in python
An example list of lists: [ ["url","name","date","category"] ["hello","world","2010","one category"] ["foo","bar","2010","another category"] ["asdfasdf","adfasdf","2010","one category"] ["qwer","req","2010","another category"] ] What I wish do to is create a dictionary -> category : [ list of entries ]. The resultant ...
[ "dict((category, list(l)) for category, l \n in itertools.groupby(l, operator.itemgetter(3))\n\nThe main thing here is the usage of itertools.groupby. It simply returns iterables instead of lists, which is why there's a call for list(l), which means that if you're ok with that, you can simply write dict(itertoo...
[ 7, 5, 2, 1, 1 ]
[ ">>> l = [\n... [\"url\",\"name\",\"date\",\"category\"],\n... [\"hello\",\"world\",\"2010\",\"one category\"],\n... [\"foo\",\"bar\",\"2010\",\"another category\"],\n... [\"asdfasdf\",\"adfasdf\",\"2010\",\"one category\"],\n... [\"qwer\",\"req\",\"2010\",\"another category\"],\n... ]\n#Intermediate list to genera...
[ -2 ]
[ "dictionary", "list", "map", "python", "sorting" ]
stackoverflow_0002092380_dictionary_list_map_python_sorting.txt
Q: Linking to boost unit test framework with boost build Using boost build, if I can link to a boost python library with this in my jamfile: project myProject : requirement /boost/python//boost_python ; how can I link to boost test? I have built the boost test library....
Linking to boost unit test framework with boost build
Using boost build, if I can link to a boost python library with this in my jamfile: project myProject : requirement /boost/python//boost_python ; how can I link to boost test? I have built the boost test library. I don't want to use file paths since my code is portable. ...
[ "If you have standard (or prebuilt) libraries installed in a location which can vary between different machines, you may consider using site-config. Then the site-config can be adapted on each machine but the project Jamfile remains the same.\nSee the Boost Build documentation: Targets in site-config.jam for detai...
[ 1 ]
[]
[]
[ "bjam", "boost", "build", "python", "testing" ]
stackoverflow_0002088924_bjam_boost_build_python_testing.txt
Q: How to know requested module name in Django In Django if a request is made to another module. Can we know where the request has made from through the request variable... In the below example I have to know that the request was made from a.html ort that corresponding module Ex: a.html <html> <form onsubmit=/b> </f...
How to know requested module name in Django
In Django if a request is made to another module. Can we know where the request has made from through the request variable... In the below example I have to know that the request was made from a.html ort that corresponding module Ex: a.html <html> <form onsubmit=/b> </form> </html>
[ "In your view code you can do something like this:\ndef my_view(request)\n referer = request.META.get('HTTP_REFERER', '')\n if referer == 'absolute/path/to/somepage.html':\n # do something\n ...\n else:\n # do something else\n ...\n\nNote that you probably want to avoid hard-coding URLs in your view ...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002092920_django_python.txt
Q: Python RegEx Discrepancy vs Kodos and RegExr: Can't Filter Specific Character in Python I'm using Python 2.6.3. When I do: import re, urllib f = urllib.urlopen(website) z = f.read() a = re.findall(r'(\b\d*\SLegos\b)[^\\/bLegos\b]', z) print a I get: ['/Legos', '/Legos', '525Legos', '53Legos', '11Legos', '8Legos',...
Python RegEx Discrepancy vs Kodos and RegExr: Can't Filter Specific Character in Python
I'm using Python 2.6.3. When I do: import re, urllib f = urllib.urlopen(website) z = f.read() a = re.findall(r'(\b\d*\SLegos\b)[^\\/bLegos\b]', z) print a I get: ['/Legos', '/Legos', '525Legos', '53Legos', '11Legos', '8Legos', '10Legos', '2Legos', '0Legos', '0Legos', '0Legos', '0Legos', '9Legos', '1Legos', '0Legos', '...
[ "your regex is too complicated and erroneous, you could just use:\n\\b(\\d+Legos)\\b\n\nif you don't really need Legos in your output, you could of course simply move it out of the brackets:\n\\b(\\d+)Legos\\b\n\n" ]
[ 3 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002092956_python_regex.txt
Q: how-to apache 2.2 mod_fcgid set python path i have trouble with seting the python path or any other enviroment variable for mod_fcgid (solaris 10, glassfish apache 2.2) I have it set in apache, but nothing in os.environ in the fcgi script: SetEnv PYTHONPATH "/opt/uusis/lib/python2.4/site-packages/:/usr/lib/python2...
how-to apache 2.2 mod_fcgid set python path
i have trouble with seting the python path or any other enviroment variable for mod_fcgid (solaris 10, glassfish apache 2.2) I have it set in apache, but nothing in os.environ in the fcgi script: SetEnv PYTHONPATH "/opt/uusis/lib/python2.4/site-packages/:/usr/lib/python2.4/" And other stuff(for example ORACLE_HOME) an...
[ "not quite sure if this help. http://httpd.apache.org/docs/2.0/env.html\n", "I found out that Solaris 10 glassfish apache 2.2 mod_fcgid has \"DefaultInitEnv\"\nThis is not documented in the apache mod_fcgid ...\nExample:\nDefaultInitEnv PYTHONPATH \"/opt/something/lib/python2.4/site-packages/:/usr/lib/python2.4/\...
[ 0, 0 ]
[]
[]
[ "apache2", "environment_variables", "mod_fcgid", "python" ]
stackoverflow_0002085369_apache2_environment_variables_mod_fcgid_python.txt
Q: SQLAlchemy Column to Row Transformation and vice versa -- is it possible? I'm looking for a SQLAlchemy only solution for converting a dict received from a form submission into a series of rows in the database, one for each field submitted. This is to handle preferences and settings that vary widely across applica...
SQLAlchemy Column to Row Transformation and vice versa -- is it possible?
I'm looking for a SQLAlchemy only solution for converting a dict received from a form submission into a series of rows in the database, one for each field submitted. This is to handle preferences and settings that vary widely across applications. But, it's very likely applicable to creating pivot table like functiona...
[ "Here is a slightly modified example from documentation to work with such table structure mapped to dictionary in model:\nfrom sqlalchemy import *\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm.collections import attribute_mapped_collection\nfrom sqlalchemy.ext.associationproxy import...
[ 9 ]
[]
[]
[ "orm", "pivot_table", "python", "sqlalchemy", "transformation" ]
stackoverflow_0002089661_orm_pivot_table_python_sqlalchemy_transformation.txt
Q: Retrieving Values with p.expect I have a program that logs into a server and issues commands. The results are printed out at the end of the script. The below code shows the script I have created to pass commands through ssh. import pexpect ssh_newkey = 'Are you sure you want to continue connecting' # my ssh comma...
Retrieving Values with p.expect
I have a program that logs into a server and issues commands. The results are printed out at the end of the script. The below code shows the script I have created to pass commands through ssh. import pexpect ssh_newkey = 'Are you sure you want to continue connecting' # my ssh command line p=pexpect.spawn('ssh user@00....
[ "do you mean save it to a file?? then try this\nopen(\"output.txt\",\"w\").write(results)\n\nor when you run the script on the command line: \n$ python script.py > output.txt\n\notherwise, define what you mean by \"capture\"\n", "Are Value = 1800 etc. the contents of results? And you want to \"capture\" that? \nD...
[ 1, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002087795_python.txt
Q: Doing something *after* handling a request in Google App Engine I would like the GAE to do something else once my app has sent a response. The handler would look like this: class FooHandler(webapp.RequestHandler): def post(self): self.response.out.write('Bar') send_response() # this is wher...
Doing something *after* handling a request in Google App Engine
I would like the GAE to do something else once my app has sent a response. The handler would look like this: class FooHandler(webapp.RequestHandler): def post(self): self.response.out.write('Bar') send_response() # this is where I need help! do_something_else() # at this point, the respo...
[ "Maybe you can use the Task Queues.\n", "As already mentioned, you can use task queues or the deferred API. Another option is outlined by Rafe Kaplan towards the end of his section in this talk here: you can do an asynchronous API call with a result hook function to process the result, and the result hook will be...
[ 9, 2, 1 ]
[ "You can't GAE sends it's response when the RequestHandler returns if you actually need Threads you will need to write your web application at another hosting company. \n" ]
[ -1 ]
[ "google_app_engine", "python", "wsgi" ]
stackoverflow_0002069713_google_app_engine_python_wsgi.txt
Q: C++ I/O with Python I am writing a module in Python which runs a C++ Program using subprocess module. Once I get the output from C++, I need to store the that in Python List . How do I do that ? A: Here is a quick and dirty method that I have used. def run_cpp_thing(parameters): proc = subprocess.Popen('my...
C++ I/O with Python
I am writing a module in Python which runs a C++ Program using subprocess module. Once I get the output from C++, I need to store the that in Python List . How do I do that ?
[ "Here is a quick and dirty method that I have used. \ndef run_cpp_thing(parameters):\n\n proc = subprocess.Popen('mycpp' + parameters,\n shell=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n stdin=subprocess.P...
[ 6, 2, 1, 0 ]
[]
[]
[ "c++", "python" ]
stackoverflow_0002093411_c++_python.txt
Q: how to erase lines with wxpython I'm trying to make a paint tool in wxpython. and i couldn't find a way to make an ( Eraser ) . how can i make an eraser tool - just like the one in windows paint - in wxpython ? please help . the idea or small code sample would be very helpful thanks in advance A: Have you made...
how to erase lines with wxpython
I'm trying to make a paint tool in wxpython. and i couldn't find a way to make an ( Eraser ) . how can i make an eraser tool - just like the one in windows paint - in wxpython ? please help . the idea or small code sample would be very helpful thanks in advance
[ "Have you made a Pen tool? Just set its colour to the canvas' background colour ;)\nby the way I actively develop my own wxpython painting program that you may want to check out; see http://code.google.com/p/whyteboard/\n" ]
[ 3 ]
[]
[]
[ "gdi", "python", "wxpython" ]
stackoverflow_0002091999_gdi_python_wxpython.txt
Q: Django/GAE anonymous users data in my application I have per-user models, let me explain with a simple example: class Item(db.Model): master = db.ReferenceProperty(User,collection_name="items") name = db.StringProperty() description = db.StringProperty() value = db.StringProperty() def __unicode__(self): retu...
Django/GAE anonymous users data
in my application I have per-user models, let me explain with a simple example: class Item(db.Model): master = db.ReferenceProperty(User,collection_name="items") name = db.StringProperty() description = db.StringProperty() value = db.StringProperty() def __unicode__(self): return u"%s"%self.name So I can store in...
[ "You could create an Item-like lightweight class and store instances of it in the session. If the user registers later on and you want to sync with what you have in the database, you can pick up what you've stored in the session and convert to the real Item objects (and then save() them).\nYou can also do it all wi...
[ 0 ]
[]
[]
[ "authentication", "django", "google_app_engine", "python" ]
stackoverflow_0002093115_authentication_django_google_app_engine_python.txt
Q: Extracting Values from a String I am trying to extract values from a string, I have tried to get re.match working but have not had any luck. The string is: '/opt/ad/bin$ ./ptzflip\r\nValue = 1800\r\nMin = 0\r\nMax = 3600\r\nStep = 1\r\n' I have tried: map(int,re.search("Value\s*=\s*").group(1)) and also: '/opt/...
Extracting Values from a String
I am trying to extract values from a string, I have tried to get re.match working but have not had any luck. The string is: '/opt/ad/bin$ ./ptzflip\r\nValue = 1800\r\nMin = 0\r\nMax = 3600\r\nStep = 1\r\n' I have tried: map(int,re.search("Value\s*=\s*").group(1)) and also: '/opt/ad/bin$ ./ptzflip\r\nValue = 1800\r\n...
[ "For that particular string, the following parses it into a dictionary:\ns = '/opt/ad/bin$ ./ptzflip\\r\\nValue = 1800\\r\\nMin = 0\\r\\nMax = 3600\\r\\nStep = 1\\r\\n'\nd = {}\nfor pair in [val.split('=') for val in s.split('\\r\\n')[1:-1]]:\n d[pair[0]] = int(pair[1])\n\n", ">>> s = '/opt/ad/bin$ ./ptzflip\\...
[ 6, 3, 0, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0002093812_python_string.txt
Q: "WindowsError: exception: access violation..." - ctypes question Here is the prototype for a C function that resides in a DLL: extern "C" void__stdcall__declspec(dllexport) ReturnPulse(double*,double*,double*,double*,double*); In another thread, I asked about how to properly create and send the necessary argument...
"WindowsError: exception: access violation..." - ctypes question
Here is the prototype for a C function that resides in a DLL: extern "C" void__stdcall__declspec(dllexport) ReturnPulse(double*,double*,double*,double*,double*); In another thread, I asked about how to properly create and send the necessary arguments to this function. Here is the thread: How do I wrap this C function,...
[ "The error you're getting is not related to Administrative rights. The problem is you're using C and inadvertently performing illegal operations (the kind of operations that if went unchecked would probably crash your system).\nThe error you get indicates that your program is trying to write to memory address 1001,...
[ 13, 0 ]
[]
[]
[ "access_violation", "ctypes", "python", "windowserror" ]
stackoverflow_0001382076_access_violation_ctypes_python_windowserror.txt
Q: Django Admin site TemplateSyntaxError at /admin/: name not defined I have an issue where, when I log in to the Django admin site, I get a template syntax error in /Library/Python/2.6/site-packages/django/template/debug.py in render_node, line 81. I can't find out how to solve this as it is part of Django, I didn't...
Django Admin site TemplateSyntaxError at /admin/: name not defined
I have an issue where, when I log in to the Django admin site, I get a template syntax error in /Library/Python/2.6/site-packages/django/template/debug.py in render_node, line 81. I can't find out how to solve this as it is part of Django, I didn't write the code and I have no idea how it works. This did work fine up u...
[ "It seems like an error in the admin.py file for your app.\nIt may be a missing import, or even a typo, but it's hard to tell without any code. It would be great if you could post your admin.py file so we can take a look.\nTemplateSyntaxErrors in Django are terrible, they almost never tell you what the real problem...
[ 1, 0 ]
[]
[]
[ "admin", "django", "python" ]
stackoverflow_0002086016_admin_django_python.txt
Q: Why can't Python decorators be chained across definitions? Why arn't the following two scripts equivalent? (Taken from another question: Understanding Python Decorators) def makebold(fn): def wrapped(): return "<b>" + fn() + "</b>" return wrapped def makeitalic(fn): def wrapped(): retu...
Why can't Python decorators be chained across definitions?
Why arn't the following two scripts equivalent? (Taken from another question: Understanding Python Decorators) def makebold(fn): def wrapped(): return "<b>" + fn() + "</b>" return wrapped def makeitalic(fn): def wrapped(): return "<i>" + fn() + "</i>" return wrapped @makebold @makeital...
[ "The problem with the second example is that\n@makebold\ndef makeitalic(fn):\n def wrapped():\n return \"<i>\" + fn() + \"</i>\"\n return wrapped\n\nis trying to decorate makeitalic, the decorator, and not wrapped, the function it returns.\nYou can do what I think you intend with something like this:\n...
[ 9, 1, 0 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0002094008_decorator_python.txt
Q: How do I write a Django view that can be called by jQuery's $.getJSON()? The javascript: $.getJSON('/jsonView', { tag: "userName", userName: 'zjm1126' }, function (H) { if (H.result == "successName") { F.showOk(h.ok); } else { if (H.result == "existName") { F.showErr(h.u...
How do I write a Django view that can be called by jQuery's $.getJSON()?
The javascript: $.getJSON('/jsonView', { tag: "userName", userName: 'zjm1126' }, function (H) { if (H.result == "successName") { F.showOk(h.ok); } else { if (H.result == "existName") { F.showErr(h.userNameExist); } } }); The view: def jsonView(request): # Wha...
[ "I suggest you work your way through James Bennett's tutorial on using AJAX with Django - he includes details on writing views that return JSON.\n", "This is relatively straightforward\ndef json_view(request):\n username=request.GET.get('username')\n result='successName'\n if username:\n try:\n user=Us...
[ 2, 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002092566_django_python.txt
Q: What permissions are required for subprocess.Popen? The following code: gb = self.request.form['groupby'] typ = self.request.form['type'] tbl = self.request.form['table'] primary = self.request.form.get('primary', None) if primary is not None: create = False else: create = True mdb = tempfile.NamedTemporary...
What permissions are required for subprocess.Popen?
The following code: gb = self.request.form['groupby'] typ = self.request.form['type'] tbl = self.request.form['table'] primary = self.request.form.get('primary', None) if primary is not None: create = False else: create = True mdb = tempfile.NamedTemporaryFile() mdb.write(self.request.form['mdb'].read()) mdb.see...
[ "Assuming that permissions on parent folders are correct (i.e. all parent folders should have +x permission), try adding:\nshell=True\n\nto the Popen command such as:\nsubprocess.Popen((\"/Users/jondoe/development/mdb-export\", mdb.name, tbl,), stdout=csv, shell=True)\n\n", "It seems the 'Permissions denied error...
[ 17, 8, 2, 0 ]
[]
[]
[ "macos", "popen", "python", "subprocess" ]
stackoverflow_0002066068_macos_popen_python_subprocess.txt
Q: Split a string at newline characters I have a string, say a = "Show details1\nShow details2\nShow details3\nShow details4\nShow details5\n" How do we split the above with the delimiter \n (a newline)? The result should be ['Show details1', 'Show details2', ..., 'Show details5'] A: Use a.splitlines(). T...
Split a string at newline characters
I have a string, say a = "Show details1\nShow details2\nShow details3\nShow details4\nShow details5\n" How do we split the above with the delimiter \n (a newline)? The result should be ['Show details1', 'Show details2', ..., 'Show details5']
[ "Use a.splitlines(). This will return you a list of the separate lines. To get your \"should be\" result, add \" \".join(a.splitlines()), and to get all in lower case as shown, the whole enchilada looks like \" \".join(a.splitlines()).lower().\n", "If you are concerned only with the trailing newline, you can do...
[ 21, 18, 6, 1, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0002094176_python_string.txt
Q: Python functional programming snippets I've seen some elegant python snippets using list comprehension and map reduce. Can you share some of these code or a web site. Thanks. A: Python is not lisp. Please don't try to make it look that way. It only reduces one of python's biggest strengths, which is its readab...
Python functional programming snippets
I've seen some elegant python snippets using list comprehension and map reduce. Can you share some of these code or a web site. Thanks.
[ "Python is not lisp. Please don't try to make it look that way. It only reduces one of python's biggest strengths, which is its readability and understandability later on.\nIf you like functional programming, learn Haskell, ML, or F#. You will be amazed at what those languages offer (pure functions to start with)....
[ 7, 5, 3, 2 ]
[]
[]
[ "functional_programming", "python" ]
stackoverflow_0002093388_functional_programming_python.txt
Q: Reverse loop inside a loop with same list num = list(str(1234567)) for n1 in num: print(n1) for n2 in reversed(num): print('\t', n2) On each iteration, it prints the first digit from the first loop and all 7 from the reverse loop. How can I print not all digits but only the last (i.e first) digit...
Reverse loop inside a loop with same list
num = list(str(1234567)) for n1 in num: print(n1) for n2 in reversed(num): print('\t', n2) On each iteration, it prints the first digit from the first loop and all 7 from the reverse loop. How can I print not all digits but only the last (i.e first) digit from reverse loop? Thanks
[ "Simplest way is to just zip the forward and reverse lists together:\nfor n1, n2 in zip(num, reversed(num)):\n print(n1, '\\t', n2)\n\n", "Here's a feeble attempt. Is this the kind of thing you're looking for?\n for idx,i in enumerate(x):\n print(i,\"\\t\",x[-(idx+1)])\n\n", "Do you mean like this?\nnum ...
[ 7, 1, 1, 0, 0 ]
[]
[]
[ "for_loop", "loops", "python", "reverse" ]
stackoverflow_0002095068_for_loop_loops_python_reverse.txt
Q: Python newbie - Input strings, return a value to a web page I've got a program I would like to use to input a password and one or multiple strings from a web page. The program takes the strings and outputs them to a time-datestamped text file, but only if the password matches the set MD5 hash. The problems I'm hav...
Python newbie - Input strings, return a value to a web page
I've got a program I would like to use to input a password and one or multiple strings from a web page. The program takes the strings and outputs them to a time-datestamped text file, but only if the password matches the set MD5 hash. The problems I'm having here are that I don't know how to get this code on the web. ...
[ "You'll need to read up on mod_python (if you're using Apache) and the Python CGI module.\n", "Take a look at django. It's an excellent web framework that can accomplish exactly what you are asking. It also has an authentication module that handles password hashing and logins for you.\n" ]
[ 2, 1 ]
[]
[]
[ "html", "python", "return_value" ]
stackoverflow_0002095227_html_python_return_value.txt
Q: First Python Program - Multiple Errors I am trying to write a python program that will eventually take a command line argument of a file, determine if its a tar or zip etc file and then exctract it accordingly. I am just trying to get the tar part working now and I am getting multiple errors. The file I am check...
First Python Program - Multiple Errors
I am trying to write a python program that will eventually take a command line argument of a file, determine if its a tar or zip etc file and then exctract it accordingly. I am just trying to get the tar part working now and I am getting multiple errors. The file I am checking for resides in my ~/ directory. Any ide...
[ "You can clearly see in your error it states\nNameError: global name 'ReadError' is not defined\n\nReadError is not a global python name. If you look at the tarfile documentation you will see ReadError is part of that modules exceptions. So in this case, you would want to do:\nexcept tarfile.ReadError:\n # rest of...
[ 10, 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002095298_python.txt
Q: Extended Form silently fails I have customized one of my forms and now it does not pass the is_valid() test. No form.errors are visible. Any ideas for where I went wrong? Form: class SearchForm(forms.Form): param = forms.CharField(required=False, max_length = 500, label = 'Search for') sets = forms.ModelMu...
Extended Form silently fails
I have customized one of my forms and now it does not pass the is_valid() test. No form.errors are visible. Any ideas for where I went wrong? Form: class SearchForm(forms.Form): param = forms.CharField(required=False, max_length = 500, label = 'Search for') sets = forms.ModelMultipleChoiceField(queryset=Set.obj...
[ "gruzczy has the right idea, but a better way to do it is to avoid changing the function signature of __init__ in the first place.\ndef __init__(self, *args, **kwargs):\n self.userN = kwargs.pop('userN', None)\n super(SearchForm,self).__init__(*args,**kwargs)\n ...etc...\n\n", "That's probably because yo...
[ 3, 2 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0002095213_django_django_forms_python.txt
Q: How to use one app to satisfy multiple URLs in Django I'm trying to use one app to satisfy multiple url paths. That is to say, I want the url /blog/ and /job/ to use the same app, but different views. There are a number of ways to do this I'm sure, but none of them seem very clean. Here's what I'm doing right n...
How to use one app to satisfy multiple URLs in Django
I'm trying to use one app to satisfy multiple url paths. That is to say, I want the url /blog/ and /job/ to use the same app, but different views. There are a number of ways to do this I'm sure, but none of them seem very clean. Here's what I'm doing right now # /urls.py urlpatterns = patterns("", (r"^(blog|job)...
[ "You can have more than one modules defining URLs. You can have /blog/ URLs in myapp/urls.py and /job/ URLs in myapp/job_urls.py. Or you can have two modules within a urls subpackage.\nAlternatively you can manually prefix your url definitions:\nurlpatterns = patterns(\"myproject.myapp.views\",\n (r\"^jobs/(?P<i...
[ 4, 0 ]
[]
[]
[ "django", "django_urls", "python" ]
stackoverflow_0002094952_django_django_urls_python.txt
Q: Python: arguments for using itertools to split a list into groups This is a question about the relative merits of fast code that uses the standard library but is obscure (at least to me) versus a hand-rolled alternative. In this thread (and others that it duplicates), it seems the "Pythonic" way to split a list i...
Python: arguments for using itertools to split a list into groups
This is a question about the relative merits of fast code that uses the standard library but is obscure (at least to me) versus a hand-rolled alternative. In this thread (and others that it duplicates), it seems the "Pythonic" way to split a list into groups is to use itertools, as in the first function in the code ex...
[ "When you reuse tools from the standard library, rather than \"reinventing the wheel\" by coding them yourself from scratch, you're not only getting well-optimized and tuned software (sometimes amazingly so, as often in the case of itertools components): more importantly, you're getting large amounts of functionali...
[ 16, 5 ]
[]
[]
[ "python" ]
stackoverflow_0002095637_python.txt
Q: Serializing objects containing django querysets Django provides tools to serialize querysets (django.core.serializers), but what about serializing querysets living inside other objects (like dictionaries)? I want to serialize the following dictionary: dictionary = { 'alfa': queryset1, 'beta': queryset2, } I deci...
Serializing objects containing django querysets
Django provides tools to serialize querysets (django.core.serializers), but what about serializing querysets living inside other objects (like dictionaries)? I want to serialize the following dictionary: dictionary = { 'alfa': queryset1, 'beta': queryset2, } I decided to do this using simplejson (comes with django). ...
[ "The correct way to do this would be:\nfrom django.utils import simplejson\nfrom django.core import serializers\nfrom django.db.models.query import QuerySet\n\nclass HandleQuerySets(simplejson.JSONEncoder):\n \"\"\" simplejson.JSONEncoder extension: handle querysets \"\"\"\n def default(self, obj):\n ...
[ 10 ]
[]
[]
[ "django", "json", "python" ]
stackoverflow_0002093840_django_json_python.txt
Q: How to create twisted.words.xish.domish.Element entirely from raw XML I was surprised that XML basic object (twisted.words.xish.domish.Element) could not be created entirely from XML string. The most alike way is: msg = "<iq to='juick@juick.com' id='id123' type='get'> \ <query xmlns='http://juick.com/q...
How to create twisted.words.xish.domish.Element entirely from raw XML
I was surprised that XML basic object (twisted.words.xish.domish.Element) could not be created entirely from XML string. The most alike way is: msg = "<iq to='juick@juick.com' id='id123' type='get'> \ <query xmlns='http://juick.com/query#messages' mid='123456'/> \ </iq>" iq = domish.Element(('','')) ...
[ "This is what I use for fragments, adapted from something found on the web somewhere.\nfrom twisted.words.xish import domish\n\nclass ElementParser(object):\n \"callable class to parse XML string into Element\"\n\n def __call__(self, s):\n self.result = None\n def onStart(el):\n self....
[ 1 ]
[]
[]
[ "python", "twisted", "twisted.words", "xml" ]
stackoverflow_0002093400_python_twisted_twisted.words_xml.txt
Q: module level garbage collection in python Let's say I have a module mod_x like the following: class X: pass x=X() Now, let's say I have another module that just performs import mod_x, and goes about its business. The module variable x will not be referenced further during the lifecycle of the interpreter. Will...
module level garbage collection in python
Let's say I have a module mod_x like the following: class X: pass x=X() Now, let's say I have another module that just performs import mod_x, and goes about its business. The module variable x will not be referenced further during the lifecycle of the interpreter. Will the class instance x get garbage collected at ...
[ "No, the variable will never get garbage-collected (until the end of the process), because the module object will stay in sys.modules['mod_x'] and it will have a reference to mod_x.x -- the reference count will never drop to 0 (until all modules are removed at the end of the program) and it's not an issue of \"cycl...
[ 4, 3, 1 ]
[]
[]
[ "garbage_collection", "python" ]
stackoverflow_0002095907_garbage_collection_python.txt
Q: Using Third-Party Modules with Python in an Automator Service I have installed Py-Appscript on my machine and it can be used with the Python installation at /Library/Frameworks/Python.framework/Versions/Current/bin/python. I am trying to use this installation of Py-Appscript with an Automator service. To do this, ...
Using Third-Party Modules with Python in an Automator Service
I have installed Py-Appscript on my machine and it can be used with the Python installation at /Library/Frameworks/Python.framework/Versions/Current/bin/python. I am trying to use this installation of Py-Appscript with an Automator service. To do this, I use the Run Shell Script action and then set the Shell to usr/bin...
[ "Okay, I was able to get it working using a hack found at How do I execute a PHP shell script as an Automator action on Mac OS X.\nInside of the Run Shell Script action, I used the /bin/sh/ shell with <<EOF ... EOF to the proper Python installation.\nSo for example, entering\n/Library/Frameworks/Python.framework/Ve...
[ 3, 0 ]
[]
[]
[ "automator", "python" ]
stackoverflow_0002093837_automator_python.txt
Q: Interaction with twisted.internet.reactor I am learning Twisted, especially its XMPP side. I am writing a Jabber client which must send and recieve messages. Here is my code: http://pastebin.com/m71225776 As I understood the workflow is like this: 1. I create handlers for important network events (i.e. connecting,...
Interaction with twisted.internet.reactor
I am learning Twisted, especially its XMPP side. I am writing a Jabber client which must send and recieve messages. Here is my code: http://pastebin.com/m71225776 As I understood the workflow is like this: 1. I create handlers for important network events (i.e. connecting, message recieving, disconnecting, etc) 2. I ru...
[ "You just need to find what events will trigger sending a message.\nFor example, in a GUI client, sending happens when the user types something. You should integrate with a graphics toolkit, using the Twisted reactor for its mainloop (there's a Gtk+ Twisted reactor for example). Then you'll be able to listen for so...
[ 2, 0 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0002080757_python_twisted.txt
Q: Closest language to Python's syntax that is more low level language! I guess topic says it all! But, I really wan't a syntax similar to Python's! And low-level... like C++ for example. I guess Java and C# is OK too, but I really have a huge problem with the { }, and always ; <-- and each line. I hate it so much......
Closest language to Python's syntax that is more low level language!
I guess topic says it all! But, I really wan't a syntax similar to Python's! And low-level... like C++ for example. I guess Java and C# is OK too, but I really have a huge problem with the { }, and always ; <-- and each line. I hate it so much...
[ "cython may be pretty close to what you want: syntax just about identical to Python, and you can basically write C-level code in it. It's tuned to generate Python-usable extensions, but you could then \"freeze\" them into a stand-alone executable.\nboo is another language with very Python-like syntax, and semantic...
[ 15, 12, 6, 3, 0 ]
[]
[]
[ "low_level", "programming_languages", "python", "syntax" ]
stackoverflow_0002096015_low_level_programming_languages_python_syntax.txt
Q: How can I find out why PIL isn't drawing the font correctly? Here's the code I'm using: from PIL import Image import ImageFont, ImageDraw import sys import pdb img = Image.new("RGBA",(300,300)) draw = ImageDraw.Draw(img) font = ImageFont.truetype(sys.argv[1],30) draw.text((0,100),"world",font=font,fill="red") del...
How can I find out why PIL isn't drawing the font correctly?
Here's the code I'm using: from PIL import Image import ImageFont, ImageDraw import sys import pdb img = Image.new("RGBA",(300,300)) draw = ImageDraw.Draw(img) font = ImageFont.truetype(sys.argv[1],30) draw.text((0,100),"world",font=font,fill="red") del draw img.save(sys.argv[2],"PNG") and here's the image that resul...
[ "PIL uses the freetype2 library, so most possibly it is an issue with the font file; for example, it could have bad metrics defined (e.g see the OS/2 related ones opening the font with FontForge).\n" ]
[ 1 ]
[]
[]
[ "fonts", "python", "python_imaging_library" ]
stackoverflow_0002095189_fonts_python_python_imaging_library.txt
Q: Execute sql query with Elixir I'm using Elixir in a project that connects to a postgres database. I want to run the following query on the database I'm connected to, but I'm not sure how to do it as I'm rather new to Elixir and SQLAlchemy. Anyone know how? VACUUM FULL ANALYZE table Update The error is: "UnboundExe...
Execute sql query with Elixir
I'm using Elixir in a project that connects to a postgres database. I want to run the following query on the database I'm connected to, but I'm not sure how to do it as I'm rather new to Elixir and SQLAlchemy. Anyone know how? VACUUM FULL ANALYZE table Update The error is: "UnboundExecutionError: Could not locate a bin...
[ "Dammit. I knew the answer was going to be right under my nose. Assuming you setup your connection like I did.\nmetadata.bind = 'postgres://user:pw@host/db'\n\nThe solution to this was as simple as \nconn = metadata.bind.engine.connect()\n\nold_lvl = conn.connection.isolation_level\nconn.connection.set_isolation_le...
[ 10, 2, 1, 0, 0 ]
[]
[]
[ "postgresql", "python", "python_elixir", "sqlalchemy" ]
stackoverflow_0001875885_postgresql_python_python_elixir_sqlalchemy.txt
Q: Fetch certain .html files from web server I would like to fetch certain .html files from a web server. My intention is to fetch .html files from a web site (http://www.thetabworld.com/) that has a word "metallica" on file name. How is that possible using python? I have heard about urllib2 but as a python noob, I d...
Fetch certain .html files from web server
I would like to fetch certain .html files from a web server. My intention is to fetch .html files from a web site (http://www.thetabworld.com/) that has a word "metallica" on file name. How is that possible using python? I have heard about urllib2 but as a python noob, I don't have a slightest idea how to use it.
[ "You need to use urllib2 together with a HTML parser such as lxml or BeautifulSoup in order to extract the links from the retrieved pages in order to crawl the site.\n", "\n\"I have heard about urllib2 but as a\n python noob, I don't have a slightest\n idea how to use it.\"\n\nwell if you don't know how to use...
[ 1, 1 ]
[]
[]
[ "python", "urllib2" ]
stackoverflow_0002096484_python_urllib2.txt
Q: A few questions regarding Pythons 'import' feature I just downloaded Beautiful Soup and I've decided I'll make a small library (is that what they call them in Python?) that will return results of a movie given and IMDB movie search. My question is, how exactly does this import thing work? For example, I downloaded...
A few questions regarding Pythons 'import' feature
I just downloaded Beautiful Soup and I've decided I'll make a small library (is that what they call them in Python?) that will return results of a movie given and IMDB movie search. My question is, how exactly does this import thing work? For example, I downloaded BeautifulSoup and all it is, is a .py file. Does that f...
[ "BeautifulSoup.py will need to be placed somewhere on the Python search path, which is available to you in the sys.path array. Note that the current directory is always included in this array (as the empty string).\n>>> import sys\n>>> sys.path\n['', 'C:\\\\Windows\\\\system32\\\\python26.zip', 'c:\\\\python26\\\\D...
[ 3, 1, 1, 1, 0 ]
[ "Might not be relevant, but have you considered using imdbpy? Last time I used it it worked pretty well...\n" ]
[ -1 ]
[ "import", "python" ]
stackoverflow_0002095505_import_python.txt
Q: TypeError upon merely opening a file with csv.DictReader? I've just uploaded this CSV file via a form, POSTing it to my Python CGI script. The upload seems to have completed successfully. Permissions on the folder are 777, on the file are 755. >>> import csv >>> csvHandle = open('files/TestData.csv', "rb") >>> csv...
TypeError upon merely opening a file with csv.DictReader?
I've just uploaded this CSV file via a form, POSTing it to my Python CGI script. The upload seems to have completed successfully. Permissions on the folder are 777, on the file are 755. >>> import csv >>> csvHandle = open('files/TestData.csv', "rb") >>> csvRawRecordDicts = csv.DictReader(csvHandle) Traceback (most rec...
[ "There are a couple of things you could be doing:\n\nread the relevant docs and see that DictReader requires two arguments at least, while you're passing one\ntry to do >>> help(csv.DictReader) and arrive to the same conclusion.\n\nAs reading of the docs might explain second of the arguments should be fieldnames (I...
[ 1, 1 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0002096466_csv_python.txt
Q: Parsing name and address information with differing number of spaces I have a comma delimited text file. The 5th field on each line contains the name and address information. The name is separated from the street information by a '¬' character. The same character also separates the city|state|zip. A sample field w...
Parsing name and address information with differing number of spaces
I have a comma delimited text file. The 5th field on each line contains the name and address information. The name is separated from the street information by a '¬' character. The same character also separates the city|state|zip. A sample field would be: "¬BOL¬MICKEY M MOUSE¬123 TOMORROW LANE¬ORLANDO FL 12345-6789¬¬¬¬E...
[ "In your examples it seems that you can in both cases solve the problem by getting the 'first fields', the 'last fields' and 'everything in between':\nm = line.split(\"¬\")[2].split()\nfirstname = m[0]\nsurname = m[-1]\ninitials = m[1:-1] # Maybe just keep this as a list?\n\nAnd:\nm = line.split(\"¬\")[4].split()\n...
[ 3, 0 ]
[]
[]
[ "parsing", "python", "street_address" ]
stackoverflow_0002097191_parsing_python_street_address.txt
Q: how to safely generate a SQL LIKE statement using python db-api I am trying to assemble the following SQL statement using python's db-api: SELECT x FROM myTable WHERE x LIKE 'BEGINNING_OF_STRING%'; where BEGINNING_OF_STRING should be a python var to be safely filled in through the DB-API. I tried beginningOfStrin...
how to safely generate a SQL LIKE statement using python db-api
I am trying to assemble the following SQL statement using python's db-api: SELECT x FROM myTable WHERE x LIKE 'BEGINNING_OF_STRING%'; where BEGINNING_OF_STRING should be a python var to be safely filled in through the DB-API. I tried beginningOfString = 'abc' cursor.execute('SELECT x FROM myTable WHERE x LIKE '%s%', ...
[ "It's best to separate the parameters from the sql if you can.\nThen you can let the db module take care of proper quoting of the parameters.\nsql='SELECT x FROM myTable WHERE x LIKE %s'\nargs=[beginningOfString+'%']\ncursor.execute(sql,args)\n\n", "EDIT:\nAs Brian and Thomas noted, the far better way to do this ...
[ 26, 3 ]
[ "Take note of Sqlite3 documentation: \n\nUsually your SQL operations will need\n to use values from Python variables.\n You shouldn’t assemble your query\n using Python’s string operations\n because doing so is insecure; it makes\n your program vulnerable to an SQL\n injection attack.\nInstead, use the DB-API...
[ -1 ]
[ "python", "python_db_api", "sql", "sql_like" ]
stackoverflow_0002097475_python_python_db_api_sql_sql_like.txt
Q: Error handling in the RequestHandler without embedding in URI When a user sends a filled form, I want to print an error message in case there is an input error. One of the GAE sample codes does this by embedding the error message in the URI. Inside the form handler (get): self.redirect('/compose?error_message=%s' ...
Error handling in the RequestHandler without embedding in URI
When a user sends a filled form, I want to print an error message in case there is an input error. One of the GAE sample codes does this by embedding the error message in the URI. Inside the form handler (get): self.redirect('/compose?error_message=%s' % message) and in the handler (get) of redirected URI, gets the me...
[ "Is the values dict being rendered by the template engine? If so, you can pass the error string directly like this:\nvalues = {\n 'error_message': 'there is an error',\n ...\n\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "python", "web_applications" ]
stackoverflow_0002092708_google_app_engine_python_web_applications.txt
Q: Property XXXX is not multi-line exception in python GAE I have a simple model object with profilename = db.StringProperty() and when I get a string with "Some More" and try to put it in model it throws exception Property profilename is not multi-line Is space equivalent to newline or I have missed somethin...
Property XXXX is not multi-line exception in python GAE
I have a simple model object with profilename = db.StringProperty() and when I get a string with "Some More" and try to put it in model it throws exception Property profilename is not multi-line Is space equivalent to newline or I have missed something here? It is put ting for single word strings without sp...
[ "The check's being done at application level, specifically in StringProperty.validate -- the code in question (which you can find in your SDK's sources in ext/db/init.py) is:\nif not self.multiline and value and value.find('\\n') != -1:\n raise BadValueError('Property %s is not multi-line' % self.name)\n\nso there...
[ 4 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0002096471_google_app_engine_google_cloud_datastore_python.txt
Q: How do I get a µ character out of sqlite and onto a web-page? On a Python driven web app using a sqlite datastore I had this error: Could not decode to UTF-8 column 'name' with text '300µL-10-10' Reading here it looks like I need to switch my text-factory to str and get bytestrings but when I do this my html o...
How do I get a µ character out of sqlite and onto a web-page?
On a Python driven web app using a sqlite datastore I had this error: Could not decode to UTF-8 column 'name' with text '300µL-10-10' Reading here it looks like I need to switch my text-factory to str and get bytestrings but when I do this my html output looks like this: 300�L-10-10 I do have my content-type set ...
[ "Unfortunately, the data in your datastore is not encoded as UTF-8; instead, it's probably either latin-1 or cp1252. To decode it automatically, try setting Connection.text_factory to your own function:\ndef convert_string(s):\n try:\n u = s.decode(\"utf-8\")\n except UnicodeDecodeError:\n u = ...
[ 3 ]
[]
[]
[ "python", "sqlite", "unicode", "utf_8" ]
stackoverflow_0002097256_python_sqlite_unicode_utf_8.txt
Q: Python readline on a pipe that has been opened as non-blocking I have a Linux fifo that has been opened in non-blocking mode. As expected, when I call read on the file object, it returns immediately. I use select to make sure there is no busy waiting, but that my program is still notified when there is any data av...
Python readline on a pipe that has been opened as non-blocking
I have a Linux fifo that has been opened in non-blocking mode. As expected, when I call read on the file object, it returns immediately. I use select to make sure there is no busy waiting, but that my program is still notified when there is any data available. Out of curiosity, I tried the readline function and was sur...
[ "The core part of Python's readline is in fileobject.c:get_line and is\nFILE_BEGIN_ALLOW_THREADS(f)\nFLOCKFILE(fp);\n\nwhile ((c = GETC(fp)) != EOF &&\n (*buf++ = c) != '\\n' &&\n buf != end)\n ;\nFUNLOCKFILE(fp);\nFILE_END_ALLOW_THREADS(f)\n\nwhere\n#ifdef HAVE_GETC_UNLOCKED\n#define GETC(f) getc...
[ 1 ]
[]
[]
[ "file", "nonblocking", "pipe", "python", "readline" ]
stackoverflow_0002093788_file_nonblocking_pipe_python_readline.txt
Q: can SimpleXMLRPCServer listen on multiple addresses? I have two IPs mapping to the machine, and I was wondering how I can have one python xmlrpc server listening on both IPs (same port), like you could do with Apache. Thank you, A: Use "" as the host: s = SimpleXMLRPCServer.SimpleXMLRPCServer(("", 8000))
can SimpleXMLRPCServer listen on multiple addresses?
I have two IPs mapping to the machine, and I was wondering how I can have one python xmlrpc server listening on both IPs (same port), like you could do with Apache. Thank you,
[ "Use \"\" as the host:\ns = SimpleXMLRPCServer.SimpleXMLRPCServer((\"\", 8000))\n\n" ]
[ 3 ]
[]
[]
[ "python", "simplexmlrpcserver" ]
stackoverflow_0002098045_python_simplexmlrpcserver.txt
Q: Using a function to create a function in Python I'm new to programming and I'm interested in if it's possible to use a function to create another function based in inputted information: def get_new_toy(self): new_toy = gui.multenterbox( msg = 'Enter the data for the new toy:', title = 'New Toy'...
Using a function to create a function in Python
I'm new to programming and I'm interested in if it's possible to use a function to create another function based in inputted information: def get_new_toy(self): new_toy = gui.multenterbox( msg = 'Enter the data for the new toy:', title = 'New Toy', fields = ('Toy Name', 'Fun for 0 to 5', 'Fu...
[ "Here is an example python function that returns a new function based on the parameter passed in. I'm not sure what you are trying to do but this might help point you in the right direction.\ndef add_to(amount):\n def f(x):\n return x + amount\n return f\n\nif __name__ == \"__main__\":\n add_2 = a...
[ 2 ]
[]
[]
[ "function", "python" ]
stackoverflow_0002098181_function_python.txt
Q: Python optparse not seeing argument I am trying to pass '-f nameoffile' to the program when I call it from the command line. I got this from the python sites documentation but when I pass '-f filename' or '--file=filename' it throws the error that I didnt pass enough arguments. If i pass -h the programs responds...
Python optparse not seeing argument
I am trying to pass '-f nameoffile' to the program when I call it from the command line. I got this from the python sites documentation but when I pass '-f filename' or '--file=filename' it throws the error that I didnt pass enough arguments. If i pass -h the programs responds how it should and gives me the help. An...
[ "Your problem is probably the if len(args) != 1:. That is looking for an additional argument (i.e. not an option). If you remove that check and look at your options dictionary you should see {'filename': 'blah'}.\n", "After parsing the options out of the argument list, you check that you were passed an argument. ...
[ 2, 1, 1, 0 ]
[]
[]
[ "optparse", "python" ]
stackoverflow_0002098211_optparse_python.txt
Q: Mod_Python + Django library import issue I recently had a site that was running perfect for months, all of a sudden it decided to dump itself for no approximate reason. I am running django + mod_python + apache, and the system decided it was time to start ignoring the import of the pycurl library, my intial first ...
Mod_Python + Django library import issue
I recently had a site that was running perfect for months, all of a sudden it decided to dump itself for no approximate reason. I am running django + mod_python + apache, and the system decided it was time to start ignoring the import of the pycurl library, my intial first thought was that somehow the library had becom...
[ "If the problem is a failing import when running under Apache but the import works when running from your login shell, double-check that there isn't a directory/file permission problem with the failing module(s). They must be read-accessible and in some cases also execute-accessible from the user id that Apache is...
[ 1, 0, 0 ]
[]
[]
[ "apache", "django", "mod_python", "pycurl", "python" ]
stackoverflow_0002094783_apache_django_mod_python_pycurl_python.txt
Q: Python re.sub question Greetings all, I'm not sure if this is possible but I'd like to use matched groups in a regex substitution to call variables. a = 'foo' b = 'bar' text = 'find a replacement for me [[:a:]] and [[:b:]]' desired_output = 'find a replacement for me foo and bar' re.sub('\[\[:(.+):\]\]',group(1...
Python re.sub question
Greetings all, I'm not sure if this is possible but I'd like to use matched groups in a regex substitution to call variables. a = 'foo' b = 'bar' text = 'find a replacement for me [[:a:]] and [[:b:]]' desired_output = 'find a replacement for me foo and bar' re.sub('\[\[:(.+):\]\]',group(1),text) #is not valid re.sub...
[ "You can specify a callback when using re.sub, which has access to the groups:\nhttp://docs.python.org/library/re.html#text-munging\na = 'foo'\nb = 'bar'\n\ntext = 'find a replacement for me [[:a:]] and [[:b:]]'\n\ndesired_output = 'find a replacement for me foo and bar'\n\ndef repl(m):\n contents = m.group(1)\n...
[ 32, 8, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002094975_python_regex.txt
Q: Python Detect Keystrokes Sent to Another Application I have a Python program that sends keystrokes to another application using SendKeys. Some of the keystrokes, however, must be sent to the application after it does some processing (which takes an unknown amount of time). So far I have had to let the Python appli...
Python Detect Keystrokes Sent to Another Application
I have a Python program that sends keystrokes to another application using SendKeys. Some of the keystrokes, however, must be sent to the application after it does some processing (which takes an unknown amount of time). So far I have had to let the Python application know the processing was finished by Alt+Tabbing bac...
[ "Have a look at pyHook.\nIt allows Keyboard hooking:\nimport pythoncom, pyHook \n\ndef OnKeyboardEvent(event):\n print 'MessageName:',event.MessageName\n print 'Message:',event.Message\n print 'Time:',event.Time\n print 'Window:',event.Window\n print 'WindowName:',event.WindowName\n print 'Ascii:', event.Asci...
[ 0 ]
[]
[]
[ "python", "sendkeys" ]
stackoverflow_0002098388_python_sendkeys.txt
Q: Best JSON library to get JSON data for Django? What is the best JSON library to get JSON data for Django, 'simplejson' or otherwise? thanks very much A: Django itself integrates simplejson and has the ability to use your own version from the system if you have it installed. from django.core import serializers js...
Best JSON library to get JSON data for Django?
What is the best JSON library to get JSON data for Django, 'simplejson' or otherwise? thanks very much
[ "Django itself integrates simplejson and has the ability to use your own version from the system if you have it installed.\nfrom django.core import serializers\njson_serializer = serializers.get_serializer(\"json\")()\n\nAs Alex notes, the json module is bundled with Python 2.6 and above -- that's actually simplejs...
[ 9, 8 ]
[]
[]
[ "django", "json", "python" ]
stackoverflow_0002098611_django_json_python.txt
Q: POSTing forms in Django's admin interface I'm writing a Django admin action to mass e-mail contacts. The action is defined as follows: def email_selected(self,request,queryset): rep_list = [] for each in queryset: reps = CorporatePerson.objects.filter(company_id = Company.objects.get(name=each.na...
POSTing forms in Django's admin interface
I'm writing a Django admin action to mass e-mail contacts. The action is defined as follows: def email_selected(self,request,queryset): rep_list = [] for each in queryset: reps = CorporatePerson.objects.filter(company_id = Company.objects.get(name=each.name)) contact_reps = reps.filter(is_con...
[ "You can use django's inbuilt url tag to avoid hardcoding links. see... \nhttp://docs.djangoproject.com/en/dev/ref/templates/builtins/#url\nChances are you'd be better off setting up a mass mailer to be triggered off by a cron job rather than on the post.\nCheck out the answer I posted here\nDjango scheduled jobs\n...
[ 1 ]
[]
[]
[ "django", "django_admin", "django_templates", "django_urls", "python" ]
stackoverflow_0002098527_django_django_admin_django_templates_django_urls_python.txt
Q: GAE datastore eager loading in python api I have two models in relation one-to-many: class Question(db.Model): questionText = db.StringProperty(multiline=False) class Answer(db.Model): answerText = db.StringProperty(multiline=False) question = db.ReferenceProperty(Question, collection_name='answers') I have f...
GAE datastore eager loading in python api
I have two models in relation one-to-many: class Question(db.Model): questionText = db.StringProperty(multiline=False) class Answer(db.Model): answerText = db.StringProperty(multiline=False) question = db.ReferenceProperty(Question, collection_name='answers') I have front-end implemented in Flex and use pyamf to ...
[ "By default PyAMF will not encode ReferenceProperty fields unless they have already been specifically loaded by the service method. This is on purpose so you don't end up encoding more than you have to.\nPyAMF looks for a special class attribute __amf__ which it uses to customise the encoding and decoding process f...
[ 1 ]
[]
[]
[ "eager_loading", "google_app_engine", "google_cloud_datastore", "pyamf", "python" ]
stackoverflow_0002098417_eager_loading_google_app_engine_google_cloud_datastore_pyamf_python.txt
Q: Reverse ForeignKey lookup I'm new to Django and am still trying to break old PHP habits. Below are two models. To make things confusing they live in separate files, in different apps... #article.models from someapp.author.models import Author class Article(model.Model): ... author = models.ForeignKey(Auth...
Reverse ForeignKey lookup
I'm new to Django and am still trying to break old PHP habits. Below are two models. To make things confusing they live in separate files, in different apps... #article.models from someapp.author.models import Author class Article(model.Model): ... author = models.ForeignKey(Author) # author.models class Aut...
[ "I think this is what you're asking for...\nclass Article(model.Model):\n ...\n author = models.ForeignKey(Author, related_name='articles')\n\nOn a side note, by default without changing anything you've got, I think this would work for you...\narticle.author_set\n\nBut to maintain the article.authors syntax y...
[ 3 ]
[]
[]
[ "django", "models", "python" ]
stackoverflow_0002099037_django_models_python.txt
Q: Parallel while Loops in Python I'm pretty new to Python, and programming in general and I'm creating a virtual pet style game for my little sister. Is it possible to run 2 while loops parallel to each other in python? eg: while 1: input_event_1 = gui.buttonbox( msg = 'Hello, what would you like to do w...
Parallel while Loops in Python
I'm pretty new to Python, and programming in general and I'm creating a virtual pet style game for my little sister. Is it possible to run 2 while loops parallel to each other in python? eg: while 1: input_event_1 = gui.buttonbox( msg = 'Hello, what would you like to do with your Potato Head?', titl...
[ "Have a look at Threading.Timer. \nThere is a code recipe here to schedule a function to run every 5 seconds.\nimport thread\nimport threading\n\nclass Operation(threading._Timer):\n def __init__(self, *args, **kwargs):\n threading._Timer.__init__(self, *args, **kwargs)\n self.setDaemon(True)\n\n ...
[ 3, 3, 3, 3, 1, 1, 0 ]
[]
[]
[ "events", "loops", "parallel_processing", "python", "while_loop" ]
stackoverflow_0002098495_events_loops_parallel_processing_python_while_loop.txt
Q: Does IronPython and Jython have the same GIL issues as CPython? I read about the problems with CPython and CPU bound threads and the GIL and some changes in Python 3.2. Do IronPython and Jython have this same problem? Thanks A: No, neither have a GIL at all. See previous answer about Jython and IronPython wiki p...
Does IronPython and Jython have the same GIL issues as CPython?
I read about the problems with CPython and CPU bound threads and the GIL and some changes in Python 3.2. Do IronPython and Jython have this same problem? Thanks
[ "No, neither have a GIL at all.\nSee previous answer about Jython and IronPython wiki page.\n" ]
[ 8 ]
[]
[]
[ "ironpython", "jython", "python" ]
stackoverflow_0002099405_ironpython_jython_python.txt
Q: TCP connection reset occurs when WSGI app responds before consuming environ['wsgi.input'] For our webservice, I wrote some logic to prevent multipart/form-data POSTs larger than, say, 4mb. It boils down to the following (I've stripped away all WebOb usage and just reduced it to plain vanilla WSGI code): import pas...
TCP connection reset occurs when WSGI app responds before consuming environ['wsgi.input']
For our webservice, I wrote some logic to prevent multipart/form-data POSTs larger than, say, 4mb. It boils down to the following (I've stripped away all WebOb usage and just reduced it to plain vanilla WSGI code): import paste.httpserver form = """\ <html> <body> <form method="post" enctype="multipart/form-data" ac...
[ "This is happening because you are discarding the input stream without reading it, and this is forcing it closed. The browser has queued up a good portion of the file to be sent already and then it gets a write error because the server closes the connection forcefully.\nThere is no way around this that I know of w...
[ 2 ]
[]
[]
[ "http", "paste", "python", "tcp", "wsgiref" ]
stackoverflow_0002099752_http_paste_python_tcp_wsgiref.txt
Q: Where is the function 'real_ugettext' in django? In django.utils.translations.__init__.py: def ugettext(message): return real_ugettext(message) I can't find it. A: Read that file a little closer: def delayed_loader(*args, **kwargs): """ Replace each real_* function with the corresponding function fr...
Where is the function 'real_ugettext' in django?
In django.utils.translations.__init__.py: def ugettext(message): return real_ugettext(message) I can't find it.
[ "Read that file a little closer:\ndef delayed_loader(*args, **kwargs):\n \"\"\"\n Replace each real_* function with the corresponding function from either\n trans_real or trans_null (e.g. real_gettext is replaced with\n trans_real.gettext or trans_null.gettext). This function is run once, the\n first...
[ 4, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002100032_django_python.txt
Q: Caching non-view returns I have a dozen or so permission lookups on views that make sure users have the right permissions to do something on the system (ie make sure they're in the right group, if they can edit their profile, if they're group administrators, etc). A check might look like this: from django.contrib....
Caching non-view returns
I have a dozen or so permission lookups on views that make sure users have the right permissions to do something on the system (ie make sure they're in the right group, if they can edit their profile, if they're group administrators, etc). A check might look like this: from django.contrib.auth.decorators import user_pa...
[ "You might need to serialize the function (which I'm not doing when I use it as the key to the cache), but something like this should work:\nfrom django.core.cache import cache\n\ndef cached_user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):\n if not login_url:\n from dj...
[ 1, 0 ]
[]
[]
[ "decorator", "django", "django_cache", "python" ]
stackoverflow_0002086420_decorator_django_django_cache_python.txt
Q: django error. about django.forms from django import forms class a(forms.Form): name = forms.CharField(initial='Your name') url = forms.URLField(initial='Your Web site') comment = forms.CharField() data = {'name': 'hahaha', 'url': '', 'comment': 'Foo'} f = a(data,auto_id=False) #print f.is_valid() pr...
django error. about django.forms
from django import forms class a(forms.Form): name = forms.CharField(initial='Your name') url = forms.URLField(initial='Your Web site') comment = forms.CharField() data = {'name': 'hahaha', 'url': '', 'comment': 'Foo'} f = a(data,auto_id=False) #print f.is_valid() print f.errors errors: Traceback (most ...
[ "That error shows up because you're not running the script as part of a Django app. There are a number of measures you can take to get it to work, but having a form separate from the app will probably not be terribly useful.\n" ]
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002100198_django_python.txt
Q: How to make os.mkfifo and subprocess.Popen work together? I'm trying to redirect a patch command output using a named pipe. I tried like this: fifo = os.path.join(self.path, 'pipe') os.mkfifo(fifo) op = os.popen('cat '+ fifo) proc = Popen(['patch', current_keyframe, '--input='+fpath, '--output='+fifo], stdin=PIPE,...
How to make os.mkfifo and subprocess.Popen work together?
I'm trying to redirect a patch command output using a named pipe. I tried like this: fifo = os.path.join(self.path, 'pipe') os.mkfifo(fifo) op = os.popen('cat '+ fifo) proc = Popen(['patch', current_keyframe, '--input='+fpath, '--output='+fifo], stdin=PIPE, stdout=PIPE) os.unlink(fifo) print op.read() But my script st...
[ "You aren't waiting for the patch command to finish before you read from the fifo. Replace the subprocess.Popen() call with subprocess.call(), and remove the stdin/stdout redirections you aren't using. Also, use open(fifo) to read from the fifo, not os.popen('cat ' + fifo).\nYou realize, I hope, that you can avoid ...
[ 1 ]
[]
[]
[ "fifo", "patch", "python", "subprocess" ]
stackoverflow_0002100581_fifo_patch_python_subprocess.txt