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: Problem using super(python 2.5.2) I'm writing a plugin system for my program and I can't get past one thing: class ThingLoader(object): ''' Loader class ''' def loadPlugins(self): ''' Get all the plugins from plugins folder ''' from diones.thingpad.plugin.IntrospectionHelper import loadClasses classList=loadClasses('./plugins', IPlugin)#Gets a list of #plugin classes self.plugins={}#Dictionary that should be filled with #touples of objects and theirs states, activated, deactivated. classList[0](self)#Runs nicelly foo = classList[1] print foo#prints <class 'TestPlugin.TestPlugin'> foo(self)#Raise an exception The test plugin looks like this: import diones.thingpad.plugin.IPlugin as plugin class TestPlugin(plugin.IPlugin): ''' classdocs ''' def __init__(self, loader): self.name='Test Plugin' super(TestPlugin, self).__init__(loader) Now the IPlugin looks like this: class IPlugin(object): ''' classdocs ''' name='' def __init__(self, loader): self.loader=loader def activate(self): pass All the IPlugin classes works flawlessy by them selves, but when called by ThingLoader the program gets an exception: File "./plugins\TestPlugin.py", line 13, in __init__ super(TestPlugin, self).__init__(loader) NameError: global name 'super' is not defined I looked all around and I simply don't know what is going on. A: ‘super’ is a builtin. Unless you went out of your way to delete builtins, you shouldn't ever see “global name 'super' is not defined”. I'm looking at your user web link where there is a dump of IntrospectionHelper. It's very hard to read without the indentation, but it looks like you may be doing exactly that: built_in_list = ['__builtins__', '__doc__', '__file__', '__name__'] for i in built_in_list: if i in module.__dict__: del module.__dict__[i] That's the original module dict you're changing there, not an informational copy you are about to return! Delete these members from a live module and you can expect much more than ‘super’ to break. It's very hard to keep track of what that module is doing, but my reaction is there is far too much magic in it. The average Python program should never need to be messing around with the import system, sys.path, and monkey-patching __magic__ module members. A little bit of magic can be a neat trick, but this is extremely fragile. Just off the top of my head from browsing it, the code could be broken by things like: name clashes with top-level modules any use of new-style classes modules supplied only as compiled bytecode zipimporter From the incredibly round-about functions like getClassDefinitions, extractModuleNames and isFromBase, it looks to me like you still have quite a bit to learn about the basics of how Python works. (Clues: getattr, module.__name__ and issubclass, respectively.) In this case now is not the time to be diving into import magic! It's hard. Instead, do things The Normal Python Way. It may be a little more typing to say at the bottom of a package's mypackage/__init__.py: from mypackage import fooplugin, barplugin, bazplugin plugins= [fooplugin.FooPlugin, barplugin.BarPlugin, bazplugin.BazPlugin] but it'll work and be understood everywhere without relying on a nest of complex, fragile magic. Incidentally, unless you are planning on some in-depth multiple inheritance work (and again, now may not be the time for that), you probably don't even need to use super(). The usual “IPlugin.__init__(self, ...)” method of calling a known superclass is the straightforward thing to do; super() is not always “the newer, better way of doing things” and there are things you should understand about it before you go charging into using it. A: Unless you're running a version of Python earlier than 2.2 (pretty unlikely), super() is definitely a built-in function (available in every scope, and without importing anything). May be worth checking your version of Python (just start up the interactive prompt by typing python at the command line).
Problem using super(python 2.5.2)
I'm writing a plugin system for my program and I can't get past one thing: class ThingLoader(object): ''' Loader class ''' def loadPlugins(self): ''' Get all the plugins from plugins folder ''' from diones.thingpad.plugin.IntrospectionHelper import loadClasses classList=loadClasses('./plugins', IPlugin)#Gets a list of #plugin classes self.plugins={}#Dictionary that should be filled with #touples of objects and theirs states, activated, deactivated. classList[0](self)#Runs nicelly foo = classList[1] print foo#prints <class 'TestPlugin.TestPlugin'> foo(self)#Raise an exception The test plugin looks like this: import diones.thingpad.plugin.IPlugin as plugin class TestPlugin(plugin.IPlugin): ''' classdocs ''' def __init__(self, loader): self.name='Test Plugin' super(TestPlugin, self).__init__(loader) Now the IPlugin looks like this: class IPlugin(object): ''' classdocs ''' name='' def __init__(self, loader): self.loader=loader def activate(self): pass All the IPlugin classes works flawlessy by them selves, but when called by ThingLoader the program gets an exception: File "./plugins\TestPlugin.py", line 13, in __init__ super(TestPlugin, self).__init__(loader) NameError: global name 'super' is not defined I looked all around and I simply don't know what is going on.
[ "‘super’ is a builtin. Unless you went out of your way to delete builtins, you shouldn't ever see “global name 'super' is not defined”.\nI'm looking at your user web link where there is a dump of IntrospectionHelper. It's very hard to read without the indentation, but it looks like you may be doing exactly that:\nbuilt_in_list = ['__builtins__', '__doc__', '__file__', '__name__']\n\nfor i in built_in_list:\n if i in module.__dict__:\n del module.__dict__[i]\n\nThat's the original module dict you're changing there, not an informational copy you are about to return! Delete these members from a live module and you can expect much more than ‘super’ to break.\nIt's very hard to keep track of what that module is doing, but my reaction is there is far too much magic in it. The average Python program should never need to be messing around with the import system, sys.path, and monkey-patching __magic__ module members. A little bit of magic can be a neat trick, but this is extremely fragile. Just off the top of my head from browsing it, the code could be broken by things like:\n\nname clashes with top-level modules\nany use of new-style classes\nmodules supplied only as compiled bytecode\nzipimporter\n\nFrom the incredibly round-about functions like getClassDefinitions, extractModuleNames and isFromBase, it looks to me like you still have quite a bit to learn about the basics of how Python works. (Clues: getattr, module.__name__ and issubclass, respectively.)\nIn this case now is not the time to be diving into import magic! It's hard. Instead, do things The Normal Python Way. It may be a little more typing to say at the bottom of a package's mypackage/__init__.py:\nfrom mypackage import fooplugin, barplugin, bazplugin\nplugins= [fooplugin.FooPlugin, barplugin.BarPlugin, bazplugin.BazPlugin]\n\nbut it'll work and be understood everywhere without relying on a nest of complex, fragile magic.\nIncidentally, unless you are planning on some in-depth multiple inheritance work (and again, now may not be the time for that), you probably don't even need to use super(). The usual “IPlugin.__init__(self, ...)” method of calling a known superclass is the straightforward thing to do; super() is not always “the newer, better way of doing things” and there are things you should understand about it before you go charging into using it.\n", "Unless you're running a version of Python earlier than 2.2 (pretty unlikely), super() is definitely a built-in function (available in every scope, and without importing anything).\nMay be worth checking your version of Python (just start up the interactive prompt by typing python at the command line).\n" ]
[ 20, 0 ]
[]
[]
[ "introspection", "python", "python_datamodel" ]
stackoverflow_0000612468_introspection_python_python_datamodel.txt
Q: What is a good strategy for constructing a directed graph for a game map (in Python)? I'm developing a procedurally-generated game world in Python. The structure of the world will be similar to the MUD/MUSH paradigm of rooms and exits arranged as a directed graph (rooms are nodes, exits are edges). (Note that this is not necessarily an acyclic graph, though I'm willing to consider acyclic solutions.) To the world generation algorithm, rooms of different sorts will be distinguished by each room's "tags" attribute (a set of strings). Once they have been instantiated, rooms can be queried and selected by tags (single-tag, tag intersection, tag union, best-candidate). I'll be creating specific sorts of rooms using a glorified system of template objects and factory methods--I don't think the details are important here, as the current implementation will probably change to match the chosen strategy. (For instance, it would be possible to add tags and tag-queries to the room template system.) For an example, I will have rooms of these sorts: side_street, main_street, plaza, bar, hotel, restaurant, shop, office Finally, the question: what is a good strategy for instantiating and arranging these rooms to create a graph that might correspond to given rules? Some rules might include: one plaza per 10,000 population; main_street connects to plaza; side_street connects to main_street or side_street; hotel favors main_street or plaza connections, and receives further tags accordingly; etc. Bonus points if a suggested strategy would enable a data-driven implementation. A: First, you need some sense of Location. Your various objects occupy some amount of coordinate space. You have to decide how regular these various things are. In the trivial case, you can drop them into your coordinate space as simple rectangles (or rectangular solids) to make locations simpler to plan out. If the things are irregular -- and densely packed -- life is somewhat more complex. Define a Map to contain locations. Each location has a span of coordinates; if you work with simple rectangles, then each location can have a (left, top, right, bottom) tuple. Your Map will need methods to determine who is residing in a given space, and what's adjacent to the space, etc. You can then unit test this with a fixed set of locations you've worked out that can all be dropped into the map and pass some basic sanity checks for non-conflicting, adjacent, and the like. Second, you need a kind of "maze generator". A simply-connected maze is easily generated as a tree structure that's folded up into the given space. The maze/tree has a "root" node that will be the center of the maze. Not necessarily the physical center of your space, but the root node will be the middle of the maze structure. Ideally, one branch from this node contains one "entrance" to the entire space. The other branch from this node contains one "exit" from the entire space. Someone can wander from entrance to exit, visiting a lot of "dead-end" locations along the way. Pick a kind of space for the root node. Drop it into your Map space. This will have 1 - n entrances, each of which is a sub-tree with a root node and 1 - n entrances. It's this multiple-entrance business that makes a tree a natural fit for this structure. Also a proper tree is always well-connected in that you never have isolated sections that can't be reached. You'll -- recursively -- fan out from the root node, picking locations and dropping them into the available space. Unit test this to be sure it fills space reasonably well. The rest of your requirements are fine-tuning on the way the maze generator picks locations. The easiest is to have a table of weights and random choices. Choose a random number, compare it with the weights to see which kind of location gets identified. Your definition of space can be 2D or 3D -- both are pretty rational. For bonus credit, consider how you'd implement a 2D-space tiled with hexagons instead of squares. This "geometry" can be a Strategy plug-in to the various algorithms. If you can replace square 2D with hexagonal 2D, you've done a good job of OO Design. A: Check out the discussions on The MUD Connector - there are some great discussions about world layout and generation, and different types of coordinate / navigation systems in the "Advanced Coding and Design" (or similar) forum.
What is a good strategy for constructing a directed graph for a game map (in Python)?
I'm developing a procedurally-generated game world in Python. The structure of the world will be similar to the MUD/MUSH paradigm of rooms and exits arranged as a directed graph (rooms are nodes, exits are edges). (Note that this is not necessarily an acyclic graph, though I'm willing to consider acyclic solutions.) To the world generation algorithm, rooms of different sorts will be distinguished by each room's "tags" attribute (a set of strings). Once they have been instantiated, rooms can be queried and selected by tags (single-tag, tag intersection, tag union, best-candidate). I'll be creating specific sorts of rooms using a glorified system of template objects and factory methods--I don't think the details are important here, as the current implementation will probably change to match the chosen strategy. (For instance, it would be possible to add tags and tag-queries to the room template system.) For an example, I will have rooms of these sorts: side_street, main_street, plaza, bar, hotel, restaurant, shop, office Finally, the question: what is a good strategy for instantiating and arranging these rooms to create a graph that might correspond to given rules? Some rules might include: one plaza per 10,000 population; main_street connects to plaza; side_street connects to main_street or side_street; hotel favors main_street or plaza connections, and receives further tags accordingly; etc. Bonus points if a suggested strategy would enable a data-driven implementation.
[ "First, you need some sense of Location. Your various objects occupy some amount of coordinate space.\nYou have to decide how regular these various things are. In the trivial case, you can drop them into your coordinate space as simple rectangles (or rectangular solids) to make locations simpler to plan out.\nIf the things are irregular -- and densely packed -- life is somewhat more complex.\nDefine a Map to contain locations. Each location has a span of coordinates; if you work with simple rectangles, then each location can have a (left, top, right, bottom) tuple. \nYour Map will need methods to determine who is residing in a given space, and what's adjacent to the space, etc.\nYou can then unit test this with a fixed set of locations you've worked out that can all be dropped into the map and pass some basic sanity checks for non-conflicting, adjacent, and the like.\n\nSecond, you need a kind of \"maze generator\". A simply-connected maze is easily generated as a tree structure that's folded up into the given space.\nThe maze/tree has a \"root\" node that will be the center of the maze. Not necessarily the physical center of your space, but the root node will be the middle of the maze structure. \nIdeally, one branch from this node contains one \"entrance\" to the entire space.\nThe other branch from this node contains one \"exit\" from the entire space. \nSomeone can wander from entrance to exit, visiting a lot of \"dead-end\" locations along the way.\nPick a kind of space for the root node. Drop it into your Map space.\nThis will have 1 - n entrances, each of which is a sub-tree with a root node and 1 - n entrances. It's this multiple-entrance business that makes a tree a natural fit for this structure. Also a proper tree is always well-connected in that you never have isolated sections that can't be reached.\nYou'll -- recursively -- fan out from the root node, picking locations and dropping them into the available space. \nUnit test this to be sure it fills space reasonably well.\n\nThe rest of your requirements are fine-tuning on the way the maze generator picks locations. \nThe easiest is to have a table of weights and random choices. Choose a random number, compare it with the weights to see which kind of location gets identified.\n\nYour definition of space can be 2D or 3D -- both are pretty rational. For bonus credit, consider how you'd implement a 2D-space tiled with hexagons instead of squares.\nThis \"geometry\" can be a Strategy plug-in to the various algorithms. If you can replace square 2D with hexagonal 2D, you've done a good job of OO Design.\n", "Check out the discussions on The MUD Connector - there are some great discussions about world layout and generation, and different types of coordinate / navigation systems in the \"Advanced Coding and Design\" (or similar) forum.\n" ]
[ 7, 2 ]
[]
[]
[ "graph", "procedural_generation", "python" ]
stackoverflow_0000610892_graph_procedural_generation_python.txt
Q: Why do I get wrong results for hmac in Python but not Perl? I'm trying to compute hmac using sha-512. The Perl code: use Digest::SHA qw(hmac_sha512_hex); $key = "\x0b"x20; $data = "Hi There"; $hash = hmac_sha512_hex($data, $key); print "$hash\n"; and gives the correct hash of 87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b30545e17cde daa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f1702e696c203a126854 Python version: import hashlib, hmac print hmac.new("\x0b"*20, "Hi There", hashlib.sha512).hexdigest() which gives the incorrect hash of 9656975ee5de55e75f2976ecce9a04501060b9dc22a6eda2eaef638966280182 477fe09f080b2bf564649cad42af8607a2bd8d02979df3a980f15e2326a0a22a any ideas why the Python version is giving me the wrong hash? Edit: version is Python 2.5.1 (r251:54863, Jan 13 2009, 10:26:13) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin A: yes indeed -- it seems the Leopard version of python2.5 is the one that is broken. below run on a Penryn-based MBP... $ **uname -a** Darwin lizard-wifi 9.6.0 Darwin Kernel Version 9.6.0: Mon Nov 24 17:37:00 PST 2008; root:xnu-1228.9.59~1/RELEASE_I386 i386 dpc@lizard-wifi:~$ **which python** /usr/bin/python Running this version installed in Leopard OS dpc@lizard-wifi:~$ python Python 2.5.1 (r251:54863, Jan 13 2009, 10:26:13) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import hashlib, hmac >>> print hmac.new("\x0b"*20, "Hi There", hashlib.sha512).hexdigest() 9656975ee5de55e75f2976ecce9a04501060b9dc22a6eda2eaef638966280182477fe09f080b2bf564649cad42af8607a2bd8d02979df3a980f15e2326a0a22a >>> And then the MacPorts version of python2.5 $ /opt/local/bin/python2.5 Python 2.5.4 (r254:67916, Feb 3 2009, 21:40:31) [GCC 4.0.1 (Apple Inc. build 5488)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import hashlib, hmac >>> print hmac.new("\x0b"*20, "Hi There", hashlib.sha512).hexdigest() 87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b30545e17cdedaa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f1702e696c203a126854 >>> A: I am unable to replicate your results here. In IDLE using Python 2.5: Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. ... IDLE 1.2.2 >>> import hashlib, hmac >>> print hmac.new("\x0b"*20, "Hi There", hashlib.sha512).hexdigest() 87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b30545e17cdedaa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f1702e696c203a126854 A: Which version of Python? Strings are Unicode in Python 3. Is this a Unicode issue? A: Under python 2.5.2 I get the correct hash I guess the old version was the problem
Why do I get wrong results for hmac in Python but not Perl?
I'm trying to compute hmac using sha-512. The Perl code: use Digest::SHA qw(hmac_sha512_hex); $key = "\x0b"x20; $data = "Hi There"; $hash = hmac_sha512_hex($data, $key); print "$hash\n"; and gives the correct hash of 87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b30545e17cde daa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f1702e696c203a126854 Python version: import hashlib, hmac print hmac.new("\x0b"*20, "Hi There", hashlib.sha512).hexdigest() which gives the incorrect hash of 9656975ee5de55e75f2976ecce9a04501060b9dc22a6eda2eaef638966280182 477fe09f080b2bf564649cad42af8607a2bd8d02979df3a980f15e2326a0a22a any ideas why the Python version is giving me the wrong hash? Edit: version is Python 2.5.1 (r251:54863, Jan 13 2009, 10:26:13) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin
[ "yes indeed -- it seems the Leopard version of python2.5 is the one that is broken. \nbelow run on a Penryn-based MBP...\n$ **uname -a**\nDarwin lizard-wifi 9.6.0 Darwin Kernel Version 9.6.0: Mon Nov 24 17:37:00 PST 2008; root:xnu-1228.9.59~1/RELEASE_I386 i386\ndpc@lizard-wifi:~$ **which python**\n/usr/bin/python\n\nRunning this version installed in Leopard OS\ndpc@lizard-wifi:~$ python\nPython 2.5.1 (r251:54863, Jan 13 2009, 10:26:13) \n[GCC 4.0.1 (Apple Inc. build 5465)] on darwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import hashlib, hmac\n>>> print hmac.new(\"\\x0b\"*20, \"Hi There\", hashlib.sha512).hexdigest()\n9656975ee5de55e75f2976ecce9a04501060b9dc22a6eda2eaef638966280182477fe09f080b2bf564649cad42af8607a2bd8d02979df3a980f15e2326a0a22a\n>>> \n\nAnd then the MacPorts version of python2.5\n$ /opt/local/bin/python2.5\nPython 2.5.4 (r254:67916, Feb 3 2009, 21:40:31) \n[GCC 4.0.1 (Apple Inc. build 5488)] on darwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import hashlib, hmac\n>>> print hmac.new(\"\\x0b\"*20, \"Hi There\", hashlib.sha512).hexdigest()\n87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b30545e17cdedaa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f1702e696c203a126854\n>>> \n\n", "I am unable to replicate your results here. In IDLE using Python 2.5:\nPython 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type \"copyright\", \"credits\" or \"license()\" for more information.\n\n...\n\nIDLE 1.2.2 \n>>> import hashlib, hmac\n>>> print hmac.new(\"\\x0b\"*20, \"Hi There\", hashlib.sha512).hexdigest()\n87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b30545e17cdedaa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f1702e696c203a126854\n\n", "Which version of Python? Strings are Unicode in Python 3. Is this a Unicode issue?\n", "Under python 2.5.2 I get the correct hash\nI guess the old version was the problem\n" ]
[ 9, 1, 0, 0 ]
[]
[]
[ "hash", "hmac", "perl", "python" ]
stackoverflow_0000613111_hash_hmac_perl_python.txt
Q: Python one-liner to print every file in the current directory How can I make the following one liner print every file through Python? python -c "import sys;print '>>',sys.argv[1:]" | dir *.* Specifically would like to know how to pipe into a python -c. DOS or Cygwin responses accepted. A: python -c "import os; print os.listdir('.')" If you want to apply some formatting like you have in your question, python -c "import os; print '\n'.join(['>>%s' % x for x in os.listdir('.')])" If you want to use a pipe, use xargs: ls | xargs python -c "import sys; print '>>', sys.argv[1:]" or backticks: python -c "import sys; print '>>', sys.argv[1:]" `ls` A: You can read data piped into a Python script by reading sys.stdin. For example: ls -al | python -c "import sys; print sys.stdin.readlines()" It is not entirely clear what you want to do (maybe I am stupid). The confusion comes from your example which is piping data out of a python script. A: If you want to print all files: find . -type f If you want to print only the current directory's files find . -type f -maxdepth 1 If you want to include the ">>" before each line find . -type f -maxdepth 1 | xargs -L 1 echo ">>" If you don't want the space between ">>" and $path from echo find . -type f -maxdepth 1 | xargs -L 1 printf ">>%s\n" This is all using cygwin, of course. A: ls | python -c "import sys; print sys.stdin.read()" just read stdin as normal for pipes A: would like to know how to pipe though You had the pipe the wrong way round, if you wanted to feed the output of ‘dir’ into Python, ‘dir’ would have to be on the left. eg.: dir "*.*" | python -c "import sys;[sys.stdout.write('>>%s\n' % line) for line in sys.stdin]" (The hack with the list comprehension is because you aren't allowed a block-introducing ‘for’ statement on one line after a semicolon.) Clearly the Python-native solution (‘os.listdir’) is much better in practice. A: Specifically would like to know how to pipe into a python -c see cobbal's answer piping through a program is transparent from the program's point of view, all the program knows is that it's getting input from the standard input stream Generally speaking, a shell command of the form A | B redirects the output of A to be the input of B so if A spits "asdf" to standard output, then B gets "asdf" into its standard input the standard input stream in python is sys.stdin
Python one-liner to print every file in the current directory
How can I make the following one liner print every file through Python? python -c "import sys;print '>>',sys.argv[1:]" | dir *.* Specifically would like to know how to pipe into a python -c. DOS or Cygwin responses accepted.
[ "python -c \"import os; print os.listdir('.')\"\n\nIf you want to apply some formatting like you have in your question,\npython -c \"import os; print '\\n'.join(['>>%s' % x for x in os.listdir('.')])\"\n\nIf you want to use a pipe, use xargs:\nls | xargs python -c \"import sys; print '>>', sys.argv[1:]\"\n\nor backticks:\npython -c \"import sys; print '>>', sys.argv[1:]\" `ls`\n\n", "You can read data piped into a Python script by reading sys.stdin. For example:\nls -al | python -c \"import sys; print sys.stdin.readlines()\"\n\nIt is not entirely clear what you want to do (maybe I am stupid). The confusion comes from your example which is piping data out of a python script.\n", "If you want to print all files:\nfind . -type f\n\nIf you want to print only the current directory's files\nfind . -type f -maxdepth 1\n\nIf you want to include the \">>\" before each line\nfind . -type f -maxdepth 1 | xargs -L 1 echo \">>\"\n\nIf you don't want the space between \">>\" and $path from echo\nfind . -type f -maxdepth 1 | xargs -L 1 printf \">>%s\\n\"\n\nThis is all using cygwin, of course.\n", "ls | python -c \"import sys; print sys.stdin.read()\"\n\njust read stdin as normal for pipes\n", "\nwould like to know how to pipe though\n\nYou had the pipe the wrong way round, if you wanted to feed the output of ‘dir’ into Python, ‘dir’ would have to be on the left. eg.:\ndir \"*.*\" | python -c \"import sys;[sys.stdout.write('>>%s\\n' % line) for line in sys.stdin]\"\n\n(The hack with the list comprehension is because you aren't allowed a block-introducing ‘for’ statement on one line after a semicolon.)\nClearly the Python-native solution (‘os.listdir’) is much better in practice.\n", "\nSpecifically would like to know how to pipe into a python -c\n\nsee cobbal's answer\npiping through a program is transparent from the program's point of view, all the program knows is that it's getting input from the standard input stream\nGenerally speaking, a shell command of the form \nA | B\n\nredirects the output of A to be the input of B\nso if A spits \"asdf\" to standard output, then B gets \"asdf\" into its standard input\nthe standard input stream in python is sys.stdin\n" ]
[ 6, 5, 4, 3, 2, 1 ]
[]
[]
[ "cmd", "cygwin", "pipe", "python" ]
stackoverflow_0000613007_cmd_cygwin_pipe_python.txt
Q: Adding twisted code to a pygtk app I have a simple pygtk app using urllib2, what changes should I make to add working twisted code? The pbgtk2.py example it's confusing A: You switch from using the gtk mainloop to the right Twisted reactor. Or you decide to run Twisted in a separate thread using reactor.run(installSignalHandlers=0), and stay with the gtk mainloop. You decide if you want to defer the urllib2 call to its own thread, or if you want to rewrite that code using Twisted's HTTP client libraries. You go to the Twisted mailing list or IRC channel and ask for help.
Adding twisted code to a pygtk app
I have a simple pygtk app using urllib2, what changes should I make to add working twisted code? The pbgtk2.py example it's confusing
[ "You switch from using the gtk mainloop to the right Twisted reactor. Or you decide to run Twisted in a separate thread using reactor.run(installSignalHandlers=0), and stay with the gtk mainloop.\nYou decide if you want to defer the urllib2 call to its own thread, or if you want to rewrite that code using Twisted's HTTP client libraries.\nYou go to the Twisted mailing list or IRC channel and ask for help.\n" ]
[ 4 ]
[]
[]
[ "pygtk", "python", "twisted" ]
stackoverflow_0000613777_pygtk_python_twisted.txt
Q: Why is the regular expression returning an error in python? Am trying the following regular expression in python but it returns an error import re ... #read a line from a file to variable line # loking for the pattern 'WORD' in the line ... m=re.search('(?<=[WORD])\w+',str(line)) m.group(0) i get the following error: AttributeError: 'NoneType' object has no attribute 'group' A: This is happening because the regular expression wasn't matched. Therefore m is None and of course you can't access group[0]. You need to first test that the search was successful, before trying to access group members. A: Two issues: your pattern does not match, therefore m is set to None, and None has no group attribute. I believe you meant either: m= re.search(r"(?<=WORD)\w+", str(line)) as entered, or m= re.search(r"(?P<WORD>\w+)", str(line)) The former matches "abc" in "WORDabc def"; the latter matches "abc" in "abc def" and the match object will have a .group("WORD") containing "abc". (Using r"" strings is generally a good idea when specifying regular expressions.) A: re.search documentation says: Return None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string. A: >>> help(re.search) Help on function search in module re: search(pattern, string, flags=0) Scan through string looking for a match to the pattern, returning a match object, or None if no match was found. Look at the last line: returning None if no match was found A: BTW, your regular expression is incorrect. If you look for 'WORD', it should be just 'WORD'. str is also extraneous. Your code should look like this: m = re.search('WORD', line) if m: print m.group[0] Your original regexp will return probably unexpected and undesired results: >>> m = re.search('(?<=[WORD])\w+', 'WORDnet') >>> m.group(0) 'ORDnet'
Why is the regular expression returning an error in python?
Am trying the following regular expression in python but it returns an error import re ... #read a line from a file to variable line # loking for the pattern 'WORD' in the line ... m=re.search('(?<=[WORD])\w+',str(line)) m.group(0) i get the following error: AttributeError: 'NoneType' object has no attribute 'group'
[ "This is happening because the regular expression wasn't matched. Therefore m is None and of course you can't access group[0]. You need to first test that the search was successful, before trying to access group members.\n", "Two issues:\n\nyour pattern does not match, therefore m is set to None, and None has no group attribute.\nI believe you meant either:\nm= re.search(r\"(?<=WORD)\\w+\", str(line))\n\nas entered, or\nm= re.search(r\"(?P<WORD>\\w+)\", str(line))\n\nThe former matches \"abc\" in \"WORDabc def\"; the latter matches \"abc\" in \"abc def\" and the match object will have a .group(\"WORD\") containing \"abc\". (Using r\"\" strings is generally a good idea when specifying regular expressions.)\n\n", "re.search documentation says:\n\nReturn None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string.\n\n", ">>> help(re.search)\nHelp on function search in module re:\n\nsearch(pattern, string, flags=0)\n Scan through string looking for a match to the pattern, returning\n a match object, or None if no match was found.\n\nLook at the last line: returning None if no match was found\n", "BTW, your regular expression is incorrect.\nIf you look for 'WORD', it should be just 'WORD'. str is also extraneous. Your code should look like this:\nm = re.search('WORD', line)\nif m:\n print m.group[0]\n\nYour original regexp will return probably unexpected and undesired results:\n>>> m = re.search('(?<=[WORD])\\w+', 'WORDnet')\n>>> m.group(0)\n'ORDnet'\n\n" ]
[ 5, 5, 2, 2, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0000614205_python_regex.txt
Q: Big images with cairo I have to render a very big image (>50.000² pixel) with cairo. To do this without running out of memory I render parts of the image (<1.000² pixel) one after another and merge them together later. Create 1000x1000 Surface Translate to position of the current part Draw image (calling the drawing instructions using pycairo) Render/Save image to file (cairo_surface_write_to_png) Repeat with next part Because cairos clipping algorithms are faster than my own, step three draws the whole image, even if only a part of it is visible. Most of the CPU is used in Step 3 (by python). Most of the memory is used in Step 4 (by cairo). Is there a way to speed things up? Something like this? Create 1000x1000 Surface Draw image Move everything to position of the current part Render/Save image to file Repeat 3 with next part or Create 50000x50000 Surface Draw image Render/Save only the current part of the image to file Repeat 3 with next part A: First of all, using C or Vala instead of Python will probably speed things up. As for memory usage, I would try writing to my own stream, rather than a file (see write_to_png_stream). This could allow you to (I didn't try this) control memory usage, assuming Cairo doesn't call your function only once after everything's done.
Big images with cairo
I have to render a very big image (>50.000² pixel) with cairo. To do this without running out of memory I render parts of the image (<1.000² pixel) one after another and merge them together later. Create 1000x1000 Surface Translate to position of the current part Draw image (calling the drawing instructions using pycairo) Render/Save image to file (cairo_surface_write_to_png) Repeat with next part Because cairos clipping algorithms are faster than my own, step three draws the whole image, even if only a part of it is visible. Most of the CPU is used in Step 3 (by python). Most of the memory is used in Step 4 (by cairo). Is there a way to speed things up? Something like this? Create 1000x1000 Surface Draw image Move everything to position of the current part Render/Save image to file Repeat 3 with next part or Create 50000x50000 Surface Draw image Render/Save only the current part of the image to file Repeat 3 with next part
[ "First of all, using C or Vala instead of Python will probably speed things up.\nAs for memory usage, I would try writing to my own stream, rather than a file (see write_to_png_stream). This could allow you to (I didn't try this) control memory usage, assuming Cairo doesn't call your function only once after everything's done.\n" ]
[ 2 ]
[]
[]
[ "cairo", "python" ]
stackoverflow_0000614949_cairo_python.txt
Q: Best Python templating library to facilitate code generation Instead of me spending the next day (or year) reading about them all, are there any suggestions for templating engines that I should look into in more detail? A: Best suggestion: try them all. It won't take long. My favourite: Jinja2 (by a mile) It has decent syntax, can trace errors through it, and is sandboxable. A: If you're doing code generation, you might find Cog useful - it's specifically for code generation, rather than being a generally applicable templating language. A: The most important concern is whether you can live with the syntax the templates require. Second and third (depending on your application needs) would be speed and ease of distribution. I looked at all of them, but the only syntax I could stand was Jinja. Jinja has the advantage of supporting a lot of Python constructs, so it's very easy to add snippets of functionality to the templates as needed, without coding special tags. Most of what requires tags in other template systems is handled by macros in Jinja. Of course, if you're looking for something easy and quick, it's hard to beat the Python templating API in the core language. A: Update: Kid appears to have been succeeded by Genshi. I've used Kid, which is I think one of the older systems. I've found it to be extremely solid, stable and reliable. It's tag-based, so it's nice for working with XML/HTML. It's kind of interesting in that template functions are done as HTML attributes, not special blocks, i.e. {% ... %}. However, some aspects of that (especially the way it does 'includes') can get pretty irksome. It also doesn't seem to be developed actively or at all anymore. It's worth taking a look at if you want something that has been around for a while and has become quite stable. If you want something more recent, I've heard good things about both Genshi and Jinja. A: I like Clearsilver because it works with several different languages and it strictly enforces the separation between data and presentation. I previously used Cheetah and while it's pretty nice, I didn't like working with what sometimes seemed like a limited form of Python. A: If you're working with X[HT]ML, one of the tag-based templating systems that can leave you with well-formed templates is a good move. I use PXTL, FWIW. (It can produce other formats, but if your emphasis isn't XML or HTML it'd not be a sensible choice.) I have an intense dislike for templating systems that claim to “help you separate business logic and presentation” by limiting expressions to their own Little Language. They don't seem to understand that there is such as thing as “presentation logic”, and it can get sometimes complicated enough to need a Real Language like Python to run it. Having you kick out your presentation logic into the app with the business logic is so not a win. Avoid! (The limited expression separate mini-language approach made some sense in JSP's ‘EL’, as Java is too annoyingly verbose to use in a templating library. But we've got Python! It's perfect for writing expressions in templates as it is; chopping functionality out and making the user learn another new language gains you nothing.) A: If you want a very lightweight option, try templete. It's only like 80 lines of code in single module. Have a look here and here (it was published in a blog). I think it is a clever and very focused solution, if the features are sufficient for you.
Best Python templating library to facilitate code generation
Instead of me spending the next day (or year) reading about them all, are there any suggestions for templating engines that I should look into in more detail?
[ "Best suggestion: try them all. It won't take long.\nMy favourite: Jinja2 (by a mile)\nIt has decent syntax, can trace errors through it, and is sandboxable.\n", "If you're doing code generation, you might find Cog useful - it's specifically for code generation, rather than being a generally applicable templating language.\n", "The most important concern is whether you can live with the syntax the templates require. Second and third (depending on your application needs) would be speed and ease of distribution.\nI looked at all of them, but the only syntax I could stand was Jinja. Jinja has the advantage of supporting a lot of Python constructs, so it's very easy to add snippets of functionality to the templates as needed, without coding special tags. Most of what requires tags in other template systems is handled by macros in Jinja.\nOf course, if you're looking for something easy and quick, it's hard to beat the Python templating API in the core language.\n", "Update: Kid appears to have been succeeded by Genshi.\nI've used Kid, which is I think one of the older systems. I've found it to be extremely solid, stable and reliable. It's tag-based, so it's nice for working with XML/HTML. It's kind of interesting in that template functions are done as HTML attributes, not special blocks, i.e. {% ... %}. However, some aspects of that (especially the way it does 'includes') can get pretty irksome. It also doesn't seem to be developed actively or at all anymore.\nIt's worth taking a look at if you want something that has been around for a while and has become quite stable. If you want something more recent, I've heard good things about both Genshi and Jinja.\n", "I like Clearsilver because it works with several different languages and it strictly enforces the separation between data and presentation. I previously used Cheetah and while it's pretty nice, I didn't like working with what sometimes seemed like a limited form of Python.\n", "If you're working with X[HT]ML, one of the tag-based templating systems that can leave you with well-formed templates is a good move. I use PXTL, FWIW. (It can produce other formats, but if your emphasis isn't XML or HTML it'd not be a sensible choice.)\nI have an intense dislike for templating systems that claim to “help you separate business logic and presentation” by limiting expressions to their own Little Language. They don't seem to understand that there is such as thing as “presentation logic”, and it can get sometimes complicated enough to need a Real Language like Python to run it. Having you kick out your presentation logic into the app with the business logic is so not a win. Avoid!\n(The limited expression separate mini-language approach made some sense in JSP's ‘EL’, as Java is too annoyingly verbose to use in a templating library. But we've got Python! It's perfect for writing expressions in templates as it is; chopping functionality out and making the user learn another new language gains you nothing.)\n", "If you want a very lightweight option, try templete. It's only like 80 lines of code in single module. Have a look here and here (it was published in a blog). I think it is a clever and very focused solution, if the features are sufficient for you.\n" ]
[ 29, 17, 10, 3, 1, 1, 1 ]
[]
[]
[ "code_generation", "python", "templates" ]
stackoverflow_0000612788_code_generation_python_templates.txt
Q: How to copy a directory and its contents to an existing location using Python? I'm trying to copy a directory and all its contents to a path that already exists. The problem is, between the os module and the shutil module, there doesn't seem to be a way to do this. the shutil.copytree() function expects that the destination path not exist beforehand. The exact result I'm looking for is to copy an entire folder structure on top of another, overwriting silently on any duplicates found. Before I jump in and start writing my own function to do this I thought I'd ask if anyone knows of an existing recipe or snippet that does this. A: distutils.dir_util.copy_tree does what you want. Copy an entire directory tree src to a new location dst. Both src and dst must be directory names. If src is not a directory, raise DistutilsFileError. If dst does not exist, it is created with mkpath(). The end result of the copy is that every file in src is copied to dst, and directories under src are recursively copied to dst. Return the list of files that were copied or might have been copied, using their output name. The return value is unaffected by update or dry_run: it is simply the list of all files under src, with the names changed to be under dst. (more documentation at the above url) A: Why not implement it on your own using os.walk? A: For highlevel file operations like that use the shutil module and in your case the copytree function. I think that is cleaner than "abusing" distutils. UPDATE:: Forget the answer, I overlooked that the OP did try shutil. A: Are you gettting the error that says "Cannot create a directory when its already present"? I am not sure how much silly is this, but all i did was to insert a single line into copytree module: I changed : def copytree(src, dst, symlinks=False): names = os.listdir(src) os.makedirs(dst) into: def copytree(src, dst, symlinks=False): names = os.listdir(src) if (os.path.isdir(dst)==False): os.makedirs(dst) I guess i did some bluder. If so, could someone point me out that? Sorry, i am very new to python :P
How to copy a directory and its contents to an existing location using Python?
I'm trying to copy a directory and all its contents to a path that already exists. The problem is, between the os module and the shutil module, there doesn't seem to be a way to do this. the shutil.copytree() function expects that the destination path not exist beforehand. The exact result I'm looking for is to copy an entire folder structure on top of another, overwriting silently on any duplicates found. Before I jump in and start writing my own function to do this I thought I'd ask if anyone knows of an existing recipe or snippet that does this.
[ "distutils.dir_util.copy_tree does what you want.\n\nCopy an entire directory tree src to a\n new location dst. Both src and dst\n must be directory names. If src is not\n a directory, raise DistutilsFileError.\n If dst does not exist, it is created\n with mkpath(). The end result of the\n copy is that every file in src is\n copied to dst, and directories under\n src are recursively copied to dst.\n Return the list of files that were\n copied or might have been copied,\n using their output name. The return\n value is unaffected by update or\n dry_run: it is simply the list of all\n files under src, with the names\n changed to be under dst.\n\n(more documentation at the above url)\n", "Why not implement it on your own using os.walk?\n", "For highlevel file operations like that use the shutil module and in your case the copytree function. I think that is cleaner than \"abusing\" distutils.\nUPDATE:: Forget the answer, I overlooked that the OP did try shutil.\n", "Are you gettting the error that says \"Cannot create a directory when its already present\"?\nI am not sure how much silly is this, but all i did was to insert a single line into copytree module:\nI changed :\ndef copytree(src, dst, symlinks=False):\n names = os.listdir(src)\n os.makedirs(dst)\n\ninto:\ndef copytree(src, dst, symlinks=False):\n names = os.listdir(src)\n if (os.path.isdir(dst)==False):\n os.makedirs(dst) \n\nI guess i did some bluder. If so, could someone point me out that? Sorry, i am very new to python :P\n" ]
[ 43, 0, 0, 0 ]
[]
[]
[ "copy", "filesystems", "operating_system", "python" ]
stackoverflow_0000512173_copy_filesystems_operating_system_python.txt
Q: Tool/library for calculating intervals like "last thursday of the month" I'm looking for a command line tool or some sort of python library (that I can then wrap), so that I can calculate dates that are specified like "last thursday of the month". i.e. I want to let people enter human friendly text like that above and it should be able to calculate all the dates for any month/year/whatever that fulfil that. Any suggestions? A: Neither mxDateTime nor Datejs nor that webservice support "last thursday of the month". The OP wants to know all of the last thursdays of the month for, say, a full year. mxDateTime supports the operations, but the question must be posed in Python code, not as a string. The best I could figure is parsedatetime, but that doesn't support "last thursday of the month". It does support: >>> c.parseDateText("last thursday of april 2001") (2001, 4, 20, 13, 55, 58, 3, 64, 0) >>> c.parseDateText("last thursday of may 2001") (2001, 5, 20, 13, 56, 3, 3, 64, 0) >>> c.parseDateText("last thursday of may 2010") (2010, 5, 20, 13, 56, 7, 3, 64, 0) >>> (Note that neither DateJS nor that web service support this syntax.) EDIT: Umm, okay, but while the year and the month are right, the day isn't. The last thursday of april 2001 was the 27th. I think you're going to have to roll your own solution here. It does not support: >>> c.parseDateText("last thursday of 2010") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "parsedatetime/parsedatetime.py", line 411, in parseDateText mth = self.ptc.MonthOffsets[mth] KeyError >>> So one possibility is text substitution: normalize the string to lowercase, single spaces, etc. then do a string substitution of "the month" for each of the months you're interested in. You'll likely have to tweak any solution you find. For example, in some old code of Skip Montanaro which he wrote for an online music calendering system: # someone keeps submitting dates with september spelled wrong... 'septmber':9, Or you write your own parser on top of mxDateTime, using all of the above links as references. A: I think you can get pretty far using just Python's standard calendar module, maybe by adding some "human-friendly" methods on top of those methods. The module gives you iterators for dates, while taking weeks into consideration, and so on. First I guess you must answer the question "what are some human-friendly ways to talk about dates?", which I guess is more than half the difficulty of this problem. A: The algorithms aren't hard. They're provided in the following book, which is worth every penny. http://emr.cs.iit.edu/home/reingold/calendar-book/third-edition/ The general approach is to find first days of a required month. You can then subtract one day to find the last day of a required month. Then you compute an offset for day of week you want relative to the day of the week you found. Assume you have a datetime.date, d. You can work out the end of the month by computing the start of the next month minus one day. monIx= d.year*12 + (d.month-1) + 1 endOfMonth= datetime.date( monIx//12, monIx%12+1, 1 ) - datetime.timedelta( days=1 ) At this point, you're looking for an offset to the required day of the week. In this case, the desired day of the week is Thursday, which is 3. dayOffset = ((3 - endOfMonth.weekday()) -7 ) % -7 lastDay = endOfMonth + datetime.timedelta( days=dayOffset ) The general approach of getting the day-of-week offset requires a little bit of thinking, but there are only a few combinations of cases to experiment with. A: I'm not entirely sure, but you might look at the Python DateUtil module. A: Well, don't know if such library exists, but date from GNU coreutils has something like that: $ date -d "last monday" Mon Mar 2 00:00:00 RST 2009 A: Use mxDateTime. http://www.egenix.com/products/python/mxBase/mxDateTime/
Tool/library for calculating intervals like "last thursday of the month"
I'm looking for a command line tool or some sort of python library (that I can then wrap), so that I can calculate dates that are specified like "last thursday of the month". i.e. I want to let people enter human friendly text like that above and it should be able to calculate all the dates for any month/year/whatever that fulfil that. Any suggestions?
[ "Neither mxDateTime nor Datejs nor that webservice support \"last thursday of the month\". The OP wants to know all of the last thursdays of the month for, say, a full year.\nmxDateTime supports the operations, but the question must be posed in Python code, not as a string.\nThe best I could figure is parsedatetime, but that doesn't support \"last thursday of the month\". It does support:\n>>> c.parseDateText(\"last thursday of april 2001\")\n(2001, 4, 20, 13, 55, 58, 3, 64, 0)\n>>> c.parseDateText(\"last thursday of may 2001\")\n(2001, 5, 20, 13, 56, 3, 3, 64, 0)\n>>> c.parseDateText(\"last thursday of may 2010\")\n(2010, 5, 20, 13, 56, 7, 3, 64, 0)\n>>> \n\n(Note that neither DateJS nor that web service support this syntax.)\nEDIT: Umm, okay, but while the year and the month are right, the day isn't. The last thursday of april 2001 was the 27th. I think you're going to have to roll your own solution here.\nIt does not support:\n>>> c.parseDateText(\"last thursday of 2010\")\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"parsedatetime/parsedatetime.py\", line 411, in parseDateText\n mth = self.ptc.MonthOffsets[mth]\nKeyError\n>>> \n\nSo one possibility is text substitution: normalize the string to lowercase, single spaces, etc. then do a string substitution of \"the month\" for each of the months you're interested in. You'll likely have to tweak any solution you find. For example, in some old code of Skip Montanaro which he wrote for an online music calendering system:\n # someone keeps submitting dates with september spelled wrong...\n 'septmber':9,\n\nOr you write your own parser on top of mxDateTime, using all of the above links as references.\n", "I think you can get pretty far using just Python's standard calendar module, maybe by adding some \"human-friendly\" methods on top of those methods. The module gives you iterators for dates, while taking weeks into consideration, and so on.\nFirst I guess you must answer the question \"what are some human-friendly ways to talk about dates?\", which I guess is more than half the difficulty of this problem.\n", "The algorithms aren't hard. They're provided in the following book, which is worth every penny.\nhttp://emr.cs.iit.edu/home/reingold/calendar-book/third-edition/\nThe general approach is to find first days of a required month. You can then subtract one day to find the last day of a required month. Then you compute an offset for day of week you want relative to the day of the week you found.\nAssume you have a datetime.date, d. You can work out the end of the month by computing the start of the next month minus one day.\nmonIx= d.year*12 + (d.month-1) + 1\nendOfMonth= datetime.date( monIx//12, monIx%12+1, 1 ) - datetime.timedelta( days=1 )\n\nAt this point, you're looking for an offset to the required day of the week. In this case, the desired day of the week is Thursday, which is 3.\ndayOffset = ((3 - endOfMonth.weekday()) -7 ) % -7 \nlastDay = endOfMonth + datetime.timedelta( days=dayOffset )\n\nThe general approach of getting the day-of-week offset requires a little bit of thinking, but there are only a few combinations of cases to experiment with.\n", "I'm not entirely sure, but you might look at the Python DateUtil module.\n", "Well, don't know if such library exists, but date from GNU coreutils has something like that:\n$ date -d \"last monday\"\nMon Mar 2 00:00:00 RST 2009\n\n", "Use mxDateTime. http://www.egenix.com/products/python/mxBase/mxDateTime/\n" ]
[ 7, 3, 3, 2, 1, 1 ]
[ "If this is for a web app take a look at Datejs, it may be easier to use that in your form then just pass it's date object's value to Python.\nIf you end up writing one yourself the source may be helpful too.\n" ]
[ -1 ]
[ "date", "datetime", "python" ]
stackoverflow_0000614518_date_datetime_python.txt
Q: How to detect errors from compileall.compile_dir? How do I detect an error when compiling a directory of python files using compile_dir? Currently I get something on stderr, but no way to detect it in my app. py_compile.compile() takes a doraise argument, but nothing here. Or is there a better way to do this from a python script? Edit: I fixed it with os.walk and calling py_compile.compile for each file. But the question remains. A: I don't see a better way. The code is designed to support the command-line program, and the API doesn't seem fully meant to be used as a library. If you really had to use the compileall then you could fake it out with this hack, which notices that "quiet" is tested for boolean-ness while in the caught exception handler. I can override that with nonzero, check the exception state to see if it came from py_compile (quiet is tested in other contexts) and do something with that information: import sys import py_compile import compileall class ReportProblem: def __nonzero__(self): type, value, traceback = sys.exc_info() if type is not None and issubclass(type, py_compile.PyCompileError): print "Problem with", repr(value) raise type, value, traceback return 1 report_problem = ReportProblem() compileall.compile_dir(".", quiet=report_problem) Förresten, det finns GothPy på första måndagen varje månad, om du skulle ta sällskap med andra Python-användare i Gbg. A: works fine for me. Could it be that you're not setting doraise to True somehow?
How to detect errors from compileall.compile_dir?
How do I detect an error when compiling a directory of python files using compile_dir? Currently I get something on stderr, but no way to detect it in my app. py_compile.compile() takes a doraise argument, but nothing here. Or is there a better way to do this from a python script? Edit: I fixed it with os.walk and calling py_compile.compile for each file. But the question remains.
[ "I don't see a better way. The code is designed to support the command-line program, and the API doesn't seem fully meant to be used as a library.\nIf you really had to use the compileall then you could fake it out with this hack, which notices that \"quiet\" is tested for boolean-ness while in the caught exception handler. I can override that with nonzero, check the exception state to see if it came from py_compile (quiet is tested in other contexts) and do something with that information:\nimport sys\nimport py_compile\nimport compileall\n\nclass ReportProblem:\n def __nonzero__(self):\n type, value, traceback = sys.exc_info()\n if type is not None and issubclass(type, py_compile.PyCompileError):\n print \"Problem with\", repr(value)\n raise type, value, traceback\n return 1\nreport_problem = ReportProblem()\n\ncompileall.compile_dir(\".\", quiet=report_problem)\n\nFörresten, det finns GothPy på första måndagen varje månad, om du skulle ta sällskap med andra Python-användare i Gbg.\n", "works fine for me. Could it be that you're not setting doraise to True somehow?\n" ]
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000615632_python.txt
Q: Framework/Language for new web 2.0 sites (2008 and 2009) I know I'll get a thousand "Depends on what you're trying to do" answers, but seriously, there really is no solid information about this online yet. Here are my assumptions - I think they're similar for alot of people right now: It is now October 2008. I want to start writing an application for January 2009. I am willing to use beta code and such but by January, I'd like a site that doesn't have 'strange' problems. With that said, if a language is simply 10% slower than another, I don't care about those things as long as the issue is linear. My main concern is developer productivity. I'll be using Linux, Apache, MySQL for the application. I want the power to do things like run scp and ftp client functions with stable libraries (I only picked those two because they're not web-related but at the same time represent pretty common network protocols that any larger app might use). Technologies like OpenID and Oauth will be used as well. Experienced web developers are readily available (i.e. I don't have to find people from financial companies and such). Whatever the choice is is common and will be around for a while. Here's a kicker. I'd like to be able to use advanced presentation layer tools/languages similar to HAML, SASS. I definitively want to use JQuery. I will be creating a Facebook app and at some point doing things like dealing with SMS messages, iPhone apps, etc... At this point, the choices for language are PHP (Cake,Symfony,Zend), Python (Django), Ruby (Merb). I'm really between Django and Merb at this point mostly because everybody else seems to be going that way. Please don't put any technologies in here that aren't made for mainstream. I know Merb is untested mostly, but their stated goal is a solid platform and it has alot of momentum behind it so I'm confident that it's workable. Please don't answer with how great Perl is or .Net. For Future References - these choices were already made: Debian (Lenny) - For converting CPU cycles into something useful. Trac 0.11 - For Project Management Gliffy - For wireframes and such Google Docs/Apps - For documentation, hosted email, etc... Amazon ec2/S3 - For hosting, storage. Cheers, Adam A: Django! Look up the DjangoCon talks on Google/Youtube - Especially "Reusable Apps" (www.youtube.com/watch?v=A-S0tqpPga4) I've been using Django for some time, after starting with Ruby/Rails. I found the Django Community easier to get into (nicer), the language documented with excellent examples, and it's modularity is awesome, especially if you're wanting to throw custom components into the mix, and not be forced to use certain things here and there. I'm sure there are probably ways to be just as flexible with Rails or some such, but I highly encourage you to take a long look at the Django introductions, etc, at http://www.djangoproject.com/ Eugene mentioned it's now at 1.0 - and therefore will remain a stable and backward-compatible codebase well through January 2009. Also, the automatic admin interfaces it builds are production ready, and extremely flexible. A: Sorry, but your question is wrong. People are probably going to vote me down for this one but I want to say it anyway: I wouldn't expect to get an objective answer! Why? That's simple: All Ruby advocates will tell to use Ruby. All Python advocates will tell to use Python. All PHP advocates will tell to use PHP. Insert additional languages here. Got the idea? I recommend you to try each of the languages you mentioned for yourself. At least a few days each. Afterwards you should have a much better foundation to make your final decision. That said, I would choose Ruby (because I am a Ruby advocate). A: All of them will get the job done. Use the one that you and your team are most familiar with This will have a far greater impact on the delivery times and stability of your app than any of the other variables. A: it depends. php - symfony is a great framework. downsides: php, wordy and directory heavy. propel gets annoying to use. upsides: php is everywhere and labor is cheap. well done framework, and good support. lots of plugins to make your life easier python - django is also a great framework. downsides: python programmers can be harder to find, django even harder. changing your db schema can be somewhat difficult since there are no official migrations. doesn't quite do mvc like you'd expect. upsides: does everything you need and has the great python std library and community behind it. ruby - i've never used merb, so I'll address rails. upsides: there is a plugin, gem, or recipe for almost anything you could want to do. easy to use. downsides: those plugins, gems, and recipes sometimes fail to work in mysterious ways. monkey patching is often evil. the community is.. vocal. opinionated software, and sometimes those opinions are wrong (lack of foreign keys). rails itself seems like a tower of cards waiting to explode and take hours of your life away. with all of that said, I'm a freelance php/symfony and ruby/rails developer. I've worked on several projects in both languages and frameworks. My latest project is in Rails solely because of ActiveMerchant. I've been looking for a reason to develop a django app for a while. If there were an ActiveMerchant like library for django, I probably would have used it. A: I would go with Django, if you are comfortable with a Python solution. It's at version 1.0 now, and is maturing nicely, with a large user base and many contributors. Integrating jQuery is no problem, and I've done it without any issues. The only thing is, as far as I can tell, Ruby is much more popular for web development nowadays, so it's easier to find Ruby developers. I get this impression from browsing recent job advertisements - there aren't that many for Python or Django. I don't know much about Merb, so I can't give a fair comparison. I've done enough PHP to not recommend starting a new project with it. A: Based in your reasons, I would go with Ruby. I see that you want some administration tools (scp, ftp client) and Ruby has it (net/sftp and net/ftp libraries). Also, there are great gems like God for monitoring your system, Vlad the Deployer for deploying, etc. And a lot of alternatives in Merb's field, just use whatever you find it's better for your needs (Thin, Mongrel, ebb, etc). A: To get a feeling of where the Django ecosystem is at currently, you might want to check out djangopeople.net (try djangopeople.net/us/ny for New York state) djangogigs.com A: I have to preface this with my agreeing with Orion Edwards, choose the one your team is most familiar with. However, I also have to note the curious lack of ASP.NET languages in your list. Not to provoke the great zealot army, but where's the beef? .NET is a stable, rapid development platform and the labor pool is growing daily. VB.NET and C# are transportable skill sets, and that can mean a lot when you're building a team of developers to work on a diverse set of tasks. .NET also allows you to separate your presentation layer from your backend code, like other languages, but also allows you to expose that backend code as web service for things like your iPhone and Facebook applications. Take every suggestion with a grain of salt, and pick what suits the application best. Do your research, and design for function and not the zealots. Disclaimer: Once a PHP, ColdFusion and Perl developer. Flex zealot, and Adobe lover. Now writing enterprise .NET applications. ;) Don't forget Mono, which will let you run .NET under *nix. Not that I'm saying it will be perfect, just playing devil's advocate. A: Don't get stuck in the mindset of server-side page layout. Consider technologies like SproutCore, GWT or ExtJS which put the layouting code fully on the client, making the server responsible only for data marshalling and processing (and easily replaced). And you really, really need to know which server platform you want. Don't pick one because it's the flavor of the month, pick one because you're comfortable with it. Flavors don't last, a solidly built codebase will. A: Having built apps in Django, I can attest to its utility. If only all frameworks were as elegant (yes Spring, I'm looking at you). However in terms of betting the farm on Django, one thing you need to factor in is that Python 3 will be released shortly. Python 3 is not backwards compatible and there's a risk that it will fork the language and end up slowing momentum for all Python projects while they deal with the fallout. To be fair, Ruby 2.0 is due soon too, but I don't think it will be as disruptive. A: My experience with various new technologies over the last ten years leads me to recommend that you make stability of the platform a serious criterion. It's all well and good developing with the latest and greatest framework, but when you find it's moved forward a point version and suddenly the way you have done everything is deprecated, that can turn out to result in extra unnecessary work. This was particularly my experience working with rails a little ahead of version 1. For that reason alone I would avoid any platform that wasn't at least at 1.0 when you start work on it. Ruby is great to work with and will keep your developer productivity high, but if Django is the more stable platform I would favour that for sure. A: It pays not to be biased about your server setup. Any modern web framework worth it's weight in source code has a SQL abstraction layer of some sort. PostgreSQL gets much better performance, and this is coming from a former MySQL partisan. Apache is a beast, both to configure and on your server's resources. Why not go with something light-weight, like nginx or lighttpd? (For the record, I'm a big Django user, but as the accepted answer said, go with whatever your team knows. Quick turn-arounds are not the time to be learning new frameworks. If you're hiring a team from scratch, go with Django.) A: Update: I ended up using, and loving, Django. I'm totally done with PHP - sorry about that. Future readers trying to create a new web 2.0 site (assuming they have a programming background), should greatly consider this setup: Amazon ec2 for hosting ($80/month - not cheap but worth it if you can afford it) Django/Python (Python is the most powerful scripting language on the planet - and Django just makes it work on the web) Development should be done with SQLlite and the development server that comes with Django. Don't waste time with Nginx, Apache, MySQL until you're withing a few weeks of a beta. Oh, and I now develop on a Mac, which works great for local Django development. Finally, Pinax is a great start for Django development.
Framework/Language for new web 2.0 sites (2008 and 2009)
I know I'll get a thousand "Depends on what you're trying to do" answers, but seriously, there really is no solid information about this online yet. Here are my assumptions - I think they're similar for alot of people right now: It is now October 2008. I want to start writing an application for January 2009. I am willing to use beta code and such but by January, I'd like a site that doesn't have 'strange' problems. With that said, if a language is simply 10% slower than another, I don't care about those things as long as the issue is linear. My main concern is developer productivity. I'll be using Linux, Apache, MySQL for the application. I want the power to do things like run scp and ftp client functions with stable libraries (I only picked those two because they're not web-related but at the same time represent pretty common network protocols that any larger app might use). Technologies like OpenID and Oauth will be used as well. Experienced web developers are readily available (i.e. I don't have to find people from financial companies and such). Whatever the choice is is common and will be around for a while. Here's a kicker. I'd like to be able to use advanced presentation layer tools/languages similar to HAML, SASS. I definitively want to use JQuery. I will be creating a Facebook app and at some point doing things like dealing with SMS messages, iPhone apps, etc... At this point, the choices for language are PHP (Cake,Symfony,Zend), Python (Django), Ruby (Merb). I'm really between Django and Merb at this point mostly because everybody else seems to be going that way. Please don't put any technologies in here that aren't made for mainstream. I know Merb is untested mostly, but their stated goal is a solid platform and it has alot of momentum behind it so I'm confident that it's workable. Please don't answer with how great Perl is or .Net. For Future References - these choices were already made: Debian (Lenny) - For converting CPU cycles into something useful. Trac 0.11 - For Project Management Gliffy - For wireframes and such Google Docs/Apps - For documentation, hosted email, etc... Amazon ec2/S3 - For hosting, storage. Cheers, Adam
[ "Django!\nLook up the DjangoCon talks on Google/Youtube - Especially \"Reusable Apps\" (www.youtube.com/watch?v=A-S0tqpPga4)\nI've been using Django for some time, after starting with Ruby/Rails. I found the Django Community easier to get into (nicer), the language documented with excellent examples, and it's modularity is awesome, especially if you're wanting to throw custom components into the mix, and not be forced to use certain things here and there.\nI'm sure there are probably ways to be just as flexible with Rails or some such, but I highly encourage you to take a long look at the Django introductions, etc, at http://www.djangoproject.com/\nEugene mentioned it's now at 1.0 - and therefore will remain a stable and backward-compatible codebase well through January 2009. \nAlso, the automatic admin interfaces it builds are production ready, and extremely flexible. \n", "Sorry, but your question is wrong. People are probably going to vote me down for this one but I want to say it anyway:\nI wouldn't expect to get an objective answer! Why? That's simple:\n\nAll Ruby advocates will tell to use Ruby.\nAll Python advocates will tell to use Python.\nAll PHP advocates will tell to use PHP.\nInsert additional languages here.\n\nGot the idea?\nI recommend you to try each of the languages you mentioned for yourself. At least a few days each. Afterwards you should have a much better foundation to make your final decision.\nThat said, I would choose Ruby (because I am a Ruby advocate).\n", "All of them will get the job done.\nUse the one that you and your team are most familiar with\nThis will have a far greater impact on the delivery times and stability of your app than any of the other variables.\n", "it depends.\nphp - symfony is a great framework. downsides: php, wordy and directory heavy. propel gets annoying to use. upsides: php is everywhere and labor is cheap. well done framework, and good support. lots of plugins to make your life easier\npython - django is also a great framework. downsides: python programmers can be harder to find, django even harder. changing your db schema can be somewhat difficult since there are no official migrations. doesn't quite do mvc like you'd expect. upsides: does everything you need and has the great python std library and community behind it.\nruby - i've never used merb, so I'll address rails. upsides: there is a plugin, gem, or recipe for almost anything you could want to do. easy to use. downsides: those plugins, gems, and recipes sometimes fail to work in mysterious ways. monkey patching is often evil. the community is.. vocal. opinionated software, and sometimes those opinions are wrong (lack of foreign keys). rails itself seems like a tower of cards waiting to explode and take hours of your life away.\nwith all of that said, I'm a freelance php/symfony and ruby/rails developer. I've worked on several projects in both languages and frameworks. My latest project is in Rails solely because of ActiveMerchant. I've been looking for a reason to develop a django app for a while. If there were an ActiveMerchant like library for django, I probably would have used it.\n", "I would go with Django, if you are comfortable with a Python solution. It's at version 1.0 now, and is maturing nicely, with a large user base and many contributors. Integrating jQuery is no problem, and I've done it without any issues.\nThe only thing is, as far as I can tell, Ruby is much more popular for web development nowadays, so it's easier to find Ruby developers. I get this impression from browsing recent job advertisements - there aren't that many for Python or Django. I don't know much about Merb, so I can't give a fair comparison.\nI've done enough PHP to not recommend starting a new project with it.\n", "Based in your reasons, I would go with Ruby. I see that you want some administration tools (scp, ftp client) and Ruby has it (net/sftp and net/ftp libraries).\nAlso, there are great gems like God for monitoring your system, Vlad the Deployer for deploying, etc. And a lot of alternatives in Merb's field, just use whatever you find it's better for your needs (Thin, Mongrel, ebb, etc).\n", "To get a feeling of where the Django ecosystem is at currently, you might want to check out\n\ndjangopeople.net (try djangopeople.net/us/ny for New York state)\ndjangogigs.com\n\n", "I have to preface this with my agreeing with Orion Edwards, choose the one your team is most familiar with.\nHowever, I also have to note the curious lack of ASP.NET languages in your list. Not to provoke the great zealot army, but where's the beef? .NET is a stable, rapid development platform and the labor pool is growing daily. VB.NET and C# are transportable skill sets, and that can mean a lot when you're building a team of developers to work on a diverse set of tasks. .NET also allows you to separate your presentation layer from your backend code, like other languages, but also allows you to expose that backend code as web service for things like your iPhone and Facebook applications.\nTake every suggestion with a grain of salt, and pick what suits the application best. Do your research, and design for function and not the zealots.\nDisclaimer: Once a PHP, ColdFusion and Perl developer. Flex zealot, and Adobe lover. Now writing enterprise .NET applications. ;)\nDon't forget Mono, which will let you run .NET under *nix. Not that I'm saying it will be perfect, just playing devil's advocate.\n", "Don't get stuck in the mindset of server-side page layout. Consider technologies like SproutCore, GWT or ExtJS which put the layouting code fully on the client, making the server responsible only for data marshalling and processing (and easily replaced).\nAnd you really, really need to know which server platform you want. Don't pick one because it's the flavor of the month, pick one because you're comfortable with it. Flavors don't last, a solidly built codebase will.\n", "Having built apps in Django, I can attest to its utility. If only all frameworks were as elegant (yes Spring, I'm looking at you).\nHowever in terms of betting the farm on Django, one thing you need to factor in is that Python 3 will be released shortly. Python 3 is not backwards compatible and there's a risk that it will fork the language and end up slowing momentum for all Python projects while they deal with the fallout. To be fair, Ruby 2.0 is due soon too, but I don't think it will be as disruptive. \n", "My experience with various new technologies over the last ten years leads me to recommend that you make stability of the platform a serious criterion. It's all well and good developing with the latest and greatest framework, but when you find it's moved forward a point version and suddenly the way you have done everything is deprecated, that can turn out to result in extra unnecessary work. This was particularly my experience working with rails a little ahead of version 1. For that reason alone I would avoid any platform that wasn't at least at 1.0 when you start work on it.\nRuby is great to work with and will keep your developer productivity high, but if Django is the more stable platform I would favour that for sure.\n", "It pays not to be biased about your server setup. Any modern web framework worth it's weight in source code has a SQL abstraction layer of some sort. PostgreSQL gets much better performance, and this is coming from a former MySQL partisan.\nApache is a beast, both to configure and on your server's resources. Why not go with something light-weight, like nginx or lighttpd?\n(For the record, I'm a big Django user, but as the accepted answer said, go with whatever your team knows. Quick turn-arounds are not the time to be learning new frameworks. If you're hiring a team from scratch, go with Django.)\n", "Update: I ended up using, and loving, Django. I'm totally done with PHP - sorry about that. Future readers trying to create a new web 2.0 site (assuming they have a programming background), should greatly consider this setup:\nAmazon ec2 for hosting ($80/month - not cheap but worth it if you can afford it)\nDjango/Python (Python is the most powerful scripting language on the planet - and Django just makes it work on the web)\nDevelopment should be done with SQLlite and the development server that comes with Django. Don't waste time with Nginx, Apache, MySQL until you're withing a few weeks of a beta.\nOh, and I now develop on a Mac, which works great for local Django development.\nFinally, Pinax is a great start for Django development.\n" ]
[ 16, 9, 7, 5, 4, 2, 2, 1, 1, 1, 0, 0, 0 ]
[]
[]
[ "django", "merb", "python", "ruby_on_rails" ]
stackoverflow_0000184049_django_merb_python_ruby_on_rails.txt
Q: Is it possible to remove recursion from this function? I have been playing with this a while, and just cannot see an obvious solution. I want to remove the recursion from the XinY_Go function. def XinY_Go(x,y,index,slots): if (y - index) == 1: slots[index] = x print slots slots[index] = 0 return for i in range(x+1): slots[index] = x-i XinY_Go(x-(x-i), y, index + 1, slots) def XinY(x,y): return XinY_Go(x,y,0,[0] * y) The function is calculating the number of ways to put X marbles in Y slots. Here is some sample output: >>> xy.XinY(1,2) [1, 0] [0, 1] >>> xy.XinY(2,3) [2, 0, 0] [1, 1, 0] [1, 0, 1] [0, 2, 0] [0, 1, 1] [0, 0, 2] A: Everything we think of as recursion can also be thought of as a stack-based problem, where the recursive function just uses the program's call stack rather than creating a separate stack. That means any recursive function can be re-written using a stack instead. I don't know python well enough to give you an implementation, but that should point you in the right direction. But in a nutshell, push the initial arguments for the function onto the stack and add a loop that runs as long as the size of the stack is greater than zero. Pop once per loop iteration, push every time the function currently calls itself. A: A naive implementation of @Joel Coehoorn's suggestion follows: def XinY_Stack(x, y): stack = [(x, 0, [0]*y)] while stack: x, index, slots = stack.pop() if (y - index) == 1: slots[index] = x print slots slots[index] = 0 else: for i in range(x + 1): slots[index] = x-i stack.append((i, index + 1, slots[:])) Example: >>> XinY_Stack(2, 3) [0, 0, 2] [0, 1, 1] [0, 2, 0] [1, 0, 1] [1, 1, 0] [2, 0, 0] Based on itertools.product def XinY_Product(nmarbles, nslots): return (slots for slots in product(xrange(nmarbles + 1), repeat=nslots) if sum(slots) == nmarbles) Based on nested loops def XinY_Iter(nmarbles, nslots): assert 0 < nslots < 22 # 22 -> too many statically nested blocks if nslots == 1: return iter([nmarbles]) # generate code for iter solution TAB = " " loopvars = [] stmt = ["def f(n):\n"] for i in range(nslots - 1): var = "m%d" % i stmt += [TAB * (i + 1), "for %s in xrange(n - (%s)):\n" % (var, '+'.join(loopvars) or 0)] loopvars.append(var) stmt += [TAB * (i + 2), "yield ", ','.join(loopvars), ', n - 1 - (', '+'.join(loopvars), ')\n'] print ''.join(stmt) # exec the code within empty namespace ns = {} exec(''.join(stmt), ns, ns) return ns['f'](nmarbles + 1) Example: >>> list(XinY_Product(2, 3)) [(0, 0, 2), (0, 1, 1), (0, 2, 0), (1, 0, 1), (1, 1, 0), (2, 0, 0)] >>> list(XinY_Iter(2, 3)) def f(n): for m0 in xrange(n - (0)): for m1 in xrange(n - (m0)): yield m0,m1, n - 1 - (m0+m1) [(0, 0, 2), (0, 1, 1), (0, 2, 0), (1, 0, 1), (1, 1, 0), (2, 0, 0)] A: Look at this code for creating all permutations, I guess I'd be relatively simple to implement something similar for your problem. How to generate all permutations of a list in python?
Is it possible to remove recursion from this function?
I have been playing with this a while, and just cannot see an obvious solution. I want to remove the recursion from the XinY_Go function. def XinY_Go(x,y,index,slots): if (y - index) == 1: slots[index] = x print slots slots[index] = 0 return for i in range(x+1): slots[index] = x-i XinY_Go(x-(x-i), y, index + 1, slots) def XinY(x,y): return XinY_Go(x,y,0,[0] * y) The function is calculating the number of ways to put X marbles in Y slots. Here is some sample output: >>> xy.XinY(1,2) [1, 0] [0, 1] >>> xy.XinY(2,3) [2, 0, 0] [1, 1, 0] [1, 0, 1] [0, 2, 0] [0, 1, 1] [0, 0, 2]
[ "Everything we think of as recursion can also be thought of as a stack-based problem, where the recursive function just uses the program's call stack rather than creating a separate stack. That means any recursive function can be re-written using a stack instead. \nI don't know python well enough to give you an implementation, but that should point you in the right direction. But in a nutshell, push the initial arguments for the function onto the stack and add a loop that runs as long as the size of the stack is greater than zero. Pop once per loop iteration, push every time the function currently calls itself. \n", "A naive implementation of @Joel Coehoorn's suggestion follows:\ndef XinY_Stack(x, y):\n stack = [(x, 0, [0]*y)]\n while stack:\n x, index, slots = stack.pop()\n if (y - index) == 1:\n slots[index] = x\n print slots\n slots[index] = 0\n else:\n for i in range(x + 1):\n slots[index] = x-i\n stack.append((i, index + 1, slots[:]))\n\nExample:\n>>> XinY_Stack(2, 3)\n[0, 0, 2]\n[0, 1, 1]\n[0, 2, 0]\n[1, 0, 1]\n[1, 1, 0]\n[2, 0, 0]\n\nBased on itertools.product\ndef XinY_Product(nmarbles, nslots):\n return (slots\n for slots in product(xrange(nmarbles + 1), repeat=nslots)\n if sum(slots) == nmarbles) \n\nBased on nested loops\ndef XinY_Iter(nmarbles, nslots):\n assert 0 < nslots < 22 # 22 -> too many statically nested blocks\n if nslots == 1: return iter([nmarbles])\n # generate code for iter solution\n TAB = \" \"\n loopvars = []\n stmt = [\"def f(n):\\n\"]\n for i in range(nslots - 1):\n var = \"m%d\" % i\n stmt += [TAB * (i + 1), \"for %s in xrange(n - (%s)):\\n\"\n % (var, '+'.join(loopvars) or 0)]\n loopvars.append(var)\n\n stmt += [TAB * (i + 2), \"yield \", ','.join(loopvars),\n ', n - 1 - (', '+'.join(loopvars), ')\\n']\n print ''.join(stmt)\n # exec the code within empty namespace\n ns = {}\n exec(''.join(stmt), ns, ns)\n return ns['f'](nmarbles + 1) \n\nExample:\n>>> list(XinY_Product(2, 3))\n[(0, 0, 2), (0, 1, 1), (0, 2, 0), (1, 0, 1), (1, 1, 0), (2, 0, 0)]\n>>> list(XinY_Iter(2, 3))\ndef f(n):\n for m0 in xrange(n - (0)):\n for m1 in xrange(n - (m0)):\n yield m0,m1, n - 1 - (m0+m1)\n\n[(0, 0, 2), (0, 1, 1), (0, 2, 0), (1, 0, 1), (1, 1, 0), (2, 0, 0)]\n\n", "Look at this code for creating all permutations, I guess I'd be relatively simple to implement something similar for your problem.\nHow to generate all permutations of a list in python?\n" ]
[ 22, 16, 2 ]
[]
[]
[ "python", "recursion" ]
stackoverflow_0000616416_python_recursion.txt
Q: Iterative version of Python's deepcopy Is there an existing implementation of an iterative version of deepcopy for Python 2.5.2? The deepcopy method available from the copy module is recursive and fails on large trees. I am not in a position where we can safely increase the stack limit at runtime. EDIT I did track this down: http://code.activestate.com/recipes/302535/ I haven't tested it, but it looks like it has potential. A: I'm not sure this would make sense. Isn't the whole point of deepcopy that each object will ask its children to copy themselves? Presumably you know exactly what kind of object you're copying and what its children look like as well, so if I were you, I'd just write my own function to copy it. Shouldn't be too hard. A: Maybe it would work as such with Stackless Python
Iterative version of Python's deepcopy
Is there an existing implementation of an iterative version of deepcopy for Python 2.5.2? The deepcopy method available from the copy module is recursive and fails on large trees. I am not in a position where we can safely increase the stack limit at runtime. EDIT I did track this down: http://code.activestate.com/recipes/302535/ I haven't tested it, but it looks like it has potential.
[ "I'm not sure this would make sense. Isn't the whole point of deepcopy that each object will ask its children to copy themselves?\nPresumably you know exactly what kind of object you're copying and what its children look like as well, so if I were you, I'd just write my own function to copy it. Shouldn't be too hard.\n", "Maybe it would work as such with Stackless Python\n" ]
[ 1, 0 ]
[]
[]
[ "iteration", "python", "recursion" ]
stackoverflow_0000617097_iteration_python_recursion.txt
Q: Python Popen, closing streams and multiple processes I have some data that I would like to gzip, uuencode and then print to standard out. What I basically have is: compressor = Popen("gzip", stdin = subprocess.PIPE, stdout = subprocess.PIPE) encoder = Popen(["uuencode", "dummy"], stdin = compressor.stdout) The way I feed data to the compressor is through compressor.stdin.write(stuff). What I really need to do is to send an EOF to the compressor, and I have no idea how to do it. At some point, I tried compressor.stdin.close() but that doesn't work -- it works well when the compressor writes to a file directly, but in the case above, the process doesn't terminate and stalls on compressor.wait(). Suggestions? In this case, gzip is an example and I really need to do something with piping the output of one process to another. Note: The data I need to compress won't fit in memory, so communicate isn't really a good option here. Also, if I just run compressor.communicate("Testing") after the 2 lines above, it still hangs with the error File "/usr/lib/python2.4/subprocess.py", line 1041, in communicate rlist, wlist, xlist = select.select(read_set, write_set, []) A: I suspect the issue is with the order in which you open the pipes. UUEncode is funny is that it will whine when you launch it if there's no incoming pipe in just the right way (try launching the darn thing on it's own in a Popen call to see the explosion with just PIPE as the stdin and stdout) Try this: encoder = Popen(["uuencode", "dummy"], stdin=PIPE, stdout=PIPE) compressor = Popen("gzip", stdin=PIPE, stdout=encoder.stdin) compressor.communicate("UUencode me please") encoded_text = encoder.communicate()[0] print encoded_text begin 644 dummy F'XL(`%]^L$D``PL-3<U+SD])5<A-52C(24TL3@4`;2O+"!(````` ` end You are right, btw... there is no way to send a generic EOF down a pipe. After all, each program really defines its own EOF. The way to do it is to close the pipe, as you were trying to do. EDIT: I should be clearer about uuencode. As a shell program, it's default behaviour is to expect console input. If you run it without a "live" incoming pipe, it will block waiting for console input. By opening the encoder second, before you had sent material down the compressor pipe, the encoder was blocking waiting for you to start typing. Jerub was right in that there was something blocking. A: This is not the sort of thing you should be doing directly in python, there are eccentricities regarding the how thing work that make it a much better idea to do this with a shell. If you can just use subprocess.Popen("foo | bar", shell=True), then all the better. What might be happening is that gzip has not been able to output all of its input yet, and the process will no exit until its stdout writes have been finished. You can look at what system call a process is blocking on if you use strace. Use ps auxwf to discover which process is the gzip process, then use strace -p $pidnum to see what system call it is performing. Note that stdin is FD 0 and stdout is FD 1, you will probably see it reading or writing on those file descriptors. A: if you just want to compress and don't need the file wrappers consider using the zlib module import zlib compressed = zlib.compress("text") any reason why the shell=True and unix pipes suggestions won't work? from subprocess import * pipes = Popen("gzip | uuencode dummy", stdin=PIPE, stdout=PIPE, shell=True) for i in range(1, 100): pipes.stdin.write("some data") pipes.stdin.close() print pipes.stdout.read() seems to work
Python Popen, closing streams and multiple processes
I have some data that I would like to gzip, uuencode and then print to standard out. What I basically have is: compressor = Popen("gzip", stdin = subprocess.PIPE, stdout = subprocess.PIPE) encoder = Popen(["uuencode", "dummy"], stdin = compressor.stdout) The way I feed data to the compressor is through compressor.stdin.write(stuff). What I really need to do is to send an EOF to the compressor, and I have no idea how to do it. At some point, I tried compressor.stdin.close() but that doesn't work -- it works well when the compressor writes to a file directly, but in the case above, the process doesn't terminate and stalls on compressor.wait(). Suggestions? In this case, gzip is an example and I really need to do something with piping the output of one process to another. Note: The data I need to compress won't fit in memory, so communicate isn't really a good option here. Also, if I just run compressor.communicate("Testing") after the 2 lines above, it still hangs with the error File "/usr/lib/python2.4/subprocess.py", line 1041, in communicate rlist, wlist, xlist = select.select(read_set, write_set, [])
[ "I suspect the issue is with the order in which you open the pipes. UUEncode is funny is that it will whine when you launch it if there's no incoming pipe in just the right way (try launching the darn thing on it's own in a Popen call to see the explosion with just PIPE as the stdin and stdout)\nTry this:\nencoder = Popen([\"uuencode\", \"dummy\"], stdin=PIPE, stdout=PIPE)\ncompressor = Popen(\"gzip\", stdin=PIPE, stdout=encoder.stdin)\n\ncompressor.communicate(\"UUencode me please\")\nencoded_text = encoder.communicate()[0]\nprint encoded_text\n\nbegin 644 dummy\nF'XL(`%]^L$D``PL-3<U+SD])5<A-52C(24TL3@4`;2O+\"!(`````\n`\nend\n\nYou are right, btw... there is no way to send a generic EOF down a pipe. After all, each program really defines its own EOF. The way to do it is to close the pipe, as you were trying to do.\nEDIT: I should be clearer about uuencode. As a shell program, it's default behaviour is to expect console input. If you run it without a \"live\" incoming pipe, it will block waiting for console input. By opening the encoder second, before you had sent material down the compressor pipe, the encoder was blocking waiting for you to start typing. Jerub was right in that there was something blocking.\n", "This is not the sort of thing you should be doing directly in python, there are eccentricities regarding the how thing work that make it a much better idea to do this with a shell. If you can just use subprocess.Popen(\"foo | bar\", shell=True), then all the better.\nWhat might be happening is that gzip has not been able to output all of its input yet, and the process will no exit until its stdout writes have been finished.\nYou can look at what system call a process is blocking on if you use strace. Use ps auxwf to discover which process is the gzip process, then use strace -p $pidnum to see what system call it is performing. Note that stdin is FD 0 and stdout is FD 1, you will probably see it reading or writing on those file descriptors.\n", "if you just want to compress and don't need the file wrappers consider using the zlib module\nimport zlib\ncompressed = zlib.compress(\"text\")\n\nany reason why the shell=True and unix pipes suggestions won't work?\nfrom subprocess import *\n\npipes = Popen(\"gzip | uuencode dummy\", stdin=PIPE, stdout=PIPE, shell=True)\nfor i in range(1, 100):\n pipes.stdin.write(\"some data\")\npipes.stdin.close()\nprint pipes.stdout.read()\n\nseems to work\n" ]
[ 4, 3, 1 ]
[]
[]
[ "eof", "popen", "python", "stream" ]
stackoverflow_0000617308_eof_popen_python_stream.txt
Q: How do I make this python command line an alias in bash? I want a quick an easy way to check my ip address after reading a recent question that had been answered on SO. For future reference, is there a way to make the following alias work? alias myip='python -c "from urllib import urlopen; print urlopen("http://whatismyip.appjet.net").read()[:-1]"' A: alias myip="python -c 'from urllib import urlopen; print urlopen(\"http://whatismyip.appjet.net\").read()[:-1]'" You need to use single quotes inside the alias to stop bash trying to interpret parts of your code inside them. The escapes on the double quotes get stripped out while processing what the alias itself is. A: Quote the inside double-quotes: alias myip='python -c "from urllib import urlopen; print urlopen(\"http://whatismyip.appjet.net\").read()[:-1]"' A: could also be done with curl: alias myip='curl "http://whatismyip.appjet.net"' or using wget: alias myip='wget -O - "http://whatismyip.appjet.net" 2>/dev/null'
How do I make this python command line an alias in bash?
I want a quick an easy way to check my ip address after reading a recent question that had been answered on SO. For future reference, is there a way to make the following alias work? alias myip='python -c "from urllib import urlopen; print urlopen("http://whatismyip.appjet.net").read()[:-1]"'
[ "alias myip=\"python -c 'from urllib import urlopen; print urlopen(\\\"http://whatismyip.appjet.net\\\").read()[:-1]'\"\n\nYou need to use single quotes inside the alias to stop bash trying to interpret parts of your code inside them. The escapes on the double quotes get stripped out while processing what the alias itself is.\n", "Quote the inside double-quotes:\nalias myip='python -c \"from urllib import urlopen; print urlopen(\\\"http://whatismyip.appjet.net\\\").read()[:-1]\"'\n\n", "could also be done with curl:\nalias myip='curl \"http://whatismyip.appjet.net\"'\n\nor using wget:\nalias myip='wget -O - \"http://whatismyip.appjet.net\" 2>/dev/null'\n\n" ]
[ 7, 6, 5 ]
[]
[]
[ "alias", "bash", "python" ]
stackoverflow_0000617952_alias_bash_python.txt
Q: Issue with Regular expressions in python Ok, so i'm working on a regular expression to search out all the header information in a site. I've compiled the regular expression: regex = re.compile(r''' <h[0-9]>\s? (<a[ ]href="[A-Za-z0-9.]*">)?\s? [A-Za-z0-9.,:'"=/?;\s]*\s? [A-Za-z0-9.,:'"=/?;\s]? ''', re.X) When i run this in python reg ex. tester, it works out wonderfully. Sample data: <body> <h1>Dog </h1> <h2>Cat </h2> <h3>Fancy </h3> <h1>Tall cup of lemons</h1> <h1><a href="dog.com">Dog thing</a></h1> </body> Now, in the REDemo, it works wonderfully. When i put it in my python code, however, it only prints <a href="dog.com"> Here's my python code, I'm not sure if i'm doing something wrong or if something is lost in translation. I appreciate your help. stories=[] response = urllib2.urlopen('http://apricotclub.org/duh.html') html = response.read().lower() p = re.compile('<h[0-9]>\\s?(<a href=\"[A-Za-z0-9.]*\">)?\\s?[A-Za-z0-9.,:\'\"=/?;\\s]*\\s?[A-Za-z0-9.,:\'\"=/?;\\s]?') stories=re.findall(p, html) for i in stories: if len(i) >= 5: print i I should also note, that when i take out the (<a href=\"[A-Za-z0-9.]*\">)? from the regular expression it works fine for non-link <hN> lines. A: This question has been asked in several forms over the last few days, so I'm going to say this very clearly. Q: How do I parse HTML with Regular Expressions? A: Please Don't. Use BeautifulSoup, html5lib or lxml.html. Please. A: Parsing things with regular expressions works for regular languages. HTML is not a regular language, and the stuff you find on web pages these days is absolute crap. BeautifulSoup deals with tag-soup HTML with browser-like heuristics so you get parsed HTML that resembles what a browser would display. The downside is it's not very fast. There's lxml for parsing well-formed html, but you should really use BeautifulSoup if you're not 100% certain that your input will always be well-formed. A: Because of the braces around the anchor tag, that part is interpreted as a capture group. This causes only the capture group to be returned, and not the whole regex match. Put the entire regex in braces and you'll see the right matches showing up as the first element in the returned tuples. But indeed, you should use a real parser. A: Building on the answers so far: It's best to use a parsing engine. It can cover a lot of cases and in an elegant way. I've tried BeautifulSoup and I like it very much. Also easy to use, with a great tutorial. If sometimes it feels like shooting flies with a cannon you can use a regular expression for quick parsing. If that's what you need here is the modified code that will catch all the headers (even those over multiple lines): p = re.compile(r'<(h[0-9])>(.+?)</\1>', re.IGNORECASE | re.DOTALL) stories = re.findall(p, html) for i in stories: print i A: I have used beautifulsoup to parse your desired HTML. I have the above HTML code in a file called foo.html and later read as a file object. from BeautifulSoup import BeautifulSoup H_TAGS = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'] def extract_data(): """Extract the data from all headers in a HTML page.""" f = open('foo.html', 'r+') html = f.read() soup = BeautifulSoup(html) headers = [soup.findAll(h) for h in H_TAGS if soup.findAll(h)] lst = [] for x in headers: for y in x: if y.string: lst.append(y.string) else: lst.append(y.contents[0].string) return lst The above function returns: >>> [u'Dog ', u'Tall cup of lemons', u'Dog thing', u'Cat ', u'Fancy '] You can add any number of header tags in h_tags list. I have assumed all the headers. If you can solve things easily using BeautifulSoup then its better to use it. :) A: As has been mentioned, you should use a parser instead of a regex. This is how you could do it with a regex though: import re html = ''' <body> <h1>Dog </h1> <h2>Cat </h2> <h3>Fancy </h3> <h1>Tall cup of lemons</h1> <h1><a href="dog.com">Dog thing</a></h1> </body> ''' p = re.compile(r''' <(?P<header>h[0-9])> # store header tag for later use \s* # zero or more whitespace (<a\shref="(?P<href>.*?)">)? # optional link tag. store href portion \s* (?P<title>.*?) # title \s* (</a>)? # optional closing link tag \s* </(?P=header)> # must match opening header tag ''', re.IGNORECASE + re.VERBOSE) stories = p.finditer(html) for match in stories: print '%(title)s [%(href)s]' % match.groupdict() Here are a couple of good regular expression resources: Python Regular Expression HOWTO Regular-Expressions.info
Issue with Regular expressions in python
Ok, so i'm working on a regular expression to search out all the header information in a site. I've compiled the regular expression: regex = re.compile(r''' <h[0-9]>\s? (<a[ ]href="[A-Za-z0-9.]*">)?\s? [A-Za-z0-9.,:'"=/?;\s]*\s? [A-Za-z0-9.,:'"=/?;\s]? ''', re.X) When i run this in python reg ex. tester, it works out wonderfully. Sample data: <body> <h1>Dog </h1> <h2>Cat </h2> <h3>Fancy </h3> <h1>Tall cup of lemons</h1> <h1><a href="dog.com">Dog thing</a></h1> </body> Now, in the REDemo, it works wonderfully. When i put it in my python code, however, it only prints <a href="dog.com"> Here's my python code, I'm not sure if i'm doing something wrong or if something is lost in translation. I appreciate your help. stories=[] response = urllib2.urlopen('http://apricotclub.org/duh.html') html = response.read().lower() p = re.compile('<h[0-9]>\\s?(<a href=\"[A-Za-z0-9.]*\">)?\\s?[A-Za-z0-9.,:\'\"=/?;\\s]*\\s?[A-Za-z0-9.,:\'\"=/?;\\s]?') stories=re.findall(p, html) for i in stories: if len(i) >= 5: print i I should also note, that when i take out the (<a href=\"[A-Za-z0-9.]*\">)? from the regular expression it works fine for non-link <hN> lines.
[ "This question has been asked in several forms over the last few days, so I'm going to say this very clearly.\nQ: How do I parse HTML with Regular Expressions?\nA: Please Don't.\nUse BeautifulSoup, html5lib or lxml.html. Please.\n", "Parsing things with regular expressions works for regular languages. HTML is not a regular language, and the stuff you find on web pages these days is absolute crap. BeautifulSoup deals with tag-soup HTML with browser-like heuristics so you get parsed HTML that resembles what a browser would display.\nThe downside is it's not very fast. There's lxml for parsing well-formed html, but you should really use BeautifulSoup if you're not 100% certain that your input will always be well-formed.\n", "Because of the braces around the anchor tag, that part is interpreted as a capture group. This causes only the capture group to be returned, and not the whole regex match.\nPut the entire regex in braces and you'll see the right matches showing up as the first element in the returned tuples.\nBut indeed, you should use a real parser.\n", "Building on the answers so far:\nIt's best to use a parsing engine. It can cover a lot of cases and in an elegant way. I've tried BeautifulSoup and I like it very much. Also easy to use, with a great tutorial.\nIf sometimes it feels like shooting flies with a cannon you can use a regular expression for quick parsing. If that's what you need here is the modified code that will catch all the headers (even those over multiple lines):\np = re.compile(r'<(h[0-9])>(.+?)</\\1>', re.IGNORECASE | re.DOTALL)\nstories = re.findall(p, html)\nfor i in stories:\n print i\n\n", "I have used beautifulsoup to parse your desired HTML. I have the above HTML code in\na file called foo.html and later read as a file object.\nfrom BeautifulSoup import BeautifulSoup\n\n\nH_TAGS = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']\n\ndef extract_data():\n \"\"\"Extract the data from all headers\n in a HTML page.\"\"\"\n f = open('foo.html', 'r+')\n html = f.read()\n soup = BeautifulSoup(html)\n headers = [soup.findAll(h) for h in H_TAGS if soup.findAll(h)]\n lst = []\n for x in headers:\n for y in x:\n if y.string:\n lst.append(y.string)\n else:\n lst.append(y.contents[0].string)\n return lst\n\nThe above function returns:\n>>> [u'Dog ', u'Tall cup of lemons', u'Dog thing', u'Cat ', u'Fancy ']\n\nYou can add any number of header tags in h_tags list. I have assumed all the headers.\nIf you can solve things easily using BeautifulSoup then its better to use it. :)\n", "As has been mentioned, you should use a parser instead of a regex.\nThis is how you could do it with a regex though:\nimport re\n\nhtml = '''\n<body>\n\n<h1>Dog </h1>\n<h2>Cat </h2>\n<h3>Fancy </h3>\n<h1>Tall cup of lemons</h1>\n<h1><a href=\"dog.com\">Dog thing</a></h1>\n</body>\n'''\n\np = re.compile(r'''\n <(?P<header>h[0-9])> # store header tag for later use\n \\s* # zero or more whitespace\n (<a\\shref=\"(?P<href>.*?)\">)? # optional link tag. store href portion\n \\s*\n (?P<title>.*?) # title\n \\s*\n (</a>)? # optional closing link tag\n \\s*\n </(?P=header)> # must match opening header tag\n''', re.IGNORECASE + re.VERBOSE)\n\nstories = p.finditer(html)\n\nfor match in stories:\n print '%(title)s [%(href)s]' % match.groupdict()\n\nHere are a couple of good regular expression resources:\n\nPython Regular Expression HOWTO\nRegular-Expressions.info\n\n" ]
[ 23, 4, 2, 2, 2, 1 ]
[]
[]
[ "html", "python", "regex" ]
stackoverflow_0000090052_html_python_regex.txt
Q: Python regex split a string by one of two delimiters I wanted to cut up a string of email addresses which may be separated by any combination of commas and white-space. And I thought it would be pretty straight-forward : sep = re.compile('(\s*,*)+') print sep.split("""[email protected], [email protected] [email protected],,[email protected]""") But it isn't. I can't find a regex that won't leave some empty slots like this : ['[email protected]', '', '[email protected]', '', '[email protected]', '', '[email protected]'] I've tried various combinations, but none seem to work. Is this, in fact, possible, with regex? A: Doh! It's just this. sep = re.compile('[\s,]+') A: without re line = 'e@d , f@g, 7@g' addresses = line.split(',') addresses = [ address.strip() for address in addresses ] A: I like the following... >>> sep= re.compile( r',*\s*' ) >>> sep.split("""[email protected], [email protected] [email protected],,[email protected]""") ['[email protected]', '[email protected]', '[email protected]', '[email protected]'] Which also seems to work on your test data.
Python regex split a string by one of two delimiters
I wanted to cut up a string of email addresses which may be separated by any combination of commas and white-space. And I thought it would be pretty straight-forward : sep = re.compile('(\s*,*)+') print sep.split("""[email protected], [email protected] [email protected],,[email protected]""") But it isn't. I can't find a regex that won't leave some empty slots like this : ['[email protected]', '', '[email protected]', '', '[email protected]', '', '[email protected]'] I've tried various combinations, but none seem to work. Is this, in fact, possible, with regex?
[ "Doh!\nIt's just this.\nsep = re.compile('[\\s,]+')\n\n", "without re\nline = 'e@d , f@g, 7@g'\n\naddresses = line.split(',') \naddresses = [ address.strip() for address in addresses ]\n\n", "I like the following...\n>>> sep= re.compile( r',*\\s*' )\n>>> sep.split(\"\"\"[email protected], [email protected]\n\n [email protected],,[email protected]\"\"\")\n['[email protected]', '[email protected]', '[email protected]', '[email protected]']\n\nWhich also seems to work on your test data.\n" ]
[ 14, 3, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0000618551_python_regex.txt
Q: dateutil.rrule.rrule.between() gives only dates after now From the IPython console: In [16]: b Out[16]: datetime.datetime(2008, 3, 1, 0, 0) In [17]: e Out[17]: datetime.datetime(2010, 5, 2, 0, 0) In [18]: rrule(MONTHLY).between(b, e, inc=True) Out[18]: [datetime.datetime(2009, 3, 6, 14, 42, 1), datetime.datetime(2009, 4, 6, 14, 42, 1), datetime.datetime(2009, 5, 6, 14, 42, 1), datetime.datetime(2009, 6, 6, 14, 42, 1), datetime.datetime(2009, 7, 6, 14, 42, 1), datetime.datetime(2009, 8, 6, 14, 42, 1), datetime.datetime(2009, 9, 6, 14, 42, 1), datetime.datetime(2009, 10, 6, 14, 42, 1), datetime.datetime(2009, 11, 6, 14, 42, 1), datetime.datetime(2009, 12, 6, 14, 42, 1), datetime.datetime(2010, 1, 6, 14, 42, 1), datetime.datetime(2010, 2, 6, 14, 42, 1), datetime.datetime(2010, 3, 6, 14, 42, 1), datetime.datetime(2010, 4, 6, 14, 42, 1)] How do I make between() return dates starting from the begining (b) date? A: You need to pass b into rrule, like this: rrule(MONTHLY, dtstart = b).between(b, e, inc=True) From these docs (http://labix.org/python-dateutil), it looks like calling rrule without specifying dtstart will use datetime.datetime.now() as the start point for the sequence that you're later applying between to. That's why your values begin at 2009-03-06.
dateutil.rrule.rrule.between() gives only dates after now
From the IPython console: In [16]: b Out[16]: datetime.datetime(2008, 3, 1, 0, 0) In [17]: e Out[17]: datetime.datetime(2010, 5, 2, 0, 0) In [18]: rrule(MONTHLY).between(b, e, inc=True) Out[18]: [datetime.datetime(2009, 3, 6, 14, 42, 1), datetime.datetime(2009, 4, 6, 14, 42, 1), datetime.datetime(2009, 5, 6, 14, 42, 1), datetime.datetime(2009, 6, 6, 14, 42, 1), datetime.datetime(2009, 7, 6, 14, 42, 1), datetime.datetime(2009, 8, 6, 14, 42, 1), datetime.datetime(2009, 9, 6, 14, 42, 1), datetime.datetime(2009, 10, 6, 14, 42, 1), datetime.datetime(2009, 11, 6, 14, 42, 1), datetime.datetime(2009, 12, 6, 14, 42, 1), datetime.datetime(2010, 1, 6, 14, 42, 1), datetime.datetime(2010, 2, 6, 14, 42, 1), datetime.datetime(2010, 3, 6, 14, 42, 1), datetime.datetime(2010, 4, 6, 14, 42, 1)] How do I make between() return dates starting from the begining (b) date?
[ "You need to pass b into rrule, like this:\nrrule(MONTHLY, dtstart = b).between(b, e, inc=True)\n\nFrom these docs (http://labix.org/python-dateutil), it looks like calling rrule without specifying dtstart will use datetime.datetime.now() as the start point for the sequence that you're later applying between to. That's why your values begin at 2009-03-06.\n" ]
[ 15 ]
[]
[]
[ "python", "python_dateutil", "rrule" ]
stackoverflow_0000618910_python_python_dateutil_rrule.txt
Q: Python build/release system I started using Pyant recenently to do various build/release tasks but have recently discovered that development for this project has ended. I did some research and can't seem to find any other Python build scripts that are comparable. Just wondering if anyone can recommend one? I basically need it to do what ANT does - do SVN updates, move/copy files, archive etc using an XML file. Thanks, g A: Probably the best answer is to use Ant as-is... that is, use the Java version. My second suggestion would be to use scons. It won't take much time using scons before you're asking, "Who ever thought of using XML to script a build?" A: Its not completely comparable but I tend to use fabric. Its more geared towards deployment with support for ssh to production host and runing things as root there etc. A: Some people use Paver for build/deployment of Python packages. While I know it works, it does not appeal to me that much. A: what about maven? (http://maven.apache.org/) With the right plugins it can do much more then ant, it can even use ant for building if you configure it so. It's very flexible and supports the full product life cycle. I really recommend you take a look at it.
Python build/release system
I started using Pyant recenently to do various build/release tasks but have recently discovered that development for this project has ended. I did some research and can't seem to find any other Python build scripts that are comparable. Just wondering if anyone can recommend one? I basically need it to do what ANT does - do SVN updates, move/copy files, archive etc using an XML file. Thanks, g
[ "Probably the best answer is to use Ant as-is... that is, use the Java version. My second suggestion would be to use scons. It won't take much time using scons before you're asking, \"Who ever thought of using XML to script a build?\"\n", "Its not completely comparable but I tend to use fabric. Its more geared towards deployment with support for ssh to production host and runing things as root there etc.\n", "Some people use Paver for build/deployment of Python packages. While I know it works, it does not appeal to me that much.\n", "what about maven? (http://maven.apache.org/) With the right plugins it can do much more then ant, it can even use ant for building if you configure it so.\nIt's very flexible and supports the full product life cycle. I really recommend you take a look at it.\n" ]
[ 6, 2, 2, 0 ]
[]
[]
[ "ant", "build_automation", "python" ]
stackoverflow_0000618958_ant_build_automation_python.txt
Q: Set the size of wx.GridBagSizer dynamically I'm creating an app where I drag button widgets into a panel. I would like to have a visible grid in the panel where i drop the widgets so the widgets will be aligned to the grid. I guess it isn't hard making a grid where the squares are 15x15 pixels using a GridBagSizer(since the widgets will span between multiple cells), but how can the number of squares be made dynamically according to the size of the panel? Do I have to calculate how many squares i need to fill the panel on init and on each resize? Using python and wxpython btw. Oerjan Pettersen A: Don't use a sizer at all for this. Just position the buttons yourself, with whatever co-ordinate rounding you like. (using wxWindow::SetSize()). (The point of a sizer is that the buttons will get moved and/or resized when the window is resized. As you don't want that behaviour, then you shouldn't use a sizer.)
Set the size of wx.GridBagSizer dynamically
I'm creating an app where I drag button widgets into a panel. I would like to have a visible grid in the panel where i drop the widgets so the widgets will be aligned to the grid. I guess it isn't hard making a grid where the squares are 15x15 pixels using a GridBagSizer(since the widgets will span between multiple cells), but how can the number of squares be made dynamically according to the size of the panel? Do I have to calculate how many squares i need to fill the panel on init and on each resize? Using python and wxpython btw. Oerjan Pettersen
[ "Don't use a sizer at all for this. Just position the buttons yourself, with whatever co-ordinate rounding you like. (using wxWindow::SetSize()).\n(The point of a sizer is that the buttons will get moved and/or resized when the window is resized. As you don't want that behaviour, then you shouldn't use a sizer.)\n" ]
[ 1 ]
[]
[]
[ "python", "wxpython", "wxwidgets" ]
stackoverflow_0000619163_python_wxpython_wxwidgets.txt
Q: (Python) socket.gaierror on every addres...except http://www.reddit.com? I'm just playing around and I'm trying to grab information from websites. Unfortunately, with the following code: import sys import socket import re from urlparse import urlsplit url = urlsplit(sys.argv[1]) sock = socket.socket() sock.connect((url[0] + '://' + url[1],80)) path = url[2] if not path: path = '/' print path sock.send('GET ' + path + ' HTTP/1.1\r\n' + 'User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) AppleWebKit/525.19 (KHTML, like Gecko) Chrome/0.3.154.9 Safari/525.19\r\n' + 'Accept: */*\r\n' + 'Accept-Language: en-US,en\r\n' + 'Accept-Charset: ISO-8859-1,*,utf-8\r\n' + 'Host: 68.33.143.182\r\n' + 'Connection: Keep-alive\r\n' + '\r\n') I get the following error: Traceback (most recent call last): File "D:\Development\Python\PyCrawler\PyCrawler.py", line 10, in sock.connect((url[0] + '://' + url[1],80)) File "", line 1, in connect socket.gaierror: (11001, 'getaddrinfo failed') The only time I do not get an error is if the url passed is http://www.reddit.com. Every other url I have tried comes up with the socket.gaierror. Can anyone explain this? And possibly give a solution? A: sock.connect((url[0] + '://' + url[1],80)) Do not do that, instead do this: sock.connect((url[1], 80)) connect expects a hostname, not a URL. Actually, you should probably use something higher-level than sockets to do HTTP. Maybe httplib. A: Please please please please please please please don't do this. urllib and urllib2 are your friends. Read the "missing" urllib2 manual if you are having trouble with it. A: Have you ever altered your Hosts file? If it has an entry for Reddit but not much else, that might explain that site's unique result. A: you forgot to resolve the hostname: addr = socket.gethostbyname(url[1]) ... sock.connect((addr,80)) A: Use urllib2. Or BeautifulSoup.
(Python) socket.gaierror on every addres...except http://www.reddit.com?
I'm just playing around and I'm trying to grab information from websites. Unfortunately, with the following code: import sys import socket import re from urlparse import urlsplit url = urlsplit(sys.argv[1]) sock = socket.socket() sock.connect((url[0] + '://' + url[1],80)) path = url[2] if not path: path = '/' print path sock.send('GET ' + path + ' HTTP/1.1\r\n' + 'User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) AppleWebKit/525.19 (KHTML, like Gecko) Chrome/0.3.154.9 Safari/525.19\r\n' + 'Accept: */*\r\n' + 'Accept-Language: en-US,en\r\n' + 'Accept-Charset: ISO-8859-1,*,utf-8\r\n' + 'Host: 68.33.143.182\r\n' + 'Connection: Keep-alive\r\n' + '\r\n') I get the following error: Traceback (most recent call last): File "D:\Development\Python\PyCrawler\PyCrawler.py", line 10, in sock.connect((url[0] + '://' + url[1],80)) File "", line 1, in connect socket.gaierror: (11001, 'getaddrinfo failed') The only time I do not get an error is if the url passed is http://www.reddit.com. Every other url I have tried comes up with the socket.gaierror. Can anyone explain this? And possibly give a solution?
[ "\nsock.connect((url[0] + '://' + url[1],80))\n\n\nDo not do that, instead do this:\nsock.connect((url[1], 80))\n\nconnect expects a hostname, not a URL.\nActually, you should probably use something higher-level than sockets to do HTTP. Maybe httplib.\n", "Please please please please please please please don't do this.\nurllib and urllib2 are your friends.\nRead the \"missing\" urllib2 manual if you are having trouble with it.\n", "Have you ever altered your Hosts file? If it has an entry for Reddit but not much else, that might explain that site's unique result.\n", "you forgot to resolve the hostname:\naddr = socket.gethostbyname(url[1])\n...\nsock.connect((addr,80))\n\n", "Use urllib2. Or BeautifulSoup.\n" ]
[ 3, 3, 2, 1, 0 ]
[]
[]
[ "http", "python", "sockets" ]
stackoverflow_0000303726_http_python_sockets.txt
Q: What does PyPy have to offer over CPython, Jython, and IronPython? From what I have seen and read on blogs, PyPy is a very ambitious project. What are some advantages it will bring to the table over its siblings (CPython, Jython, and IronPython)? Is it speed, cross-platform compatibility (including mobile platforms), the ability to use c-extensions without the GIL, or is this more of a technical exercise on what can be done? A: PyPy is really two projects: An interpreter compiler toolchain allowing you to write interpreters in RPython (a static subset of Python) and have cross-platform interpreters compiled standalone, for the JVM, for .NET (etc) An implementation of Python in RPython These two projects allow for many things. Maintaining Python in Python is much easier than maintaining it in C From a single codebase you can generate Python interpreters that run on the JVM, .NET and standalone - rather than having multiple slightly incompatible implementations Part of the compiler toolchain includes an experimental JIT generator (now in its fifth incarnation and starting to work really well) - the goal is for a JITed PyPy to run much faster than CPython It is much easier to experiment with fundamental language features - like removing the GIL, better garbage collection, integrating stackless and so on So there are really a lot of reasons for PyPy to be exciting, and it is finally starting to live up to all its promises. A: The most important feature is of course the JIT compiler. In CPython files are compiled to bytecode (.pyc) or optimized bytecode (.pyo) and then interpreted. With PyPy they will be compiled to native code. PyPy also includes Stackless Python patches, including it's impressive features (tasklet serialization, light threads etc.) A: In case that Python gets a real JIT I think it's going to be as fast as any other implementation. The advantage is that it's much easier to implement new features. One can see this today by observing the library. Often modules are written in Python first and then translated into C. A: cross-platform compatibility Yes
What does PyPy have to offer over CPython, Jython, and IronPython?
From what I have seen and read on blogs, PyPy is a very ambitious project. What are some advantages it will bring to the table over its siblings (CPython, Jython, and IronPython)? Is it speed, cross-platform compatibility (including mobile platforms), the ability to use c-extensions without the GIL, or is this more of a technical exercise on what can be done?
[ "PyPy is really two projects:\n\nAn interpreter compiler toolchain allowing you to write interpreters in RPython (a static subset of Python) and have cross-platform interpreters compiled standalone, for the JVM, for .NET (etc)\nAn implementation of Python in RPython\n\nThese two projects allow for many things.\n\nMaintaining Python in Python is much easier than maintaining it in C\nFrom a single codebase you can generate Python interpreters that run on the JVM, .NET and standalone - rather than having multiple slightly incompatible implementations\nPart of the compiler toolchain includes an experimental JIT generator (now in its fifth incarnation and starting to work really well) - the goal is for a JITed PyPy to run much faster than CPython\nIt is much easier to experiment with fundamental language features - like removing the GIL, better garbage collection, integrating stackless and so on\n\nSo there are really a lot of reasons for PyPy to be exciting, and it is finally starting to live up to all its promises.\n", "The most important feature is of course the JIT compiler. In CPython files are compiled to bytecode (.pyc) or optimized bytecode (.pyo) and then interpreted. With PyPy they will be compiled to native code. PyPy also includes Stackless Python patches, including it's impressive features (tasklet serialization, light threads etc.)\n", "In case that Python gets a real JIT I think it's going to be as fast as any other implementation.\nThe advantage is that it's much easier to implement new features. One can see this today by observing the library. Often modules are written in Python first and then translated into C.\n", "\ncross-platform compatibility\n\nYes\n" ]
[ 38, 4, 0, 0 ]
[]
[]
[ "interpreter", "pypy", "python" ]
stackoverflow_0000619437_interpreter_pypy_python.txt
Q: Will python provide enough performance for a proxy? I want to start writing a http proxy that will modify responses according to some rules/filters I will configure. However, before I start coding it, I want to make sure I'm making the right choice in going with Python. Later, this tool would have to be able to process a lot of requests, so, I would like to know I can count on it later on to be able to perform when "push comes to shove". A: As long as the bulk of the processing uses Python's built-in modules it should be fine as far as performance. The biggest strength of Python is its clear syntax and ease of testing/maintainability. If you find that one section of your code is slowing down the process, you can rewrite that section and use it as a C module, while keeping the bulk of your control code in Python. However if you're looking to make the most optimized Python Code you may want to check out this SO post. A: This will depend on the library you use more than the language itself. The twisted framework is known to scale well. Here's a proxy server example in python/twisted to get you started. Bottomline: choose your third party tools wisely and I'm sure you'll be fine. A: Yes, I think you will find Python to be perfectly adequate for your needs. There's a huge number of web frameworks, WSGI libraries, etc. to choose from, or learn from when building your own. There's an interesting post on the Python History blog about how Python was supporting high performance websites in 1996. A: Python performs pretty well for most tasks, but you'll need to change the way you program if you're used to other languages. See Python is not Java for more info. If plain old CPython doesn't give the performance you need, you have other options as well. As has been mentioned, you can extend it in C (using a tool like swig or Pyrex). I also hear good things about PyPy as well, but bear in mind that it uses a restricted subset of Python. Lastly, a lot of people use psyco to speed up performance.
Will python provide enough performance for a proxy?
I want to start writing a http proxy that will modify responses according to some rules/filters I will configure. However, before I start coding it, I want to make sure I'm making the right choice in going with Python. Later, this tool would have to be able to process a lot of requests, so, I would like to know I can count on it later on to be able to perform when "push comes to shove".
[ "As long as the bulk of the processing uses Python's built-in modules it should be fine as far as performance. The biggest strength of Python is its clear syntax and ease of testing/maintainability. If you find that one section of your code is slowing down the process, you can rewrite that section and use it as a C module, while keeping the bulk of your control code in Python. \nHowever if you're looking to make the most optimized Python Code you may want to check out this SO post.\n", "This will depend on the library you use more than the language itself. The twisted framework is known to scale well. \nHere's a proxy server example in python/twisted to get you started.\nBottomline: choose your third party tools wisely and I'm sure you'll be fine.\n", "Yes, I think you will find Python to be perfectly adequate for your needs. There's a huge number of web frameworks, WSGI libraries, etc. to choose from, or learn from when building your own.\nThere's an interesting post on the Python History blog about how Python was supporting high performance websites in 1996.\n", "Python performs pretty well for most tasks, but you'll need to change the way you program if you're used to other languages. See Python is not Java for more info.\nIf plain old CPython doesn't give the performance you need, you have other options as well.\nAs has been mentioned, you can extend it in C (using a tool like swig or Pyrex). I also hear good things about PyPy as well, but bear in mind that it uses a restricted subset of Python. Lastly, a lot of people use psyco to speed up performance.\n" ]
[ 4, 2, 2, 2 ]
[]
[]
[ "performance", "proxy", "python" ]
stackoverflow_0000619575_performance_proxy_python.txt
Q: Do Django custom authentication backends need to take a password? Here's how my university handles authentication: we redirect the user to a website, they enter in their username and password, then they get redirected back to us with the username and a login key passed in the query string. When we get the user back, we call a stored procedure in the university's database that takes the username, login key, and ip address and tells us if this is valid. I've got a Django custom authentication backend set up to handle our end of all of this. Does it make any difference one way or another whether I make it able to accept a password argument (since we're not actually taking their password)? Right now, I have it set up so that it takes the login key as the password argument. Would it be good, bad, or neither for me to change this to take this as say, login_key instead of as password? A: The Django docs say this: Either way, authenticate should check the credentials it gets, and it should return a User object that matches those credentials, if the credentials are valid. If they're not valid, it should return None. The 'Either way' refers to whether the authenticate() method takes a username/password combination, or just a token. Your scenario falls between those two, so I'd think that the 'best' answer would be to write your authenticate() to take a username and a login key, and return the right User or None as appropriate.
Do Django custom authentication backends need to take a password?
Here's how my university handles authentication: we redirect the user to a website, they enter in their username and password, then they get redirected back to us with the username and a login key passed in the query string. When we get the user back, we call a stored procedure in the university's database that takes the username, login key, and ip address and tells us if this is valid. I've got a Django custom authentication backend set up to handle our end of all of this. Does it make any difference one way or another whether I make it able to accept a password argument (since we're not actually taking their password)? Right now, I have it set up so that it takes the login key as the password argument. Would it be good, bad, or neither for me to change this to take this as say, login_key instead of as password?
[ "The Django docs say this:\n\nEither way, authenticate should check\n the credentials it gets, and it should\n return a User object that matches\n those credentials, if the credentials\n are valid. If they're not valid, it\n should return None.\n\nThe 'Either way' refers to whether the authenticate() method takes a username/password combination, or just a token. Your scenario falls between those two, so I'd think that the 'best' answer would be to write your authenticate() to take a username and a login key, and return the right User or None as appropriate.\n" ]
[ 6 ]
[]
[]
[ "authentication", "custom_backend", "django", "django_authentication", "python" ]
stackoverflow_0000619620_authentication_custom_backend_django_django_authentication_python.txt
Q: Python's PubSub/observer Pattern for C++? i'm looking for a C++ replacement of the Python PubSub Library in which i don't have to connect a signal with a slot or so, but instead can register for a special Kind of messages, without knowing the object which can send it. A: Perhaps you misunderstand what signals and slots are. With signals and slots you don't have to know who sends signals. Your "client" class just declares slots, and an outside manager can connect signals to them. I recommend you to check out Qt. It's an amazing cross-platform library with much more than just GUI support. It has a convenient and efficient implementation of signals and slots which you can use. These days it's also licensed with LGPL (in addition to GPL and commercial), so you can use it for practically any purpose. Re your clarification comment, why not raise an exception for the error? The parent can notify the GUI, or alternatively the GUI can register for a signal the parent emits. This way the parent also doesn't have to know about the GUI. A: Can you use the boost libraries? If so then combining the function and bind libraries allows you to do the following. You may be able to do the same using the tr1 functionality if your compiler supports it. #include <iostream> #include <list> #include <boost/function.hpp> #include <boost/bind.hpp> typedef boost::function< void() > EVENT_T ; template<typename F> class Subject { public: virtual void attach ( F o ) { obs_.push_back ( o ); } virtual void notify() { for ( typename std::list<F>::iterator i = obs_.begin(); i != obs_.end(); ++i ) ( *i ) (); } private: std::list<F> obs_; } ; class Button : public Subject<EVENT_T> { public: void onClick() { notify() ; }; }; class Player { public: void play() { std::cout << "play" << std::endl ; } void stop() { std::cout << "stop" << std::endl ; } }; class Display { public: void started() { std::cout << "Started playing" << std::endl ; } }; Button playButton ; Button stopButton ; Player thePlayer; Display theDisplay ; int main ( int argc, char **argv ) { playButton.attach ( boost::bind ( &Player::play, &thePlayer ) ); playButton.attach ( boost::bind ( &Display::started, &theDisplay ) ); stopButton.attach ( boost::bind ( &Player::stop, &thePlayer ) ); playButton.onClick() ; stopButton.onClick() ; return 0; } So when you run this you get: play Started playing stop Press any key to continue. So.. is this the kind of thing you are looking for? See here and here for the source of most of this code. EDIT: The boost::signal library might also do what you want. A: Why don't you just implement one? It's not a complicated pattern (well, depending what you really want). Anyway, I already implemented a quick and dirty one some time ago. It is not optimized, synchronous and single threaded. I hope you can use it to make your own. #include <vector> #include <iostream> #include <algorithm> template<typename MESSAGE> class Topic; class Subscriber; class TopicBase { friend class Subscriber; private: virtual void RemoveSubscriber(Subscriber* subscriber)=0; }; template<typename MESSAGE> class Topic : public TopicBase { friend class Subscriber; private: class Callable { public: Callable(Subscriber* subscriber, void (Subscriber::*method)(const MESSAGE&)) :m_subscriber(subscriber) ,m_method(method) { } void operator()(const MESSAGE& message) { (m_subscriber->*m_method)(message); } bool operator==(const Callable& other) const { return m_subscriber == other.m_subscriber && m_method == other.m_method; } public: Subscriber* m_subscriber; void (Subscriber::*m_method)(const MESSAGE&); }; public: ~Topic() { //unregister each subscriber for(std::vector<Callable>::iterator i = m_subscribers.begin(); i != m_subscribers.end(); i++) { std::vector<TopicBase*>& topics = i->m_subscriber->m_topics; for(std::vector<TopicBase*>::iterator ti = topics.begin();;) { ti = std::find(ti, topics.end(), this); if(ti == topics.end()) break; ti = topics.erase(ti); } } } void SendMessage(const MESSAGE& message) { for(std::vector<Callable>::iterator i = m_subscribers.begin(); i != m_subscribers.end(); i++) { (*i)(message); } } private: void Subscribe(Subscriber* subscriber, void (Subscriber::*method)(const MESSAGE&)) { m_subscribers.push_back(Callable(subscriber, method)); subscriber->m_topics.push_back(this); } void Unsubscribe(Subscriber* subscriber, void (Subscriber::*method)(const MESSAGE&)) { std::vector<Callable>::iterator i = std::find(m_subscribers.begin(), m_subscribers.end(), Callable(subscriber, method)); if(i != m_subscribers.end()) { m_subscribers.erase(i); subscriber->m_topics.erase(std::find(subscriber->m_topics.begin(), subscriber->m_topics.end(), this)); //should always find one } } virtual void RemoveSubscriber(Subscriber* subscriber) { for(std::vector<Callable>::iterator i = m_subscribers.begin() ; i != m_subscribers.end(); i++) { if(i->m_subscriber == subscriber) { m_subscribers.erase(i); break; } } } private: std::vector<Callable> m_subscribers; }; class Subscriber { template<typename T> friend class Topic; public: ~Subscriber() { for(std::vector<TopicBase*>::iterator i = m_topics.begin(); i !=m_topics.end(); i++) { (*i)->RemoveSubscriber(this); } } protected: template<typename MESSAGE, typename SUBSCRIBER> void Subscribe(Topic<MESSAGE>& topic, void (SUBSCRIBER::*method)(const MESSAGE&)) { topic.Subscribe(this, static_cast<void (Subscriber::*)(const MESSAGE&)>(method)); } template<typename MESSAGE, typename SUBSCRIBER> void Unsubscribe(Topic<MESSAGE>& topic, void (SUBSCRIBER::*method)(const MESSAGE&)) { topic.Unsubscribe(this, static_cast<void (Subscriber::*)(const MESSAGE&)>(method)); } private: std::vector<TopicBase*> m_topics; }; // Test Topic<int> Topic1; class TestSubscriber1 : public Subscriber { public: TestSubscriber1() { Subscribe(Topic1, &TestSubscriber1::onTopic1); } private: void onTopic1(const int& message) { std::cout<<"TestSubscriber1::onTopic1 "<<message<<std::endl; } }; class TestSubscriber2 : public Subscriber { public: void Subscribe(Topic<const char*> &subscriber) { Subscriber::Subscribe(subscriber, &TestSubscriber2::onTopic); } void Unsubscribe(Topic<const char*> &subscriber) { Subscriber::Unsubscribe(subscriber, &TestSubscriber2::onTopic); } private: void onTopic(const char* const& message) { std::cout<<"TestSubscriber1::onTopic1 "<<message<<std::endl; } }; int main() { Topic<const char*>* topic2 = new Topic<const char*>(); { TestSubscriber1 testSubscriber1; Topic1.SendMessage(42); Topic1.SendMessage(5); } Topic1.SendMessage(256); TestSubscriber2 testSubscriber2; testSubscriber2.Subscribe(*topic2); topic2->SendMessage("owl"); testSubscriber2.Unsubscribe(*topic2); topic2->SendMessage("owl"); testSubscriber2.Subscribe(*topic2); delete topic2; return 0; }
Python's PubSub/observer Pattern for C++?
i'm looking for a C++ replacement of the Python PubSub Library in which i don't have to connect a signal with a slot or so, but instead can register for a special Kind of messages, without knowing the object which can send it.
[ "Perhaps you misunderstand what signals and slots are. With signals and slots you don't have to know who sends signals. Your \"client\" class just declares slots, and an outside manager can connect signals to them.\nI recommend you to check out Qt. It's an amazing cross-platform library with much more than just GUI support. It has a convenient and efficient implementation of signals and slots which you can use.\nThese days it's also licensed with LGPL (in addition to GPL and commercial), so you can use it for practically any purpose.\nRe your clarification comment, why not raise an exception for the error? The parent can notify the GUI, or alternatively the GUI can register for a signal the parent emits. This way the parent also doesn't have to know about the GUI.\n", "Can you use the boost libraries? If so then combining the function and bind libraries allows you to do the following. You may be able to do the same using the tr1 functionality if your compiler supports it.\n#include <iostream>\n#include <list>\n#include <boost/function.hpp>\n#include <boost/bind.hpp>\n\ntypedef boost::function< void() > EVENT_T ;\n\ntemplate<typename F>\nclass Subject\n{\n public:\n virtual void attach ( F o )\n {\n obs_.push_back ( o );\n }\n\n virtual void notify()\n {\n for ( typename std::list<F>::iterator i = obs_.begin(); i != obs_.end(); ++i )\n ( *i ) ();\n }\n\n private:\n std::list<F> obs_;\n} ;\n\nclass Button : public Subject<EVENT_T>\n{\n public:\n void onClick()\n {\n notify() ;\n };\n};\n\nclass Player\n{\n public:\n\n void play()\n {\n std::cout << \"play\" << std::endl ;\n }\n void stop()\n {\n std::cout << \"stop\" << std::endl ;\n }\n\n};\n\nclass Display\n{\n public:\n void started()\n {\n std::cout << \"Started playing\" << std::endl ;\n }\n};\n\nButton playButton ;\nButton stopButton ;\nPlayer thePlayer;\nDisplay theDisplay ;\n\nint main ( int argc, char **argv )\n{\n playButton.attach ( boost::bind ( &Player::play, &thePlayer ) );\n playButton.attach ( boost::bind ( &Display::started, &theDisplay ) );\n stopButton.attach ( boost::bind ( &Player::stop, &thePlayer ) );\n\n playButton.onClick() ;\n stopButton.onClick() ;\n return 0;\n}\n\nSo when you run this you get:\nplay\nStarted playing\nstop\n\nPress any key to continue.\n\nSo.. is this the kind of thing you are looking for?\nSee here and here for the source of most of this code.\nEDIT: The boost::signal library might also do what you want.\n", "Why don't you just implement one? It's not a complicated pattern (well, depending what you really want). Anyway, I already implemented a quick and dirty one some time ago. It is not optimized, synchronous and single threaded. I hope you can use it to make your own.\n#include <vector>\n#include <iostream>\n#include <algorithm>\n\ntemplate<typename MESSAGE> class Topic;\nclass Subscriber;\n\nclass TopicBase\n{\n friend class Subscriber;\nprivate:\n virtual void RemoveSubscriber(Subscriber* subscriber)=0;\n};\n\ntemplate<typename MESSAGE>\nclass Topic : public TopicBase\n{\n friend class Subscriber;\nprivate:\n class Callable\n {\n public:\n Callable(Subscriber* subscriber, void (Subscriber::*method)(const MESSAGE&))\n :m_subscriber(subscriber)\n ,m_method(method)\n {\n }\n void operator()(const MESSAGE& message)\n {\n (m_subscriber->*m_method)(message);\n }\n bool operator==(const Callable& other) const\n {\n return m_subscriber == other.m_subscriber && m_method == other.m_method;\n }\n public:\n Subscriber* m_subscriber;\n void (Subscriber::*m_method)(const MESSAGE&);\n };\npublic:\n ~Topic()\n {\n //unregister each subscriber\n for(std::vector<Callable>::iterator i = m_subscribers.begin(); i != m_subscribers.end(); i++)\n {\n std::vector<TopicBase*>& topics = i->m_subscriber->m_topics;\n for(std::vector<TopicBase*>::iterator ti = topics.begin();;)\n {\n ti = std::find(ti, topics.end(), this);\n if(ti == topics.end()) break;\n ti = topics.erase(ti);\n }\n }\n }\n void SendMessage(const MESSAGE& message)\n {\n for(std::vector<Callable>::iterator i = m_subscribers.begin(); i != m_subscribers.end(); i++)\n {\n (*i)(message);\n }\n }\nprivate:\n void Subscribe(Subscriber* subscriber, void (Subscriber::*method)(const MESSAGE&))\n {\n m_subscribers.push_back(Callable(subscriber, method));\n subscriber->m_topics.push_back(this);\n }\n void Unsubscribe(Subscriber* subscriber, void (Subscriber::*method)(const MESSAGE&))\n {\n std::vector<Callable>::iterator i = std::find(m_subscribers.begin(), m_subscribers.end(), Callable(subscriber, method));\n if(i != m_subscribers.end())\n {\n m_subscribers.erase(i);\n subscriber->m_topics.erase(std::find(subscriber->m_topics.begin(), subscriber->m_topics.end(), this)); //should always find one\n }\n }\n virtual void RemoveSubscriber(Subscriber* subscriber)\n {\n for(std::vector<Callable>::iterator i = m_subscribers.begin() ; i != m_subscribers.end(); i++)\n {\n if(i->m_subscriber == subscriber)\n {\n m_subscribers.erase(i);\n break;\n }\n }\n }\nprivate:\n std::vector<Callable> m_subscribers;\n};\n\n\nclass Subscriber\n{\n template<typename T> friend class Topic;\npublic:\n ~Subscriber()\n {\n for(std::vector<TopicBase*>::iterator i = m_topics.begin(); i !=m_topics.end(); i++)\n {\n (*i)->RemoveSubscriber(this);\n }\n }\nprotected:\n template<typename MESSAGE, typename SUBSCRIBER>\n void Subscribe(Topic<MESSAGE>& topic, void (SUBSCRIBER::*method)(const MESSAGE&))\n {\n topic.Subscribe(this, static_cast<void (Subscriber::*)(const MESSAGE&)>(method));\n }\n template<typename MESSAGE, typename SUBSCRIBER>\n void Unsubscribe(Topic<MESSAGE>& topic, void (SUBSCRIBER::*method)(const MESSAGE&))\n {\n topic.Unsubscribe(this, static_cast<void (Subscriber::*)(const MESSAGE&)>(method));\n }\nprivate:\n std::vector<TopicBase*> m_topics;\n};\n\n// Test\n\nTopic<int> Topic1;\n\nclass TestSubscriber1 : public Subscriber\n{\npublic:\n TestSubscriber1()\n {\n Subscribe(Topic1, &TestSubscriber1::onTopic1);\n }\nprivate:\n void onTopic1(const int& message)\n {\n std::cout<<\"TestSubscriber1::onTopic1 \"<<message<<std::endl;\n }\n};\n\nclass TestSubscriber2 : public Subscriber\n{\npublic:\n void Subscribe(Topic<const char*> &subscriber)\n {\n Subscriber::Subscribe(subscriber, &TestSubscriber2::onTopic);\n }\n void Unsubscribe(Topic<const char*> &subscriber)\n {\n Subscriber::Unsubscribe(subscriber, &TestSubscriber2::onTopic);\n }\nprivate:\n void onTopic(const char* const& message)\n {\n std::cout<<\"TestSubscriber1::onTopic1 \"<<message<<std::endl;\n }\n};\n\n\nint main()\n{\n Topic<const char*>* topic2 = new Topic<const char*>();\n {\n TestSubscriber1 testSubscriber1;\n Topic1.SendMessage(42);\n Topic1.SendMessage(5);\n }\n Topic1.SendMessage(256);\n\n TestSubscriber2 testSubscriber2;\n testSubscriber2.Subscribe(*topic2);\n topic2->SendMessage(\"owl\");\n testSubscriber2.Unsubscribe(*topic2);\n topic2->SendMessage(\"owl\");\n testSubscriber2.Subscribe(*topic2);\n delete topic2;\n\n return 0;\n}\n\n" ]
[ 2, 2, 2 ]
[]
[]
[ "c++", "observer_pattern", "publish_subscribe", "python" ]
stackoverflow_0000605629_c++_observer_pattern_publish_subscribe_python.txt
Q: Using pixel fonts in PIL I am creating images using PIL that contain numerous exactly placed text strings. My first attempt was to convert pixel fonts into the pil-compatible format as described here. For example, I download the Silkscreen font and convert it: otf2bdf -p 8pt -o fonts/slkscr.bdf fonts/slkscr.ttf pilfont.py fonts/slkscr.bdf I can then use the font in PIL like so: import Image, ImageDraw, os, sys, ImageFont im = Image.new("RGB", (40,10)) draw = ImageDraw.Draw(im) fn = ImageFont.load('fonts/slkscr.pil') draw.text((0,0), "Hello", font=fn) del draw # write to stdout im.save(sys.stdout, "PNG") However, the resulting image () does not reflect what the font should look like. What procedure should I be using to convert and use pixel fonts so that they render as intended? Thanks in advance. A: Eureka! Just needed to specify a resolution of 72 dpi (default is 100) for otf2bdf: otf2bdf -p 8 -r 72 -o fonts/slkscr.bdf fonts/slkscr.ttf Now, looks great!
Using pixel fonts in PIL
I am creating images using PIL that contain numerous exactly placed text strings. My first attempt was to convert pixel fonts into the pil-compatible format as described here. For example, I download the Silkscreen font and convert it: otf2bdf -p 8pt -o fonts/slkscr.bdf fonts/slkscr.ttf pilfont.py fonts/slkscr.bdf I can then use the font in PIL like so: import Image, ImageDraw, os, sys, ImageFont im = Image.new("RGB", (40,10)) draw = ImageDraw.Draw(im) fn = ImageFont.load('fonts/slkscr.pil') draw.text((0,0), "Hello", font=fn) del draw # write to stdout im.save(sys.stdout, "PNG") However, the resulting image () does not reflect what the font should look like. What procedure should I be using to convert and use pixel fonts so that they render as intended? Thanks in advance.
[ "Eureka!\nJust needed to specify a resolution of 72 dpi (default is 100) for otf2bdf:\notf2bdf -p 8 -r 72 -o fonts/slkscr.bdf fonts/slkscr.ttf\n\nNow, looks great!\n" ]
[ 4 ]
[]
[]
[ "imaging", "python" ]
stackoverflow_0000619618_imaging_python.txt
Q: Supplying password to wrapped-up MySQL Greetings. I have written a little python script that calls MySQL in a subprocess. [Yes, I know that the right approach is to use MySQLdb, but compiling it under OS X Leopard is a pain, and likely more painful if I wanted to use the script on computers of different architectures.] The subprocess technique works, provided that I supply the password in the command that starts the process; however, that means that other users on the machine could see the password. The original code I wrote can be seen here. This variant below is very similar, although I will omit the test routine to keep it shorter: #!/usr/bin/env python from subprocess import Popen, PIPE # Set the command you need to connect to your database mysql_cmd_line = "/Applications/MAMP/Library/bin/mysql -u root -p" mysql_password = "root" def RunSqlCommand(sql_statement, database=None): """Pass in the SQL statement that you would like executed. Optionally, specify a database to operate on. Returns the result.""" command_list = mysql_cmd_line.split() if database: command_list.append(database) # Run mysql in a subprocess process = Popen(command_list, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True) #print "Asking for output" #needs_pw = process.stdout.readline() #print "Got: " + needs_pw # pass it in the password process.stdin.write(mysql_password + "\n") # pass it our commands, and get the results #(stdout, stderr) = process.communicate( mysql_password + "\n" + sql_statement) (stdout, stderr) = process.communicate( sql_statement ) return stdout I am suspicious that the MySQL password prompt is not actually on stdout (or stderr), although I don't know how that could be or if it means I could trap it. I did try reading output first, before supplying a password, but it didn't work. I also tried passing the password Again, if I supply the password on the command line (and thus have no code between the "Popen" and "communicate" functions) my wrapped function works. Two new thoughts, months laster: Using pexpect would let me supply a password. It simulates a tty and gets all output, even that which bypasses stdout and stderr. There is a project called MySQL Connector/Python, in early alpha, that will allow provide a pure python library for accessing MySQL, without requiring you to compile any C-code. A: You could simply build a my.cnf file and point to that on the mysql command. Obviously you'll want to protect that file with permissions/acls. But it shouldn't be really an more/less secure then having the password in your python script, or the config for your python script. So you would do something like mysql_cmd_line = "/Applications/MAMP/Library/bin/mysql --defaults-file=credentials.cnf" and your config would look about like this [client] host = localhost user = root password = password socket = /var/run/mysqld/mysqld.sock A: The only secure method is to use a MySQL cnf file as one of the other posters mentions. You can also pass a MYSQL_PWD env variable, but that is insecure as well: http://dev.mysql.com/doc/refman/5.0/en/password-security.html Alternatively, you can communicate with the database using a Unix socket file and with a little bit of tweaking you can control permissions at the user id level. Even better, you can use the free BitNami stack DjangoStack that has Python and MySQLDB precompiled for OS X (And Windows and Linux) http://bitnami.org/stacks A: This may be a windows / SQL Server feature, but could you use a Trusted Connection (i.e. use your OS login/password to access the DB)? There may be an OS X equivalent for MySQL. Or you may just need to set up your DB to use the OS login and password so that you don't need to keep it in your code. Anyway, just an idea. A: Try this: process.stdin.write(mysql_password + "\n") process.communicate() (stdout, stderr) = process.communicate( sql_statement ) process.stdin.close() return stdout Call communicate() to force what you just wrote to the buffer to send. Also, it's good to close stdin when you are done.
Supplying password to wrapped-up MySQL
Greetings. I have written a little python script that calls MySQL in a subprocess. [Yes, I know that the right approach is to use MySQLdb, but compiling it under OS X Leopard is a pain, and likely more painful if I wanted to use the script on computers of different architectures.] The subprocess technique works, provided that I supply the password in the command that starts the process; however, that means that other users on the machine could see the password. The original code I wrote can be seen here. This variant below is very similar, although I will omit the test routine to keep it shorter: #!/usr/bin/env python from subprocess import Popen, PIPE # Set the command you need to connect to your database mysql_cmd_line = "/Applications/MAMP/Library/bin/mysql -u root -p" mysql_password = "root" def RunSqlCommand(sql_statement, database=None): """Pass in the SQL statement that you would like executed. Optionally, specify a database to operate on. Returns the result.""" command_list = mysql_cmd_line.split() if database: command_list.append(database) # Run mysql in a subprocess process = Popen(command_list, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True) #print "Asking for output" #needs_pw = process.stdout.readline() #print "Got: " + needs_pw # pass it in the password process.stdin.write(mysql_password + "\n") # pass it our commands, and get the results #(stdout, stderr) = process.communicate( mysql_password + "\n" + sql_statement) (stdout, stderr) = process.communicate( sql_statement ) return stdout I am suspicious that the MySQL password prompt is not actually on stdout (or stderr), although I don't know how that could be or if it means I could trap it. I did try reading output first, before supplying a password, but it didn't work. I also tried passing the password Again, if I supply the password on the command line (and thus have no code between the "Popen" and "communicate" functions) my wrapped function works. Two new thoughts, months laster: Using pexpect would let me supply a password. It simulates a tty and gets all output, even that which bypasses stdout and stderr. There is a project called MySQL Connector/Python, in early alpha, that will allow provide a pure python library for accessing MySQL, without requiring you to compile any C-code.
[ "You could simply build a my.cnf file and point to that on the mysql command. Obviously you'll want to protect that file with permissions/acls. But it shouldn't be really an more/less secure then having the password in your python script, or the config for your python script.\nSo you would do something like \nmysql_cmd_line = \"/Applications/MAMP/Library/bin/mysql --defaults-file=credentials.cnf\"\n\nand your config would look about like this\n[client]\nhost = localhost\nuser = root\npassword = password\nsocket = /var/run/mysqld/mysqld.sock\n\n", "The only secure method is to use a MySQL cnf file as one of the other posters mentions. You can also pass a MYSQL_PWD env variable, but that is insecure as well: http://dev.mysql.com/doc/refman/5.0/en/password-security.html\nAlternatively, you can communicate with the database using a Unix socket file and with a little bit of tweaking you can control permissions at the user id level.\nEven better, you can use the free BitNami stack DjangoStack that has Python and MySQLDB precompiled for OS X (And Windows and Linux) http://bitnami.org/stacks\n", "This may be a windows / SQL Server feature, but could you use a Trusted Connection (i.e. use your OS login/password to access the DB)? There may be an OS X equivalent for MySQL.\nOr you may just need to set up your DB to use the OS login and password so that you don't need to keep it in your code.\nAnyway, just an idea.\n", "Try this:\nprocess.stdin.write(mysql_password + \"\\n\")\nprocess.communicate()\n(stdout, stderr) = process.communicate( sql_statement )\nprocess.stdin.close()\n\nreturn stdout\n\nCall communicate() to force what you just wrote to the buffer to send. Also, it's good to close stdin when you are done.\n" ]
[ 6, 3, 2, 0 ]
[]
[]
[ "mysql", "python", "subprocess" ]
stackoverflow_0000619804_mysql_python_subprocess.txt
Q: Where can I find a GUI designer for Python? Does anyone know of any GUI designer for python like Glade but for windows? A: Glade/Gtk+ for Windows is exactly like Glade but for Windows. A: I would suggest using PyQt and the Qt-designer(WYSIWYG gui designer) for making cross platform gui apps. Qt has even gone LGPL, making it even more attractive. You can find PyQt at: http://www.riverbankcomputing.co.uk/software/pyqt/download A: http://wxformbuilder.org A: I use PyQt; it is built on the QT Toolkit. If you are deploying to Windows, it works well with the py2exe module. It's fairly straightforward to use, especially if you already have experience with the QT libraries. Note: this was my answer to a similar question. A: I use wxGlade A: It deppends of the GUI toolkit you're using. For wxPython, there is boa-constructor. It's a Delphi-like IDE.
Where can I find a GUI designer for Python?
Does anyone know of any GUI designer for python like Glade but for windows?
[ "Glade/Gtk+ for Windows is exactly like Glade but for Windows.\n", "I would suggest using PyQt and the Qt-designer(WYSIWYG gui designer) for making cross platform gui apps.\nQt has even gone LGPL, making it even more attractive.\nYou can find PyQt at:\nhttp://www.riverbankcomputing.co.uk/software/pyqt/download\n", "http://wxformbuilder.org\n", "I use PyQt; it is built on the QT Toolkit.\nIf you are deploying to Windows, it works well with the py2exe module.\nIt's fairly straightforward to use, especially if you already have experience with the QT libraries.\nNote: this was my answer to a similar question.\n", "I use wxGlade\n", "It deppends of the GUI toolkit you're using.\nFor wxPython, there is boa-constructor. It's a Delphi-like IDE.\n" ]
[ 13, 4, 2, 2, 1, 1 ]
[]
[]
[ "glade", "python", "user_interface" ]
stackoverflow_0000561283_glade_python_user_interface.txt
Q: Django labels and translations - Model Design Lets say I have the following Django model: class StandardLabel(models.Model): id = models.AutoField(primary_key=True) label = models.CharField(max_length=255) abbreviation = models.CharField(max_length=255) Each label has an ID number, the label text, and an abbreviation. Now, I want to have these labels translatable into other languages. What is the best way to do this? As I see it, I have a few options: 1: Add the translations as fields on the model: class StandardLabel(models.Model): id = models.AutoField(primary_key=True) label_english = models.CharField(max_length=255) abbreviation_english = models.CharField(max_length=255) label_spanish = models.CharField(max_length=255) abbreviation_spanish = models.CharField(max_length=255) This is obviously not ideal - adding languages requires editing the model, the correct field name depends on the language. 2: Add the language as a foreign key: class StandardLabel(models.Model): id = models.AutoField(primary_key=True) label = models.CharField(max_length=255) abbreviation = models.CharField(max_length=255) language = models.ForeignKey('languages.Language') This is much better, now I can ask for all labels with a certain language, and throw them into a dict: labels = StandardLabel.objects.filter(language=1) labels = dict((x.pk, x) for x in labels) But the problem here is that the labels dict is meant to be a lookup table, like so: x = OtherObjectWithAReferenceToTheseLabels.object.get(pk=3) thelabel = labels[x.labelIdNumber].label Which doesn't work if there is a row per label, possibly with multiple languages for a single label. To solve that one, I need another field: class StandardLabel(models.Model): id = models.AutoField(primary_key=True) group_id = models.IntegerField(db_index=True) label = models.CharField(max_length=255) abbreviation = models.CharField(max_length=255) language = models.ForeignKey('languages.Language') class Meta: unique_together=(("group_id", "language"),) #and I need to group them differently: labels = StandardLabel.objects.filter(language=1) labels = dict((x.group_id, x) for x in labels) 3: Throw label text out into a new model: class StandardLabel(models.Model): id = models.AutoField(primary_key=True) text = models.ManyToManyField('LabelText') class LabelText(models.Model): id = models.AutoField(primary_key=True) label = models.CharField(max_length=255) abbreviation = models.CharField(max_length=255) language = models.ForeignKey('languages.Language') labels = StandardLabel.objects.filter(text__language=1) labels = dict((x.pk, x) for x in labels) But then this doesn't work, and causes a database hit every time I reference the label's text: x = OtherObjectWithAReferenceToTheseLabels.object.get(pk=3) thelabel = labels[x.labelIdNumber].text.get(language=1) I've implemented option 2, but I find it very ugly - i don't like the group_id field, and I can't think of anything better to name it. In addition, StandardLabel as i'm using it is an abstract model, which I subclass to get different label sets for different fields. I suppose that if option 3 /didn't/ hit the database, it's what I'd choose. I believe the real problem is that the filter text__language=1 doesn't cache the LabelText instances, and so the DB is hit when I text.get(language=1) What are your thoughts on this? Can anyone recommend a cleaner solution? Edit: Just to make it clear, these are not form labels, so the Django Internationalization system doesn't help. A: Another option you might consider, depending on your application design of course, is to make use of Django's internationalization features. The approach they use is quite common to the approach found in desktop software. I see the question was edited to add a reference to Django internationalization, so you do know about it, but the intl features in Django apply to much more than just Forms; it touchs quite a lot, and needs only a few tweaks to your app design. Their docs are here: http://docs.djangoproject.com/en/dev/topics/i18n/#topics-i18n The idea is that you define your model as if there was only one language. In other words, make no reference to language at all, and put only, say, English in the model. So: class StandardLabel(models.Model): abbreviation = models.CharField(max_length=255) label = models.CharField(max_length=255) I know this looks like you've totally thrown out the language issue, but you've actually just relocated it. Instead of the language being in your data model, you've pushed it to the view. The django internationalization features allow you to generate text translation files, and provides a number of features for pulling text out of the system into files. This is actually quite useful because it allows you to send plain files to your translator, which makes their job easier. Adding a new language is as easy as getting the file translated into a new language. The translation files define the label from the database, and a translation for that language. There are functions for handling the language translation dynamically at run time for models, admin views, javascript, and templates. For example, in a template, you might do something like: <b>Hello {% trans "Here's the string in english" %}</b> Or in view code, you could do: # See docs on setting language, or getting Django to auto-set language s = StandardLabel.objects.get(id=1) lang_specific_label = ugettext(s.label) Of course, if your app is all about entering new languages on the fly, then this approach may not work for you. Still, have a look at the Internationalization project as you may either be able to use it "as is", or be inspired to a django-appropriate solution that does work for your domain. A: I would keep things as simple as possible. The lookup will be faster and the code cleaner with something like this: class StandardLabel(models.Model): abbreviation = models.CharField(max_length=255) label = models.CharField(max_length=255) language = models.CharField(max_length=2) # or, alternately, specify language as a foreign key: #language = models.ForeignKey(Language) class Meta: unique_together = ('language', 'abbreviation') Then query based on abbreviation and language: l = StandardLabel.objects.get(language='en', abbreviation='suite') A: I'd much prefer to add a field per language than a new model instance per language. It does require schema alteration when you add a new language, but that isn't hard, and how often do you expect to add languages? In the meantime, it'll give you better database performance (no added joins or indexes) and you don't have to muck up your query logic with translation stuff; keep it all in the templates where it belongs. Even better, use a reusable app like django-transmeta or django-modeltranslation that makes this stupid simple and almost completely transparent. A: Although I would go with Daniel's solution, here is an alternative from what I've understood from your comments: You can use an XMLField or JSONField to store your language/translation pairs. This would allow your objects referencing your labels to use a single id for all translations. And then you can have a custom manager method to call a specific translation: Label.objects.get_by_language('ru', **kwargs) Or a slightly cleaner and slightly more complicated solution that plays well with admin would be to denormalize the XMLField to another model with many-to-one relationship to the Label model. Same API, but instead of parsing XML it could query related models. For both suggestions there's a single object where users of a label will point to. I wouldn't worry about the queries too much, Django caches queries and your DBMS would probably have superior caching there as well.
Django labels and translations - Model Design
Lets say I have the following Django model: class StandardLabel(models.Model): id = models.AutoField(primary_key=True) label = models.CharField(max_length=255) abbreviation = models.CharField(max_length=255) Each label has an ID number, the label text, and an abbreviation. Now, I want to have these labels translatable into other languages. What is the best way to do this? As I see it, I have a few options: 1: Add the translations as fields on the model: class StandardLabel(models.Model): id = models.AutoField(primary_key=True) label_english = models.CharField(max_length=255) abbreviation_english = models.CharField(max_length=255) label_spanish = models.CharField(max_length=255) abbreviation_spanish = models.CharField(max_length=255) This is obviously not ideal - adding languages requires editing the model, the correct field name depends on the language. 2: Add the language as a foreign key: class StandardLabel(models.Model): id = models.AutoField(primary_key=True) label = models.CharField(max_length=255) abbreviation = models.CharField(max_length=255) language = models.ForeignKey('languages.Language') This is much better, now I can ask for all labels with a certain language, and throw them into a dict: labels = StandardLabel.objects.filter(language=1) labels = dict((x.pk, x) for x in labels) But the problem here is that the labels dict is meant to be a lookup table, like so: x = OtherObjectWithAReferenceToTheseLabels.object.get(pk=3) thelabel = labels[x.labelIdNumber].label Which doesn't work if there is a row per label, possibly with multiple languages for a single label. To solve that one, I need another field: class StandardLabel(models.Model): id = models.AutoField(primary_key=True) group_id = models.IntegerField(db_index=True) label = models.CharField(max_length=255) abbreviation = models.CharField(max_length=255) language = models.ForeignKey('languages.Language') class Meta: unique_together=(("group_id", "language"),) #and I need to group them differently: labels = StandardLabel.objects.filter(language=1) labels = dict((x.group_id, x) for x in labels) 3: Throw label text out into a new model: class StandardLabel(models.Model): id = models.AutoField(primary_key=True) text = models.ManyToManyField('LabelText') class LabelText(models.Model): id = models.AutoField(primary_key=True) label = models.CharField(max_length=255) abbreviation = models.CharField(max_length=255) language = models.ForeignKey('languages.Language') labels = StandardLabel.objects.filter(text__language=1) labels = dict((x.pk, x) for x in labels) But then this doesn't work, and causes a database hit every time I reference the label's text: x = OtherObjectWithAReferenceToTheseLabels.object.get(pk=3) thelabel = labels[x.labelIdNumber].text.get(language=1) I've implemented option 2, but I find it very ugly - i don't like the group_id field, and I can't think of anything better to name it. In addition, StandardLabel as i'm using it is an abstract model, which I subclass to get different label sets for different fields. I suppose that if option 3 /didn't/ hit the database, it's what I'd choose. I believe the real problem is that the filter text__language=1 doesn't cache the LabelText instances, and so the DB is hit when I text.get(language=1) What are your thoughts on this? Can anyone recommend a cleaner solution? Edit: Just to make it clear, these are not form labels, so the Django Internationalization system doesn't help.
[ "Another option you might consider, depending on your application design of course, is to make use of Django's internationalization features. The approach they use is quite common to the approach found in desktop software. \nI see the question was edited to add a reference to Django internationalization, so you do know about it, but the intl features in Django apply to much more than just Forms; it touchs quite a lot, and needs only a few tweaks to your app design.\nTheir docs are here: http://docs.djangoproject.com/en/dev/topics/i18n/#topics-i18n\nThe idea is that you define your model as if there was only one language. In other words, make no reference to language at all, and put only, say, English in the model.\nSo:\nclass StandardLabel(models.Model):\n abbreviation = models.CharField(max_length=255)\n label = models.CharField(max_length=255)\n\nI know this looks like you've totally thrown out the language issue, but you've actually just relocated it. Instead of the language being in your data model, you've pushed it to the view.\nThe django internationalization features allow you to generate text translation files, and provides a number of features for pulling text out of the system into files. This is actually quite useful because it allows you to send plain files to your translator, which makes their job easier. Adding a new language is as easy as getting the file translated into a new language.\nThe translation files define the label from the database, and a translation for that language. There are functions for handling the language translation dynamically at run time for models, admin views, javascript, and templates.\nFor example, in a template, you might do something like:\n<b>Hello {% trans \"Here's the string in english\" %}</b>\n\nOr in view code, you could do:\n# See docs on setting language, or getting Django to auto-set language\ns = StandardLabel.objects.get(id=1)\nlang_specific_label = ugettext(s.label)\n\nOf course, if your app is all about entering new languages on the fly, then this approach may not work for you. Still, have a look at the Internationalization project as you may either be able to use it \"as is\", or be inspired to a django-appropriate solution that does work for your domain.\n", "I would keep things as simple as possible. The lookup will be faster and the code cleaner with something like this:\nclass StandardLabel(models.Model):\n abbreviation = models.CharField(max_length=255)\n label = models.CharField(max_length=255)\n language = models.CharField(max_length=2)\n # or, alternately, specify language as a foreign key:\n #language = models.ForeignKey(Language)\n\n class Meta:\n unique_together = ('language', 'abbreviation')\n\nThen query based on abbreviation and language:\nl = StandardLabel.objects.get(language='en', abbreviation='suite')\n\n", "I'd much prefer to add a field per language than a new model instance per language. It does require schema alteration when you add a new language, but that isn't hard, and how often do you expect to add languages? In the meantime, it'll give you better database performance (no added joins or indexes) and you don't have to muck up your query logic with translation stuff; keep it all in the templates where it belongs.\nEven better, use a reusable app like django-transmeta or django-modeltranslation that makes this stupid simple and almost completely transparent.\n", "Although I would go with Daniel's solution, here is an alternative from what I've understood from your comments:\nYou can use an XMLField or JSONField to store your language/translation pairs. This would allow your objects referencing your labels to use a single id for all translations. And then you can have a custom manager method to call a specific translation:\nLabel.objects.get_by_language('ru', **kwargs)\n\nOr a slightly cleaner and slightly more complicated solution that plays well with admin would be to denormalize the XMLField to another model with many-to-one relationship to the Label model. Same API, but instead of parsing XML it could query related models.\nFor both suggestions there's a single object where users of a label will point to.\nI wouldn't worry about the queries too much, Django caches queries and your DBMS would probably have superior caching there as well.\n" ]
[ 3, 2, 1, 0 ]
[]
[]
[ "django", "django_models", "localization", "python" ]
stackoverflow_0000616187_django_django_models_localization_python.txt
Q: Programmatically restart windows to make system logs think user logged out I'm hoping to make a quick script to log-out/restart windows at a set time. For example, start a script to "Restart windows in ten minutes". For this implementation I don't need it to run in the background or pop=up on its own. I just want to set the script and walk away knowing that the computer will log-out/restart at a set time. Why would I want to do this? On a corporate network, sometimes system logs will be reviewed and if one is found to be leaving X minutes too early, then complications arise. Kinda annoying. Did I already Google it? Yep. I found this. But it wasn't too helpful. It requires a framework I couldn't find, and likely couldn't install since we don't have admin privs on these machines. I'd like to use Python for it, and I'd really like for it to look like the user did it, not a script. Perhaps screen scraping would be the only way, and if so just point me to a quick guide or IDE and I'll post the source code for everyone. EDIT: I also ran into this A: The shutdown command in batch will shutdown the computer -s to turn it off, -f to force it, -t xx to have it shutdown in x seconds, use the subprocess module in python to call it. Since you want it to shutdown at a specific time, to automate the job completely you'd need to use something like autosys. Set the script up to call shutdown with a value for T equal to time you want to shut down - current time in seconds. Run it before you leave for the day, or have it set to run on start up and just ignore that stupid window it brings up. A: PsShutdown is probably what you are looking for. A: You can use the shutdown command in a batch script.
Programmatically restart windows to make system logs think user logged out
I'm hoping to make a quick script to log-out/restart windows at a set time. For example, start a script to "Restart windows in ten minutes". For this implementation I don't need it to run in the background or pop=up on its own. I just want to set the script and walk away knowing that the computer will log-out/restart at a set time. Why would I want to do this? On a corporate network, sometimes system logs will be reviewed and if one is found to be leaving X minutes too early, then complications arise. Kinda annoying. Did I already Google it? Yep. I found this. But it wasn't too helpful. It requires a framework I couldn't find, and likely couldn't install since we don't have admin privs on these machines. I'd like to use Python for it, and I'd really like for it to look like the user did it, not a script. Perhaps screen scraping would be the only way, and if so just point me to a quick guide or IDE and I'll post the source code for everyone. EDIT: I also ran into this
[ "The shutdown command in batch will shutdown the computer\n-s to turn it off,\n-f to force it,\n-t xx to have it shutdown in x seconds,\nuse the subprocess module in python to call it.\nSince you want it to shutdown at a specific time, to automate the job completely you'd need to use something like autosys. Set the script up to call shutdown with a value for T equal to time you want to shut down - current time in seconds. Run it before you leave for the day, or have it set to run on start up and just ignore that stupid window it brings up.\n", "PsShutdown is probably what you are looking for.\n", "You can use the shutdown command in a batch script.\n" ]
[ 10, 1, 1 ]
[]
[]
[ "automation", "python", "windows" ]
stackoverflow_0000620154_automation_python_windows.txt
Q: SQLAlchemy Obtain Primary Key With Autoincrement Before Commit When I have created a table with an auto-incrementing primary key, is there a way to obtain what the primary key would be (that is, do something like reserve the primary key) without actually committing? I would like to place two operations inside a transaction however one of the operations will depend on what primary key was assigned in the previous operation. A: You don't need to commit, you just need to flush. Here's some sample code. After the call to flush you can access the primary key that was assigned. Note this is with SQLAlchemy v1.3.6 and Python 3.7.4. from sqlalchemy import * import sqlalchemy.ext.declarative Base = sqlalchemy.ext.declarative.declarative_base() class User(Base): __tablename__ = 'user' user_id = Column('user_id', Integer, primary_key=True) name = Column('name', String) if __name__ == '__main__': import unittest from sqlalchemy.orm import * import datetime class Blah(unittest.TestCase): def setUp(self): self.engine = create_engine('sqlite:///:memory:', echo=True) self.sessionmaker = scoped_session(sessionmaker(bind=self.engine)) Base.metadata.bind = self.engine Base.metadata.create_all() self.now = datetime.datetime.now() def test_pkid(self): user = User(name="Joe") session = self.sessionmaker() session.add(user) session.flush() print('user_id', user.user_id) session.commit() session.close() unittest.main()
SQLAlchemy Obtain Primary Key With Autoincrement Before Commit
When I have created a table with an auto-incrementing primary key, is there a way to obtain what the primary key would be (that is, do something like reserve the primary key) without actually committing? I would like to place two operations inside a transaction however one of the operations will depend on what primary key was assigned in the previous operation.
[ "You don't need to commit, you just need to flush. Here's some sample code. After the call to flush you can access the primary key that was assigned. Note this is with SQLAlchemy v1.3.6 and Python 3.7.4.\nfrom sqlalchemy import *\nimport sqlalchemy.ext.declarative\n\nBase = sqlalchemy.ext.declarative.declarative_base()\n\nclass User(Base):\n __tablename__ = 'user'\n user_id = Column('user_id', Integer, primary_key=True)\n name = Column('name', String)\n\nif __name__ == '__main__':\n import unittest\n from sqlalchemy.orm import *\n import datetime\n\n class Blah(unittest.TestCase):\n def setUp(self):\n self.engine = create_engine('sqlite:///:memory:', echo=True)\n self.sessionmaker = scoped_session(sessionmaker(bind=self.engine))\n Base.metadata.bind = self.engine\n Base.metadata.create_all()\n self.now = datetime.datetime.now()\n\n def test_pkid(self):\n user = User(name=\"Joe\")\n session = self.sessionmaker()\n session.add(user)\n session.flush()\n print('user_id', user.user_id)\n session.commit()\n session.close()\n\n unittest.main()\n\n" ]
[ 93 ]
[ "You can use multiple transactions and manage it within scope.\n" ]
[ -4 ]
[ "python", "sql", "sqlalchemy" ]
stackoverflow_0000620610_python_sql_sqlalchemy.txt
Q: Why do I get unexpected behavior in Python isinstance after pickling? Putting aside whether the use of isinstance is harmful, I have run into the following conundrum when trying to evaluate isinstance after serializing/deserializing an object via Pickle: from __future__ import with_statement import pickle # Simple class definition class myclass(object): def __init__(self, data): self.data = data # Create an instance of the class x = myclass(100) # Pickle the instance to a file with open("c:\\pickletest.dat", "wb") as f: pickle.dump(x, f) # Replace class with exact same definition class myclass(object): def __init__(self, data): self.data = data # Read an object from the pickled file with open("c:\\pickletest.dat", "rb") as f: x2 = pickle.load(f) # The class names appear to match print x.__class__ print x2.__class__ # Uh oh, this fails...(why?) assert isinstance(x2, x.__class__) Can anyone shed some light on why isinstance would fail in this situation? In other words, why does Python think these objects are of two different classes? When I remove the second class definition, isinstance works fine. A: The obvious answer, because its not the same class. Its a similar class, but not the same. class myclass(object): pass x = myclass() class myclass(object): pass y = myclass() assert id(x.__class__) == id(y.__class__) # Will fail, not the same object x.__class__.foo = "bar" assert y.__class__.foo == "bar" # will raise AttributeError A: This is how the unpickler works (site-packages/pickle.py): def find_class(self, module, name): # Subclasses may override this __import__(module) mod = sys.modules[module] klass = getattr(mod, name) return klass To find and instantiate a class. So of course if you replace a class with an identically named class, the klass = getattr(mod, name) will return the new class, and the instance will be of the new class, and so isinstance will fail. A: Change your code to print the id of x.__class__ and x2.__class__ and you'll see that they are different: $ python foo4.py 199876736 200015248
Why do I get unexpected behavior in Python isinstance after pickling?
Putting aside whether the use of isinstance is harmful, I have run into the following conundrum when trying to evaluate isinstance after serializing/deserializing an object via Pickle: from __future__ import with_statement import pickle # Simple class definition class myclass(object): def __init__(self, data): self.data = data # Create an instance of the class x = myclass(100) # Pickle the instance to a file with open("c:\\pickletest.dat", "wb") as f: pickle.dump(x, f) # Replace class with exact same definition class myclass(object): def __init__(self, data): self.data = data # Read an object from the pickled file with open("c:\\pickletest.dat", "rb") as f: x2 = pickle.load(f) # The class names appear to match print x.__class__ print x2.__class__ # Uh oh, this fails...(why?) assert isinstance(x2, x.__class__) Can anyone shed some light on why isinstance would fail in this situation? In other words, why does Python think these objects are of two different classes? When I remove the second class definition, isinstance works fine.
[ "The obvious answer, because its not the same class.\nIts a similar class, but not the same.\nclass myclass(object):\n pass\n\nx = myclass()\n\nclass myclass(object):\n pass\n\ny = myclass()\n\n\nassert id(x.__class__) == id(y.__class__) # Will fail, not the same object\n\nx.__class__.foo = \"bar\"\n\nassert y.__class__.foo == \"bar\" # will raise AttributeError\n\n", "This is how the unpickler works (site-packages/pickle.py):\ndef find_class(self, module, name):\n # Subclasses may override this\n __import__(module)\n mod = sys.modules[module]\n klass = getattr(mod, name)\n return klass\n\nTo find and instantiate a class.\nSo of course if you replace a class with an identically named class, the klass = getattr(mod, name) will return the new class, and the instance will be of the new class, and so isinstance will fail.\n", "Change your code to print the id of x.__class__ and x2.__class__ and you'll see that they are different:\n$ python foo4.py\n199876736\n200015248\n\n" ]
[ 5, 5, 3 ]
[]
[]
[ "pickle", "python" ]
stackoverflow_0000620844_pickle_python.txt
Q: What's the best way to find the closest matching type to an existing type? I've got a registry of classes and types in Python 2.5, like so: class ClassA(object): pass class ClassB(ClassA): pass MY_TYPES = { basestring : 'A string', int : 'An integer', ClassA : 'This is ClassA or a subclass', } I'd like to be able to pass types to a function, and have it look up the closest matching type in the hierarchy. So, looking up str would return "A string" and looking up ClassB would return "This is ClassA or a subclass" The problem is, I don't know how to find the superclass (or, rather, trace the MRO chain) of a type object. What's the best way of handling this? A: from inspect import getmro [st for cls, st in MY_TYPES.items() if cls in getmro(ClassB)] ['This is ClassA or a subclass'] or if you're only interested in first match(es) generator version: (st for cls, st in MY_TYPES.iteritems() if cls in getmro(ClassB)) A: To get the superclasses of a class, use __bases__: class ClassA(object): pass class ClassB(ClassA): pass print ClassB.__bases__ (<class '__main__.ClassA'>,) Beware of things like int, though. The base for all of those will be <type 'object'>. You'll have to do some testing and iteration to match the dict keys you've listed in your example. Another option would be to use isinstance on any object instance, or issubclass on the parameters, testing each against your dict keys. Some consider isinstance and its ilk to be the mark of the devil, but c'est la vie. Again, though, beware of using issubclass with ints and other such types. You'll probably need to combine a few approaches given your dict keys. A: (st for cls, st in MY_TYPES.iteritems() if cls in getmro(ClassB)) The simpler way to write that would be: (st for cls, st in MY_TYPES.iteritems() if issubclass(ClassB, cls)) However this does not find the “nearest” match; if ‘object’ were in the lookup, it could match everything! If you had things that were subclasses of other things in the lookup, or you wanted to support multiple inheritance, you'd have to pick out the one that was the first in MRO: for cls in inspect.getmro(ClassB): if cls in MY_TYPES: print MY_TYPES[cls] break else: print 'Dunno what it is' Anyway... I would generally regard type lookups as a little bit of a code smell, is there no nicer way to do what you want? A: This is really a job for generic functions. See PEAK-Rules and PEP 3124. Generic functions will allow you to dispatch arbitrary functions based on argument types, or even more complex expressions. Or if you're really a sucker for punishment, witness this chapter from Practical Common Lisp.
What's the best way to find the closest matching type to an existing type?
I've got a registry of classes and types in Python 2.5, like so: class ClassA(object): pass class ClassB(ClassA): pass MY_TYPES = { basestring : 'A string', int : 'An integer', ClassA : 'This is ClassA or a subclass', } I'd like to be able to pass types to a function, and have it look up the closest matching type in the hierarchy. So, looking up str would return "A string" and looking up ClassB would return "This is ClassA or a subclass" The problem is, I don't know how to find the superclass (or, rather, trace the MRO chain) of a type object. What's the best way of handling this?
[ "from inspect import getmro\n[st for cls, st in MY_TYPES.items() if cls in getmro(ClassB)]\n\n['This is ClassA or a subclass']\n\nor if you're only interested in first match(es) generator version:\n(st for cls, st in MY_TYPES.iteritems() if cls in getmro(ClassB))\n\n", "To get the superclasses of a class, use __bases__:\nclass ClassA(object):\n pass\n\nclass ClassB(ClassA):\n pass\n\nprint ClassB.__bases__\n(<class '__main__.ClassA'>,)\n\nBeware of things like int, though. The base for all of those will be <type 'object'>. You'll have to do some testing and iteration to match the dict keys you've listed in your example.\nAnother option would be to use isinstance on any object instance, or issubclass on the parameters, testing each against your dict keys. Some consider isinstance and its ilk to be the mark of the devil, but c'est la vie. Again, though, beware of using issubclass with ints and other such types. You'll probably need to combine a few approaches given your dict keys.\n", "\n(st for cls, st in MY_TYPES.iteritems() if cls in getmro(ClassB))\n\nThe simpler way to write that would be:\n(st for cls, st in MY_TYPES.iteritems() if issubclass(ClassB, cls))\n\nHowever this does not find the “nearest” match; if ‘object’ were in the lookup, it could match everything! If you had things that were subclasses of other things in the lookup, or you wanted to support multiple inheritance, you'd have to pick out the one that was the first in MRO:\nfor cls in inspect.getmro(ClassB):\n if cls in MY_TYPES:\n print MY_TYPES[cls]\n break\nelse:\n print 'Dunno what it is'\n\nAnyway... I would generally regard type lookups as a little bit of a code smell, is there no nicer way to do what you want?\n", "This is really a job for generic functions. See PEAK-Rules and PEP 3124. Generic functions will allow you to dispatch arbitrary functions based on argument types, or even more complex expressions.\nOr if you're really a sucker for punishment, witness this chapter from Practical Common Lisp.\n" ]
[ 4, 2, 1, 0 ]
[]
[]
[ "python", "types" ]
stackoverflow_0000620530_python_types.txt
Q: What does re.compile(r'[[]]') match? With Python's re module, why do the following act differently: >>> r = re.compile(r'[][]') >>> r.findall(r'[]') ['[', ']'] >>> r = re.compile(r'[[]]') >>> r.findall(r'[]') ['[]'] >>> r.findall(r'][') [] A: The regular expression "[[]]" matches the substring "[]". The first [ in the expression begins a character class, and the first ] ends it. There is only one character ([) in the class, and then it has to be followed by the second ]. So the expression is "any of the characters in "[", followed by a "]". A: Character classes begin with a [ and end with the first ]. So the expression [][] is a character class with the characters ] and [ as character classes must not be empty: [][] And the expression [[]] is a character class with just [ and the single character ] after that: [[]] A: and r'[][]' forms a character class {'[',']'}, and match either '[' or ']'.
What does re.compile(r'[[]]') match?
With Python's re module, why do the following act differently: >>> r = re.compile(r'[][]') >>> r.findall(r'[]') ['[', ']'] >>> r = re.compile(r'[[]]') >>> r.findall(r'[]') ['[]'] >>> r.findall(r'][') []
[ "The regular expression \"[[]]\" matches the substring \"[]\". The first [ in the expression begins a character class, and the first ] ends it. There is only one character ([) in the class, and then it has to be followed by the second ]. So the expression is \"any of the characters in \"[\", followed by a \"]\".\n", "Character classes begin with a [ and end with the first ].\nSo the expression [][] is a character class with the characters ] and [ as character classes must not be empty: [][]\nAnd the expression [[]] is a character class with just [ and the single character ] after that: [[]]\n", "and r'[][]' forms a character class {'[',']'}, and match either '[' or ']'.\n" ]
[ 16, 4, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0000621560_python_regex.txt
Q: Unable to import python-mysqldb I installed python-mysqldb using sudo apt-get install python-mysqldb I have tried to use it unsuccessfully. The following commands do not work in Python prompt: import python-mysqldb Or import mysqldb How can I solve this problem? A: The package name is "MySQLdb". Case counts.
Unable to import python-mysqldb
I installed python-mysqldb using sudo apt-get install python-mysqldb I have tried to use it unsuccessfully. The following commands do not work in Python prompt: import python-mysqldb Or import mysqldb How can I solve this problem?
[ "The package name is \"MySQLdb\". Case counts.\n" ]
[ 11 ]
[]
[]
[ "import", "mysql", "python" ]
stackoverflow_0000621968_import_mysql_python.txt
Q: Is there a Django apps pattern equivalent in Google App Engine? Django has a very handy pattern known as "apps". Essentially, a self-contained plug-in that requires a minimal amount of wiring, configuring, and glue code to integrate into an existing project. Examples are tagging, comments, contact-form, etc. They let you build up large projects by gathering together a collection of useful apps, rather than writing everything from scratch. The apps you do end up writing can be made portable so you can recycle them in other projects. Does this pattern exist in Google App Engine? Is there any way to create self-contained apps that can be easily be dropped into an App Engine project? Right off the bat, the YAML url approach looks like it could require a significant re-imagining to the way its done in Django. Note: I know I can run Django on App Engine, but that's not what I'm interested in doing this time around. A: The Django implementation of apps is closely tied to Django operation as a framework - I mean plugging application using Django url mapping features (for mapping urls to view functions) and Django application component discovery (for discovering models and admin configuration). There is no such mechanisms in WebApp (I guess you think of WebApp framework when you refer to AppEngine, which is rather platform) itself - you have to write them by yourself then persuade people to write such applications in a way that will work with your url plugger and component discovery after plugging app to the rest of site code. There are generic pluggable modules, ready to use with AppEngine, like sharded counters or GAE utilities library, but they do not provide such level of functionality like Django apps (django-registration for example). I thing this comes from much greater freedom of design (basically, on GAE you can model your app after Django layout or after any other you might think of) and lack of widely used conventions. A: I'd like to add that you can run Django apps inside App Engine. I've been doing this successfully for the last few months. Basically, you can make use of the App Engine Helper project or App Engine Patcher. The App Engine Helper is maintained, in part, by google employees, so that's the one I use, thought the App Engine Patcher's maintainer is always feverishly promoting and updating his project (perhaps a little too much :)
Is there a Django apps pattern equivalent in Google App Engine?
Django has a very handy pattern known as "apps". Essentially, a self-contained plug-in that requires a minimal amount of wiring, configuring, and glue code to integrate into an existing project. Examples are tagging, comments, contact-form, etc. They let you build up large projects by gathering together a collection of useful apps, rather than writing everything from scratch. The apps you do end up writing can be made portable so you can recycle them in other projects. Does this pattern exist in Google App Engine? Is there any way to create self-contained apps that can be easily be dropped into an App Engine project? Right off the bat, the YAML url approach looks like it could require a significant re-imagining to the way its done in Django. Note: I know I can run Django on App Engine, but that's not what I'm interested in doing this time around.
[ "The Django implementation of apps is closely tied to Django operation as a framework - I mean plugging application using Django url mapping features (for mapping urls to view functions) and Django application component discovery (for discovering models and admin configuration). There is no such mechanisms in WebApp (I guess you think of WebApp framework when you refer to AppEngine, which is rather platform) itself - you have to write them by yourself then persuade people to write such applications in a way that will work with your url plugger and component discovery after plugging app to the rest of site code.\nThere are generic pluggable modules, ready to use with AppEngine, like sharded counters or GAE utilities library, but they do not provide such level of functionality like Django apps (django-registration for example). I thing this comes from much greater freedom of design (basically, on GAE you can model your app after Django layout or after any other you might think of) and lack of widely used conventions.\n", "I'd like to add that you can run Django apps inside App Engine. I've been doing this successfully for the last few months. Basically, you can make use of the App Engine Helper project or App Engine Patcher. The App Engine Helper is maintained, in part, by google employees, so that's the one I use, thought the App Engine Patcher's maintainer is always feverishly promoting and updating his project (perhaps a little too much :)\n" ]
[ 3, 2 ]
[]
[]
[ "design_patterns", "django", "django_apps", "google_app_engine", "python" ]
stackoverflow_0000588342_design_patterns_django_django_apps_google_app_engine_python.txt
Q: .cgi problem with web server The code #!/usr/bin/env python import MySQLdb print "Content-Type: text/html" print print "<html><head><title>Books</title></head>" print "<body>" print "<h1>Books</h1>" print "<ul>" connection = MySQLdb.connect(user='me', passwd='letmein', db='my_db') cursor = connection.cursor() cursor.execute(“SELECT name FROM books ORDER BY pub_date DESC LIMIT 10”) for row in cursor.fetchall(): print "<li>%s</li>" % row[0] print "</ul>" print "</body></html>" connection.close() I saved it as test.cgi to my web server. I run it by www.mysite.com/test.cgi unsuccessfully Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. How can you solve the problem? [edit] after the first answer test.cgi is executable (I run $ chmod +x test.cgi) I use Apache. I have this in .bashrc export PATH=${PATH}:~/bin Python module MySQLdb is installed. The code does not have smart quotes. [edit] after the second answer you're getting that error because you haven't installed the MySQLdb module that Python needs to talk to a MySQL database I installed MySQLdb to my system. The module works, since I can import them. However, I still get the same error whet I go to the www.[mysite].com/test.cgi. [edit] I am not sure about the questions Are the connect() parameters correct? Is MySQL running on localhost at the default port? I run MySQL on my server. Is the question about the connect() parameters relevant here? Is the SELECT statement correct? You mean whether I have my SQL statements such as SELECT statement correct? I have not used any SQL queries yet. Do I need them here? A: I've tidied up the code a bit by inserting linebreaks where necessary and replacing smart quotes with " and '. Do you have any more luck with the following? Can you run it from a terminal just by typing python test.cgi? #!/usr/bin/env python import MySQLdb print "Content-Type: text/html" print print "<html><head><title>Books</title></head>" print "<body>" print "<h1>Books</h1>" print "<ul>" connection = MySQLdb.connect(user='me', passwd='letmein', db='my_db') cursor = connection.cursor() cursor.execute("SELECT name FROM books ORDER BY pub_date DESC LIMIT 10") for row in cursor.fetchall(): print "<li>%s</li>" % row[0] print "</ul>" print "</body></html>" connection.close() A: Any number of issues can cause the error you are seeing: Is test.cgi executable (chmod 755) on the server? Is the directory in which you placed test.cgi designated as a ScriptAlias location or have the ExecCGI option enabled (or equivalent if you're not using Apache)? Is python in the system PATH or in the PATH in the Web server's startup environment? Is the MySQLdb Python library installed? Are the connect() parameters correct? Is MySQL running on localhost at the default port? Is the SELECT statement correct? If you're sure that python is found (test using the simplest possible script or by logging into the Web server if you can and typing which python) then you can get much better debug output by adding the following to the top of your script just below the shebang: import cgitb cgitb.enable() More details: http://docs.python.org/library/cgitb.html Additionally, if you have shell access to the Web server, try running python and just typing: >>> import MySQLdb If the command returns with no error, you have your answer for #4 above. If an error is printed, you will need to get MySQLdb installed into the Web server's Python installation. EDIT: Looking more closely at the top of your question, I see that the code was scraped from an illustrative example at the very beginning of the Django Book. As such, I might expand #5 above to include the caveat that, of course, the requisite database, tables, user, and permissions need to be set up on the MySQL installation available to the Web server. A: The error in http://dpaste.com/8866/ is occurring because you are using "curly quotes" instead of standard ASCII quotation marks. You'll want to replace the “ and ” with ". Just use find and replace in your text editor. A: Make sure you're saving the file with correct line endings. i.e. LF only on unix, or CR/LF for Windows. I just recently had the exact same problem...
.cgi problem with web server
The code #!/usr/bin/env python import MySQLdb print "Content-Type: text/html" print print "<html><head><title>Books</title></head>" print "<body>" print "<h1>Books</h1>" print "<ul>" connection = MySQLdb.connect(user='me', passwd='letmein', db='my_db') cursor = connection.cursor() cursor.execute(“SELECT name FROM books ORDER BY pub_date DESC LIMIT 10”) for row in cursor.fetchall(): print "<li>%s</li>" % row[0] print "</ul>" print "</body></html>" connection.close() I saved it as test.cgi to my web server. I run it by www.mysite.com/test.cgi unsuccessfully Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. How can you solve the problem? [edit] after the first answer test.cgi is executable (I run $ chmod +x test.cgi) I use Apache. I have this in .bashrc export PATH=${PATH}:~/bin Python module MySQLdb is installed. The code does not have smart quotes. [edit] after the second answer you're getting that error because you haven't installed the MySQLdb module that Python needs to talk to a MySQL database I installed MySQLdb to my system. The module works, since I can import them. However, I still get the same error whet I go to the www.[mysite].com/test.cgi. [edit] I am not sure about the questions Are the connect() parameters correct? Is MySQL running on localhost at the default port? I run MySQL on my server. Is the question about the connect() parameters relevant here? Is the SELECT statement correct? You mean whether I have my SQL statements such as SELECT statement correct? I have not used any SQL queries yet. Do I need them here?
[ "I've tidied up the code a bit by inserting linebreaks where necessary and replacing smart quotes with \" and '. Do you have any more luck with the following? Can you run it from a terminal just by typing python test.cgi?\n#!/usr/bin/env python\n\nimport MySQLdb\n\nprint \"Content-Type: text/html\"\nprint\nprint \"<html><head><title>Books</title></head>\"\nprint \"<body>\"\nprint \"<h1>Books</h1>\"\nprint \"<ul>\"\n\nconnection = MySQLdb.connect(user='me', passwd='letmein', db='my_db')\ncursor = connection.cursor()\ncursor.execute(\"SELECT name FROM books ORDER BY pub_date DESC LIMIT 10\")\n\nfor row in cursor.fetchall():\n print \"<li>%s</li>\" % row[0]\n\nprint \"</ul>\"\nprint \"</body></html>\"\n\nconnection.close()\n\n", "Any number of issues can cause the error you are seeing:\n\nIs test.cgi executable (chmod 755) on the server?\nIs the directory in which you placed test.cgi designated as a ScriptAlias location or have the ExecCGI option enabled (or equivalent if you're not using Apache)?\nIs python in the system PATH or in the PATH in the Web server's startup environment?\nIs the MySQLdb Python library installed?\nAre the connect() parameters correct? Is MySQL running on localhost at the default port?\nIs the SELECT statement correct?\n\nIf you're sure that python is found (test using the simplest possible script or by logging into the Web server if you can and typing which python) then you can get much better debug output by adding the following to the top of your script just below the shebang:\nimport cgitb\ncgitb.enable()\n\nMore details: http://docs.python.org/library/cgitb.html\nAdditionally, if you have shell access to the Web server, try running python and just typing:\n>>> import MySQLdb\n\nIf the command returns with no error, you have your answer for #4 above. If an error is printed, you will need to get MySQLdb installed into the Web server's Python installation.\nEDIT: Looking more closely at the top of your question, I see that the code was scraped from an illustrative example at the very beginning of the Django Book. As such, I might expand #5 above to include the caveat that, of course, the requisite database, tables, user, and permissions need to be set up on the MySQL installation available to the Web server.\n", "The error in http://dpaste.com/8866/ is occurring because you are using \"curly quotes\" instead of standard ASCII quotation marks.\nYou'll want to replace the “ and ” with \". Just use find and replace in your text editor.\n", "Make sure you're saving the file with correct line endings. i.e. LF only on unix, or CR/LF for Windows. I just recently had the exact same problem...\n" ]
[ 2, 2, 1, 0 ]
[]
[]
[ "cgi", "python" ]
stackoverflow_0000621874_cgi_python.txt
Q: Django Forms Newbie Question Alright, I'm at a loss with the Django Forms, as the documentation just doesn't seem to quite cover what I'm looking for. At least it seems to come to a screeching halt once you get past the most rudimentary of forms. I'm more than willing to take a link to good documentation, or a link to a good book that covers this topic, as an answer. Basically, this is how it breaks down, I have 3 models (quiz, questions, answers). I have 20 questions, with 4 potential answers (multi-choice), per quiz. The numbers can vary, but you get the point. I need to create a form for these items, much like you'd expect in a multiple choice quiz. However, when I create the form by hand in the templates, rather than using django.forms, I get the following: invalid literal for int() with base 10: 'test' So I'm trying to mess with the django.forms, but I guess I'm just not grasping the idea of how to build a proper form out of those. Any help would be greatly appreciated, thanks. For what it's worth here are the models: class Quiz(models.Model): label = models.CharField(blank=True, max_length=400) slug = models.SlugField() def __unicode__(self): return self.label class Question(models.Model): label = models.CharField(blank=True, max_length=400) quiz = models.ForeignKey(Quiz) def __unicode__(self): return self.label class Answer(models.Model): label = models.CharField(blank=True, max_length=400) question = models.ForeignKey(Question) correct = models.BooleanField() def __unicode__(self): return self.label A: Yeah I have to agree the documentation and examples are really lacking here. The is no out of the box solution for the case you are describing because it goes three layers deep: quiz->question->answer. Django has model inline formsets which solve the problem for two layers deep. What you will need to do to generate the form you want is: Load up a quiz form (just a label text box from your model) Load a an question formset: QuestionFormSet(queryset=Question.objects.filter(quiz=quiz)) For each question load up a answer formset in much the same way you load up the question formset Make sure you save everything in the right order: quiz->question->answer, since each lower level needs the foreign key of the item above it A: First, you create a ModelForm for a given Model. In this example I'm doing it for Quiz but you can rinse and repeat for your other models. For giggles, I'm making the "label" be a Select box with preset choices: from django.models import BaseModel from django import forms from django.forms import ModelForm CHOICES_LABEL = ( ('label1', 'Label One'), ('label2', 'Label Two') ) class Quiz(models.Model): label = models.CharField(blank=True, max_length=400) slug = models.SlugField() def __unicode__(self): return self.label class QuizForm(ModelForm): # Change the 'label' widget to a select box. label = forms.CharField(widget=forms.Select(choices=CHOICES_LABEL)) class Meta: # This tells django to get attributes from the Quiz model model=Quiz Next, in your views.py you might have something like this: from django.shortcuts import render_to_response from forms import * import my_quiz_model def displayQuizForm(request, *args, **kwargs): if request.method == 'GET': # Create an empty Quiz object. # Alternately you can run a query to edit an existing object. quiz = Quiz() form = QuizForm(instance=Quiz) # Render the template and pass the form object along to it. return render_to_response('form_template.html',{'form': form}) elif request.method == 'POST' and request.POST.get('action') == 'Save': form = Quiz(request.POST, instance=account) form.save() return HttpResponseRedirect("http://example.com/myapp/confirmsave") Finally your template would look like this: <html> <title>My Quiz Form</title> <body> <form id="form" method="post" action="."> <ul> {{ form.as_ul }} </ul> <input type="submit" name="action" value="Save"> <input type="submit" name="action" value="Cancel"> </form> </body> </html>
Django Forms Newbie Question
Alright, I'm at a loss with the Django Forms, as the documentation just doesn't seem to quite cover what I'm looking for. At least it seems to come to a screeching halt once you get past the most rudimentary of forms. I'm more than willing to take a link to good documentation, or a link to a good book that covers this topic, as an answer. Basically, this is how it breaks down, I have 3 models (quiz, questions, answers). I have 20 questions, with 4 potential answers (multi-choice), per quiz. The numbers can vary, but you get the point. I need to create a form for these items, much like you'd expect in a multiple choice quiz. However, when I create the form by hand in the templates, rather than using django.forms, I get the following: invalid literal for int() with base 10: 'test' So I'm trying to mess with the django.forms, but I guess I'm just not grasping the idea of how to build a proper form out of those. Any help would be greatly appreciated, thanks. For what it's worth here are the models: class Quiz(models.Model): label = models.CharField(blank=True, max_length=400) slug = models.SlugField() def __unicode__(self): return self.label class Question(models.Model): label = models.CharField(blank=True, max_length=400) quiz = models.ForeignKey(Quiz) def __unicode__(self): return self.label class Answer(models.Model): label = models.CharField(blank=True, max_length=400) question = models.ForeignKey(Question) correct = models.BooleanField() def __unicode__(self): return self.label
[ "Yeah I have to agree the documentation and examples are really lacking here. The is no out of the box solution for the case you are describing because it goes three layers deep: quiz->question->answer.\nDjango has model inline formsets which solve the problem for two layers deep. What you will need to do to generate the form you want is:\n\nLoad up a quiz form (just a label text box from your model)\nLoad a an question formset: QuestionFormSet(queryset=Question.objects.filter(quiz=quiz))\nFor each question load up a answer formset in much the same way you load up the question formset\nMake sure you save everything in the right order: quiz->question->answer, since each lower level needs the foreign key of the item above it\n\n", "First, you create a ModelForm for a given Model. In this example I'm doing it for Quiz but you can rinse and repeat for your other models. For giggles, I'm making the \"label\" be a Select box with preset choices:\nfrom django.models import BaseModel\nfrom django import forms\nfrom django.forms import ModelForm\n\nCHOICES_LABEL = (\n ('label1', 'Label One'),\n ('label2', 'Label Two')\n\n)\n\nclass Quiz(models.Model):\n label = models.CharField(blank=True, max_length=400)\n slug = models.SlugField()\n\n def __unicode__(self):\n return self.label\n\nclass QuizForm(ModelForm):\n # Change the 'label' widget to a select box.\n label = forms.CharField(widget=forms.Select(choices=CHOICES_LABEL))\n\n class Meta:\n # This tells django to get attributes from the Quiz model\n model=Quiz\n\nNext, in your views.py you might have something like this:\nfrom django.shortcuts import render_to_response\nfrom forms import *\nimport my_quiz_model\n\ndef displayQuizForm(request, *args, **kwargs):\n if request.method == 'GET':\n # Create an empty Quiz object. \n # Alternately you can run a query to edit an existing object.\n\n quiz = Quiz()\n form = QuizForm(instance=Quiz)\n # Render the template and pass the form object along to it.\n return render_to_response('form_template.html',{'form': form})\n\n elif request.method == 'POST' and request.POST.get('action') == 'Save':\n form = Quiz(request.POST, instance=account)\n form.save()\n return HttpResponseRedirect(\"http://example.com/myapp/confirmsave\")\n\nFinally your template would look like this:\n<html>\n <title>My Quiz Form</title>\n <body>\n\n <form id=\"form\" method=\"post\" action=\".\">\n\n <ul>\n {{ form.as_ul }}\n </ul>\n\n <input type=\"submit\" name=\"action\" value=\"Save\">\n <input type=\"submit\" name=\"action\" value=\"Cancel\">\n </form>\n\n </body>\n</html>\n\n" ]
[ 6, 2 ]
[]
[]
[ "django", "forms", "python" ]
stackoverflow_0000621121_django_forms_python.txt
Q: Granularity of Paradigm Mixing When using a multi-paradigm language such as Python, C++, D, or Ruby, how much do you mix paradigms within a single application? Within a single module? Do you believe that mixing the functional, procedural and OO paradigms at a fine granularity leads to clearer, more concise code because you're using the right tool for every subproblem, or an inconsistent mess because you're doing similar things 3 different ways? A: Different paradigms mix in different ways. For example, Using OOP doesn't eliminate the use of subroutines and procedural code from an outside library. It merely moves the procedures around into a different place. It is impossible to purely program with one paradigm. You may think you have a single one in mind when you program, but that's your illusion. Your resultant code will land along the borders and within the bounds of many paradigms. A: I am not sure that I ever think about it like this. Once you start "thinking in Ruby" the multi-paradigms just merge into ... well, Ruby. Ruby is object-oriented, but I find that other things such as the functional aspect tend to mean that some of the "traditional" design patters present in OO languages are just simply not relevant. The iterator is a classic example ... iteration is something that is handled elegantly in Ruby and the heavy-weight OO iteration patterns no longer really apply. This seems to be true throughout the language. A: Mixing paradigms has an advantage of letting you express solutions in most natural and esy way. Which is very good thing when it help keeping your program logic smaller. For example, filtering a list by some criteria is several times simpler to express with functional solution compared to traditional loop. On the other hand, to get benefit from mixing two or more paradigms programmer should be reasonably fluent with all of them. So this is powerful tool that should be used with care. A: Different problems require different solutions, but it helps if you solve things the same way in the same layer. And varying to wildly will just confuse you and everyone else in the project. For C++, I've found that statically typed OOP (use zope.interface in Python) work well for higher-level parts (connecting, updating, signaling, etc) and functional stuff solves many lower-level problems (parsing, nuts 'n bolts data processing, etc) more nicely. And usually, a dynamically typed scripting system is good for selecting and configuring the specific app, game level, whatnot. This may be the language itself (i.e. Python) or something else (an xml-script engine + necessary system for dynamic links in C++).
Granularity of Paradigm Mixing
When using a multi-paradigm language such as Python, C++, D, or Ruby, how much do you mix paradigms within a single application? Within a single module? Do you believe that mixing the functional, procedural and OO paradigms at a fine granularity leads to clearer, more concise code because you're using the right tool for every subproblem, or an inconsistent mess because you're doing similar things 3 different ways?
[ "Different paradigms mix in different ways. For example, Using OOP doesn't eliminate the use of subroutines and procedural code from an outside library. It merely moves the procedures around into a different place.\nIt is impossible to purely program with one paradigm. You may think you have a single one in mind when you program, but that's your illusion. Your resultant code will land along the borders and within the bounds of many paradigms.\n", "I am not sure that I ever think about it like this. \nOnce you start \"thinking in Ruby\" the multi-paradigms just merge into ... well, Ruby. \nRuby is object-oriented, but I find that other things such as the functional aspect tend to mean that some of the \"traditional\" design patters present in OO languages are just simply not relevant. The iterator is a classic example ... iteration is something that is handled elegantly in Ruby and the heavy-weight OO iteration patterns no longer really apply. This seems to be true throughout the language.\n", "Mixing paradigms has an advantage of letting you express solutions in most natural and esy way. Which is very good thing when it help keeping your program logic smaller. For example, filtering a list by some criteria is several times simpler to express with functional solution compared to traditional loop.\nOn the other hand, to get benefit from mixing two or more paradigms programmer should be reasonably fluent with all of them. So this is powerful tool that should be used with care. \n", "Different problems require different solutions, but it helps if you solve things the same way in the same layer. And varying to wildly will just confuse you and everyone else in the project.\nFor C++, I've found that statically typed OOP (use zope.interface in Python) work well for higher-level parts (connecting, updating, signaling, etc) and functional stuff solves many lower-level problems (parsing, nuts 'n bolts data processing, etc) more nicely. \nAnd usually, a dynamically typed scripting system is good for selecting and configuring the specific app, game level, whatnot. This may be the language itself (i.e. Python) or something else (an xml-script engine + necessary system for dynamic links in C++). \n" ]
[ 2, 2, 1, 0 ]
[]
[]
[ "coding_style", "python", "ruby" ]
stackoverflow_0000543140_coding_style_python_ruby.txt
Q: pycurl cancel a transfer and try & except How do i cancel a transfer in pycurl? i use to return -1 in libcurl but pycurl doesnt seem to like that ("pycurl.error: invalid return value for write callback -1 17") return 0 doesnt work either, i get "error: (23, 'Failed writing body')" . Also how do i do a try/except with pycurl? i dont see any examples online nor the pycurl examples from the site A: Example code would help here. Judging from the error message, and grepping for it in the source code, you've set up a write callback. This is configured, I think, by CURLOPT_WRITEFUNCTION, and the documentation for that says: Return the number of bytes actually taken care of. If that amount differs from the amount passed to your function, it'll signal an error to the library and it will abort the transfer and return CURLE_WRITE_ERROR. The pycurl wrapper code checks that the value is between 0 and the number passed to it. That's why -1 failed, and why 0, triggers CURLE_WRITE_ERROR, raises the "failed writing body" exception. The pycurl code is: /* run callback */ arglist = Py_BuildValue("(s#)", ptr, total_size); if (arglist == NULL) goto verbose_error; result = PyEval_CallObject(cb, arglist); Py_DECREF(arglist); if (result == NULL) goto verbose_error; /* handle result */ if (result == Py_None) { ret = total_size; /* None means success */ } else if (PyInt_Check(result)) { long obj_size = PyInt_AsLong(result); if (obj_size < 0 || obj_size > total_size) { PyErr_Format(ErrorObject, "invalid return value for write callback %ld %ld", (long)obj_size, (long)total_size); goto verbose_error; } ret = (size_t) obj_size; /* success */ } else if (PyLong_Check(result)) { ... identical code for Long ... } else { PyErr_SetString(ErrorObject, "write callback must return int or None"); goto verbose_error; } I don't see any way in pycurl for this function to support another return value. There might be other ways, like setting up a progress callback, which does seem to allow aborts. The relevant code in curl itself is: /* If the previous block of data ended with CR and this block of data is just a NL, then the length might be zero */ if(len) { wrote = data->set.fwrite_func(ptr, 1, len, data->set.out); } else { wrote = len; } if(CURL_WRITEFUNC_PAUSE == wrote) return pausewrite(data, type, ptr, len); if(wrote != len) { failf(data, "Failed writing body (%d != %d)", (int)wrote, (int)len); return CURLE_WRITE_ERROR; } so you can see that pycurl does not support returning the CURL_WRITEFUNC_PAUSE which curl itself allows. You can also see that curl has no way to support aborts through the write callback function. You will have to use something else.
pycurl cancel a transfer and try & except
How do i cancel a transfer in pycurl? i use to return -1 in libcurl but pycurl doesnt seem to like that ("pycurl.error: invalid return value for write callback -1 17") return 0 doesnt work either, i get "error: (23, 'Failed writing body')" . Also how do i do a try/except with pycurl? i dont see any examples online nor the pycurl examples from the site
[ "Example code would help here. Judging from the error message, and grepping for it in the source code, you've set up a write callback. This is configured, I think, by CURLOPT_WRITEFUNCTION, and the documentation for that says:\n\nReturn the number of bytes actually\n taken care of. If that amount differs\n from the amount passed to your\n function, it'll signal an error to the\n library and it will abort the transfer\n and return CURLE_WRITE_ERROR.\n\nThe pycurl wrapper code checks that the value is between 0 and the number passed to it. That's why -1 failed, and why 0, triggers CURLE_WRITE_ERROR, raises the \"failed writing body\" exception. The pycurl code is:\n /* run callback */\n arglist = Py_BuildValue(\"(s#)\", ptr, total_size);\n if (arglist == NULL)\n goto verbose_error;\n result = PyEval_CallObject(cb, arglist);\n Py_DECREF(arglist);\n if (result == NULL)\n goto verbose_error;\n\n /* handle result */\n if (result == Py_None) {\n ret = total_size; /* None means success */\n }\n else if (PyInt_Check(result)) {\n long obj_size = PyInt_AsLong(result);\n if (obj_size < 0 || obj_size > total_size) {\n PyErr_Format(ErrorObject, \"invalid return value for write callback %ld %ld\", (long)obj_size, (long)total_size);\n goto verbose_error;\n }\n ret = (size_t) obj_size; /* success */\n }\n else if (PyLong_Check(result)) {\n ... identical code for Long ...\n }\n else {\n PyErr_SetString(ErrorObject, \"write callback must return int or None\");\n goto verbose_error;\n }\n\nI don't see any way in pycurl for this function to support another return value. There might be other ways, like setting up a progress callback, which does seem to allow aborts.\nThe relevant code in curl itself is:\n/* If the previous block of data ended with CR and this block of data is\n just a NL, then the length might be zero */\nif(len) {\n wrote = data->set.fwrite_func(ptr, 1, len, data->set.out);\n}\nelse {\n wrote = len;\n}\n\nif(CURL_WRITEFUNC_PAUSE == wrote)\n return pausewrite(data, type, ptr, len);\n\nif(wrote != len) {\n failf(data, \"Failed writing body (%d != %d)\", (int)wrote, (int)len);\n return CURLE_WRITE_ERROR;\n}\n\nso you can see that pycurl does not support returning the CURL_WRITEFUNC_PAUSE which curl itself allows. You can also see that curl has no way to support aborts through the write callback function. You will have to use something else.\n" ]
[ 3 ]
[]
[]
[ "pycurl", "python" ]
stackoverflow_0000526325_pycurl_python.txt
Q: Why doesn't Python have static variables? There is a questions asking how to simulate static variables in python. Also, on the web one can find many different solutions to create static variables. (Though I haven't seen one that I like yet.) Why doesn't Python support static variables in methods? Is this considered unpythonic or has it something to do with Python's syntax? Edit: I asked specifically about the why of the design decision and I haven't provided any code example because I wanted to avoid explanation to simulate static variables. A: The idea behind this omission is that static variables are only useful in two situations: when you really should be using a class and when you really should be using a generator. If you want to attach stateful information to a function, what you need is a class. A trivially simple class, perhaps, but a class nonetheless: def foo(bar): static my_bar # doesn't work if not my_bar: my_bar = bar do_stuff(my_bar) foo(bar) foo() # -- becomes -> class Foo(object): def __init__(self, bar): self.bar = bar def __call__(self): do_stuff(self.bar) foo = Foo(bar) foo() foo() If you want your function's behavior to change each time it's called, what you need is a generator: def foo(bar): static my_bar # doesn't work if not my_bar: my_bar = bar my_bar = my_bar * 3 % 5 return my_bar foo(bar) foo() # -- becomes -> def foogen(bar): my_bar = bar while True: my_bar = my_bar * 3 % 5 yield my_bar foo = foogen(bar) foo.next() foo.next() Of course, static variables are useful for quick-and-dirty scripts where you don't want to deal with the hassle of big structures for little tasks. But there, you don't really need anything more than global — it may seem a but kludgy, but that's okay for small, one-off scripts: def foo(): global bar do_stuff(bar) foo() foo() A: One alternative to a class is a function attribute: def foo(arg): if not hasattr(foo, 'cache'): foo.cache = get_data_dict() return foo.cache[arg] While a class is probably cleaner, this technique can be useful and is nicer, in my opinion, then a global. A: In Python 3, I would use a closure: def makefoo(): x = 0 def foo(): nonlocal x x += 1 return x return foo foo = makefoo() print(foo()) print(foo()) A: I think most uses of local static variables is to simulate generators, that is, having some function which performs some iteration of a process, returns the result, but mantains the state for the subsequent invocation. Python handles this very elegantly using the yield command, so it seems there is not so much need for static variables. A: It's a design choice. I'm assuming Guido thinks you don't need them very often, and you never really need them: you can always just use a global variable and tell everyone to keep their greasy paws offa' your variable ;-) A: For caching or memoization purposes, decorators can be used as an elegant and general solution. A: The answer's pretty much the same as why nobody uses static methods (even though they exist). You have a module-level namespace that serves about the same purpose as a class would anyway. A: An ill-advised alternative: You can also use the side-effects of the definition time evaluation of function defaults: def func(initial=0, my_static=[]) if not my_static: my_static.append(initial) my_static[0] += 1 return my_static[0] print func(0), func(0), func(0) Its really ugly and easily subverted, but works. Using global would be cleaner than this, imo.
Why doesn't Python have static variables?
There is a questions asking how to simulate static variables in python. Also, on the web one can find many different solutions to create static variables. (Though I haven't seen one that I like yet.) Why doesn't Python support static variables in methods? Is this considered unpythonic or has it something to do with Python's syntax? Edit: I asked specifically about the why of the design decision and I haven't provided any code example because I wanted to avoid explanation to simulate static variables.
[ "The idea behind this omission is that static variables are only useful in two situations: when you really should be using a class and when you really should be using a generator.\nIf you want to attach stateful information to a function, what you need is a class. A trivially simple class, perhaps, but a class nonetheless:\ndef foo(bar):\n static my_bar # doesn't work\n\n if not my_bar:\n my_bar = bar\n\n do_stuff(my_bar)\n\nfoo(bar)\nfoo()\n\n# -- becomes ->\n\nclass Foo(object):\n def __init__(self, bar):\n self.bar = bar\n\n def __call__(self):\n do_stuff(self.bar)\n\nfoo = Foo(bar)\nfoo()\nfoo()\n\nIf you want your function's behavior to change each time it's called, what you need is a generator:\ndef foo(bar):\n static my_bar # doesn't work\n\n if not my_bar:\n my_bar = bar\n\n my_bar = my_bar * 3 % 5\n\n return my_bar\n\nfoo(bar)\nfoo()\n\n# -- becomes ->\n\ndef foogen(bar):\n my_bar = bar\n\n while True:\n my_bar = my_bar * 3 % 5\n yield my_bar\n\nfoo = foogen(bar)\nfoo.next()\nfoo.next()\n\nOf course, static variables are useful for quick-and-dirty scripts where you don't want to deal with the hassle of big structures for little tasks. But there, you don't really need anything more than global — it may seem a but kludgy, but that's okay for small, one-off scripts:\ndef foo():\n global bar\n do_stuff(bar)\n\nfoo()\nfoo()\n\n", "One alternative to a class is a function attribute:\ndef foo(arg):\n if not hasattr(foo, 'cache'):\n foo.cache = get_data_dict()\n return foo.cache[arg]\n\nWhile a class is probably cleaner, this technique can be useful and is nicer, in my opinion, then a global. \n", "In Python 3, I would use a closure:\ndef makefoo():\n x = 0\n def foo():\n nonlocal x\n x += 1\n return x\n return foo\n\nfoo = makefoo()\n\nprint(foo())\nprint(foo())\n\n", "I think most uses of local static variables is to simulate generators, that is, having some function which performs some iteration of a process, returns the result, but mantains the state for the subsequent invocation. Python handles this very elegantly using the yield command, so it seems there is not so much need for static variables.\n", "It's a design choice.\nI'm assuming Guido thinks you don't need them very often, and you never really need them: you can always just use a global variable and tell everyone to keep their greasy paws offa' your variable ;-)\n", "For caching or memoization purposes, decorators can be used as an elegant and general solution.\n", "The answer's pretty much the same as why nobody uses static methods (even though they exist). You have a module-level namespace that serves about the same purpose as a class would anyway.\n", "An ill-advised alternative:\nYou can also use the side-effects of the definition time evaluation of function defaults:\ndef func(initial=0, my_static=[])\n if not my_static:\n my_static.append(initial)\n\n my_static[0] += 1\n return my_static[0]\n\nprint func(0), func(0), func(0)\n\nIts really ugly and easily subverted, but works. Using global would be cleaner than this, imo.\n" ]
[ 80, 19, 8, 6, 5, 4, 0, 0 ]
[ "From one of your comments: \"I'd like to use them to cache things loaded from disk. I think it clutters the instance less, if I could assign them to the function\"\nUse a caching class then, as a class or instance attribute to your other class. That way, you can use the full feature set of classes without cluttering other things. Also, you get a reusable tool.\nThis shows that on SO it always pays off to state one's problem instead of asking for a specific, low level solution (e.g. for a missing language feature). That way, instead of endless debates about simulating \"static\" (a deprecated feature from an ancient language, in my view) someone could have given a good answer to you problem sooner.\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0000592931_python.txt
Q: How to change cursor position of wxRichTextCtrl in event handler? I have a RichTextCtrl in my application, that has a handler for EVT_KEY_DOWN. The code that is executed is the following : def move_caret(self): pdb.set_trace() self.rich.GetCaret().Move((0,0)) self.Refresh() def onClick(self,event): self.move_caret() event.Skip() rich is my RichTextCtrl. Here is what I would like it to do : on each key press, add the key to the control ( which is default behaviour ) move the cursor at the beginning of the control, first position Here's what it actually does : it adds the key to the control I inspected the caret position, and the debugger reports it's located at 0,0 but on the control, it blinks at the current position ( which is position before I pressed a key + 1 ) Do you see anything wrong here? There must be something I'm doing wrong. A: Apparently, there are two problems with your code: You listen on EVT_KEY_DOWN, which is probably handled before EVT_TEXT, whose default handler sets the cursor position. You modify the Caret object instead of using SetInsertionPoint method, which both moves the caret and makes the next character appear in given place. So the working example (I tested it and it works as you would like it to) would be: # Somewhere in __init__: self.rich.Bind(wx.EVT_TEXT, self.onClick) def onClick(self, event): self.rich.SetInsertionPoint(0) # No refresh necessary. event.Skip() EDIT: if you want the text to be added at the end, but the cursor to remain at the beginning (see comments), you can take advantage of the fact that EVT_KEY_DOWN is handled before EVT_TEXT (which in turn is handled after character addition). So the order of events is: handle EVT_KEY_DOWN add character at current insertion point handle EVT_TEXT Adding a handler of EVT_KEY_DOWN that moves the insertion point to the end just before actually adding the character does the job quite nicely. So, in addition to the code mentioned earlier, write: # Somewhere in __init__: self.rich.Bind(wx.EVT_KEY_DOWN, self.onKeyDown) def onKeyDown(self, event): self.rich.SetInsertionPointEnd() event.Skip() By the way, event.Skip() does not immediately invoke next event handler, it justs sets a flag in the event object, so that event processor knows whether to stop propagating the event after this handler.
How to change cursor position of wxRichTextCtrl in event handler?
I have a RichTextCtrl in my application, that has a handler for EVT_KEY_DOWN. The code that is executed is the following : def move_caret(self): pdb.set_trace() self.rich.GetCaret().Move((0,0)) self.Refresh() def onClick(self,event): self.move_caret() event.Skip() rich is my RichTextCtrl. Here is what I would like it to do : on each key press, add the key to the control ( which is default behaviour ) move the cursor at the beginning of the control, first position Here's what it actually does : it adds the key to the control I inspected the caret position, and the debugger reports it's located at 0,0 but on the control, it blinks at the current position ( which is position before I pressed a key + 1 ) Do you see anything wrong here? There must be something I'm doing wrong.
[ "Apparently, there are two problems with your code:\n\nYou listen on EVT_KEY_DOWN, which is probably handled before EVT_TEXT, whose default handler sets the cursor position.\nYou modify the Caret object instead of using SetInsertionPoint method, which both moves the caret and makes the next character appear in given place.\n\nSo the working example (I tested it and it works as you would like it to) would be:\n# Somewhere in __init__:\n self.rich.Bind(wx.EVT_TEXT, self.onClick)\n\ndef onClick(self, event):\n self.rich.SetInsertionPoint(0) # No refresh necessary.\n event.Skip()\n\n\nEDIT: if you want the text to be added at the end, but the cursor to remain at the beginning (see comments), you can take advantage of the fact that EVT_KEY_DOWN is handled before EVT_TEXT (which in turn is handled after character addition). So the order of events is:\n\nhandle EVT_KEY_DOWN\nadd character at current insertion point\nhandle EVT_TEXT\n\nAdding a handler of EVT_KEY_DOWN that moves the insertion point to the end just before actually adding the character does the job quite nicely. So, in addition to the code mentioned earlier, write:\n# Somewhere in __init__:\n self.rich.Bind(wx.EVT_KEY_DOWN, self.onKeyDown)\n\ndef onKeyDown(self, event):\n self.rich.SetInsertionPointEnd()\n event.Skip()\n\nBy the way, event.Skip() does not immediately invoke next event handler, it justs sets a flag in the event object, so that event processor knows whether to stop propagating the event after this handler.\n" ]
[ 3 ]
[]
[]
[ "events", "python", "wxpython", "wxwidgets" ]
stackoverflow_0000622417_events_python_wxpython_wxwidgets.txt
Q: How can I insert RTF into a wxpython RichTextCtrl? Is there a way to directly insert RTF text in a RichTextCtrl, ex:without going through BeginTextColour? I would like to use pygments together with the RichTextCtrl. A: No. As authors admit in wxRichTextCtrl roadmap: This is a list of some of the features that have yet to be implemented. Help with them will be appreciated. RTF input and output
How can I insert RTF into a wxpython RichTextCtrl?
Is there a way to directly insert RTF text in a RichTextCtrl, ex:without going through BeginTextColour? I would like to use pygments together with the RichTextCtrl.
[ "No. As authors admit in wxRichTextCtrl roadmap:\n\nThis is a list of some of the features that have yet to be implemented. Help with them will be appreciated.\n\nRTF input and output \n\n\n" ]
[ 2 ]
[]
[]
[ "python", "richtextctrl", "rtf", "wxpython" ]
stackoverflow_0000623384_python_richtextctrl_rtf_wxpython.txt
Q: For my app, how many threads would be optimal? I have a simple Python web crawler. It uses SQLite to store its output and also to keep a queue. I want to make the crawler multi-threaded so that it can crawl several pages at a time. I figured i would make a thread and just run several instances of the class at once, so they all run concurrently. But the question is, how many should i run at once? should i stick to two? can i go higher? what would be a reasonable limit for a number of threads? Keep in mind that each thread goes out to a web page, downloads the html, runs a few regex searches through it, stores the info it finds in a SQLite db, and then pops the next url off the queue. A: You will probably find your application is bandwidth limited not CPU or I/O limited. As such, add as many as you like until performance begins to degrade. You may come up against other limits depending on your network setup. Like if you're behind an ADSL router, there will be a limit on the number of concurrent NAT sessions, which may impact making too many HTTP requests at once. Make too many and your provider may treat you as being infected by a virus or the like. There's also the issue of how many requests the server you're crawling can handle and how much of a load you want to put on it. I wrote a crawler once that used just one thread. It took about a day to process all the information I wanted at about one page every two seconds. I could've done it faster but I figured this was less of a burden for the server. So really theres no hard and fast answer. Assuming a 1-5 megabit connection I'd say you could easily have up to 20-30 threads without any problems. A: I would use one thread and twisted with either a deferred semaphore or a task cooperator if you already have an easy way to feed an arbitrarily long list of URLs in. It's extremely unlikely you'll be able to make a multi-threaded crawler that's faster or smaller than a twisted-based crawler. A: It's usually simpler to make multiple concurrent processes. Simply use subprocess to create as many Popens as you feel it necessary to run concurrently. There's no "optimal" number. Generally, when you run just one crawler, your PC spends a lot of time waiting. How much? Hard to say. When you're running some small number of concurrent crawlers, you'll see that they take about the same amount of time as one. Your CPU switches among the various processes, filling up the wait time on one with work on the others. You you run some larger number, you see that the overall elapsed time is longer because there's now more to do than your CPU can manage. So the overall process takes longer. You can create a graph that shows how the process scales. Based on this you can balance the number of processes and your desirable elapsed time. Think of it this way. 1 crawler does it's job in 1 minute. 100 pages done serially could take a 100 minutes. 100 crawlers concurrently might take on hour. Let's say that 25 crawlers finishes the job in 50 minutes. You don't know what's optimal until you run various combinations and compare the results. A: cletus's answer is the one you want. A couple of people proposed an alternate solution using asynchronous I/O, especially looking at Twisted. If you decide to go that route, a different solution is pycurl, which is a thin wrapper to libcurl, which is a widely used URL transfer library. PyCurl's home page has a 'retriever-multi.py' example of how to fetch multiple pages in parallel, in about 120 lines of code. A: You can go higher that two. How much higher depends entirely on the hardware of the system you're running this on, how much processing is going on after the network operations, and what else is running on the machine at the time. Since it's being written in Python (and being called "simple") I'm going to assume you're not exactly concerned with squeezing every ounce of performance out of the thing. In that case, I'd suggest just running some tests under common working conditions and seeing how it performs. I'd guess around 5-10 is probably reasonable, but that's a complete stab in the dark. Since you're using a dual-core machine, I'd highly recommend checking out the Python multiprocessing module (in Python 2.6). It will let you take advantage of multiple processors on your machine, which would be a significant performance boost. A: One thing you should keep in mind is that some servers may interpret too many concurrent requests from the same IP address as a DoS attack and abort connections or return error pages for requests that would otherwise succeed. So it might be a good idea to limit the number of concurrent requests to the same server to a relatively low number (5 should be on the safe side). A: Threading isn't necessary in this case. Your program is I/O bound rather than CPU bound. The networking part would probably be better done using select() on the sockets. This reduces the overhead of creating and maintaining threads. I haven't used Twisted, but I heard it has really good support for asynchronous networking. This would allow you you to specify the URLs you wish to download and register a callback for each. When each is downloaded you the callback will be called, and the page can be processed. In order to allow multiple sites to be downloaded, without waiting for each to be processed, a second "worker" thread can be created with a queue. The callback would add the site's contents to the queue. The "worker" thread would do the actual processing. As already stated in some answers, the optimal amount of simultaneous downloads depends on your bandwidth. I'd use one or two threads - one for the actual crawling and the other (with a queue) for processing.
For my app, how many threads would be optimal?
I have a simple Python web crawler. It uses SQLite to store its output and also to keep a queue. I want to make the crawler multi-threaded so that it can crawl several pages at a time. I figured i would make a thread and just run several instances of the class at once, so they all run concurrently. But the question is, how many should i run at once? should i stick to two? can i go higher? what would be a reasonable limit for a number of threads? Keep in mind that each thread goes out to a web page, downloads the html, runs a few regex searches through it, stores the info it finds in a SQLite db, and then pops the next url off the queue.
[ "You will probably find your application is bandwidth limited not CPU or I/O limited.\nAs such, add as many as you like until performance begins to degrade.\nYou may come up against other limits depending on your network setup. Like if you're behind an ADSL router, there will be a limit on the number of concurrent NAT sessions, which may impact making too many HTTP requests at once. Make too many and your provider may treat you as being infected by a virus or the like.\nThere's also the issue of how many requests the server you're crawling can handle and how much of a load you want to put on it.\nI wrote a crawler once that used just one thread. It took about a day to process all the information I wanted at about one page every two seconds. I could've done it faster but I figured this was less of a burden for the server.\nSo really theres no hard and fast answer. Assuming a 1-5 megabit connection I'd say you could easily have up to 20-30 threads without any problems.\n", "I would use one thread and twisted with either a deferred semaphore or a task cooperator if you already have an easy way to feed an arbitrarily long list of URLs in.\nIt's extremely unlikely you'll be able to make a multi-threaded crawler that's faster or smaller than a twisted-based crawler.\n", "It's usually simpler to make multiple concurrent processes. Simply use subprocess to create as many Popens as you feel it necessary to run concurrently.\nThere's no \"optimal\" number. Generally, when you run just one crawler, your PC spends a lot of time waiting. How much? Hard to say.\nWhen you're running some small number of concurrent crawlers, you'll see that they take about the same amount of time as one. Your CPU switches among the various processes, filling up the wait time on one with work on the others.\nYou you run some larger number, you see that the overall elapsed time is longer because there's now more to do than your CPU can manage. So the overall process takes longer.\nYou can create a graph that shows how the process scales. Based on this you can balance the number of processes and your desirable elapsed time.\nThink of it this way. \n1 crawler does it's job in 1 minute. 100 pages done serially could take a 100 minutes. 100 crawlers concurrently might take on hour. Let's say that 25 crawlers finishes the job in 50 minutes.\nYou don't know what's optimal until you run various combinations and compare the results.\n", "cletus's answer is the one you want.\nA couple of people proposed an alternate solution using asynchronous I/O, especially looking at Twisted. If you decide to go that route, a different solution is pycurl, which is a thin wrapper to libcurl, which is a widely used URL transfer library. PyCurl's home page has a 'retriever-multi.py' example of how to fetch multiple pages in parallel, in about 120 lines of code.\n", "You can go higher that two. How much higher depends entirely on the hardware of the system you're running this on, how much processing is going on after the network operations, and what else is running on the machine at the time.\nSince it's being written in Python (and being called \"simple\") I'm going to assume you're not exactly concerned with squeezing every ounce of performance out of the thing. In that case, I'd suggest just running some tests under common working conditions and seeing how it performs. I'd guess around 5-10 is probably reasonable, but that's a complete stab in the dark.\nSince you're using a dual-core machine, I'd highly recommend checking out the Python multiprocessing module (in Python 2.6). It will let you take advantage of multiple processors on your machine, which would be a significant performance boost.\n", "One thing you should keep in mind is that some servers may interpret too many concurrent requests from the same IP address as a DoS attack and abort connections or return error pages for requests that would otherwise succeed.\nSo it might be a good idea to limit the number of concurrent requests to the same server to a relatively low number (5 should be on the safe side).\n", "Threading isn't necessary in this case. Your program is I/O bound rather than CPU bound. The networking part would probably be better done using select() on the sockets. This reduces the overhead of creating and maintaining threads. I haven't used Twisted, but I heard it has really good support for asynchronous networking. This would allow you you to specify the URLs you wish to download and register a callback for each. When each is downloaded you the callback will be called, and the page can be processed. In order to allow multiple sites to be downloaded, without waiting for each to be processed, a second \"worker\" thread can be created with a queue. The callback would add the site's contents to the queue. The \"worker\" thread would do the actual processing.\nAs already stated in some answers, the optimal amount of simultaneous downloads depends on your bandwidth.\nI'd use one or two threads - one for the actual crawling and the other (with a queue) for processing.\n" ]
[ 13, 7, 3, 3, 1, 1, 0 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0000623054_multithreading_python.txt
Q: Increment Page Hit Count in Django I have a table with an IntegerField (hit_count), and when a page is visited (for example, http://site/page/3) I want record ID 3's hit_count column in the database to increment by 1. The query should be like: update table set hit_count = hit_count + 1 where id = 3 Can I do this with the standard Django Model conventions? Or should I just write the query by hand? A: If you use Django 1.1+, just use F expressions: from django.db.models import F ... MyModel.objects.filter(id=...).update(hit_count=F('hit_count')+1) This will perform a single atomic database query. As gerdemb says, you should consider putting this in a middleware to make it easily reusable so it doesn't clutter up all your views. A: As gerdemb says, you should write it into a middleware to make it really reusable. Or (simpler) write a function decorator. In fact, there are adaptors to use a middleware as a decorator and viceversa. But if you're worried about performance and want to keep the DB queries per page hit low, you can use memcached's atomic increment operation. of course, in this case, you have to take care of persistence yourself. A: The model conventions won't be atomic; write it by hand: BEGIN SELECT * FROM table WHERE id=3 FOR UPDATE UPDATE table SET hit_count=hit_count+1 WHERE id=3 COMMIT A: I would start by looking at the documentation for middleware. Ignacio's comment about the lack of atomic transactions is true, but this is a problem with the entire Django framework. Unless you're concerned about having a 100% accurate counter I wouldn't worry about it.
Increment Page Hit Count in Django
I have a table with an IntegerField (hit_count), and when a page is visited (for example, http://site/page/3) I want record ID 3's hit_count column in the database to increment by 1. The query should be like: update table set hit_count = hit_count + 1 where id = 3 Can I do this with the standard Django Model conventions? Or should I just write the query by hand?
[ "If you use Django 1.1+, just use F expressions:\nfrom django.db.models import F\n...\nMyModel.objects.filter(id=...).update(hit_count=F('hit_count')+1)\n\nThis will perform a single atomic database query.\nAs gerdemb says, you should consider putting this in a middleware to make it easily reusable so it doesn't clutter up all your views.\n\n", "As gerdemb says, you should write it into a middleware to make it really reusable. Or (simpler) write a function decorator. In fact, there are adaptors to use a middleware as a decorator and viceversa.\nBut if you're worried about performance and want to keep the DB queries per page hit low, you can use memcached's atomic increment operation. of course, in this case, you have to take care of persistence yourself.\n", "The model conventions won't be atomic; write it by hand:\nBEGIN\nSELECT * FROM table WHERE id=3 FOR UPDATE\nUPDATE table SET hit_count=hit_count+1 WHERE id=3\nCOMMIT\n\n", "I would start by looking at the documentation for middleware. Ignacio's comment about the lack of atomic transactions is true, but this is a problem with the entire Django framework. Unless you're concerned about having a 100% accurate counter I wouldn't worry about it.\n" ]
[ 33, 4, 0, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0000622652_django_django_models_python.txt
Q: django login middleware not working as expected A quickie, and hopefully an easy one. I'm following the docs at http://docs.djangoproject.com/en/dev/topics/auth/ to get just some simple user authentication in place. I don't have any special requirements at all, I just need to know if a user is logged in or not, that's about it. I'm using the login_required decorator, and it's working exactly as I expected. I'm actually using the 'django.contrib.auth.views.login' for my login view, and the exact form they show in the docs: {% if form.errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} <form method="post" action="."> <table> <tr> <td>{{ form.username.label_tag }}</td> <td>{{ form.username }}</td> </tr> <tr> <td>{{ form.password.label_tag }}</td> <td>{{ form.password }}</td> </tr> </table> <input type="submit" value="login" /> <input type="hidden" name="next" value="{{ next }}" /> </form> What I guess I don't understand is why I can put whatever I want in the user/pass fields, and I never receive an error for invalid user/pass combo. I can put in non-existant users, correct users with right passwords, whatever I want basically, and it sends me off to whatever is in the 'next' variable. This leads me to believe that it's actually not doing anything whatsoever. I've checked what I'm sending via the request variables after logging in, and I'm always showing as an AnonymousUser, even though I "successfully logged in". Am I overlooking something blatantly obvious here? Seems like I've read that page on authentication 6 or 7 times now. Also, if I login as a user with "Staff Status", I show as authenticated without any issues. If the user doesn't have that status, then it doesn't work. A: I believe I fixed it: Right: url(r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'quiz/quiz_login.html'}) Wrong: url(r'^login$', 'django.contrib.auth.views.login', {'template_name': 'quiz/quiz_login.html'}) Meh.
django login middleware not working as expected
A quickie, and hopefully an easy one. I'm following the docs at http://docs.djangoproject.com/en/dev/topics/auth/ to get just some simple user authentication in place. I don't have any special requirements at all, I just need to know if a user is logged in or not, that's about it. I'm using the login_required decorator, and it's working exactly as I expected. I'm actually using the 'django.contrib.auth.views.login' for my login view, and the exact form they show in the docs: {% if form.errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} <form method="post" action="."> <table> <tr> <td>{{ form.username.label_tag }}</td> <td>{{ form.username }}</td> </tr> <tr> <td>{{ form.password.label_tag }}</td> <td>{{ form.password }}</td> </tr> </table> <input type="submit" value="login" /> <input type="hidden" name="next" value="{{ next }}" /> </form> What I guess I don't understand is why I can put whatever I want in the user/pass fields, and I never receive an error for invalid user/pass combo. I can put in non-existant users, correct users with right passwords, whatever I want basically, and it sends me off to whatever is in the 'next' variable. This leads me to believe that it's actually not doing anything whatsoever. I've checked what I'm sending via the request variables after logging in, and I'm always showing as an AnonymousUser, even though I "successfully logged in". Am I overlooking something blatantly obvious here? Seems like I've read that page on authentication 6 or 7 times now. Also, if I login as a user with "Staff Status", I show as authenticated without any issues. If the user doesn't have that status, then it doesn't work.
[ "I believe I fixed it:\nRight:\nurl(r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'quiz/quiz_login.html'})\n\nWrong:\nurl(r'^login$', 'django.contrib.auth.views.login', {'template_name': 'quiz/quiz_login.html'})\n\nMeh.\n" ]
[ 0 ]
[]
[]
[ "django", "django_authentication", "python" ]
stackoverflow_0000624043_django_django_authentication_python.txt
Q: Upgrading Python on OS X 10.4.11 I downloaded a package installer for Python 2.6.1, but when I use the python command in terminal (bash) Apple's shipped 2.3.5 version loads up. How can I get 2.6.1 to load up instead? A: You probably need to edit your ~/.profile file. It contains your PATH variable, which tells the command line where to find things. You can do so like this: export PATH=/path/to/new/python:$PATH That puts your new path as the first place to look. A: I am running Leopard, 10.5.5. The python binary, /usr/bin/python, is merely a symlink to the actual binary in the version specific Python folder. For example: $ ls -l /usr/bin/python lrwxr-xr-x 1 root wheel 72 Aug 31 2008 /usr/bin/python -> ../../System/Library/Frameworks/Python.framework/Versions/2.5/bin/python And a look inside that /Versions folder reveals this: $ ls -l /System/Library/Frameworks/Python.framework/Versions/ total 8 drwxr-xr-x 7 root wheel 238 Aug 31 2008 2.3 drwxr-xr-x 13 root wheel 442 Nov 22 20:40 2.5 lrwxr-xr-x 1 root wheel 3 Aug 31 2008 Current -> 2.5 With the help of the ln command to create symlinks, you will be able to set the python in your path to point to the version of python you want to use. A: Apart of making symlink or putting /usr/local at the front of PATH environment variable, you can try to make use of MacPorts. Installing Python from ports takes bit longer (it has to be compiled from source), but ports provide you with the most reliable way of installing PIL into your Python (apart of issuing sudo apt-get install python-imaging in Ubuntu...). A: you could try typing python2.6 instead of python. This may require you to set up your PATH "correctly" I'd recommend that if you'd like to do single machine python development on your Mac to use MacPorts. It gives you the control (since by default, everything gets installed in /opt/local) over which version of python you use (assuming you can modify your $PATH envariable). It also makes it simple and easy to have installed multiple versions of python simultaneously, along with their optional binary packages. The MacPorts path to python2.6 on my system is: /opt/local/bin/python2.6 if you use something like #!/usr/bin/env python2.6, you may need to modify your PATH environment variable to include MacPorts (or your other python2.6 version) in order to pull in the desired version of python when the script runs Here's an example command which assuming BASH shell, and the location to my MacPorts bin directory: export PATH=/opt/local/bin:$PATH A: As for putting environment variables in your profiles... If you're on Leopard, try putting them in /etc/paths.d see here for more...
Upgrading Python on OS X 10.4.11
I downloaded a package installer for Python 2.6.1, but when I use the python command in terminal (bash) Apple's shipped 2.3.5 version loads up. How can I get 2.6.1 to load up instead?
[ "You probably need to edit your ~/.profile file. It contains your PATH variable, which tells the command line where to find things. You can do so like this:\nexport PATH=/path/to/new/python:$PATH\n\nThat puts your new path as the first place to look.\n", "I am running Leopard, 10.5.5. The python binary, /usr/bin/python, is merely a symlink to the actual binary in the version specific Python folder. For example:\n$ ls -l /usr/bin/python\nlrwxr-xr-x 1 root wheel 72 Aug 31 2008 /usr/bin/python -> ../../System/Library/Frameworks/Python.framework/Versions/2.5/bin/python\n\nAnd a look inside that /Versions folder reveals this:\n$ ls -l /System/Library/Frameworks/Python.framework/Versions/\ntotal 8\ndrwxr-xr-x 7 root wheel 238 Aug 31 2008 2.3\ndrwxr-xr-x 13 root wheel 442 Nov 22 20:40 2.5\nlrwxr-xr-x 1 root wheel 3 Aug 31 2008 Current -> 2.5\n\nWith the help of the ln command to create symlinks, you will be able to set the python in your path to point to the version of python you want to use.\n", "Apart of making symlink or putting /usr/local at the front of PATH environment variable, you can try to make use of MacPorts. Installing Python from ports takes bit longer (it has to be compiled from source), but ports provide you with the most reliable way of installing PIL into your Python (apart of issuing sudo apt-get install python-imaging in Ubuntu...).\n", "you could try typing python2.6 instead of python. This may require you to set up your PATH \"correctly\"\nI'd recommend that if you'd like to do single machine python development on your Mac to use MacPorts. It gives you the control (since by default, everything gets installed in /opt/local) over which version of python you use (assuming you can modify your $PATH envariable). It also makes it simple and easy to have installed multiple versions of python simultaneously, along with their optional binary packages.\nThe MacPorts path to python2.6 on my system is:\n/opt/local/bin/python2.6\n\nif you use something like #!/usr/bin/env python2.6, you may need to modify your PATH environment variable to include MacPorts (or your other python2.6 version) in order to pull in the desired version of python when the script runs \nHere's an example command which assuming BASH shell, and the location to my MacPorts bin directory:\nexport PATH=/opt/local/bin:$PATH\n\n", "As for putting environment variables in your profiles... If you're on Leopard, try putting them in /etc/paths.d\nsee here for more...\n" ]
[ 4, 4, 1, 0, 0 ]
[]
[]
[ "bash", "macos", "python", "terminal" ]
stackoverflow_0000616480_bash_macos_python_terminal.txt
Q: How do I make a Django ModelForm menu item selected by default? I am working on a Django app. One of my models, "User", includes a "gender" field, as defined below: GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) gender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=True) I am using a ModelForm to generate a "new user" HTML form. My Google-fu seems to be failing me -- how can I make this HTML form have the "Male" item selected by default in the drop-down box? (i.e. so selected="selected" for this item.) A: If you need a blank form with a default value selected, then pass an 'initial' dictionary to the constructor of your model form using the name of your field as the key: form = MyModelForm (initial={'gender':'M'}) -OR- You can override certain attributes of a ModelForm using the declarative nature of the Forms API. However, this is probably a little cumbersome for this use case and I mention it only to show you that you can do it. You may find other uses for this in the future. class MyModelForm (forms.ModelForm): gender = forms.ChoiceField (choices=..., initial='M', ...) class Meta: model=MyModel -OR- If you want a ModelForm that is bound to a particular instance of your model, you can pass an 'instance' of your model which causes Django to pull the selected value from that model. form = MyModelForm (instance=someinst) A: Surely default will do the trick? e.g. gender = models.CharField(max_length=1, choices=GENDER_CHOICES, default='M', null=True)
How do I make a Django ModelForm menu item selected by default?
I am working on a Django app. One of my models, "User", includes a "gender" field, as defined below: GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) gender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=True) I am using a ModelForm to generate a "new user" HTML form. My Google-fu seems to be failing me -- how can I make this HTML form have the "Male" item selected by default in the drop-down box? (i.e. so selected="selected" for this item.)
[ "If you need a blank form with a default value selected, then pass an 'initial' dictionary to the constructor of your model form using the name of your field as the key:\nform = MyModelForm (initial={'gender':'M'})\n\n-OR-\nYou can override certain attributes of a ModelForm using the declarative nature of the Forms API. However, this is probably a little cumbersome for this use case and I mention it only to show you that you can do it. You may find other uses for this in the future.\nclass MyModelForm (forms.ModelForm):\n gender = forms.ChoiceField (choices=..., initial='M', ...)\n class Meta:\n model=MyModel\n\n-OR-\nIf you want a ModelForm that is bound to a particular instance of your model, you can pass an 'instance' of your model which causes Django to pull the selected value from that model. \nform = MyModelForm (instance=someinst)\n\n", "Surely default will do the trick?\ne.g.\ngender = models.CharField(max_length=1, choices=GENDER_CHOICES, default='M', null=True)\n" ]
[ 16, 8 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0000624265_django_django_forms_python.txt
Q: Why am I getting an invalid syntax easy_install error? I need to use easy_install to install a package. I installed the enthought distribution, and popped into IDLE to say: >>> easy_install SQLobject SyntaxError: invalid syntax What am I doing wrong? easy_install certainly exists, as does the package. help('easy_install') gives me some basic help. import easy_install doesn't change things either. Any hints? I know I'm missing something really basic here. A: easy_install is a shell command. You don't need to put it in a python script. easy_install SQLobject Type that straight into a bash (or other) shell, as long as easy_install is in your path.
Why am I getting an invalid syntax easy_install error?
I need to use easy_install to install a package. I installed the enthought distribution, and popped into IDLE to say: >>> easy_install SQLobject SyntaxError: invalid syntax What am I doing wrong? easy_install certainly exists, as does the package. help('easy_install') gives me some basic help. import easy_install doesn't change things either. Any hints? I know I'm missing something really basic here.
[ "easy_install is a shell command. You don't need to put it in a python script.\neasy_install SQLobject\n\nType that straight into a bash (or other) shell, as long as easy_install is in your path.\n" ]
[ 19 ]
[]
[]
[ "easy_install", "python" ]
stackoverflow_0000624492_easy_install_python.txt
Q: Setting up a Python web development environment on OS X I'm running Mac OS X Leopard and wanted to know what the easy way to setup a web development environment to use Python, MySQL, Apache on my machine which would allow me to develop on my Mac and then easily move it to a host in the future. I've been trying to get mod_wsgi installed and configured to work with Django and have a headache now. Are there any web hosts that currently use mod_wsgi besides Google, so I could just develop there? A: Most Python applications are moving away from mod_python. It can vary by framework or provider, but most development effort is going into mod_wsgi. Using the WSGI standard will make your Python application server agnostic, and allow for other nice additions like WSGI middleware. Other providers may only provide CGI (which won't scale well performance wise), or FastCGI. A: FWIW, we've found virtualenv [http://pypi.python.org/pypi/virtualenv] to be an invaluable part of our dev setup. We typically work on multiple projects that use different versions of Python libraries etc. It's very difficult to do this on one machine without some way to provide a localized, customized Python environment, as virtualenv does. A: I've worked with Django using only the included server in the manager.py script and have not had any trouble moving to a production environment. If you put your application in a host that does the environment configuration for you (like WebFaction) you should not have problems moving from development to production. A: I run a Linux virtual machine on my Mac laptop. This allows me to keep my development environment and production environments perfectly in sync (and make snapshots for easy experimentation / rollback). I've found VMWare Fusion works the best, but there are free open source alternatives such as VirtualBox if you just want to get your feet wet. I share the source folders from the guest Linux operating system on my Mac and edit them with the Mac source editor of my choosing (I use Eclipse / PyDev because the otherwise excellent TextMate doesn't deal well with Chinese text yet). I've documented the software setup for the guest Linux operating system here; it's optimized for serving multiple Django applications (including geodjango). For extra added fun, you can edit your Mac's /etc/hosts file to make yourdomainname.com resolve to your guest Linux boxes internal IP address and have a simple way to work on / test multiple web projects online or offline without too much hassle. A: What you're looking for is Mod_Python. It's an Apache-based interpreter for Python. Check it out here: http://www.modpython.org/ A: Google App Engine has done it for you. Some limitations but it works great, and it gives you a path to hosting free. A: Of course Mac OS X, in recent versions, comes with Python and Apache. However you may want to have more flexibility in the versions you use, or you may not like the tweaks Apple has made to the way they are configured. A good way to get a more generic set of tools, including MySQL, is to install them anew. This will help your portability issues. The frameworks can be installed relatively easily with one of these open source package providers. Fink MacPorts MAMP A: You may want to look into web2py. It includes an administration interface to develop via your browser. All you need in one package, including Python. A: Check out WebFaction—although I don't use them (nor am I related to / profit from their business in any way). I've read over and over how great their service is and particularly how Django-friendly they are. There's a specific post in their forums about getting up and running with Django and mod_wsgi. Like others before me in this thread, I highly recommend using Ian Bicking's virtualenv to isolate your development environment; there's a dedicated page in the mod_wsgi documentation for exactly that sort of setup. I'd also urge you to check out pip, which is basically a smarter easy_install which knows about virtualenv. Pip does two really nice things for virtualenv-style development: Knows how to install from source control (SVN, Git, etc...) Knows how to "freeze" an existing development environement's requirements so that you can create that environment somewhere else—very very nice for multiple developers or deployment. A: mod_wsgi is really, really simple. Pyerweb is a really simple (~90 lines including comments/whitespace) WSGI-compliant routing-framework I wrote. Basically the WSGI API is just a function that gets passed environ, and wsgi_start_response, and it returns a string. envrion is a dict with the request info, for example environ['PATH_INFO'] is the request URI) wsgi_start_response which is a callable function which you execute to set the headers,: wsgi_start_response(output_response, output_headers) output_response is the string containing the HTTP status you wish to send (200 OK etc), and output_headers is a list-of-tuples containing your headers (for example, [("Content-type", "text/html")] would set the content-type) Then the function returns a string containing your output.. That's all there is to it! To run it, using spawning you can just do spawn scriptname.my_wsgi_function_nae and it will start listening on port 8080. To use it via mod_wsgi, it's documentation is good, http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide and there is a django specific section The up-side to using mod_wsgi is it's the standard for serving Python web-applications. I recently decided to play with Google App Engine, and was surprised when Pyerweb (which I linked to at the start of this answer) worked perfectly on it, completely unintentionally. I was even more impressed when I noticed Django applications run on it too.. Standardisation is a good thing!
Setting up a Python web development environment on OS X
I'm running Mac OS X Leopard and wanted to know what the easy way to setup a web development environment to use Python, MySQL, Apache on my machine which would allow me to develop on my Mac and then easily move it to a host in the future. I've been trying to get mod_wsgi installed and configured to work with Django and have a headache now. Are there any web hosts that currently use mod_wsgi besides Google, so I could just develop there?
[ "Most Python applications are moving away from mod_python. It can vary by framework or provider, but most development effort is going into mod_wsgi.\nUsing the WSGI standard will make your Python application server agnostic, and allow for other nice additions like WSGI middleware. Other providers may only provide CGI (which won't scale well performance wise), or FastCGI.\n", "FWIW, we've found virtualenv [http://pypi.python.org/pypi/virtualenv] to be an invaluable part of our dev setup. We typically work on multiple projects that use different versions of Python libraries etc. It's very difficult to do this on one machine without some way to provide a localized, customized Python environment, as virtualenv does.\n", "I've worked with Django using only the included server in the manager.py script and have not had any trouble moving to a production environment.\nIf you put your application in a host that does the environment configuration for you (like WebFaction) you should not have problems moving from development to production.\n", "I run a Linux virtual machine on my Mac laptop. This allows me to keep my development environment and production environments perfectly in sync (and make snapshots for easy experimentation / rollback). I've found VMWare Fusion works the best, but there are free open source alternatives such as VirtualBox if you just want to get your feet wet.\nI share the source folders from the guest Linux operating system on my Mac and edit them with the Mac source editor of my choosing (I use Eclipse / PyDev because the otherwise excellent TextMate doesn't deal well with Chinese text yet). I've documented the software setup for the guest Linux operating system here; it's optimized for serving multiple Django applications (including geodjango).\nFor extra added fun, you can edit your Mac's /etc/hosts file to make yourdomainname.com resolve to your guest Linux boxes internal IP address and have a simple way to work on / test multiple web projects online or offline without too much hassle.\n", "What you're looking for is Mod_Python. It's an Apache-based interpreter for Python. Check it out here:\nhttp://www.modpython.org/\n", "Google App Engine has done it for you. Some limitations but it works great, and it gives you a path to hosting free.\n", "Of course Mac OS X, in recent versions, comes with Python and Apache. However you may want to have more flexibility in the versions you use, or you may not like the tweaks Apple has made to the way they are configured. A good way to get a more generic set of tools, including MySQL, is to install them anew. This will help your portability issues. The frameworks can be installed relatively easily with one of these open source package providers.\n\nFink\nMacPorts\nMAMP\n\n", "You may want to look into web2py. It includes an administration interface to develop via your browser. All you need in one package, including Python.\n", "Check out WebFaction—although I don't use them (nor am I related to / profit from their business in any way). I've read over and over how great their service is and particularly how Django-friendly they are. There's a specific post in their forums about getting up and running with Django and mod_wsgi.\nLike others before me in this thread, I highly recommend using Ian Bicking's virtualenv to isolate your development environment; there's a dedicated page in the mod_wsgi documentation for exactly that sort of setup. \nI'd also urge you to check out pip, which is basically a smarter easy_install which knows about virtualenv. Pip does two really nice things for virtualenv-style development:\n\nKnows how to install from source control (SVN, Git, etc...)\nKnows how to \"freeze\" an existing development environement's requirements so that you can create that environment somewhere else—very very nice for multiple developers or deployment.\n\n", "mod_wsgi is really, really simple.\nPyerweb is a really simple (~90 lines including comments/whitespace) WSGI-compliant routing-framework I wrote. Basically the WSGI API is just a function that gets passed environ, and wsgi_start_response, and it returns a string.\nenvrion is a dict with the request info, for example environ['PATH_INFO'] is the request URI)\nwsgi_start_response which is a callable function which you execute to set the headers,:\nwsgi_start_response(output_response, output_headers)\n\noutput_response is the string containing the HTTP status you wish to send (200 OK etc), and output_headers is a list-of-tuples containing your headers (for example, [(\"Content-type\", \"text/html\")] would set the content-type)\nThen the function returns a string containing your output.. That's all there is to it!\nTo run it, using spawning you can just do spawn scriptname.my_wsgi_function_nae and it will start listening on port 8080.\nTo use it via mod_wsgi, it's documentation is good, http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide and there is a django specific section\nThe up-side to using mod_wsgi is it's the standard for serving Python web-applications. I recently decided to play with Google App Engine, and was surprised when Pyerweb (which I linked to at the start of this answer) worked perfectly on it, completely unintentionally. I was even more impressed when I noticed Django applications run on it too.. Standardisation is a good thing!\n" ]
[ 2, 2, 1, 1, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "apache", "macos", "mysql", "python" ]
stackoverflow_0000266114_apache_macos_mysql_python.txt
Q: Why aren't signals simply called events? From what I can tell, in Python and and Django, signals are simply delegated events. Is there anything that functionally differentiates them from the typical notion of events in C#, Java, ActionScript, etc? A: Actually, "signals" have been around longer than events have. In the earliest usage, a signal was an asynchronous way for processes to get notified that events had occurred. Since Unix is much older than Django (and since a lot of the Django work came from pydispatcher, where the original stuff was done), the name has stuck. Events are really signals, you might say! A: Signals typically have an association with an operating system facility and events are typically application-defined. In some technology stacks, the OS-level stuff may be hidden well enough that there isn't a difference in the API, but in others perhaps not. A: Afaik Qt had the first signal/slot implementation. Qt's docs explain the metaphor: "A signal is emitted when a particular event occurs". The distinction is so subtle that the nomenclature has been blurred. A: You might as well ask "Why aren't events simply called signals?". Differences in terminology happen.
Why aren't signals simply called events?
From what I can tell, in Python and and Django, signals are simply delegated events. Is there anything that functionally differentiates them from the typical notion of events in C#, Java, ActionScript, etc?
[ "Actually, \"signals\" have been around longer than events have. In the earliest usage, a signal was an asynchronous way for processes to get notified that events had occurred. Since Unix is much older than Django (and since a lot of the Django work came from pydispatcher, where the original stuff was done), the name has stuck.\nEvents are really signals, you might say!\n", "Signals typically have an association with an operating system facility and events are typically application-defined. In some technology stacks, the OS-level stuff may be hidden well enough that there isn't a difference in the API, but in others perhaps not.\n", "Afaik Qt had the first signal/slot implementation. Qt's docs explain the metaphor: \"A signal is emitted when a particular event occurs\". The distinction is so subtle that the nomenclature has been blurred.\n", "You might as well ask \"Why aren't events simply called signals?\". Differences in terminology happen.\n" ]
[ 24, 4, 2, 1 ]
[]
[]
[ "django_signals", "python", "signals" ]
stackoverflow_0000624844_django_signals_python_signals.txt
Q: Best Resource for mysql + python 2.6 programming I need a great resource for interacting with MySql (version 5.0.45) with Python2.6. I'm using cherrypy, mako, the standard library, and nothing else. The resources can be blogs, howtos, books (online of offline), whatever. Additional information: The python mysql module, MySQLdb, is compatible with Python DB-API 2.0 . See http://sourceforge.net/projects/mysql-python. A: Python connectivity to DBs is accomplished (most of the times) through the DBI (Python Database API). The Python DBI has 2 versions and their documentation is the place for you to start: v.1 and v.2. You must check what version is supported by the MySQL connector and use the corresponding spec version. For more details about Python and MySQL, you can find good articles on Using MySQL With Python and here is the article that walks you through most of the operations: Writing MySQL Scripts with Python DB-API ./alex A: MySQL and Python discussions: http://forums.mysql.com/list.php?50
Best Resource for mysql + python 2.6 programming
I need a great resource for interacting with MySql (version 5.0.45) with Python2.6. I'm using cherrypy, mako, the standard library, and nothing else. The resources can be blogs, howtos, books (online of offline), whatever. Additional information: The python mysql module, MySQLdb, is compatible with Python DB-API 2.0 . See http://sourceforge.net/projects/mysql-python.
[ "Python connectivity to DBs is accomplished (most of the times) through the DBI (Python Database API). \nThe Python DBI has 2 versions and their documentation is the place for you to start:\nv.1 and v.2. You must check what version is supported by the MySQL connector and use the corresponding spec version.\nFor more details about Python and MySQL, you can find good articles on Using MySQL With Python and here is the article that walks you through most of the operations: Writing MySQL Scripts with Python DB-API\n./alex\n", "MySQL and Python discussions:\nhttp://forums.mysql.com/list.php?50\n" ]
[ 3, 2 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0000623276_mysql_python.txt
Q: Unable to install python-setuptools: ./configure: No such file or directory The question is related to the answer to "Unable to install Python without sudo access". I need to install python-setuptools to install python modules. I have extracted the installation package. I get the following error when configuring [~/wepapps/pythonModules/setuptools-0.6c9]# ./configure --prefix=/home/masi/.local -bash: ./configure: No such file or directory I did not find the solution at the program's homepage. How can I resolve this error? A: As Noah states, setuptools isn't an automake package so doesn't use ‘./configure’. Instead it's a pure-Python-style ‘setup.py’ (distutils) script. You shouldn't normally need to play with .pydistutils.cfg, as long as you run it with the right version of Python. So if you haven't added the .local/bin folder to PATH, you'd have to say explicitly: /home/masi/.local/bin/python setup.py install AIUI this should Just Work. I did not find the solution at the program's homepage. Yeah, they want you to install it from a shell script egg which uses the default version of Python. Which you don't want. (Another approach if you can't get setuptools to work is to skip it and install each module and dependency manually. Personally I have a bit of an aversion to setuptools/egg, as it contains far too much “clever” magic for my tastes and makes a mess of my filesystem. But I'm an old curmudgeon like that. Most Python modules can be obtained as simple Python files or plain old distutils scripts, but unfortunately there are some that demand eggs.) A: You might want to check http://peak.telecommunity.com/DevCenter/EasyInstall#custom-installation-locations. EasyInstall is a python module with some shell scripts (or some shell scripts with a python module?) and does not use the unix make tool that gets configured with the "./configure" command. It looks like your best bet is to try editing ~/.pydistutils.cfg to include: [install] install_lib = /home/masi/.local/lib/python/site-packages/ install_scripts = /home/masi/.local/bin You'll also presumably have made the ~/.local/bin/ folder part of your PATH so you can run the easy_install script. (I'm not sure exactly where the site-packages directory will be under .local, but it shouldn't be hard to find.) Hope this helps.
Unable to install python-setuptools: ./configure: No such file or directory
The question is related to the answer to "Unable to install Python without sudo access". I need to install python-setuptools to install python modules. I have extracted the installation package. I get the following error when configuring [~/wepapps/pythonModules/setuptools-0.6c9]# ./configure --prefix=/home/masi/.local -bash: ./configure: No such file or directory I did not find the solution at the program's homepage. How can I resolve this error?
[ "As Noah states, setuptools isn't an automake package so doesn't use ‘./configure’. Instead it's a pure-Python-style ‘setup.py’ (distutils) script.\nYou shouldn't normally need to play with .pydistutils.cfg, as long as you run it with the right version of Python. So if you haven't added the .local/bin folder to PATH, you'd have to say explicitly:\n/home/masi/.local/bin/python setup.py install\n\nAIUI this should Just Work.\n\nI did not find the solution at the program's homepage.\n\nYeah, they want you to install it from a shell script egg which uses the default version of Python. Which you don't want.\n(Another approach if you can't get setuptools to work is to skip it and install each module and dependency manually. Personally I have a bit of an aversion to setuptools/egg, as it contains far too much “clever” magic for my tastes and makes a mess of my filesystem. But I'm an old curmudgeon like that. Most Python modules can be obtained as simple Python files or plain old distutils scripts, but unfortunately there are some that demand eggs.)\n", "You might want to check http://peak.telecommunity.com/DevCenter/EasyInstall#custom-installation-locations.\nEasyInstall is a python module with some shell scripts (or some shell scripts with a python module?) and does not use the unix make tool that gets configured with the \"./configure\" command. It looks like your best bet is to try editing ~/.pydistutils.cfg to include:\n[install]\ninstall_lib = /home/masi/.local/lib/python/site-packages/\ninstall_scripts = /home/masi/.local/bin\n\nYou'll also presumably have made the ~/.local/bin/ folder part of your PATH so you can run the easy_install script. (I'm not sure exactly where the site-packages directory will be under .local, but it shouldn't be hard to find.)\nHope this helps.\n" ]
[ 2, 1 ]
[]
[]
[ "failed_installation", "python", "setuptools" ]
stackoverflow_0000624671_failed_installation_python_setuptools.txt
Q: python conditional lock How can I implement conditional lock in threaded application, for instance I haw 30 threads that are calling function and for most off the time all threads can access is simultaneous, but depending on function input there can be condition when only one thread can do that one thing. (If value for input is repeated and some thread is still working then I need lock.) I now that there is module threading with Rlock() but I don't now how to use it in a way that i described it in first part. Edit: The question is actually about how to prevent any two threads from running the same function with the same argument at the same time. (Thanks to David for helping me formulate my question :) ) A: Try this: have a lock in the module where your function is, and if the input to the function is such that locking is required, acquire the lock inside the function. Otherwise don't. l = threading.RLock() def fn(arg): if arg == arg_that_needs_lock: l.acquire() try: # do stuff finally: l.release() else: # do other stuff EDIT: As far as I can tell now, the question is actually about how to prevent any two threads from running the same function with the same argument at the same time. There's no problem with two threads running the same function with different arguments at the same time, though. The simple method to do this, if all valid arguments to the function can be dictionary keys, is to create a dictionary of arguments to locks: import threading dict_lock = threading.RLock() locks = {} def fn_dict(arg): dict_lock.acquire() try: if arg not in dict: locks[arg] = threading.RLock() l = locks[arg] finally: dict_lock.release() l.acquire() try: # do stuff finally: l.release() If your function can be called with many different arguments, though, that amounts to a lot of locks. Probably a better way is to have a set of all arguments with which the function is currently executing, and have the contents of that set protected by a lock. I think this should work: set_condition = threading.Condition() current_args = set() def fn_set(arg): set_condition.acquire() try: while arg in current_args: set_condition.wait() current_args.add(arg) finally: set_condition.release() # do stuff set_condition.acquire() try: current_args.remove(arg) set_condition.notifyAll() finally: set_condition.release() A: It sounds like you want something similar to a Readers-Writer lock. This is probably not what you want, but might be a clue: from __future__ import with_statement import threading def RWLock(readers = 1, writers = 1): m = _Monitor(readers, writers) return (_RWLock(m.r_increment, m.r_decrement), _RWLock(m.w_increment, m.w_decrement)) class _RWLock(object): def __init__(self, inc, dec): self.inc = inc self.dec = dec def acquire(self): self.inc() def release(self): self.dec() def __enter__(self): self.inc() def __exit__(self): self.dec() class _Monitor(object): def __init__(self, max_readers, max_writers): self.max_readers = max_readers self.max_writers = max_writers self.readers = 0 self.writers = 0 self.monitor = threading.Condition() def r_increment(self): with self.monitor: while self.writers > 0 and self.readers < self.max_readers: self.monitor.wait() self.readers += 1 self.monitor.notify() def r_decrement(self): with self.monitor: while self.writers > 0: self.monitor.wait() assert(self.readers > 0) self.readers -= 1 self.monitor.notify() def w_increment(self): with self.monitor: while self.readers > 0 and self.writers < self.max_writers: self.monitor.wait() self.writers += 1 self.monitor.notify() def w_decrement(self): with self.monitor: assert(self.writers > 0) self.writers -= 1 self.monitor.notify() if __name__ == '__main__': rl, wl = RWLock() wl.acquire() wl.release() rl.acquire() rl.release() (Unfortunately not tested)
python conditional lock
How can I implement conditional lock in threaded application, for instance I haw 30 threads that are calling function and for most off the time all threads can access is simultaneous, but depending on function input there can be condition when only one thread can do that one thing. (If value for input is repeated and some thread is still working then I need lock.) I now that there is module threading with Rlock() but I don't now how to use it in a way that i described it in first part. Edit: The question is actually about how to prevent any two threads from running the same function with the same argument at the same time. (Thanks to David for helping me formulate my question :) )
[ "Try this: have a lock in the module where your function is, and if the input to the function is such that locking is required, acquire the lock inside the function. Otherwise don't.\nl = threading.RLock()\n\ndef fn(arg):\n if arg == arg_that_needs_lock:\n l.acquire()\n try:\n # do stuff\n finally:\n l.release()\n else:\n # do other stuff\n\n\nEDIT:\nAs far as I can tell now, the question is actually about how to prevent any two threads from running the same function with the same argument at the same time. There's no problem with two threads running the same function with different arguments at the same time, though. The simple method to do this, if all valid arguments to the function can be dictionary keys, is to create a dictionary of arguments to locks:\nimport threading\n\ndict_lock = threading.RLock()\nlocks = {}\n\ndef fn_dict(arg):\n dict_lock.acquire()\n try:\n if arg not in dict:\n locks[arg] = threading.RLock()\n l = locks[arg]\n finally:\n dict_lock.release()\n l.acquire()\n try:\n # do stuff\n finally:\n l.release()\n\nIf your function can be called with many different arguments, though, that amounts to a lot of locks. Probably a better way is to have a set of all arguments with which the function is currently executing, and have the contents of that set protected by a lock. I think this should work:\nset_condition = threading.Condition()\ncurrent_args = set()\n\ndef fn_set(arg):\n set_condition.acquire()\n try:\n while arg in current_args:\n set_condition.wait()\n current_args.add(arg)\n finally:\n set_condition.release()\n # do stuff\n set_condition.acquire()\n try:\n current_args.remove(arg)\n set_condition.notifyAll()\n finally:\n set_condition.release()\n\n", "It sounds like you want something similar to a Readers-Writer lock.\nThis is probably not what you want, but might be a clue:\nfrom __future__ import with_statement\nimport threading\n\ndef RWLock(readers = 1, writers = 1):\n m = _Monitor(readers, writers)\n return (_RWLock(m.r_increment, m.r_decrement), _RWLock(m.w_increment, m.w_decrement))\n\nclass _RWLock(object):\n def __init__(self, inc, dec):\n self.inc = inc\n self.dec = dec\n\n def acquire(self):\n self.inc()\n def release(self):\n self.dec()\n def __enter__(self):\n self.inc()\n def __exit__(self):\n self.dec()\n\nclass _Monitor(object):\n def __init__(self, max_readers, max_writers):\n self.max_readers = max_readers\n self.max_writers = max_writers\n self.readers = 0\n self.writers = 0\n self.monitor = threading.Condition()\n\n def r_increment(self):\n with self.monitor:\n while self.writers > 0 and self.readers < self.max_readers:\n self.monitor.wait()\n self.readers += 1\n self.monitor.notify()\n\n def r_decrement(self):\n with self.monitor:\n while self.writers > 0:\n self.monitor.wait()\n assert(self.readers > 0)\n self.readers -= 1\n self.monitor.notify()\n\n def w_increment(self):\n with self.monitor:\n while self.readers > 0 and self.writers < self.max_writers:\n self.monitor.wait()\n self.writers += 1\n self.monitor.notify()\n\n def w_decrement(self):\n with self.monitor:\n assert(self.writers > 0)\n self.writers -= 1\n self.monitor.notify()\n\nif __name__ == '__main__':\n\n rl, wl = RWLock()\n wl.acquire()\n wl.release()\n rl.acquire()\n rl.release()\n\n(Unfortunately not tested)\n" ]
[ 6, 1 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0000625491_multithreading_python.txt
Q: How can I pass all the parameters to a decorator? I tried to trace the execution of some methods using a decorator. Here is the decorator code: def trace(func): def ofunc(*args): func_name = func.__name__ xargs = args print "entering %s with args %s" % (func_name,xargs) ret_val = func(args) print "return value %s" % ret_val print "exiting %s" % (func_name) return ofunc The thing is, if I try to apply this decorator to methods, the self parameter doesn't get sent. Can you tell me why, and how can I fix that? A: This line is incorrect: ret_val = func(args) You're forgetting to expand the argument list when you're passing it on. It should be: ret_val = func(*args) Sample output with this modification in place: >>> class Test2: ... @trace ... def test3(self, a, b): ... pass ... >>> t = Test2() >>> t.test3(1,2) entering test3 with args (<__main__.Test2 instance at 0x7ff2b42c>, 1, 2) return value None exiting test3 >>> If you ever expand your decorator to also take keyword arguments, you'd also need to expand those appropriately when passing them on, using **.
How can I pass all the parameters to a decorator?
I tried to trace the execution of some methods using a decorator. Here is the decorator code: def trace(func): def ofunc(*args): func_name = func.__name__ xargs = args print "entering %s with args %s" % (func_name,xargs) ret_val = func(args) print "return value %s" % ret_val print "exiting %s" % (func_name) return ofunc The thing is, if I try to apply this decorator to methods, the self parameter doesn't get sent. Can you tell me why, and how can I fix that?
[ "This line is incorrect:\nret_val = func(args)\n\nYou're forgetting to expand the argument list when you're passing it on. It should be:\nret_val = func(*args)\n\nSample output with this modification in place:\n>>> class Test2:\n... @trace\n... def test3(self, a, b):\n... pass\n... \n>>> t = Test2()\n>>> t.test3(1,2)\nentering test3 with args (<__main__.Test2 instance at 0x7ff2b42c>, 1, 2)\nreturn value None\nexiting test3\n>>> \n\nIf you ever expand your decorator to also take keyword arguments, you'd also need to expand those appropriately when passing them on, using **.\n" ]
[ 6 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0000625786_decorator_python.txt
Q: wxpython auinotebook close tab event What event is used when I close a tab in an auinotebook? I tested with EVT_AUINOTEBOOK_PAGE_CLOSE(D). It didn't work. I would also like to fire a right click on the tab itself event. Where can I find all the events that can be used with the aui manager/notebook? Might just be my poor searching skills, but I can't find any lists over the different events that exist, not for mouse/window events either. It would be really handy to have a complete list. #!/usr/bin/python #12_aui_notebook1.py import wx import wx.lib.inspection class MyFrame(wx.Frame): def __init__(self, *args, **kwds): wx.Frame.__init__(self, *args, **kwds) self.nb = wx.aui.AuiNotebook(self) self.new_panel('Page 1') self.new_panel('Page 2') self.new_panel('Page 3') self.nb.Bind(wx.EVT_AUINOTEBOOK_PAGE_CLOSED, self.close) def new_panel(self, nm): pnl = wx.Panel(self) pnl.identifierTag = nm self.nb.AddPage(pnl, nm) self.sizer = wx.BoxSizer() self.sizer.Add(self.nb, 1, wx.EXPAND) self.SetSizer(self.sizer) def close(self, event): print 'closed' class MyApp(wx.App): def OnInit(self): frame = MyFrame(None, -1, '12_aui_notebook1.py') frame.Show() self.SetTopWindow(frame) return 1 if __name__ == "__main__": app = MyApp(0) # wx.lib.inspection.InspectionTool().Show() app.MainLoop() Oerjan Pettersen A: This is the bind command you want: self.Bind(wx.aui.EVT_AUINOTEBOOK_PAGE_CLOSED, self.close, self.nb) To detect a right click on the tab (e.g. to show a custom context menu): self.Bind(wx.aui.EVT_AUINOTEBOOK_TAB_RIGHT_DOWN, self.right, self.nb) Here's a list of the aui notebook events: EVT_AUINOTEBOOK_PAGE_CLOSE EVT_AUINOTEBOOK_PAGE_CLOSED EVT_AUINOTEBOOK_PAGE_CHANGED EVT_AUINOTEBOOK_PAGE_CHANGING EVT_AUINOTEBOOK_BUTTON EVT_AUINOTEBOOK_BEGIN_DRAG EVT_AUINOTEBOOK_END_DRAG EVT_AUINOTEBOOK_DRAG_MOTION EVT_AUINOTEBOOK_ALLOW_DND EVT_AUINOTEBOOK_DRAG_DONE EVT_AUINOTEBOOK_BG_DCLICK EVT_AUINOTEBOOK_TAB_MIDDLE_DOWN EVT_AUINOTEBOOK_TAB_MIDDLE_UP EVT_AUINOTEBOOK_TAB_RIGHT_DOWN EVT_AUINOTEBOOK_TAB_RIGHT_UP From: {python folder}/Lib/site-packages/{wxpython folder}/wx/aui.py
wxpython auinotebook close tab event
What event is used when I close a tab in an auinotebook? I tested with EVT_AUINOTEBOOK_PAGE_CLOSE(D). It didn't work. I would also like to fire a right click on the tab itself event. Where can I find all the events that can be used with the aui manager/notebook? Might just be my poor searching skills, but I can't find any lists over the different events that exist, not for mouse/window events either. It would be really handy to have a complete list. #!/usr/bin/python #12_aui_notebook1.py import wx import wx.lib.inspection class MyFrame(wx.Frame): def __init__(self, *args, **kwds): wx.Frame.__init__(self, *args, **kwds) self.nb = wx.aui.AuiNotebook(self) self.new_panel('Page 1') self.new_panel('Page 2') self.new_panel('Page 3') self.nb.Bind(wx.EVT_AUINOTEBOOK_PAGE_CLOSED, self.close) def new_panel(self, nm): pnl = wx.Panel(self) pnl.identifierTag = nm self.nb.AddPage(pnl, nm) self.sizer = wx.BoxSizer() self.sizer.Add(self.nb, 1, wx.EXPAND) self.SetSizer(self.sizer) def close(self, event): print 'closed' class MyApp(wx.App): def OnInit(self): frame = MyFrame(None, -1, '12_aui_notebook1.py') frame.Show() self.SetTopWindow(frame) return 1 if __name__ == "__main__": app = MyApp(0) # wx.lib.inspection.InspectionTool().Show() app.MainLoop() Oerjan Pettersen
[ "This is the bind command you want:\nself.Bind(wx.aui.EVT_AUINOTEBOOK_PAGE_CLOSED, self.close, self.nb)\n\nTo detect a right click on the tab (e.g. to show a custom context menu):\nself.Bind(wx.aui.EVT_AUINOTEBOOK_TAB_RIGHT_DOWN, self.right, self.nb)\n\nHere's a list of the aui notebook events:\nEVT_AUINOTEBOOK_PAGE_CLOSE\nEVT_AUINOTEBOOK_PAGE_CLOSED\nEVT_AUINOTEBOOK_PAGE_CHANGED\nEVT_AUINOTEBOOK_PAGE_CHANGING\nEVT_AUINOTEBOOK_BUTTON\nEVT_AUINOTEBOOK_BEGIN_DRAG\nEVT_AUINOTEBOOK_END_DRAG\nEVT_AUINOTEBOOK_DRAG_MOTION\nEVT_AUINOTEBOOK_ALLOW_DND\nEVT_AUINOTEBOOK_DRAG_DONE\nEVT_AUINOTEBOOK_BG_DCLICK\nEVT_AUINOTEBOOK_TAB_MIDDLE_DOWN\nEVT_AUINOTEBOOK_TAB_MIDDLE_UP\nEVT_AUINOTEBOOK_TAB_RIGHT_DOWN\nEVT_AUINOTEBOOK_TAB_RIGHT_UP\n\nFrom: {python folder}/Lib/site-packages/{wxpython folder}/wx/aui.py\n" ]
[ 8 ]
[]
[]
[ "python", "wxpython", "wxwidgets" ]
stackoverflow_0000625714_python_wxpython_wxwidgets.txt
Q: Using Django admin look and feel in my own application I like the very simple but still really elegant look and feel of the django admin and I was wondering if there is a way to apply it to my own application. (I think that I've read something like that somewhere, but now I cannot find the page again.) (edited: what I am looking for is a way to do it automatically by extending templates, importing modules, or something similar, not just copy&paste the css and javascript code) A: Are you sure you want to take every bit of admin-site's look & feel?? I think you would need to customize some, as in header footer etc. To do that, just copy base.html from "djangosrc/contrib/admin/templates/admin/" and keep it in "your_template_dir/admin/base.html" or "your_template_dir/admin/mybase.html" Just change whatever HTML you want to customize and keep rest as it is (like CSS and Javascript) and keep on extending this template in other templates of your application. Your view should provide what it needs to render (take a look at any django view from source) and you'll have everything what admin look & feel had. More you can do by extending base_site.html in same manner. (Note: if you keep the name 'base.html' the changes made in html will affect Django Admin too. As this is the way we change how Django Admin look itself.) A: {% extends "admin/base_site.html" %} is usually a good place to start but do look at the templates in contrib/admin/templates and copy some of the techniques there.
Using Django admin look and feel in my own application
I like the very simple but still really elegant look and feel of the django admin and I was wondering if there is a way to apply it to my own application. (I think that I've read something like that somewhere, but now I cannot find the page again.) (edited: what I am looking for is a way to do it automatically by extending templates, importing modules, or something similar, not just copy&paste the css and javascript code)
[ "Are you sure you want to take every bit of admin-site's look & feel??\nI think you would need to customize some, as in header footer etc.\nTo do that, just copy base.html from \n\n\"djangosrc/contrib/admin/templates/admin/\"\n\nand keep it in \n\n\"your_template_dir/admin/base.html\" or\n \"your_template_dir/admin/mybase.html\"\n\nJust change whatever HTML you want to customize and keep rest as it is (like CSS and Javascript) and keep on extending this template in other templates of your application. Your view should provide what it needs to render (take a look at any django view from source) and you'll have everything what admin look & feel had. More you can do by extending base_site.html in same manner.\n\n(Note: if you keep the name\n 'base.html' the changes made in\n html will affect Django Admin too.\n As this is the way we change how\n Django Admin look itself.)\n\n", "{% extends \"admin/base_site.html\" %}\n\nis usually a good place to start but do look at the templates in contrib/admin/templates and copy some of the techniques there. \n" ]
[ 4, 4 ]
[]
[]
[ "django", "django_admin", "look_and_feel", "python", "styles" ]
stackoverflow_0000624535_django_django_admin_look_and_feel_python_styles.txt
Q: Store Django form.cleaned_data in null model field? I have a django model, which has a int field (with null=True, blank=True). Now when I get a form submit from the user, I assign it like so: my_model.width= form.cleaned_data['width'] However sometimes I get an error: ValueError: invalid literal for int() with base 10: '' I was wandering if it's the blank ('') string value that gets assigned to the field? Because my understanding was the model will treat blank string as null/blank? Any help would be appreciated in this matter. Thanks. A: No, it doesn't. If you want to assign NULL, use Python's None. Otherwise Django will try to parse a number from the string and that fails for the empty string. You can use the or construct to achieve this: my_model.width = form.cleaned_data['width'] or None
Store Django form.cleaned_data in null model field?
I have a django model, which has a int field (with null=True, blank=True). Now when I get a form submit from the user, I assign it like so: my_model.width= form.cleaned_data['width'] However sometimes I get an error: ValueError: invalid literal for int() with base 10: '' I was wandering if it's the blank ('') string value that gets assigned to the field? Because my understanding was the model will treat blank string as null/blank? Any help would be appreciated in this matter. Thanks.
[ "No, it doesn't. If you want to assign NULL, use Python's None. Otherwise Django will try to parse a number from the string and that fails for the empty string. \nYou can use the or construct to achieve this:\nmy_model.width = form.cleaned_data['width'] or None\n\n" ]
[ 5 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000625977_django_python.txt
Q: Loading bundled python framework dependencies using only python I've come across this question but I don't like the solution that is presented. Shell scripting is operating system dependent. Is there a python solution to this problem? I'm not looking for python to machine code compilers, just a way to modify the include paths with python. A: Generally speaking, python follows the paths in sys.path when trying to resolve library dependencies. sys.path is a list, and it is searched in order. If your application modified sys.path on load to put its own library paths at the front, this should do the trick. This section from the python docs has a good explanation of how python finds its dependencies: https://docs.python.org/reference/simple_stmts.html#the-import-statement. A: Well, as far as I know there are many different pieces of advice on how to do it. Here are 2 approaches that may help you distribute your app I/ . include all dependencies in my project directory structure . manipulate the sys.path to make sure that the app is always looking in my dir structure before looking into the system available modules (Disclaimer: this solution might not work if C libs are involved) II/ Another approach is using a tool like EasyInstall and eggs. This solution might be a bit more complex, but it will offer you a lot of freedom on how to configure your app and its dependencies (plus it will work with C dependencies). ./alex
Loading bundled python framework dependencies using only python
I've come across this question but I don't like the solution that is presented. Shell scripting is operating system dependent. Is there a python solution to this problem? I'm not looking for python to machine code compilers, just a way to modify the include paths with python.
[ "Generally speaking, python follows the paths in sys.path when trying to resolve library dependencies. sys.path is a list, and it is searched in order. If your application modified sys.path on load to put its own library paths at the front, this should do the trick.\nThis section from the python docs has a good explanation of how python finds its dependencies: https://docs.python.org/reference/simple_stmts.html#the-import-statement.\n", "Well, as far as I know there are many different pieces of advice on how to do it. \nHere are 2 approaches that may help you distribute your app\nI/\n. include all dependencies in my project directory structure\n. manipulate the sys.path to make sure that the app is always looking in my dir structure before looking into the system available modules\n(Disclaimer: this solution might not work if C libs are involved)\nII/\nAnother approach is using a tool like EasyInstall and eggs. This solution might be a bit more complex, but it will offer you a lot of freedom on how to configure your app and its dependencies (plus it will work with C dependencies).\n./alex\n" ]
[ 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0000626157_python.txt
Q: Is it possible to write to a python frame object as returned by sys._getframe() from python code running within the interpreter? Apropos of This question, there is a bit of scaffolding within the interpreter to inspect frame objects, which can be retrieved by sys._getframe(). The frame objects appear to be read only, but I can't find anything obvious in the docs that explicitly states this. Can someone confirm whether these objects are writeable (in some way) or read only? import sys def foobar(): xx='foo' ff = sys._getframe() ff.f_locals['xx'] = 'bar' print xx if __name__ == '__main__': foobar() This prints out 'foo' when run but the post below demonstrates the variable being writable when run from the current frame in an interactive shell. A: From CPython source, Objects/frameobject.c: static PyMemberDef frame_memberlist[] = { {"f_back", T_OBJECT, OFF(f_back), RO}, {"f_code", T_OBJECT, OFF(f_code), RO}, {"f_builtins", T_OBJECT, OFF(f_builtins),RO}, {"f_globals", T_OBJECT, OFF(f_globals), RO}, {"f_lasti", T_INT, OFF(f_lasti), RO}, {"f_exc_type", T_OBJECT, OFF(f_exc_type)}, {"f_exc_value", T_OBJECT, OFF(f_exc_value)}, {"f_exc_traceback", T_OBJECT, OFF(f_exc_traceback)}, {NULL} /* Sentinel */ }; ... static PyGetSetDef frame_getsetlist[] = { {"f_locals", (getter)frame_getlocals, NULL, NULL}, {"f_lineno", (getter)frame_getlineno, (setter)frame_setlineno, NULL}, {"f_trace", (getter)frame_gettrace, (setter)frame_settrace, NULL}, {"f_restricted",(getter)frame_getrestricted,NULL, NULL}, {0} }; For the PyMemberDef, the flags RO or READONLY means it's attributes are read-only. For the PyGetSetDef, if it only has a getter, it's read only. This means all attributes but f_exc_type, f_exc_value, f_exc_traceback and f_trace are read-only after creation. This is also mentioned in the docs, under Data model. The objects referred to by the attributes is not necessarily read-only. You could do this: >>> f = sys._getframe() >>> f.f_locals['foo'] = 3 >>> foo 3 >>> Though this works in the interpreter, it fails inside functions. The execution engine uses a separate array for local variables (f_fastlocals), which is merged into f_locals on access, but the converse is not true. >>> def foo(): ... x = 3 ... f = sys._getframe() ... print f.f_locals['x'] ... x = 4 ... print f.f_locals['x'] ... d = f.f_locals ... x = 5 ... print d['x'] ... f.f_locals ... print d['x'] ... >>> foo() 3 4 4 5 >>> On the global frame, f_local refers to f_globals, which makes this trick work in the interpreter. Modifying f_globals works, but affects the whole module. A: The f_locals['foo'] example by NXC works because the code is in module scope. In that case, f_locals is f_globals, and f_globals is both modifiable and modifications are reflected in the module. Inside of function scope, locals() and f_locals are writable, but "[changes may not affect the values of local variables used by the interpreter]." 1 It's an implementation choice. In CPython there's a optimized bytecode for local variables, LOAD_FAST. In Python, local variables are (almost always) known once the function is defined, and CPython uses an index lookup to get the variable value, rather than a dictionary lookup. In theory the dictionary lookup could proxy that table, but that's a lot of work for little gain. The exceptions to "local variables are known" are if the function uses an exec statement, and the deprecated case of "from module import *". The generated byte code is different, and slower, for these cases.
Is it possible to write to a python frame object as returned by sys._getframe() from python code running within the interpreter?
Apropos of This question, there is a bit of scaffolding within the interpreter to inspect frame objects, which can be retrieved by sys._getframe(). The frame objects appear to be read only, but I can't find anything obvious in the docs that explicitly states this. Can someone confirm whether these objects are writeable (in some way) or read only? import sys def foobar(): xx='foo' ff = sys._getframe() ff.f_locals['xx'] = 'bar' print xx if __name__ == '__main__': foobar() This prints out 'foo' when run but the post below demonstrates the variable being writable when run from the current frame in an interactive shell.
[ "From CPython source, Objects/frameobject.c:\nstatic PyMemberDef frame_memberlist[] = {\n {\"f_back\", T_OBJECT, OFF(f_back), RO},\n {\"f_code\", T_OBJECT, OFF(f_code), RO},\n {\"f_builtins\", T_OBJECT, OFF(f_builtins),RO},\n {\"f_globals\", T_OBJECT, OFF(f_globals), RO},\n {\"f_lasti\", T_INT, OFF(f_lasti), RO},\n {\"f_exc_type\", T_OBJECT, OFF(f_exc_type)},\n {\"f_exc_value\", T_OBJECT, OFF(f_exc_value)},\n {\"f_exc_traceback\", T_OBJECT, OFF(f_exc_traceback)},\n {NULL} /* Sentinel */\n};\n...\nstatic PyGetSetDef frame_getsetlist[] = {\n {\"f_locals\", (getter)frame_getlocals, NULL, NULL},\n {\"f_lineno\", (getter)frame_getlineno,\n (setter)frame_setlineno, NULL},\n {\"f_trace\", (getter)frame_gettrace, (setter)frame_settrace, NULL},\n {\"f_restricted\",(getter)frame_getrestricted,NULL, NULL},\n {0}\n};\n\nFor the PyMemberDef, the flags RO or READONLY means it's attributes are read-only. For the PyGetSetDef, if it only has a getter, it's read only. This means all attributes but f_exc_type, f_exc_value, f_exc_traceback and f_trace are read-only after creation. This is also mentioned in the docs, under Data model.\nThe objects referred to by the attributes is not necessarily read-only. You could do this:\n>>> f = sys._getframe()\n>>> f.f_locals['foo'] = 3\n>>> foo\n3\n>>>\n\nThough this works in the interpreter, it fails inside functions. The execution engine uses a separate array for local variables (f_fastlocals), which is merged into f_locals on access, but the converse is not true.\n>>> def foo():\n... x = 3\n... f = sys._getframe()\n... print f.f_locals['x']\n... x = 4\n... print f.f_locals['x']\n... d = f.f_locals\n... x = 5\n... print d['x']\n... f.f_locals\n... print d['x']\n...\n>>> foo()\n3\n4\n4\n5\n>>>\n\nOn the global frame, f_local refers to f_globals, which makes this trick work in the interpreter. Modifying f_globals works, but affects the whole module.\n", "The f_locals['foo'] example by NXC works because the code is in module scope. In that case, f_locals is f_globals, and f_globals is both modifiable and modifications are reflected in the module.\nInside of function scope, locals() and f_locals are writable, but \"[changes may not affect the values of local variables used by the interpreter].\" 1 It's an implementation choice. In CPython there's a optimized bytecode for local variables, LOAD_FAST. In Python, local variables are (almost always) known once the function is defined, and CPython uses an index lookup to get the variable value, rather than a dictionary lookup.\nIn theory the dictionary lookup could proxy that table, but that's a lot of work for little gain.\nThe exceptions to \"local variables are known\" are if the function uses an exec statement, and the deprecated case of \"from module import *\". The generated byte code is different, and slower, for these cases.\n" ]
[ 13, 1 ]
[]
[]
[ "frame", "introspection", "python", "sys" ]
stackoverflow_0000626835_frame_introspection_python_sys.txt
Q: File editing in python I wrote a little python program as a personal utility to help me with some refactoring. It's similar to unix replace, except it supports regular expressions and operates on all files in a directory and (optionally) all subdirectories. The problem is I'm not replacing in place. I'm opening files, passing the contents into memory, and then overwriting the file, like so: file = open('path/to/file','r') in_string = file.read() file.close() # ... #Processing logic # ... file = open('path/to/file','w') file.write(out_string) file.close() Besides the obvious performance/memory concerns, which are legitimate, but not so much a problem for my use, there's another drawback to this method. SVN freaks out. I can do some copy and paste workarounds after the fact to fix the checksum error that svn throws on a commit, but it makes the utility pointless. Is there a better way to do this? I'm guessing that if I were editing the file in place there wouldn't be any sort of problem. How do I go about that? A: I suspect the problem is that you are in fact editing wrong files. Subversion should never raise any errors about check sums when you are just modifying your tracked files -- independently of how you are modifying them. Maybe you are accidentally editing files in the .svn directory? In .svn/text-base, Subversion stores copies of your files using the same name plus the extension .svn-base, make sure that you are not editing those! A: What do you mean by "SVN freaks out"? Anyway, the way vi/emacs/etc works is as follows: f = open("/path/to/.file.tmp", "w") f.write(out_string) f.close() os.rename("/path/to/.file.tmp", "/path/to/file") (ok, there's actually an "fsync" in there... But I don't know off hand how to do that in Python) The reason it does that copy is to ensure that, if the system dies half way through writing the new file, the old one is still there... And the 'rename' operation is defined as being atomic, so it will either work (you get 100% of the new file) or not work (you get 100% of the old file) -- you'll never be left with a half-file. A: Perhaps the fileinput module can make your code simpler/shorter: Here's an example: import fileinput for line in fileinput.input("test.txt", inplace=1): print "%d: %s" % (fileinput.filelineno(), line), A: Freaks out how? What you're describing, if it's working, is editing the file "in place", at least as much as vi(1) does. A: Try 'file = open('path/to/file', 'w+')'. This means you are updating an existing file, not writing a new one. A: I suspect Ferdinand's answer, that you are recursing into the .svn dir, explains why you are messing up SVN, but note that there is another flaw in the way you are processing files. If your program is killed, or your computer crashes at the wrong point (when you are writing out the changed contents), you risk losing both the original and new contents of the file. A more robust approach is to perform the following steps: Read the file into memory, and perform your translations Write the new contents to "filename.new", rather than the original filename. Delete the original file, and rename "filename.new" to "filename" This way, you won't risk losing data if killed at the wrong point. Note that the fileinput module will handle much of this for you. It can be given a sequence of files to process, and if you specify inplace=True, will redirect stdout to the appropriate file (keeping a backup). You could then structure your code something like: import os import fileinput def allfiles(dir, ignore_dirs=set(['.svn'])): """Generator yielding all writable filenames below dir. Ignores directories specified """ for basedir, dirs, files in os.walk(dir): if basedir in ignore_dirs: dirs[:]=[] # Don't recurse continue # Skip this directory for filename in files: filename = os.path.join(basedir, filename) # Check the file is writable if os.access(filename, os.W_OK): yield filename for line in fileinput.input(allfiles(PATH_TO_PROCESS), inplace=True): line = perform_some_substitution(line) print line.rstrip("\n") # Print adds a newline, but line already has one
File editing in python
I wrote a little python program as a personal utility to help me with some refactoring. It's similar to unix replace, except it supports regular expressions and operates on all files in a directory and (optionally) all subdirectories. The problem is I'm not replacing in place. I'm opening files, passing the contents into memory, and then overwriting the file, like so: file = open('path/to/file','r') in_string = file.read() file.close() # ... #Processing logic # ... file = open('path/to/file','w') file.write(out_string) file.close() Besides the obvious performance/memory concerns, which are legitimate, but not so much a problem for my use, there's another drawback to this method. SVN freaks out. I can do some copy and paste workarounds after the fact to fix the checksum error that svn throws on a commit, but it makes the utility pointless. Is there a better way to do this? I'm guessing that if I were editing the file in place there wouldn't be any sort of problem. How do I go about that?
[ "I suspect the problem is that you are in fact editing wrong files. Subversion should never raise any errors about check sums when you are just modifying your tracked files -- independently of how you are modifying them.\nMaybe you are accidentally editing files in the .svn directory? In .svn/text-base, Subversion stores copies of your files using the same name plus the extension .svn-base, make sure that you are not editing those!\n", "What do you mean by \"SVN freaks out\"?\nAnyway, the way vi/emacs/etc works is as follows:\nf = open(\"/path/to/.file.tmp\", \"w\")\nf.write(out_string)\nf.close()\nos.rename(\"/path/to/.file.tmp\", \"/path/to/file\")\n\n(ok, there's actually an \"fsync\" in there... But I don't know off hand how to do that in Python)\nThe reason it does that copy is to ensure that, if the system dies half way through writing the new file, the old one is still there... And the 'rename' operation is defined as being atomic, so it will either work (you get 100% of the new file) or not work (you get 100% of the old file) -- you'll never be left with a half-file.\n", "Perhaps the fileinput module can make your code simpler/shorter:\nHere's an example:\nimport fileinput\n\nfor line in fileinput.input(\"test.txt\", inplace=1):\n print \"%d: %s\" % (fileinput.filelineno(), line),\n\n", "Freaks out how? What you're describing, if it's working, is editing the file \"in place\", at least as much as vi(1) does.\n", "Try 'file = open('path/to/file', 'w+')'. This means you are updating an existing file, not writing a new one.\n", "I suspect Ferdinand's answer, that you are recursing into the .svn dir, explains why you are messing up SVN, but note that there is another flaw in the way you are processing files.\nIf your program is killed, or your computer crashes at the wrong point (when you are writing out the changed contents), you risk losing both the original and new contents of the file. A more robust approach is to perform the following steps:\n\nRead the file into memory, and perform your translations\nWrite the new contents to \"filename.new\", rather than the original filename.\nDelete the original file, and rename \"filename.new\" to \"filename\"\n\nThis way, you won't risk losing data if killed at the wrong point. Note that the fileinput module will handle much of this for you. It can be given a sequence of files to process, and if you specify inplace=True, will redirect stdout to the appropriate file (keeping a backup). You could then structure your code something like:\nimport os\nimport fileinput\n\ndef allfiles(dir, ignore_dirs=set(['.svn'])):\n \"\"\"Generator yielding all writable filenames below dir.\n Ignores directories specified \n \"\"\"\n for basedir, dirs, files in os.walk(dir):\n if basedir in ignore_dirs:\n dirs[:]=[] # Don't recurse\n continue # Skip this directory\n\n for filename in files:\n filename = os.path.join(basedir, filename)\n # Check the file is writable\n if os.access(filename, os.W_OK):\n yield filename\n\n\nfor line in fileinput.input(allfiles(PATH_TO_PROCESS), inplace=True):\n line = perform_some_substitution(line)\n print line.rstrip(\"\\n\") # Print adds a newline, but line already has one\n\n" ]
[ 8, 2, 1, 0, 0, 0 ]
[]
[]
[ "python", "svn" ]
stackoverflow_0000626617_python_svn.txt
Q: Select mails from inbox alone via poplib I need to download emails from the gmail inbox only using poplib.Unfortunately I do not see any option to select Inbox alone, and poplib gives me emails from sent items too. How do I select emails only from inbox? I dont want to use any gmail specific libraries. A: POP3 has no concept of 'folders'. If gmail is showing you both 'sent' as well as 'received' mail, then you really don't have any option but to receive all that email. Perhaps you would be better off using IMAP4 instead of POP3. Python has libraries that will work with gmail's IMAP4 server. A: I assume you have enabled POP3/IMAP access to your GMail account. This is sample code: import imaplib conn= imaplib.IMAP4_SSL('imap.googlemail.com') conn.login('yourusername', 'yourpassword') code, dummy= conn.select('INBOX') if code != 'OK': raise RuntimeError, "Failed to select inbox" code, data= self.conn.search(None, ALL) if code == 'OK': msgid_list= data[0].split() else: raise RuntimeError, "Failed to get message IDs" for msgid in msgid_list: code, data= conn.fetch(msgid, '(RFC822)') # you can also use '(RFC822.HEADER)' only for headers if code == 'OK': pass # your code here else: raise RuntimeError, "could not retrieve msgid %r" % msgid conn.close() conn.logout() or something like this. A: This Java code would suggest that you can select a particular "folder" to download, even when using POP3. Again, this is using Java, not Python so YMMV. How to download message from GMail using Java (blog post discusses pushing content into a Lucene search engine locally)
Select mails from inbox alone via poplib
I need to download emails from the gmail inbox only using poplib.Unfortunately I do not see any option to select Inbox alone, and poplib gives me emails from sent items too. How do I select emails only from inbox? I dont want to use any gmail specific libraries.
[ "POP3 has no concept of 'folders'. If gmail is showing you both 'sent' as well as 'received' mail, then you really don't have any option but to receive all that email.\nPerhaps you would be better off using IMAP4 instead of POP3. Python has libraries that will work with gmail's IMAP4 server.\n", "I assume you have enabled POP3/IMAP access to your GMail account.\nThis is sample code:\nimport imaplib\nconn= imaplib.IMAP4_SSL('imap.googlemail.com')\nconn.login('yourusername', 'yourpassword')\ncode, dummy= conn.select('INBOX')\nif code != 'OK':\n raise RuntimeError, \"Failed to select inbox\"\n\ncode, data= self.conn.search(None, ALL)\nif code == 'OK':\n msgid_list= data[0].split()\nelse:\n raise RuntimeError, \"Failed to get message IDs\"\n\nfor msgid in msgid_list:\n code, data= conn.fetch(msgid, '(RFC822)')\n # you can also use '(RFC822.HEADER)' only for headers\n if code == 'OK':\n pass # your code here\n else:\n raise RuntimeError, \"could not retrieve msgid %r\" % msgid\n\nconn.close()\nconn.logout()\n\nor something like this.\n", "This Java code would suggest that you can select a particular \"folder\" to download, even when using POP3. Again, this is using Java, not Python so YMMV.\nHow to download message from GMail using Java (blog post discusses pushing content into a Lucene search engine locally)\n" ]
[ 4, 3, 2 ]
[]
[]
[ "gmail", "pop3", "poplib", "python" ]
stackoverflow_0000625148_gmail_pop3_poplib_python.txt
Q: wx's idle and UI update events in PyQt wx (and wxPython) has two events I miss in PyQt: EVT_IDLE that's being sent to a frame. It can be used to update the various widgets according to the application's state EVT_UPDATE_UI that's being sent to a widget when it has to be repainted and updated, so I can compute its state in the handler Now, PyQt doesn't seem to have these, and the PyQt book suggests writing an updateUi method and calling it manually. I even ended up calling it from a timer once per 0.1 seconds, in order to avoid many manual calls from methods that may update the GUI. Am I missing something? Is there a better way to achieve this? An example: I have a simple app with a Start button that initiates some processing. The start button should be enabled only when a file has been opened using the menu. In addition, there's a permanent widget on the status bar that displays information. My application has states: Before the file is opened (in this state the status bar show something special and the start button is disabled) File was opened and processing wasn't started: the start button is enabled, status bar shows something else The processing is running: the start button now says "Stop", and the status bar reports progress In Wx, I'd have the update UI event of the button handle its state: the text on it, and whether it's enabled, depending on the application state. The same for the status bar (or I'd use EVT_IDLE for that). In Qt, I have to update the button in several methods that may affect the state, or just create a update_ui method and call it periodically in a timer. What is the more "QT"-ish way? A: The use of EVT_UPDATE_UI in wxWidgets seems to highlight one of the fundamental differences in the way wxWidgets and Qt expect developers to handle events in their code. With Qt, you connect signals and slots between widgets in the user interface, either handling "business logic" in each slot or delegating it to a dedicated method. You typically don't worry about making separate changes to each widget in your GUI because any repaint requests will be placed in the event queue and delivered when control returns to the event loop. Some paint events may even be merged together for the sake of efficiency. So, in a normal Qt application where signals and slots are used to handle state changes, there's basically no need to have an idle mechanism that monitors the state of the application and update widgets because those updates should occur automatically. You would have to say a bit more about what you are doing to explain why you need an equivalent to this event in Qt. A: I would send Qt signals to indicate state changes (e.g. fileOpened, processingStarted, processingDone). Slots in objects managing the start button and status bar widget (or subclasses) can be connected to those signals, rather than "polling" for current state in an idle event. If you want the signal to be deferred later on in the event loop rather than immediately (e.g. because it's going to take a bit of time to do something), you can use a "queued" signal-slot connection rather than the normal kind. http://doc.trolltech.com/4.5/signalsandslots.html#signals The connection type is an optional parameter to the connect() function: http://doc.trolltech.com/4.5/qobject.html#connect , http://doc.trolltech.com/4.5/qt.html#ConnectionType-enum A: As far as I understand EVT_IDLE is sent when application message queue is empty. There is no such event in Qt, but if you need to execute something in Qt when there are no pending events, you should use QTimer with 0 timeout. A: In general, the more Qt-ish way is to update the button/toolbar as necessary in whatever functions require the update, or to consolidate some of the functionality and directly call that function when the program needs it (such as an updateUi function). You should be aware that in Qt, changing an attribute of a Ui element doesn't cause an immediate redraw, but queues a redraw in the event system, and multiple redraw calls are compressed into one where possible. As for the multiple changes relating to state, have a look at this blog post about a hopefully-upcoming addition to Qt to more easily handle states. It looks like this would take care of a lot of your complaints, because in your multiple functions, you could just transition the state variable, and the other parts of the UI should update to match. It's not positive this will make it into the next Qt release (although I would bet on it, or something similar), and I have no idea how closely PyQt tracks the Qt releases. Or alternately, you could use the concept and create your own class to track the state as needed.
wx's idle and UI update events in PyQt
wx (and wxPython) has two events I miss in PyQt: EVT_IDLE that's being sent to a frame. It can be used to update the various widgets according to the application's state EVT_UPDATE_UI that's being sent to a widget when it has to be repainted and updated, so I can compute its state in the handler Now, PyQt doesn't seem to have these, and the PyQt book suggests writing an updateUi method and calling it manually. I even ended up calling it from a timer once per 0.1 seconds, in order to avoid many manual calls from methods that may update the GUI. Am I missing something? Is there a better way to achieve this? An example: I have a simple app with a Start button that initiates some processing. The start button should be enabled only when a file has been opened using the menu. In addition, there's a permanent widget on the status bar that displays information. My application has states: Before the file is opened (in this state the status bar show something special and the start button is disabled) File was opened and processing wasn't started: the start button is enabled, status bar shows something else The processing is running: the start button now says "Stop", and the status bar reports progress In Wx, I'd have the update UI event of the button handle its state: the text on it, and whether it's enabled, depending on the application state. The same for the status bar (or I'd use EVT_IDLE for that). In Qt, I have to update the button in several methods that may affect the state, or just create a update_ui method and call it periodically in a timer. What is the more "QT"-ish way?
[ "The use of EVT_UPDATE_UI in wxWidgets seems to highlight one of the fundamental differences in the way wxWidgets and Qt expect developers to handle events in their code.\nWith Qt, you connect signals and slots between widgets in the user interface, either handling \"business logic\" in each slot or delegating it to a dedicated method. You typically don't worry about making separate changes to each widget in your GUI because any repaint requests will be placed in the event queue and delivered when control returns to the event loop. Some paint events may even be merged together for the sake of efficiency.\nSo, in a normal Qt application where signals and slots are used to handle state changes, there's basically no need to have an idle mechanism that monitors the state of the application and update widgets because those updates should occur automatically.\nYou would have to say a bit more about what you are doing to explain why you need an equivalent to this event in Qt.\n", "I would send Qt signals to indicate state changes (e.g. fileOpened, processingStarted, processingDone). Slots in objects managing the start button and status bar widget (or subclasses) can be connected to those signals, rather than \"polling\" for current state in an idle event.\nIf you want the signal to be deferred later on in the event loop rather than immediately (e.g. because it's going to take a bit of time to do something), you can use a \"queued\" signal-slot connection rather than the normal kind. \nhttp://doc.trolltech.com/4.5/signalsandslots.html#signals\nThe connection type is an optional parameter to the connect() function: \nhttp://doc.trolltech.com/4.5/qobject.html#connect , http://doc.trolltech.com/4.5/qt.html#ConnectionType-enum\n", "As far as I understand EVT_IDLE is sent when application message queue is empty. There is no such event in Qt, but if you need to execute something in Qt when there are no pending events, you should use QTimer with 0 timeout.\n", "In general, the more Qt-ish way is to update the button/toolbar as necessary in whatever functions require the update, or to consolidate some of the functionality and directly call that function when the program needs it (such as an updateUi function).\nYou should be aware that in Qt, changing an attribute of a Ui element doesn't cause an immediate redraw, but queues a redraw in the event system, and multiple redraw calls are compressed into one where possible.\nAs for the multiple changes relating to state, have a look at this blog post about a hopefully-upcoming addition to Qt to more easily handle states. It looks like this would take care of a lot of your complaints, because in your multiple functions, you could just transition the state variable, and the other parts of the UI should update to match. It's not positive this will make it into the next Qt release (although I would bet on it, or something similar), and I have no idea how closely PyQt tracks the Qt releases. Or alternately, you could use the concept and create your own class to track the state as needed.\n" ]
[ 5, 2, 1, 1 ]
[]
[]
[ "pyqt", "python", "qt", "wxpython" ]
stackoverflow_0000624050_pyqt_python_qt_wxpython.txt
Q: Form Field API? I am iterating through list of form fields. How do I identify the type of each field? For checkbox I can call field.is_checkbox...are there similar methods for lists, multiplechoicefields etc. ? Thanks A: Have a look at the class for each field on your form: for f_name, f_type in my_form_instance.fields.items(): print "I am a ",type(f_type) # or f_type.__class__ This will produce output similar to <class 'django.forms.fields.BooleanField'>. You can get the name as a simple string, if you prefer that, with: print type(f_type).__name__ # produces 'BooleanField' Edit: Also be careful about the distinction between a field and a widget. There isn't a Checkbox field in Django, but only a CheckboxInput widget, which is the default for a BooleanField. Do you mean to look up the widget (which is very rendering specific), or the field (which has more of a relation to the data type and validation for that form field)? If the widget, you can get the widget type using: f_type.widget Hope that helps! A: I am not sure if this is what you want, but if you want to know what kind of field it is going to end up being in the HTML, you can check it with this: {% for field in form %} {{ field.field.widget.input_type }} {% endfor %} widget.input_type will hold text, password, select, etc. P.S. I did not know this until 5 seconds ago. #django irc.freenode.net always has good help.
Form Field API?
I am iterating through list of form fields. How do I identify the type of each field? For checkbox I can call field.is_checkbox...are there similar methods for lists, multiplechoicefields etc. ? Thanks
[ "Have a look at the class for each field on your form:\nfor f_name, f_type in my_form_instance.fields.items():\n print \"I am a \",type(f_type)\n # or f_type.__class__\n\nThis will produce output similar to <class 'django.forms.fields.BooleanField'>.\nYou can get the name as a simple string, if you prefer that, with:\nprint type(f_type).__name__\n# produces 'BooleanField'\n\nEdit: Also be careful about the distinction between a field and a widget. There isn't a Checkbox field in Django, but only a CheckboxInput widget, which is the default for a BooleanField. Do you mean to look up the widget (which is very rendering specific), or the field (which has more of a relation to the data type and validation for that form field)? If the widget, you can get the widget type using:\nf_type.widget\n\nHope that helps!\n", "I am not sure if this is what you want, but if you want to know what kind of field it is going to end up being in the HTML, you can check it with this:\n{% for field in form %}\n {{ field.field.widget.input_type }}\n{% endfor %}\n\nwidget.input_type will hold text, password, select, etc.\nP.S. I did not know this until 5 seconds ago. #django irc.freenode.net always has good help.\n" ]
[ 3, 1 ]
[ "Presuming you're using HTML here... Because it isn't very clear.\nHow about giving it an extra class.\nAnd if you didn't know allready, the class attribute will recognise this:\nclass=\"hello there you\"\n\nas having 3 classes. The class 'hello', the class 'there', and the class 'you'.\nSo if they allready have a class, just add a space and your custom clasname.\n" ]
[ -1 ]
[ "django", "django_forms", "python" ]
stackoverflow_0000627583_django_django_forms_python.txt
Q: Python dlopen/dlfunc/dlsym wrappers Anybody knows if actually exists a wrapper or ported library to access to Unix dynamic linker on Python? A: Would ctypes do what you want? A: The module is called dl: >>> import dl >>> dl.open("libfoo.so") <dl.dl object at 0xb7f580c0> >>> dl.open("libfoo.so").sym('bar') 1400432 ... though it's nasty and you might want to consider using ctypes or an extension module. Edit Apparently, dl is deprecated in 2.6 so you'll want to use ctypes which has a better API anyhow.
Python dlopen/dlfunc/dlsym wrappers
Anybody knows if actually exists a wrapper or ported library to access to Unix dynamic linker on Python?
[ "Would ctypes do what you want?\n", "The module is called dl:\n>>> import dl\n>>> dl.open(\"libfoo.so\")\n<dl.dl object at 0xb7f580c0>\n>>> dl.open(\"libfoo.so\").sym('bar')\n1400432\n\n... though it's nasty and you might want to consider using ctypes or an extension module.\nEdit\nApparently, dl is deprecated in 2.6 so you'll want to use ctypes which has a better API anyhow.\n" ]
[ 8, 2 ]
[]
[]
[ "dlopen", "linker", "python" ]
stackoverflow_0000627786_dlopen_linker_python.txt
Q: Validating a Unicode Name In ASCII, validating a name isn't too difficult: just make sure all the characters are alphabetical. But what about in Unicode (utf-8) ? How can I make sure there are no commas or underscores (outside of ASCII scope) in a given string? (ideally in Python) A: Maybe the unicodedata module is useful for this task. Especially the category() function. For existing unicode categories look at unicode.org. You can then filter on punctuation characters etc. A: Just convert bytestring (your utf-8) to unicode objects and check if all characters are alphabetic: s.isalpha() This method is locale-dependent for bytestrings. A: Depending on how you define "name", you could go with checking it against this regex: ^\w+$ However, this will allow numbers and underscores. To rule them out, you can do a second test against: [\d_] and make your check fail on match. These two could be combined as follows: ^(?:(?![\d_])\w)+$ But for regex performance reasons, I would rather do two separate checks. From the docs: \w When the LOCALE and UNICODE flags are not specified, matches any alphanumeric character and the underscore; this is equivalent to the set [a-zA-Z0-9_]. With LOCALE, it will match the set [0-9_] plus whatever characters are defined as alphanumeric for the current locale. If UNICODE is set, this will match the characters [0-9_] plus whatever is classified as alphanumeric in the Unicode character properties database. A: This might be a step towards a solution: import unicodedata EXCEPTIONS= frozenset(u"'.") CATEGORIES= frozenset( ('Lu', 'Ll', 'Lt', 'Pd', 'Zs') ) # O'Rourke, Franklin D. Roosevelt def test_unicode_name(unicode_name): return all( uchar in EXCEPTIONS or unicodedata.category(uchar) in CATEGORIES for uchar in unicode_name) >>> test_unicode_name(u"Michael O'Rourke") True >>> test_unicode_name(u"Χρήστος Γεωργίου") True >>> test_unicode_name(u"Jean-Luc Géraud") True Add exceptions, and further checks that I possibly missed. A: The letters property of the string module should give you what you want. This property is locale-specific, so as long as you know the language of the text being passed to you, you can use setlocale() and validate against those characters. http://docs.python.org/library/string.html#module-string As you point out, though, in a truly "unicode" world, there's no way at all to know what characters are "alphabetical" unless you know the language. If you don't know the language, you could either default to ASCII, or run through the locales for common languages.
Validating a Unicode Name
In ASCII, validating a name isn't too difficult: just make sure all the characters are alphabetical. But what about in Unicode (utf-8) ? How can I make sure there are no commas or underscores (outside of ASCII scope) in a given string? (ideally in Python)
[ "Maybe the unicodedata module is useful for this task. Especially the category() function. For existing unicode categories look at unicode.org. You can then filter on punctuation characters etc.\n", "Just convert bytestring (your utf-8) to unicode objects and check if all characters are alphabetic:\ns.isalpha()\n\nThis method is locale-dependent for bytestrings.\n", "Depending on how you define \"name\", you could go with checking it against this regex:\n^\\w+$\n\nHowever, this will allow numbers and underscores. To rule them out, you can do a second test against:\n[\\d_]\n\nand make your check fail on match. These two could be combined as follows:\n^(?:(?![\\d_])\\w)+$\n\nBut for regex performance reasons, I would rather do two separate checks.\nFrom the docs:\n\n\\w\nWhen the LOCALE and UNICODE flags are\n not specified, matches any\n alphanumeric character and the\n underscore; this is equivalent to the\n set [a-zA-Z0-9_]. With LOCALE, it will\n match the set [0-9_] plus whatever\n characters are defined as alphanumeric\n for the current locale. If UNICODE is\n set, this will match the characters\n [0-9_] plus whatever is classified as\n alphanumeric in the Unicode character\n properties database.\n\n", "This might be a step towards a solution:\nimport unicodedata\nEXCEPTIONS= frozenset(u\"'.\")\nCATEGORIES= frozenset( ('Lu', 'Ll', 'Lt', 'Pd', 'Zs') )\n# O'Rourke, Franklin D. Roosevelt\n\ndef test_unicode_name(unicode_name):\n return all(\n uchar in EXCEPTIONS\n or unicodedata.category(uchar) in CATEGORIES\n for uchar in unicode_name)\n\n>>> test_unicode_name(u\"Michael O'Rourke\")\nTrue\n>>> test_unicode_name(u\"Χρήστος Γεωργίου\")\nTrue\n>>> test_unicode_name(u\"Jean-Luc Géraud\")\nTrue\n\nAdd exceptions, and further checks that I possibly missed.\n", "The letters property of the string module should give you what you want. This property is locale-specific, so as long as you know the language of the text being passed to you, you can use setlocale() and validate against those characters.\nhttp://docs.python.org/library/string.html#module-string\nAs you point out, though, in a truly \"unicode\" world, there's no way at all to know what characters are \"alphabetical\" unless you know the language. If you don't know the language, you could either default to ASCII, or run through the locales for common languages.\n" ]
[ 5, 5, 1, 1, 0 ]
[]
[]
[ "character_properties", "python", "unicode", "validation" ]
stackoverflow_0000626697_character_properties_python_unicode_validation.txt
Q: How can I use named arguments in a decorator? If I have the following function: def intercept(func): # do something here @intercept(arg1=20) def whatever(arg1,arg2): # do something here I would like for intercept to fire up only when arg1 is 20. I would like to be able to pass named parameters to the function. How could I accomplish this? Here's a little code sample : def intercept(func): def intercepting_func(*args,**kargs): print "whatever" return func(*args,**kargs) return intercepting_func @intercept(a="g") def test(a,b): print "test with %s %s" %(a,b) test("g","d") This throws the following exception TypeError: intercept() got an unexpected keyword argument 'a' A: Remember that @foo def bar(): pass is equivalent to: def bar(): pass bar = foo(bar) so if you do: @foo(x=3) def bar(): pass that's equivalent to: def bar(): pass bar = foo(x=3)(bar) so your decorator needs to look something like this: def foo(x=1): def wrap(f): def f_foo(*args, **kw): # do something to f return f(*args, **kw) return f_foo return wrap In other words, def wrap(f) is really the decorator, and foo(x=3) is a function call that returns a decorator. A: from functools import wraps def intercept(target,**trigger): def decorator(func): names = getattr(func,'_names',None) if names is None: code = func.func_code names = code.co_varnames[:code.co_argcount] @wraps(func) def decorated(*args,**kwargs): all_args = kwargs.copy() for n,v in zip(names,args): all_args[n] = v for k,v in trigger.iteritems(): if k in all_args and all_args[k] != v: break else: return target(all_args) return func(*args,**kwargs) decorated._names = names return decorated return decorator Example: def interceptor1(kwargs): print 'Intercepted by #1!' def interceptor2(kwargs): print 'Intercepted by #2!' def interceptor3(kwargs): print 'Intercepted by #3!' @intercept(interceptor1,arg1=20,arg2=5) # if arg1 == 20 and arg2 == 5 @intercept(interceptor2,arg1=20) # elif arg1 == 20 @intercept(interceptor3,arg2=5) # elif arg2 == 5 def foo(arg1,arg2): return arg1+arg2 >>> foo(3,4) 7 >>> foo(20,4) Intercepted by #2! >>> foo(3,5) Intercepted by #3! >>> foo(20,5) Intercepted by #1! >>> functools.wraps does what the "simple decorator" on the wiki does; Updates __doc__, __name__ and other attribute of the decorator. A: You can do this by using *args and **kwargs in the decorator: def intercept(func, *dargs, **dkwargs): def intercepting_func(*args, **kwargs): if (<some condition on dargs, dkwargs, args and kwargs>): print 'I intercepted you.' return func(*args, **kwargs) return intercepting_func It's up to you how you wish to pass in arguments to control the behavior of the decorator. To make this as transparent as possible to the end user, you can use the "simple decorator" on the Python wiki or Michele Simionato's "decorator decorator"
How can I use named arguments in a decorator?
If I have the following function: def intercept(func): # do something here @intercept(arg1=20) def whatever(arg1,arg2): # do something here I would like for intercept to fire up only when arg1 is 20. I would like to be able to pass named parameters to the function. How could I accomplish this? Here's a little code sample : def intercept(func): def intercepting_func(*args,**kargs): print "whatever" return func(*args,**kargs) return intercepting_func @intercept(a="g") def test(a,b): print "test with %s %s" %(a,b) test("g","d") This throws the following exception TypeError: intercept() got an unexpected keyword argument 'a'
[ "Remember that\n@foo\ndef bar():\n pass\n\nis equivalent to:\ndef bar():\n pass\nbar = foo(bar)\n\nso if you do:\n@foo(x=3)\ndef bar():\n pass\n\nthat's equivalent to:\ndef bar():\n pass\nbar = foo(x=3)(bar)\n\nso your decorator needs to look something like this:\ndef foo(x=1):\n def wrap(f):\n def f_foo(*args, **kw):\n # do something to f\n return f(*args, **kw)\n return f_foo\n return wrap\n\nIn other words, def wrap(f) is really the decorator, and foo(x=3) is a function call that returns a decorator.\n", "from functools import wraps\n\ndef intercept(target,**trigger):\n def decorator(func):\n names = getattr(func,'_names',None)\n if names is None:\n code = func.func_code\n names = code.co_varnames[:code.co_argcount]\n @wraps(func)\n def decorated(*args,**kwargs):\n all_args = kwargs.copy()\n for n,v in zip(names,args):\n all_args[n] = v\n for k,v in trigger.iteritems():\n if k in all_args and all_args[k] != v:\n break\n else:\n return target(all_args)\n return func(*args,**kwargs)\n decorated._names = names\n return decorated\n return decorator\n\nExample:\ndef interceptor1(kwargs):\n print 'Intercepted by #1!'\n\ndef interceptor2(kwargs):\n print 'Intercepted by #2!'\n\ndef interceptor3(kwargs):\n print 'Intercepted by #3!'\n\n@intercept(interceptor1,arg1=20,arg2=5) # if arg1 == 20 and arg2 == 5\n@intercept(interceptor2,arg1=20) # elif arg1 == 20\n@intercept(interceptor3,arg2=5) # elif arg2 == 5\ndef foo(arg1,arg2):\n return arg1+arg2\n\n>>> foo(3,4)\n7\n>>> foo(20,4)\nIntercepted by #2!\n>>> foo(3,5)\nIntercepted by #3!\n>>> foo(20,5)\nIntercepted by #1!\n>>>\n\nfunctools.wraps does what the \"simple decorator\" on the wiki does; Updates __doc__, __name__ and other attribute of the decorator.\n", "You can do this by using *args and **kwargs in the decorator:\ndef intercept(func, *dargs, **dkwargs):\n def intercepting_func(*args, **kwargs):\n if (<some condition on dargs, dkwargs, args and kwargs>):\n print 'I intercepted you.'\n return func(*args, **kwargs)\n return intercepting_func\n\nIt's up to you how you wish to pass in arguments to control the behavior of the decorator.\nTo make this as transparent as possible to the end user, you can use the \"simple decorator\" on the Python wiki or Michele Simionato's \"decorator decorator\"\n" ]
[ 19, 12, 4 ]
[]
[]
[ "decorator", "language_features", "python" ]
stackoverflow_0000627501_decorator_language_features_python.txt
Q: How to implement a function to cover both single and multiple values Say you have a value like this: n = 5 and a function that returns the factorial of it, like so: factorial(5) How do you handle multiple values: nums = [1,2,3,4,5] factorial (nums) so it returns the factorials of all these values as a list? What's the cleanest way to handle this, without writing 2 methods? Does Python have a good way to handle these kinds of situations? A: def Factorial(arg): try: it = iter(arg) except TypeError: pass else: return [Factorial(x) for x in it] return math.factorial(arg) If it's iterable, apply recursivly. Otherwise, proceed normally. Alternatively, you could move the last return into the except block. If you are sure the body of Factorial will never raise TypeError, it could be simplified to: def Factorial(arg): try: return [Factorial(x) for x in arg] except TypeError: return math.factorial(arg) A: List comprehension: [fac(n) for n in nums] EDIT: Sorry, I misunderstood, you want a method that handles both sequences and single values? I can't imagine why you wouldn't do this with two methods. def factorial(n): # implement factorial here return answer def factorial_list(nums): return [factorial(n) for n in nums] The alternative would be to do some sort of type-checking, which is better avoided unless you have some terribly compelling reason to do so. EDIT 2: MizardX's answer is better, vote for that one. Cheers. A: This is done sometimes. def factorial( *args ): def fact( n ): if n == 0: return 1 return n*fact(n-1) return [ fact(a) for a in args ] It gives an almost magical function that works with simple values as well as sequences. >>> factorial(5) [120] >>> factorial( 5, 6, 7 ) [120, 720, 5040] >>> factorial( *[5, 6, 7] ) [120, 720, 5040] A: If you're asking if Python can do method overloading: no. Hence, doing multi-methods like that is a rather un-Pythonic way of defining a method. Also, naming convention usually upper-cases class names, and lower-cases functions/methods. If you want to go ahead anyway, simplest way would be to just make a branch: def Factorial(arg): if getattr(arg, '__iter__', False): # checks if arg is iterable return [Factorial(x) for x in arg] else: # ... Or, if you're feeling fancy, you could make a decorator that does this to any function: def autoMap(f): def mapped(arg): if getattr(arg, '__iter__', False): return [mapped(x) for x in arg] else: return f(arg) return mapped @autoMap def fact(x): if x == 1 or x == 0: return 1 else: return fact(x-1) + fact(x-2) >>> fact(3) 3 >>> fact(4) 5 >>> fact(5) 8 >>> fact(6) 13 >>> fact([3,4,5,6]) [3, 5, 8, 13] Although a more Pythonic way is to use variable argument lengths: def autoMap2(f): def mapped(*arg): if len(arg) != 1: return [f(x) for x in arg] else: return f(arg[0]) return mapped @autoMap2 def fact(n): # ... >>> fact(3,4,5,6) [3, 5, 8, 13] Putting the two together into a deep mapping decorator: def autoDeepMap(f): def mapped(*args): if len(args) != 1: return [mapped(x) for x in args] elif getattr(args[0], '__iter__', False): return [mapped(x) for x in args[0]] else: return f(args[0]) return mapped @autoDeepMap def fact(n): # ... >>> fact(0) 1 >>> fact(0,1,2,3,4,5,6) [1, 1, 2, 3, 5, 8, 13] >>> fact([0,1,2,3,4,5,6]) [1, 1, 2, 3, 5, 8, 13] >>> fact([0,1,2],[3,4,5,6]) [[1, 1, 2], [3, 5, 8, 13]] >>> fact([0,1,2],[3,(4,5),6]) [[1, 1, 2], [3, [5, 8], 13]] A: Or if you don't like the list comprehension syntax, and wish to skip having a new method: def factorial(num): if num == 0: return 1 elif num > 0: return num * factorial(num - 1) else: raise Exception("Negative num has no factorial.") nums = [1, 2, 3, 4, 5] # [1, 2, 3, 4, 5] map(factorial, nums) # [1, 2, 6, 24, 120, 720] A: You might want to take a look at NumPy/SciPy's vectorize. In the numpy world, given your single-int-arg Factorial function, you'd do things like vFactorial=np.vectorize(Factorial) vFactorial([1,2,3,4,5]) vFactorial(6) although note that the last case returns a single-element numpy array rather than a raw int.
How to implement a function to cover both single and multiple values
Say you have a value like this: n = 5 and a function that returns the factorial of it, like so: factorial(5) How do you handle multiple values: nums = [1,2,3,4,5] factorial (nums) so it returns the factorials of all these values as a list? What's the cleanest way to handle this, without writing 2 methods? Does Python have a good way to handle these kinds of situations?
[ "def Factorial(arg):\n try:\n it = iter(arg)\n except TypeError:\n pass\n else:\n return [Factorial(x) for x in it]\n return math.factorial(arg)\n\nIf it's iterable, apply recursivly. Otherwise, proceed normally.\nAlternatively, you could move the last return into the except block.\nIf you are sure the body of Factorial will never raise TypeError, it could be simplified to:\ndef Factorial(arg):\n try:\n return [Factorial(x) for x in arg]\n except TypeError:\n return math.factorial(arg)\n\n", "List comprehension:\n[fac(n) for n in nums]\n\nEDIT:\nSorry, I misunderstood, you want a method that handles both sequences and single values? I can't imagine why you wouldn't do this with two methods.\ndef factorial(n):\n # implement factorial here\n return answer\n\ndef factorial_list(nums):\n return [factorial(n) for n in nums]\n\nThe alternative would be to do some sort of type-checking, which is better avoided unless you have some terribly compelling reason to do so.\nEDIT 2:\nMizardX's answer is better, vote for that one. Cheers.\n", "This is done sometimes.\ndef factorial( *args ):\n def fact( n ):\n if n == 0: return 1\n return n*fact(n-1)\n return [ fact(a) for a in args ]\n\nIt gives an almost magical function that works with simple values as well as sequences.\n>>> factorial(5)\n[120]\n>>> factorial( 5, 6, 7 )\n[120, 720, 5040]\n>>> factorial( *[5, 6, 7] )\n[120, 720, 5040]\n\n", "If you're asking if Python can do method overloading: no. Hence, doing multi-methods like that is a rather un-Pythonic way of defining a method. Also, naming convention usually upper-cases class names, and lower-cases functions/methods.\nIf you want to go ahead anyway, simplest way would be to just make a branch:\ndef Factorial(arg):\n if getattr(arg, '__iter__', False): # checks if arg is iterable\n return [Factorial(x) for x in arg]\n else:\n # ...\n\nOr, if you're feeling fancy, you could make a decorator that does this to any function:\ndef autoMap(f):\n def mapped(arg):\n if getattr(arg, '__iter__', False):\n return [mapped(x) for x in arg]\n else:\n return f(arg)\n return mapped\n\n@autoMap\ndef fact(x):\n if x == 1 or x == 0:\n return 1\n else:\n return fact(x-1) + fact(x-2)\n\n>>> fact(3)\n3\n>>> fact(4)\n5\n>>> fact(5)\n8\n>>> fact(6)\n13\n>>> fact([3,4,5,6])\n[3, 5, 8, 13]\n\nAlthough a more Pythonic way is to use variable argument lengths:\ndef autoMap2(f):\n def mapped(*arg):\n if len(arg) != 1:\n return [f(x) for x in arg]\n else:\n return f(arg[0])\n return mapped\n\n@autoMap2\ndef fact(n):\n# ...\n\n>>> fact(3,4,5,6)\n[3, 5, 8, 13]\n\nPutting the two together into a deep mapping decorator:\ndef autoDeepMap(f):\n def mapped(*args):\n if len(args) != 1:\n return [mapped(x) for x in args]\n elif getattr(args[0], '__iter__', False):\n return [mapped(x) for x in args[0]]\n else:\n return f(args[0])\n return mapped\n\n@autoDeepMap\ndef fact(n):\n# ...\n\n>>> fact(0)\n1\n>>> fact(0,1,2,3,4,5,6)\n[1, 1, 2, 3, 5, 8, 13]\n>>> fact([0,1,2,3,4,5,6])\n[1, 1, 2, 3, 5, 8, 13]\n>>> fact([0,1,2],[3,4,5,6])\n[[1, 1, 2], [3, 5, 8, 13]]\n>>> fact([0,1,2],[3,(4,5),6])\n[[1, 1, 2], [3, [5, 8], 13]]\n\n", "Or if you don't like the list comprehension syntax, and wish to skip having a new method:\ndef factorial(num):\n if num == 0:\n return 1\n elif num > 0:\n return num * factorial(num - 1)\n else:\n raise Exception(\"Negative num has no factorial.\")\n\nnums = [1, 2, 3, 4, 5]\n# [1, 2, 3, 4, 5]\n\nmap(factorial, nums)\n# [1, 2, 6, 24, 120, 720]\n\n", "You might want to take a look at NumPy/SciPy's vectorize.\nIn the numpy world, given your single-int-arg Factorial function,\nyou'd do things like\n vFactorial=np.vectorize(Factorial)\n vFactorial([1,2,3,4,5])\n vFactorial(6)\n\nalthough note that the last case returns a single-element numpy array rather than a raw int.\n" ]
[ 13, 9, 7, 6, 3, 3 ]
[]
[]
[ "function", "list", "python", "vectorization" ]
stackoverflow_0000628162_function_list_python_vectorization.txt
Q: Using Python to get Windows system internals info I'd like to write some quick Python code to assess the CPU, memory, disk, and networking usage of my Windows XP system. Are there existing Python libraries that would allow me to access that information? Or, are there DLL's that I can call from Python? (If so, a code sample would be appreciated) A: I think WMI is the resource to use. Especially, look at the Win32_PerfFormattedData* classes in the MSDN. A quick search turned this up (among others): http://timgolden.me.uk/python/wmi.html A: The MS Scriptomatic tool can generate WMI scripts in Python as well as VBScript, JScript and Perl.
Using Python to get Windows system internals info
I'd like to write some quick Python code to assess the CPU, memory, disk, and networking usage of my Windows XP system. Are there existing Python libraries that would allow me to access that information? Or, are there DLL's that I can call from Python? (If so, a code sample would be appreciated)
[ "I think WMI is the resource to use. Especially, look at the Win32_PerfFormattedData* classes in the MSDN.\nA quick search turned this up (among others):\nhttp://timgolden.me.uk/python/wmi.html\n", "The MS Scriptomatic tool can generate WMI scripts in Python as well as VBScript, JScript and Perl.\n" ]
[ 4, 0 ]
[]
[]
[ "python", "windows_xp" ]
stackoverflow_0000627596_python_windows_xp.txt
Q: Decoding HTML Entities With Python The following Python code uses BeautifulStoneSoup to fetch the LibraryThing API information for Tolkien's "The Children of Húrin". import urllib2 from BeautifulSoup import BeautifulStoneSoup URL = ("http://www.librarything.com/services/rest/1.0/" "?method=librarything.ck.getwork&id=1907912" "&apikey=2a2e596b887f554db2bbbf3b07ff812a") soup = BeautifulStoneSoup(urllib2.urlopen(URL), convertEntities=BeautifulStoneSoup.ALL_ENTITIES) title_field = soup.find('field', attrs={'name': 'canonicaltitle'}) print title_field.find('fact').string Unfortunately, instead of 'Húrin', it prints out 'Húrin'. This is obviously an encoding issue, but I can't work out what I need to do to get the expected output. Help would be greatly appreciated. A: In the source of the web page it looks like this: The Children of H&Atilde;&ordm;rin. So the encoding is already broken somewhere on their side before it even gets converted to XML... If it's a general issue with all the books and you need to work around it, this seems to work: unicode(title_field.find('fact').string).encode("latin1").decode("utf-8") A: The web page may be lying about its encoding. The output looks like UTF-8. If you got a str at the end then you'll need to decode it as UTF-8. If you have a unicode instead then you'll need to encode as Latin-1 first.
Decoding HTML Entities With Python
The following Python code uses BeautifulStoneSoup to fetch the LibraryThing API information for Tolkien's "The Children of Húrin". import urllib2 from BeautifulSoup import BeautifulStoneSoup URL = ("http://www.librarything.com/services/rest/1.0/" "?method=librarything.ck.getwork&id=1907912" "&apikey=2a2e596b887f554db2bbbf3b07ff812a") soup = BeautifulStoneSoup(urllib2.urlopen(URL), convertEntities=BeautifulStoneSoup.ALL_ENTITIES) title_field = soup.find('field', attrs={'name': 'canonicaltitle'}) print title_field.find('fact').string Unfortunately, instead of 'Húrin', it prints out 'Húrin'. This is obviously an encoding issue, but I can't work out what I need to do to get the expected output. Help would be greatly appreciated.
[ "In the source of the web page it looks like this: The Children of H&Atilde;&ordm;rin. So the encoding is already broken somewhere on their side before it even gets converted to XML...\nIf it's a general issue with all the books and you need to work around it, this seems to work:\nunicode(title_field.find('fact').string).encode(\"latin1\").decode(\"utf-8\")\n\n", "The web page may be lying about its encoding. The output looks like UTF-8. If you got a str at the end then you'll need to decode it as UTF-8. If you have a unicode instead then you'll need to encode as Latin-1 first.\n" ]
[ 4, 1 ]
[]
[]
[ "beautifulsoup", "encoding", "python", "unicode", "utf_8" ]
stackoverflow_0000628332_beautifulsoup_encoding_python_unicode_utf_8.txt
Q: Django Form Preview - How to work with 'cleaned_data' Thanks to Insin for answering a previous question related to this one. His answer worked and works well, however, I'm perplexed at the provision of 'cleaned_data', or more precisely, how to use it? class RegistrationFormPreview(FormPreview): preview_template = 'workshops/workshop_register_preview.html' form_template = 'workshops/workshop_register_form.html' def done(self, request, cleaned_data): # Do something with the cleaned_data, then redirect # to a "success" page. registration = Registration(cleaned_data) registration.user = request.user registration.save() # an attempt to work with cleaned_data throws the error: TypeError # int() argument must be a string or a number, not 'dict' # obviously the fk are python objects(?) and not fk_id # but how to proceed here in an easy way? # the following works fine, however, it seems to be double handling the POST data # which had already been processed in the django.formtools.preview.post_post # method, and passed through to this 'done' method, which is designed to # be overidden. ''' form = self.form(request.POST) # instansiate the form with POST data registration = form.save(commit=False) # save before adding the user registration.user = request.user # add the user registration.save() # and save. ''' return HttpResponseRedirect('/register/success') For quick reference, here's the contents of the post_post method: def post_post(self, request): "Validates the POST data. If valid, calls done(). Else, redisplays form." f = self.form(request.POST, auto_id=AUTO_ID) if f.is_valid(): if self.security_hash(request, f) != request.POST.get(self.unused_name('hash')): return self.failed_hash(request) # Security hash failed. return self.done(request, f.cleaned_data) else: return render_to_response(self.form_template, {'form': f, 'stage_field': self.unused_name('stage'), 'state': self.state}, context_instance=RequestContext(request)) A: I've never tried what you're doing here with a ModelForm before, but you might be able to use the ** operator to expand your cleaned_data dictionary into the keyword arguments expected for your Registration constructor: registration = Registration (**cleaned_data) The constructor to your model classes take keyword arguments that Django's Model meta class converts to instance-level attributes on the resulting object. The ** operator is a calling convention that tells Python to expand your dictionary into those keyword arguments. In other words... What you're doing currently is tantamount to this: registration = Registration ({'key':'value', ...}) Which is not what you want because the constructor expects keyword arguments as opposed to a dictionary that contains your keyword arguments. What you want to be doing is this registration = Registration (key='value', ...) Which is analogous to this: registration = Registration (**{'key':'value', ...}) Again, I've never tried it, but it seems like it would work as long as you aren't doing anything fancy with your form, such as adding new attributes to it that aren't expected by your Registration constructor. In that case you'd likely have to modify the items in the cleaned_data dictionary prior to doing this. It does seem like you're losing out on some of the functionality inherent in ModelForms by going through the form preview utility, though. Perhaps you should take your use case to the Django mailing list and see if there's a potential enhancement to this API that could make it work better with ModelForms. Edit Short of what I've described above, you can always just extract the fields from your cleaned_data dictionary "by hand" and pass those into your Registration constructor too, but with the caveat that you have to remember to update this code as you add new fields to your model. registration = Registration ( x=cleaned_data['x'], y=cleaned_data['y'], z=cleaned_data['z'], ... )
Django Form Preview - How to work with 'cleaned_data'
Thanks to Insin for answering a previous question related to this one. His answer worked and works well, however, I'm perplexed at the provision of 'cleaned_data', or more precisely, how to use it? class RegistrationFormPreview(FormPreview): preview_template = 'workshops/workshop_register_preview.html' form_template = 'workshops/workshop_register_form.html' def done(self, request, cleaned_data): # Do something with the cleaned_data, then redirect # to a "success" page. registration = Registration(cleaned_data) registration.user = request.user registration.save() # an attempt to work with cleaned_data throws the error: TypeError # int() argument must be a string or a number, not 'dict' # obviously the fk are python objects(?) and not fk_id # but how to proceed here in an easy way? # the following works fine, however, it seems to be double handling the POST data # which had already been processed in the django.formtools.preview.post_post # method, and passed through to this 'done' method, which is designed to # be overidden. ''' form = self.form(request.POST) # instansiate the form with POST data registration = form.save(commit=False) # save before adding the user registration.user = request.user # add the user registration.save() # and save. ''' return HttpResponseRedirect('/register/success') For quick reference, here's the contents of the post_post method: def post_post(self, request): "Validates the POST data. If valid, calls done(). Else, redisplays form." f = self.form(request.POST, auto_id=AUTO_ID) if f.is_valid(): if self.security_hash(request, f) != request.POST.get(self.unused_name('hash')): return self.failed_hash(request) # Security hash failed. return self.done(request, f.cleaned_data) else: return render_to_response(self.form_template, {'form': f, 'stage_field': self.unused_name('stage'), 'state': self.state}, context_instance=RequestContext(request))
[ "I've never tried what you're doing here with a ModelForm before, but you might be able to use the ** operator to expand your cleaned_data dictionary into the keyword arguments expected for your Registration constructor:\n registration = Registration (**cleaned_data)\n\nThe constructor to your model classes take keyword arguments that Django's Model meta class converts to instance-level attributes on the resulting object. The ** operator is a calling convention that tells Python to expand your dictionary into those keyword arguments.\nIn other words...\nWhat you're doing currently is tantamount to this:\nregistration = Registration ({'key':'value', ...})\n\nWhich is not what you want because the constructor expects keyword arguments as opposed to a dictionary that contains your keyword arguments.\nWhat you want to be doing is this\nregistration = Registration (key='value', ...)\n\nWhich is analogous to this:\nregistration = Registration (**{'key':'value', ...})\n\nAgain, I've never tried it, but it seems like it would work as long as you aren't doing anything fancy with your form, such as adding new attributes to it that aren't expected by your Registration constructor. In that case you'd likely have to modify the items in the cleaned_data dictionary prior to doing this.\nIt does seem like you're losing out on some of the functionality inherent in ModelForms by going through the form preview utility, though. Perhaps you should take your use case to the Django mailing list and see if there's a potential enhancement to this API that could make it work better with ModelForms.\nEdit\nShort of what I've described above, you can always just extract the fields from your cleaned_data dictionary \"by hand\" and pass those into your Registration constructor too, but with the caveat that you have to remember to update this code as you add new fields to your model.\nregistration = Registration (\n x=cleaned_data['x'],\n y=cleaned_data['y'],\n z=cleaned_data['z'],\n ...\n)\n\n" ]
[ 10 ]
[]
[]
[ "django", "django_forms", "django_models", "python" ]
stackoverflow_0000628132_django_django_forms_django_models_python.txt
Q: Is Google data source JSON not valid? I am implementing a Google data source using their Python library. I would like the response from the library to be able to be imported in another Python script using the simplejson library. However, even their example doesn't validate in JSONLint: {cols: [{id:'name',label:'Name',type:'string'}, {id:'salary',label:'Salary',type:'number'}, {id:'full_time',label:'Full Time Employee',type:'boolean'}], rows: [{c:[{v:'Jim'},{v:800,f:'$800'},{v:false}]}, {c:[{v:'Bob'},{v:7000,f:'$7,000'},{v:true}]}, {c:[{v:'Mike'},{v:10000,f:'$10,000'},{v:true}]}, {c:[{v:'Alice'},{v:12500,f:'$12,500'},{v:true}]}]} How do I tweak the simplejson 'loads' function to import the above JSON content? I think the main problem is that the object keys are not strings. I would rather not write a regular expression to convert the keys to strings since I think such code would be annoying to maintain. I am currently getting an "Expecting property name: line 1 column 1 (char 1)" error when trying to import the above JSON into Python with simplejson. A: It is considered to be invalid JSON without the string keys. {id:'name',label:'Name',type:'string'} must be: {'id':'name','label':'Name','type':'string'} According to the Google Data Source page, they're returning invalid JSON. They don't specifically say it, but all their examples lack quotes on the keys. Here is a fairly complete list of JSON processors for Python which goes into detail about what formats they support, and how well. Most don't support non-string keys, but it appears that demjson will convert it. easy_install demjson
Is Google data source JSON not valid?
I am implementing a Google data source using their Python library. I would like the response from the library to be able to be imported in another Python script using the simplejson library. However, even their example doesn't validate in JSONLint: {cols: [{id:'name',label:'Name',type:'string'}, {id:'salary',label:'Salary',type:'number'}, {id:'full_time',label:'Full Time Employee',type:'boolean'}], rows: [{c:[{v:'Jim'},{v:800,f:'$800'},{v:false}]}, {c:[{v:'Bob'},{v:7000,f:'$7,000'},{v:true}]}, {c:[{v:'Mike'},{v:10000,f:'$10,000'},{v:true}]}, {c:[{v:'Alice'},{v:12500,f:'$12,500'},{v:true}]}]} How do I tweak the simplejson 'loads' function to import the above JSON content? I think the main problem is that the object keys are not strings. I would rather not write a regular expression to convert the keys to strings since I think such code would be annoying to maintain. I am currently getting an "Expecting property name: line 1 column 1 (char 1)" error when trying to import the above JSON into Python with simplejson.
[ "It is considered to be invalid JSON without the string keys.\n{id:'name',label:'Name',type:'string'}\n\nmust be:\n{'id':'name','label':'Name','type':'string'}\n\nAccording to the Google Data Source page, they're returning invalid JSON. They don't specifically say it, but all their examples lack quotes on the keys.\nHere is a fairly complete list of JSON processors for Python which goes into detail about what formats they support, and how well. Most don't support non-string keys, but it appears that demjson will convert it.\neasy_install demjson\n\n" ]
[ 8 ]
[]
[]
[ "python", "simplejson" ]
stackoverflow_0000628505_python_simplejson.txt
Q: Difference between the use of double quote and quotes in python Is there any difference between the use of double quotes to single quotes in Python? "A string with double quotes" 'A string with single quotes' Are they identical? Are there differences in how python interprets these strings? A: Short answer: almost no difference except stylistically. Short blurb: If you don't want to escape the quote characters inside your string, use the other type. eg: string1 = "He turned to me and said, \"Hello there\"" would be slightly more unsightly than saying string2 = 'He turned to me and said, "Hello there"' The same applies to single quotes/apostrophes. A: Not generally, you just have to be consistent within a given statement. E.g., don't do "foo' For further reading, see here. A: Double quotes look distinctive. Single quotes look like single ticks. Apart from that ...
Difference between the use of double quote and quotes in python
Is there any difference between the use of double quotes to single quotes in Python? "A string with double quotes" 'A string with single quotes' Are they identical? Are there differences in how python interprets these strings?
[ "Short answer: almost no difference except stylistically.\nShort blurb: If you don't want to escape the quote characters inside your string, use the other type. eg:\nstring1 = \"He turned to me and said, \\\"Hello there\\\"\"\n\nwould be slightly more unsightly than saying\nstring2 = 'He turned to me and said, \"Hello there\"'\n\nThe same applies to single quotes/apostrophes.\n", "Not generally, you just have to be consistent within a given statement. E.g., don't do \"foo'\nFor further reading, see here.\n", "Double quotes look distinctive. Single quotes look like single ticks. Apart from that ...\n" ]
[ 25, 4, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000628657_python.txt
Q: Best practice for integrating CherryPy web-framework, SQLAlchemy sessions and lighttpd to serve a high-load webservice I'm developing a CherryPy FastCGI server behind lighttpd with the following setup to enable using ORM SQLAlchemy sessions inside CherryPy controllers. However, when I run stress tests with 14 concurrent requests for about 500 loops, it starts to give errors like AttributeError: '_ThreadData' object has no attribute 'scoped_session_class' in open_dbsession() or AttributeError: 'Request' object has no attribute 'scoped_session_class' in close_dbsession() after a while. The error rate is around 50% in total. This happens only when I run the server behind lighttpd, not when it's run directly through cherrypy.engine.start(). It's confirmed that connect() isn't raising exceptions. I also tried assigning the return value of scoped_session to GlobalSession (like it does here), but then it gave out errors like UnboundExceptionError and other SA-level errors. (Concurrency: 10, loops: 1000, error rate: 16%. Occurs even when run directly.) There are some possible causes but I lack sufficient knowledge to pick one. 1. Are start_thread subscriptions unreliable under FastCGI environment? It seems that open_dbsession() is called before connect() 2. Does cherrypy.thread_data get cleared for some reason? server code import sqlalchemy as sa from sqlalchemy.orm import session_maker, scoped_session engine = sa.create_engine(dburi, strategy="threadlocal") GlobalSession = session_maker(bind=engine, transactional=False) def connect(thread_index): cherrypy.thread_data.scoped_session_class = scoped_session(GlobalSession) def open_dbsession(): cherrypy.request.scoped_session_class = cherrypy.thread_data.scoped_session_class def close_dbsession(): cherrypy.request.scoped_session_class.remove() cherrypy.tools.dbsession_open = cherrypy.Tool('on_start_resource', open_dbsession) cherrypy.tools.dbsession_close = cherrypy.Tool('on_end_resource', close_dbsession) cherrypy.engine.subscribe('start_thread', connect) lighttpd fastcgi config ... var.server_name = "test" var.server_root = "/path/to/root" var.svc_env = "test" fastcgi.server = ( "/" => ( "cherry.fcgi" => ( "bin-path" => server_root + "/fcgi_" + server_name + ".fcgi", "bin-environment" => ( "SVC_ENV" => svc_env ), "bin-copy-environment" => ("PATH", "LC_CTYPE"), "socket" => "/tmp/cherry_" + server_name + "." + svc_env + ".sock", "check-local" => "disable", "disable-time" => 1, "min-procs" => 1, "max-procs" => 4, ), ), ) edits Restored the missing thread_index argument in the code example from the original source code (thanks to the comment) Clarified that errors do not occur immediately Narrowed down the conditions to lighttpd A: If you look at plugins.ThreadManager.acquire_thread, you'll see the line self.bus.publish('start_thread', i), where i is the array index of the seen thread. Any listener subscribed to the start_thread channel needs to accept that i value as a positional argument. So rewrite your connect function to read: def connect(i): My guess it that's failing silently somehow; I'll see if I can track that down, test and fix it. A: I also tried assigning the return value of scoped_session to GlobalSession (like it does here), but then it gave out errors like UnboundExceptionError and other SA-level errors. (Concurrency: 10, loops: 1000, error rate: 16%) This error did not occur if I didn't instantiate the scoped_session class explicitly. i.e. GlobalSession = scoped_session(session_maker(bind=engine, transactional=False)) def connect(thread_index): cherrypy.thread_data.scoped_session_class = GlobalSession def open_dbsession(): cherrypy.request.scoped_session_class = cherrypy.thread_data.scoped_session_class def close_dbsession(): cherrypy.request.scoped_session_class.remove()
Best practice for integrating CherryPy web-framework, SQLAlchemy sessions and lighttpd to serve a high-load webservice
I'm developing a CherryPy FastCGI server behind lighttpd with the following setup to enable using ORM SQLAlchemy sessions inside CherryPy controllers. However, when I run stress tests with 14 concurrent requests for about 500 loops, it starts to give errors like AttributeError: '_ThreadData' object has no attribute 'scoped_session_class' in open_dbsession() or AttributeError: 'Request' object has no attribute 'scoped_session_class' in close_dbsession() after a while. The error rate is around 50% in total. This happens only when I run the server behind lighttpd, not when it's run directly through cherrypy.engine.start(). It's confirmed that connect() isn't raising exceptions. I also tried assigning the return value of scoped_session to GlobalSession (like it does here), but then it gave out errors like UnboundExceptionError and other SA-level errors. (Concurrency: 10, loops: 1000, error rate: 16%. Occurs even when run directly.) There are some possible causes but I lack sufficient knowledge to pick one. 1. Are start_thread subscriptions unreliable under FastCGI environment? It seems that open_dbsession() is called before connect() 2. Does cherrypy.thread_data get cleared for some reason? server code import sqlalchemy as sa from sqlalchemy.orm import session_maker, scoped_session engine = sa.create_engine(dburi, strategy="threadlocal") GlobalSession = session_maker(bind=engine, transactional=False) def connect(thread_index): cherrypy.thread_data.scoped_session_class = scoped_session(GlobalSession) def open_dbsession(): cherrypy.request.scoped_session_class = cherrypy.thread_data.scoped_session_class def close_dbsession(): cherrypy.request.scoped_session_class.remove() cherrypy.tools.dbsession_open = cherrypy.Tool('on_start_resource', open_dbsession) cherrypy.tools.dbsession_close = cherrypy.Tool('on_end_resource', close_dbsession) cherrypy.engine.subscribe('start_thread', connect) lighttpd fastcgi config ... var.server_name = "test" var.server_root = "/path/to/root" var.svc_env = "test" fastcgi.server = ( "/" => ( "cherry.fcgi" => ( "bin-path" => server_root + "/fcgi_" + server_name + ".fcgi", "bin-environment" => ( "SVC_ENV" => svc_env ), "bin-copy-environment" => ("PATH", "LC_CTYPE"), "socket" => "/tmp/cherry_" + server_name + "." + svc_env + ".sock", "check-local" => "disable", "disable-time" => 1, "min-procs" => 1, "max-procs" => 4, ), ), ) edits Restored the missing thread_index argument in the code example from the original source code (thanks to the comment) Clarified that errors do not occur immediately Narrowed down the conditions to lighttpd
[ "If you look at plugins.ThreadManager.acquire_thread, you'll see the line self.bus.publish('start_thread', i), where i is the array index of the seen thread. Any listener subscribed to the start_thread channel needs to accept that i value as a positional argument. So rewrite your connect function to read: def connect(i):\nMy guess it that's failing silently somehow; I'll see if I can track that down, test and fix it.\n", "\nI also tried assigning the return value of scoped_session to GlobalSession (like it does here), but then it gave out errors like UnboundExceptionError and other SA-level errors. (Concurrency: 10, loops: 1000, error rate: 16%)\n\nThis error did not occur if I didn't instantiate the scoped_session class explicitly.\ni.e. \nGlobalSession = scoped_session(session_maker(bind=engine, transactional=False))\n\ndef connect(thread_index): \n cherrypy.thread_data.scoped_session_class = GlobalSession\n\ndef open_dbsession(): \n cherrypy.request.scoped_session_class = cherrypy.thread_data.scoped_session_class\n\ndef close_dbsession(): \n cherrypy.request.scoped_session_class.remove()\n\n" ]
[ 1, 0 ]
[]
[]
[ "cherrypy", "lighttpd", "python", "sqlalchemy" ]
stackoverflow_0000625288_cherrypy_lighttpd_python_sqlalchemy.txt
Q: How would you translate this from Perl to Python? I've got a Perl function which takes a timestamp and returns either the unchanged timestamp (if it's never seen it before) or otherwise, it appends some letters to make it unique: sub uniqify($) { my $timestamp = shift; state $last_ts = -1; state $next_letter = 'A'; if ($timestamp == $last_ts) { $timestamp .= $next_letter++; } else { $last_ts = $timestamp; $next_letter = 'A'; } return $timestamp; } So if you call it four times, with the values 1, 1, 1, and 2, it will return 1, then 1A, then 1B, then 2. Note: It only ever gets called with ever-increasing timestamps, so it doesn't need to recall every one it's ever seen, just the last one. Now I need to translate this function to Python. I've learned that I can replace the "state" variables with globals (yuck!) or perhaps attach them to the function as attributes, but neither of those is particularly elegant. Also, Python doesn't have something like Perl's magic autoincrement, where if you "++" a variable whose value is "A", it becomes "B" -- or if it's "Z", it becomes "AA". So that's a curveball too. I'm hacking together a solution, but it's really ugly and hard to read. Translating from Perl to Python is supposed to have the opposite effect, right? :) So I'm offering this as a challenge to SO users. Can you make it an elegant Python function? A: Look at this answer for a robust method to convert a number to an alphanumeric id The code I present doesn't go from 'Z' to 'AA', instead goes to 'BA', but I suppose that doesn't matter, it still produces a unique id from string import uppercase as up import itertools def to_base(q, alphabet): if q < 0: raise ValueError( "must supply a positive integer" ) l = len(alphabet) converted = [] while q != 0: q, r = divmod(q, l) converted.insert(0, alphabet[r]) return "".join(converted) or alphabet[0] class TimestampUniqifier( object ): def __init__(self): self.last = '' self.counter = itertools.count() def __call__( self, str ): if str == self.last: suf = self.counter.next() return str + to_base( suf, up ) else: self.last = str self.counter = itertools.count() return str timestamp_uniqify = TimestampUniqifier() usage: timestamp_uniqify('1') '1' timestamp_uniqify('1') '1A' timestamp_uniqify('1') '1B' timestamp_uniqify('1') '1C' timestamp_uniqify('2') '2' timestamp_uniqify('3') '3' timestamp_uniqify('3') '3A' timestamp_uniqify('3') '3B' You can call it maaaany times and it will still produce good results: for i in range(100): print timestamp_uniqify('4') 4 4A 4B 4C 4D 4E 4F 4G 4H 4I 4J 4K 4L 4M 4N 4O 4P 4Q 4R 4S 4T 4U 4V 4W 4X 4Y 4Z 4BA 4BB 4BC 4BD 4BE 4BF 4BG 4BH 4BI 4BJ 4BK 4BL 4BM 4BN 4BO 4BP 4BQ 4BR 4BS 4BT 4BU 4BV 4BW 4BX 4BY 4BZ 4CA 4CB 4CC 4CD 4CE 4CF 4CG 4CH 4CI 4CJ 4CK 4CL 4CM 4CN 4CO 4CP 4CQ 4CR 4CS 4CT 4CU 4CV 4CW 4CX 4CY 4CZ 4DA 4DB 4DC 4DD 4DE 4DF 4DG 4DH 4DI 4DJ 4DK 4DL 4DM 4DN 4DO 4DP 4DQ 4DR 4DS 4DT 4DU A: Well, sorry to say, but you can't just do a direct translation from Perl to Python (including bit-for-bit Perlisms) and expect the outcome to be prettier. It won't be, it will be considerably uglier. If you want the prettiness of Python you will need to use Python idioms instead. Now for the question at hand: from string import uppercase class Uniquifier(object): def __init__(self): self.last_timestamp = None self.last_suffix = 0 def uniquify(self, timestamp): if timestamp == self.last_timestamp: timestamp = '%s%s' % (timestamp, uppercase[self.last_suffix]) self.last_suffix += 1 else: self.last_suffix = 0 self.timestamp = timestamp return timestamp uniquifier = Uniquifier() uniquifier.uniquify(a_timestamp) Prettier? Maybe. More readable? Probably. Edit (re comments): Yes this fails after Z, and I am altogether unhappy with this solution. So I won't fix it, but might offer something better, like using a number instead: timestamp = '%s%s' % (timestamp, self.last_suffix) If it were me, I would do this: import uuid def uniquify(timestamp): return '%s-%s' % (timestamp, uuid.uuid4()) And just be happy. A: I just tested this up to 1000 against the original perl implementation and diff returns the same results for both. The suffix code is tricky -- this is not a base 36 counter. Hasen J's solution - though it produces a unique timestamp - isn't quite the same since it goes from 'Z' to 'BA', when it should instead go to 'AA' to match the perl ++ operator. #!/usr/bin/python class uniqify: def __init__(self): self.last_timestamp = -1 self.next_suffix = 'A' return def suffix(self): s = self.next_suffix letters = [l for l in self.next_suffix] if letters[-1] == 'Z': letters.reverse() nonz = None for i in range(len(letters)): if letters[i] != 'Z': nonz = i break if nonz is not None: letters[nonz] = chr(ord(letters[nonz]) + 1) for i in range(0, nonz): letters[i] = 'A' else: letters = ['A'] * (len(letters) + 1) letters.reverse() else: letters[-1] = chr(ord(letters[-1]) + 1) self.next_suffix = ''.join(letters) return s def reset(self): self.next_suffix = 'A' return def __call__(self, timestamp): if timestamp == self.last_timestamp: timestamp_str = '%s%s' % (timestamp, self.suffix()) else: self.last_timestamp = timestamp self.reset() timestamp_str = '%s' % timestamp return timestamp_str uniqify = uniqify() if __name__ == '__main__': for n in range(1000): print uniqify(1) for n in range(1000): print uniqify(2) A: The class is generic and boring, but This is my very first recursive generator. <3 def stamptag(): yield '' prefixtag = stamptag() prefix = prefixtag.next() while True: for i in range(ord('A'),ord('Z')+1): yield prefix+chr(i) prefix = prefixtag.next() tagger = stamptag() for i in range(3000): tagger.next() print tagger.next() class uniquestamp: def __init__(self): self.timestamp = -1 self.tagger = stamptag() def format(self,newstamp): if self.timestamp < newstamp: self.tagger = stamptag() self.timestamp = newstamp return str(newstamp)+self.tagger.next() stamper = uniquestamp() print map(stamper.format, [1,1,1,2,2,3,4,4]) output: DKJ ['1', '1A', '1B', '2', '2A', '3', '4', '4A'] A: Quite similar to Ali A, but I'll post mine anyway: class unique_timestamp: suffixes = " ABCDEFGHIJKLMNOPQRSTUVWXYZ" def __init__(self): self.previous_timestamps = {} pass def uniquify(self, timestamp): times_seen_before = self.previous_timestamps.get(timestamp, 0) self.previous_timestamps[timestamp] = times_seen_before + 1 if times_seen_before > 0: return str(timestamp) + self.suffixes[times_seen_before] else: return str(timestamp) Usage: >>> u = unique_timestamp() >>> u.uniquify(1) '1' >>> u.uniquify(1) '1A' >>> u.uniquify(1) '1B' >>> u.uniquify(2) '2' A: Does the suffix have to be letters like that? from itertools import count def unique(timestamp): if timestamp in unique.ts.keys(): return timestamp + '.' + str(unique.ts[timestamp].next()) else: unique.ts[timestamp] = count() return timestamp unique.ts = {} You can define a different count if you want the letters back. This isn't the same as your perl code, though. It keeps a dict around so if you have lots of unique timestamps then you'll use lots of memory. It handles out of order calls, which the original doesn't (i.e. u(1), u(2), u(1)). A: This is my first time answering, and I used globals, but it seemed the simplest way to me. from string import uppercase last_ts = None letters = None def increment(letters): if not letters: return "A" last_letter = letters[-1] if last_letter == "Z": return increment(letters[:-1]) + "A" return letters[:-1] + uppercase[uppercase.index(last_letter) + 1] def uniquify(timestamp): global last_ts, letters if timestamp == last_ts: letters = increment(letters) return timestamp + letters last_ts = timestamp letters = None return timestamp print uniquify("1") print uniquify('1') print uniquify("1") print uniquify("2") for each in range(100): print uniquify("2") 1 1A 1B 2 2A 2B 2C 2D 2E 2F 2G 2H 2I 2J 2K 2L 2M 2N 2O 2P 2Q 2R 2S 2T 2U 2V 2W 2X 2Y 2Z 2AA 2AB 2AC 2AD 2AE 2AF 2AG 2AH 2AI 2AJ 2AK 2AL 2AM 2AN 2AO 2AP 2AQ 2AR 2AS 2AT 2AU 2AV 2AW 2AX 2AY 2AZ 2BA 2BB 2BC 2BD 2BE 2BF 2BG 2BH 2BI 2BJ 2BK 2BL 2BM 2BN 2BO 2BP 2BQ 2BR 2BS 2BT 2BU 2BV 2BW 2BX 2BY 2BZ 2CA 2CB 2CC 2CD 2CE 2CF 2CG 2CH 2CI 2CJ 2CK 2CL 2CM 2CN 2CO 2CP 2CQ 2CR 2CS 2CT 2CU 2CV A: Looking at the problem it seems like a good fit for a coroutine (Python 2.5 or higher). Here's some code that will roughly produce the same result: def uniqify(): seen = {} val = (yield None) while True: if val in seen: idxa, idxb = seen[val] idxb += 1 else: idxa, idxb = (len(seen)+1, ord('a')) seen[val] = (idxa, idxb) uniq = "%s%s" % (idxa, chr(idxb)) val = (yield uniq) And here's how you use it: >>> u = send.uniqify() >>> u.next() #need this to start the generator >>> u.send(1) '1a' >>> u.send(1) '1b' >>> u.send(1) '1c' >>> u.send(2) '2a' >>> u.send(2) '2b' >>> u.send(1) #you can go back to previous values '1d' >>> u.send('stringy') #you can send it anything that can be used as a dict key '3a'
How would you translate this from Perl to Python?
I've got a Perl function which takes a timestamp and returns either the unchanged timestamp (if it's never seen it before) or otherwise, it appends some letters to make it unique: sub uniqify($) { my $timestamp = shift; state $last_ts = -1; state $next_letter = 'A'; if ($timestamp == $last_ts) { $timestamp .= $next_letter++; } else { $last_ts = $timestamp; $next_letter = 'A'; } return $timestamp; } So if you call it four times, with the values 1, 1, 1, and 2, it will return 1, then 1A, then 1B, then 2. Note: It only ever gets called with ever-increasing timestamps, so it doesn't need to recall every one it's ever seen, just the last one. Now I need to translate this function to Python. I've learned that I can replace the "state" variables with globals (yuck!) or perhaps attach them to the function as attributes, but neither of those is particularly elegant. Also, Python doesn't have something like Perl's magic autoincrement, where if you "++" a variable whose value is "A", it becomes "B" -- or if it's "Z", it becomes "AA". So that's a curveball too. I'm hacking together a solution, but it's really ugly and hard to read. Translating from Perl to Python is supposed to have the opposite effect, right? :) So I'm offering this as a challenge to SO users. Can you make it an elegant Python function?
[ "Look at this answer for a robust method to convert a number to an alphanumeric id\nThe code I present doesn't go from 'Z' to 'AA', instead goes to 'BA', but I suppose that doesn't matter, it still produces a unique id\nfrom string import uppercase as up\nimport itertools\n\ndef to_base(q, alphabet):\n if q < 0: raise ValueError( \"must supply a positive integer\" )\n l = len(alphabet)\n converted = []\n while q != 0:\n q, r = divmod(q, l)\n converted.insert(0, alphabet[r])\n return \"\".join(converted) or alphabet[0]\n\nclass TimestampUniqifier( object ):\n def __init__(self):\n self.last = ''\n self.counter = itertools.count()\n def __call__( self, str ):\n if str == self.last:\n suf = self.counter.next()\n return str + to_base( suf, up )\n else:\n self.last = str\n self.counter = itertools.count()\n return str \n\ntimestamp_uniqify = TimestampUniqifier()\n\nusage:\ntimestamp_uniqify('1')\n'1'\ntimestamp_uniqify('1')\n'1A'\ntimestamp_uniqify('1')\n'1B'\ntimestamp_uniqify('1')\n'1C'\ntimestamp_uniqify('2')\n'2'\ntimestamp_uniqify('3')\n'3'\ntimestamp_uniqify('3')\n'3A'\ntimestamp_uniqify('3')\n'3B'\n\nYou can call it maaaany times and it will still produce good results:\nfor i in range(100): print timestamp_uniqify('4')\n\n4\n4A\n4B\n4C\n4D\n4E\n4F\n4G\n4H\n4I\n4J\n4K\n4L\n4M\n4N\n4O\n4P\n4Q\n4R\n4S\n4T\n4U\n4V\n4W\n4X\n4Y\n4Z\n4BA\n4BB\n4BC\n4BD\n4BE\n4BF\n4BG\n4BH\n4BI\n4BJ\n4BK\n4BL\n4BM\n4BN\n4BO\n4BP\n4BQ\n4BR\n4BS\n4BT\n4BU\n4BV\n4BW\n4BX\n4BY\n4BZ\n4CA\n4CB\n4CC\n4CD\n4CE\n4CF\n4CG\n4CH\n4CI\n4CJ\n4CK\n4CL\n4CM\n4CN\n4CO\n4CP\n4CQ\n4CR\n4CS\n4CT\n4CU\n4CV\n4CW\n4CX\n4CY\n4CZ\n4DA\n4DB\n4DC\n4DD\n4DE\n4DF\n4DG\n4DH\n4DI\n4DJ\n4DK\n4DL\n4DM\n4DN\n4DO\n4DP\n4DQ\n4DR\n4DS\n4DT\n4DU\n\n", "Well, sorry to say, but you can't just do a direct translation from Perl to Python (including bit-for-bit Perlisms) and expect the outcome to be prettier. It won't be, it will be considerably uglier.\nIf you want the prettiness of Python you will need to use Python idioms instead.\nNow for the question at hand:\nfrom string import uppercase\n\nclass Uniquifier(object):\n\n def __init__(self):\n self.last_timestamp = None\n self.last_suffix = 0\n\n def uniquify(self, timestamp):\n if timestamp == self.last_timestamp:\n timestamp = '%s%s' % (timestamp,\n uppercase[self.last_suffix])\n self.last_suffix += 1\n else:\n self.last_suffix = 0\n self.timestamp = timestamp\n return timestamp\n\nuniquifier = Uniquifier()\nuniquifier.uniquify(a_timestamp)\n\nPrettier? Maybe. More readable? Probably.\nEdit (re comments): Yes this fails after Z, and I am altogether unhappy with this solution. So I won't fix it, but might offer something better, like using a number instead:\ntimestamp = '%s%s' % (timestamp,\n self.last_suffix)\n\nIf it were me, I would do this:\nimport uuid\n\ndef uniquify(timestamp):\n return '%s-%s' % (timestamp, uuid.uuid4())\n\nAnd just be happy.\n", "I just tested this up to 1000 against the original perl implementation and diff returns the same results for both. The suffix code is tricky -- this is not a base 36 counter. Hasen J's solution - though it produces a unique timestamp - isn't quite the same since it goes from 'Z' to 'BA', when it should instead go to 'AA' to match the perl ++ operator.\n#!/usr/bin/python\n\nclass uniqify:\n def __init__(self):\n self.last_timestamp = -1\n self.next_suffix = 'A'\n return\n\n def suffix(self):\n s = self.next_suffix\n letters = [l for l in self.next_suffix]\n if letters[-1] == 'Z':\n letters.reverse()\n nonz = None\n for i in range(len(letters)):\n if letters[i] != 'Z':\n nonz = i\n break\n if nonz is not None:\n letters[nonz] = chr(ord(letters[nonz]) + 1)\n for i in range(0, nonz):\n letters[i] = 'A'\n else:\n letters = ['A'] * (len(letters) + 1)\n letters.reverse()\n else:\n letters[-1] = chr(ord(letters[-1]) + 1)\n\n self.next_suffix = ''.join(letters)\n return s\n\n def reset(self):\n self.next_suffix = 'A'\n return\n\n def __call__(self, timestamp):\n if timestamp == self.last_timestamp:\n timestamp_str = '%s%s' % (timestamp, self.suffix())\n else:\n self.last_timestamp = timestamp\n self.reset()\n timestamp_str = '%s' % timestamp\n\n return timestamp_str\n\nuniqify = uniqify()\n\nif __name__ == '__main__':\n for n in range(1000):\n print uniqify(1)\n for n in range(1000):\n print uniqify(2)\n\n", "The class is generic and boring, but This is my very first recursive generator. <3\ndef stamptag():\n yield ''\n prefixtag = stamptag()\n prefix = prefixtag.next()\n while True:\n for i in range(ord('A'),ord('Z')+1):\n yield prefix+chr(i)\n prefix = prefixtag.next()\n\ntagger = stamptag()\nfor i in range(3000):\n tagger.next()\nprint tagger.next()\n\nclass uniquestamp:\n def __init__(self):\n self.timestamp = -1\n self.tagger = stamptag()\n\n def format(self,newstamp):\n if self.timestamp < newstamp:\n self.tagger = stamptag()\n self.timestamp = newstamp\n return str(newstamp)+self.tagger.next()\n\nstamper = uniquestamp()\nprint map(stamper.format, [1,1,1,2,2,3,4,4])\n\noutput:\nDKJ\n['1', '1A', '1B', '2', '2A', '3', '4', '4A']\n\n", "Quite similar to Ali A, but I'll post mine anyway:\nclass unique_timestamp:\n suffixes = \" ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n def __init__(self):\n self.previous_timestamps = {}\n pass\n def uniquify(self, timestamp):\n times_seen_before = self.previous_timestamps.get(timestamp, 0)\n self.previous_timestamps[timestamp] = times_seen_before + 1\n if times_seen_before > 0:\n return str(timestamp) + self.suffixes[times_seen_before]\n else:\n return str(timestamp)\n\nUsage:\n>>> u = unique_timestamp()\n>>> u.uniquify(1)\n'1'\n>>> u.uniquify(1)\n'1A'\n>>> u.uniquify(1)\n'1B'\n>>> u.uniquify(2)\n'2'\n\n", "Does the suffix have to be letters like that?\nfrom itertools import count\ndef unique(timestamp): \n if timestamp in unique.ts.keys():\n return timestamp + '.' + str(unique.ts[timestamp].next())\n else:\n unique.ts[timestamp] = count()\n return timestamp\nunique.ts = {}\n\nYou can define a different count if you want the letters back.\nThis isn't the same as your perl code, though.\n\nIt keeps a dict around so if you have lots of unique timestamps then you'll use lots of memory.\nIt handles out of order calls, which the original doesn't (i.e. u(1), u(2), u(1)).\n\n", "This is my first time answering, and I used globals, but it seemed the simplest way to me.\nfrom string import uppercase\n\nlast_ts = None\nletters = None\n\ndef increment(letters):\n if not letters:\n return \"A\"\n last_letter = letters[-1]\n if last_letter == \"Z\":\n return increment(letters[:-1]) + \"A\" \n return letters[:-1] + uppercase[uppercase.index(last_letter) + 1]\n\ndef uniquify(timestamp):\n global last_ts, letters\n if timestamp == last_ts:\n letters = increment(letters)\n return timestamp + letters\n last_ts = timestamp\n letters = None\n return timestamp\n\nprint uniquify(\"1\")\nprint uniquify('1')\nprint uniquify(\"1\")\nprint uniquify(\"2\")\nfor each in range(100): print uniquify(\"2\")\n\n\n1\n1A\n1B\n2\n2A\n2B\n2C\n2D\n2E\n2F\n2G\n2H\n2I\n2J\n2K\n2L\n2M\n2N\n2O\n2P\n2Q\n2R\n2S\n2T\n2U\n2V\n2W\n2X\n2Y\n2Z\n2AA\n2AB\n2AC\n2AD\n2AE\n2AF\n2AG\n2AH\n2AI\n2AJ\n2AK\n2AL\n2AM\n2AN\n2AO\n2AP\n2AQ\n2AR\n2AS\n2AT\n2AU\n2AV\n2AW\n2AX\n2AY\n2AZ\n2BA\n2BB\n2BC\n2BD\n2BE\n2BF\n2BG\n2BH\n2BI\n2BJ\n2BK\n2BL\n2BM\n2BN\n2BO\n2BP\n2BQ\n2BR\n2BS\n2BT\n2BU\n2BV\n2BW\n2BX\n2BY\n2BZ\n2CA\n2CB\n2CC\n2CD\n2CE\n2CF\n2CG\n2CH\n2CI\n2CJ\n2CK\n2CL\n2CM\n2CN\n2CO\n2CP\n2CQ\n2CR\n2CS\n2CT\n2CU\n2CV\n\n", "Looking at the problem it seems like a good fit for a coroutine (Python 2.5 or higher). Here's some code that will roughly produce the same result:\ndef uniqify():\n seen = {}\n val = (yield None)\n while True:\n if val in seen:\n idxa, idxb = seen[val]\n idxb += 1\n else:\n idxa, idxb = (len(seen)+1, ord('a'))\n seen[val] = (idxa, idxb)\n uniq = \"%s%s\" % (idxa, chr(idxb))\n val = (yield uniq)\n\nAnd here's how you use it:\n>>> u = send.uniqify()\n>>> u.next() #need this to start the generator\n>>> u.send(1)\n'1a'\n>>> u.send(1)\n'1b'\n>>> u.send(1)\n'1c'\n>>> u.send(2)\n'2a'\n>>> u.send(2)\n'2b'\n>>> u.send(1) #you can go back to previous values\n'1d'\n>>> u.send('stringy') #you can send it anything that can be used as a dict key\n'3a'\n\n" ]
[ 7, 5, 3, 2, 1, 1, 0, 0 ]
[]
[]
[ "perl", "python" ]
stackoverflow_0000604721_perl_python.txt
Q: How to run an operation on a collection in Python and collect the results? How to run an operation on a collection in Python and collect the results? So if I have a list of 100 numbers, and I want to run a function like this for each of them: Operation ( originalElement, anotherVar ) # returns new number. and collect the result like so: result = another list... How do I do it? Maybe using lambdas? A: List comprehensions. In Python they look something like: a = [f(x) for x in bar] Where f(x) is some function and bar is a sequence. You can define f(x) as a partially applied function with a construct like: def foo(x): return lambda f: f*x Which will return a function that multiplies the parameter by x. A trivial example of this type of construct used in a list comprehension looks like: >>> def foo (x): ... return lambda f: f*x ... >>> a=[1,2,3] >>> fn_foo = foo(5) >>> [fn_foo (y) for y in a] [5, 10, 15] Although I don't imagine using this sort of construct in any but fairly esoteric cases. Python is not a true functional language, so it has less scope to do clever tricks with higher order functions than (say) Haskell. You may find applications for this type of construct, but it's not really that pythonic. You could achieve a simple transformation with something like: >>> y=5 >>> a=[1,2,3] >>> [x*y for x in a] [5, 10, 15] A: Another (somewhat depreciated) method of doing this is: def kevin(v): return v*v vals = range(0,100) map(kevin,vals) A: List comprehensions, generator expressions, reduce function.
How to run an operation on a collection in Python and collect the results?
How to run an operation on a collection in Python and collect the results? So if I have a list of 100 numbers, and I want to run a function like this for each of them: Operation ( originalElement, anotherVar ) # returns new number. and collect the result like so: result = another list... How do I do it? Maybe using lambdas?
[ "List comprehensions. In Python they look something like:\na = [f(x) for x in bar]\n\nWhere f(x) is some function and bar is a sequence.\nYou can define f(x) as a partially applied function with a construct like:\ndef foo(x):\n return lambda f: f*x\n\nWhich will return a function that multiplies the parameter by x. A trivial example of this type of construct used in a list comprehension looks like:\n>>> def foo (x):\n... return lambda f: f*x\n... \n>>> a=[1,2,3]\n>>> fn_foo = foo(5)\n>>> [fn_foo (y) for y in a]\n[5, 10, 15]\n\nAlthough I don't imagine using this sort of construct in any but fairly esoteric cases. Python is not a true functional language, so it has less scope to do clever tricks with higher order functions than (say) Haskell. You may find applications for this type of construct, but it's not really that pythonic. You could achieve a simple transformation with something like:\n>>> y=5\n>>> a=[1,2,3]\n>>> [x*y for x in a]\n[5, 10, 15]\n\n", "Another (somewhat depreciated) method of doing this is:\ndef kevin(v):\n return v*v\nvals = range(0,100)\nmap(kevin,vals)\n", "List comprehensions, generator expressions, reduce function.\n" ]
[ 12, 1, 0 ]
[]
[]
[ "lambda", "list", "python" ]
stackoverflow_0000628150_lambda_list_python.txt
Q: How do i write a regular expression for the following pattern in python? How do i look for the following pattern using regular expression in python? for the two cases Am looking for str2 after the "=" sign Case 1: str1=str2 Case 2: str1 = str2 please note there can be a space or none between the either side of the "=" sign Mine is like this, but only works for one of the cases! m=re.search('(?<=str\s\=\s)\w+','str = str2') returns str2 Help! Gath A: if you indeed have only such simple strings to parse you don't need regular expression. you can just partition on = and strip (or even lstrip) last element of a resulting tuple: >>> case = 'str = str2' >>> case.partition('=')[2].lstrip() 'str2' it'll be much faster than regexps. and just to show how fast i've made a simple test: >>> timeit.timeit("'str1 = str2 '.partition('=')[2].strip()") 0.49051564213846177 >>> timeit.timeit("'str1 = str2 '.split('=')[1].strip()") 0.97673281637025866 >>> timeit.timeit('import re') 0.65663786250422618 A: re.search(r'=\s*(.*)', 'str = str2').group(1) or if you just want a single word: re.search(r'=\s*(\w+)', 'str = str2').group(1) Extended to specific initial string: re.search(r'\bstr\s*=\s*(\w+)', 'str=str2').group(1) \b = word boundary, so won't match "somestr=foo" It would be quicker to go trough all options once, instead of searching for single options one at the time: option_str = "a=b, c=d, g=h" options = dict(re.findall(r'(\w+)\s*=\s*(\w+)', option_str)) options['c'] # -> 'd' A: If your data is fixed then you can do this without using regex. Just split it on '='. For example: >>> case1 = "str1=str2" >>> case2 = "str1 = str2" >>> str2 = case1.split('=')[1].strip() >>> str2 = case2.split('=')[1].strip() This YOURCASE.split('=')[1].strip() statement will work for any cases. A: Simply use split function A: I think a regex is overkill if you only want to deal with the above two cases. Here's what I'd do- >>> case1 = "str1=str2" >>> case2 = "str1 = str2" >>> case2.split() ['str1', '=', 'str2'] >>> ''.join(case2.split()) 'str1=str2' >>> case1[5:] 'str2' >>> ''.join(case2.split())[5:] 'str2' >>> Assumption I assume you are looking for the specific token 'str1'. I also assume that str1 can be assigned different values. Something like what you'd have in a configuration file => propertyName = value. This is just my opinion. I knew that other ways were possible! SilentGhost gives a nice (better!) alternative. Hope this helps. A: Expanding on @batbrat's answer, and the other suggestions, you can use re.split() to separate the input string. The pattern can use \s (whitespace) or an explicit space. >>> import re >>> c1="str1=str2" >>> c2="str1 = str2" >>> re.split(' ?= ?',c1) ['str1', 'str2'] >>> re.split(' ?= ?',c2) ['str1', 'str2'] >>> re.split(r'\s?=\s?',c1) ['str1', 'str2'] >>> re.split(r'\s?=\s?',c2) ['str1', 'str2'] >>> A: Two cases: (case 1) if there is a single space before the '=', then there must also be a single space after the '=' m=re.search(r'(?<=\S)(?:\s=\s|=)(\w+)','str = str2') print m.group(1) (case 2) otherwise, m=re.search(r'(?<=\S)\s?=\s?(\w+)','str = str2') print m.group(1) In the first case, you could also use the "(?P=…" construct for the second space or lack of it, but it still wouldn't work for a positive lookbehind assertion, since it wouldn't be a constant length subexpression. A: Related idea: I find using graphical regular expression tool helpful when trying to figure out correct pattern: http://kodos.sf.net.
How do i write a regular expression for the following pattern in python?
How do i look for the following pattern using regular expression in python? for the two cases Am looking for str2 after the "=" sign Case 1: str1=str2 Case 2: str1 = str2 please note there can be a space or none between the either side of the "=" sign Mine is like this, but only works for one of the cases! m=re.search('(?<=str\s\=\s)\w+','str = str2') returns str2 Help! Gath
[ "if you indeed have only such simple strings to parse you don't need regular expression. you can just partition on = and strip (or even lstrip) last element of a resulting tuple:\n>>> case = 'str = str2'\n>>> case.partition('=')[2].lstrip()\n'str2'\n\nit'll be much faster than regexps. and just to show how fast i've made a simple test:\n>>> timeit.timeit(\"'str1 = str2 '.partition('=')[2].strip()\")\n0.49051564213846177\n>>> timeit.timeit(\"'str1 = str2 '.split('=')[1].strip()\")\n0.97673281637025866\n>>> timeit.timeit('import re')\n0.65663786250422618\n\n", "re.search(r'=\\s*(.*)', 'str = str2').group(1)\n\nor if you just want a single word:\nre.search(r'=\\s*(\\w+)', 'str = str2').group(1)\n\nExtended to specific initial string:\nre.search(r'\\bstr\\s*=\\s*(\\w+)', 'str=str2').group(1)\n\n\\b = word boundary, so won't match \"somestr=foo\" \nIt would be quicker to go trough all options once, instead of searching for single options one at the time:\noption_str = \"a=b, c=d, g=h\"\noptions = dict(re.findall(r'(\\w+)\\s*=\\s*(\\w+)', option_str))\noptions['c'] # -> 'd'\n\n", "If your data is fixed then you can do this without using regex. Just split it on '='.\nFor example:\n>>> case1 = \"str1=str2\"\n>>> case2 = \"str1 = str2\"\n\n>>> str2 = case1.split('=')[1].strip()\n>>> str2 = case2.split('=')[1].strip()\n\nThis YOURCASE.split('=')[1].strip() statement will work for any cases.\n", "Simply use split function\n", "I think a regex is overkill if you only want to deal with the above two cases. Here's what I'd do-\n>>> case1 = \"str1=str2\"\n>>> case2 = \"str1 = str2\"\n>>> case2.split()\n['str1', '=', 'str2']\n>>> ''.join(case2.split())\n'str1=str2'\n>>> case1[5:]\n'str2'\n>>> ''.join(case2.split())[5:]\n'str2'\n>>> \n\nAssumption\nI assume you are looking for the specific token 'str1'. I also assume that str1 can be assigned different values. Something like what you'd have in a configuration file => propertyName = value.\nThis is just my opinion.\nI knew that other ways were possible! SilentGhost gives a nice (better!) alternative.\nHope this helps.\n", "Expanding on @batbrat's answer, and the other suggestions, you can use re.split() to separate the input string. The pattern can use \\s (whitespace) or an explicit space.\n>>> import re\n>>> c1=\"str1=str2\"\n>>> c2=\"str1 = str2\"\n>>> re.split(' ?= ?',c1)\n['str1', 'str2']\n>>> re.split(' ?= ?',c2)\n['str1', 'str2']\n>>> re.split(r'\\s?=\\s?',c1)\n['str1', 'str2']\n>>> re.split(r'\\s?=\\s?',c2)\n['str1', 'str2']\n>>> \n\n", "Two cases:\n\n(case 1) if there is a single space before the '=', then there must also be a single space after the '='\nm=re.search(r'(?<=\\S)(?:\\s=\\s|=)(\\w+)','str = str2')\nprint m.group(1)\n\n(case 2) otherwise,\nm=re.search(r'(?<=\\S)\\s?=\\s?(\\w+)','str = str2')\nprint m.group(1)\n\n\nIn the first case, you could also use the \"(?P=…\" construct for the second space or lack of it, but it still wouldn't work for a positive lookbehind assertion, since it wouldn't be a constant length subexpression.\n", "Related idea: I find using graphical regular expression tool helpful when trying to figure out correct pattern: http://kodos.sf.net.\n" ]
[ 8, 3, 1, 1, 0, 0, 0, 0 ]
[]
[]
[ "python", "regex", "string" ]
stackoverflow_0000614458_python_regex_string.txt
Q: How do you get the text from an HTML 'datacell' using BeautifulSoup I have been trying to strip out some data from HTML files. I have the logic coded to get the right cells. Now I am struggling to get the actual contents of the 'cell': here is my HTML snippet: headerRows[0][10].contents [<font size="+0"><font face="serif" size="1"><b>Apples Produced</b><font size="3"> </font></font></font>] Note that this is a list item from Python []. I need the value Apples Produced but can't get to it. Any suggestions would be appreciated Suggestions on a good book that explains this would earn my eternal gratitude Thanks for that answer. However-isn't there a more general answer. What happens if my cell doesn't have a bold attribute say it is: [<font size="+0"><font face="serif" size="1"><I>Apples Produced</I><font size="3"> </font></font></font>] Apples Produced I am trying to learn to read/understand the documentation and your response will help I really appreciate this help. The best thing about these answers is that it is a lot easier to generalize from them then I have been able to do so from the BeautifulSoup documentation. I learned to program in the Fortran era and now I am learning python and I am amazed at its power - BeautifulSoup is an example. Making a coherent whole of the documentation is tough for me. Cheers A: The BeautifulSoup documentation should cover everything you need - in this case it looks like you want to use findNext: headerRows[0][10].findNext('b').string A more generic solution which doesn't rely on the <b> tag would be to use the text argument to findAll, which allows you to search only for NavigableString objects: >>> s = BeautifulSoup(u'<p>Test 1 <span>More</span> Test 2</p>') >>> u''.join([s.string for s in s.findAll(text=True)]) u'Test 1 More Test 2' A: headerRows[0][10].contents[0].find('b').string A: I have a base class that I extend all Beautiful Soup classes with a bunch of methods that help me get at text within a group of elements that I don't necessarily want to rely on the structure of. One of those methods is the following: def clean(self, val): if type(val) is not StringType: val = str(val) val = re.sub(r'<.*?>', '', s) #remove tags val = re.sub("\s+" , " ", val) #collapse internal whitespace return val.strip() #remove leading & trailing whitespace
How do you get the text from an HTML 'datacell' using BeautifulSoup
I have been trying to strip out some data from HTML files. I have the logic coded to get the right cells. Now I am struggling to get the actual contents of the 'cell': here is my HTML snippet: headerRows[0][10].contents [<font size="+0"><font face="serif" size="1"><b>Apples Produced</b><font size="3"> </font></font></font>] Note that this is a list item from Python []. I need the value Apples Produced but can't get to it. Any suggestions would be appreciated Suggestions on a good book that explains this would earn my eternal gratitude Thanks for that answer. However-isn't there a more general answer. What happens if my cell doesn't have a bold attribute say it is: [<font size="+0"><font face="serif" size="1"><I>Apples Produced</I><font size="3"> </font></font></font>] Apples Produced I am trying to learn to read/understand the documentation and your response will help I really appreciate this help. The best thing about these answers is that it is a lot easier to generalize from them then I have been able to do so from the BeautifulSoup documentation. I learned to program in the Fortran era and now I am learning python and I am amazed at its power - BeautifulSoup is an example. Making a coherent whole of the documentation is tough for me. Cheers
[ "The BeautifulSoup documentation should cover everything you need - in this case it looks like you want to use findNext:\nheaderRows[0][10].findNext('b').string\n\nA more generic solution which doesn't rely on the <b> tag would be to use the text argument to findAll, which allows you to search only for NavigableString objects:\n>>> s = BeautifulSoup(u'<p>Test 1 <span>More</span> Test 2</p>')\n>>> u''.join([s.string for s in s.findAll(text=True)])\nu'Test 1 More Test 2'\n\n", "headerRows[0][10].contents[0].find('b').string\n\n", "I have a base class that I extend all Beautiful Soup classes with a bunch of methods that help me get at text within a group of elements that I don't necessarily want to rely on the structure of. One of those methods is the following:\n def clean(self, val):\n if type(val) is not StringType: val = str(val)\n val = re.sub(r'<.*?>', '', s) #remove tags\n val = re.sub(\"\\s+\" , \" \", val) #collapse internal whitespace\n return val.strip() #remove leading & trailing whitespace\n\n" ]
[ 5, 3, 0 ]
[]
[]
[ "beautifulsoup", "html", "parsing", "python" ]
stackoverflow_0000223328_beautifulsoup_html_parsing_python.txt
Q: BeautifulSoup gives me unicode+html symbols, rather than straight up unicode. Is this a bug or misunderstanding? I'm using BeautifulSoup to scrape a website. The website's page renders fine in my browser: Oxfam International’s report entitled “Offside! http://www.coopamerica.org/programs/responsibleshopper/company.cfm?id=271 In particular, the single and double quotes look fine. They look html symbols rather than ascii, though strangely when I view source in FF3 they appear to be normal ascii. Unfortunately, when I scrape I get something like this u'Oxfam International\xe2€™s report entitled \xe2€œOffside! oops, I mean this: u'Oxfam International\xe2€™s report entitled \xe2€œOffside! The page's meta data indicates 'iso-88959-1' encoding. I've tried different encodings, played with unicode->ascii and html->ascii third party functions, and looked at the MS/iso-8859-1 discrepancy, but the fact of the matter is that ™ has nothing to do with a single quote, and I can't seem to turn the unicode+htmlsymbol combo into the right ascii or html symbol--in my limited knowledge, which is why I'm seeking help. I'd be happy with an ascii double quote, " or " The problem the following is that I'm concerned there are other funny symbols decoded incorrectly. \xe2€™ Below is some python to reproduce what I'm seeing, followed by the things I've tried. import twill from twill import get_browser from twill.commands import go from BeautifulSoup import BeautifulSoup as BSoup url = 'http://www.coopamerica.org/programs/responsibleshopper/company.cfm?id=271' twill.commands.go(url) soup = BSoup(twill.commands.get_browser().get_html()) ps = soup.body("p") p = ps[52] >>> p Traceback (most recent call last): File "<stdin>", line 1, in <module> UnicodeEncodeError: 'ascii' codec can't encode character u'\xe2' in position 22: ordinal not in range(128) >>> p.string u'Oxfam International\xe2€™s report entitled \xe2€œOffside!<elided>\r\n' http://groups.google.com/group/comp.lang.python/browse_frm/thread/9b7bb3f621b4b8e4/3b00a890cf3a5e46?q=htmlentitydefs&rnum=3&hl=en#3b00a890cf3a5e46 http://www.fourmilab.ch/webtools/demoroniser/ http://www.crummy.com/software/BeautifulSoup/documentation.html http://www.cs.tut.fi/~jkorpela/www/windows-chars.html >>> AsciiDammit.asciiDammit(p.decode()) u'<p>Oxfam International\xe2€™s report entitled \xe2€œOffside! >>> handle_html_entities(p.decode()) u'<p>Oxfam International\xe2\u20ac\u2122s report entitled \xe2\u20ac\u0153Offside! >>> unicodedata.normalize('NFKC', p.decode()).encode('ascii','ignore') '<p>Oxfam International€™s report entitled €œOffside! >>> htmlStripEscapes(p.string) u'Oxfam International\xe2TMs report entitled \xe2Offside! EDIT: I've tried using a different BS parser: import html5lib bsoup_parser = html5lib.HTMLParser(tree=html5lib.treebuilders.getTreeBuilder("beautifulsoup")) soup = bsoup_parser.parse(twill.commands.get_browser().get_html()) ps = soup.body("p") ps[55].decode() which gives me this u'<p>Oxfam International\xe2\u20ac\u2122s report entitled \xe2\u20ac\u0153Offside! the best case decode seems to give me the same results: unicodedata.normalize('NFKC', p.decode()).encode('ascii','ignore') '<p>Oxfam InternationalTMs report entitled Offside! EDIT 2: I am running Mac OS X 4 with FF 3.0.7 and Firebug Python 2.5 (wow, can't believe I didn't state this from the beginning) A: That's one seriously messed up page, encoding-wise :-) There's nothing really wrong with your approach at all. I would probably tend to do the conversion before passing it to BeautifulSoup, just because I'm persnickity: import urllib html = urllib.urlopen('http://www.coopamerica.org/programs/responsibleshopper/company.cfm?id=271').read() h = html.decode('iso-8859-1') soup = BeautifulSoup(h) In this case, the page's meta tag is lying about the encoding. The page is actually in utf-8... Firefox's page info reveals the real encoding, and you can actually see this charset in the response headers returned by the server: curl -i http://www.coopamerica.org/programs/responsibleshopper/company.cfm?id=271 HTTP/1.1 200 OK Connection: close Date: Tue, 10 Mar 2009 13:14:29 GMT Server: Microsoft-IIS/6.0 X-Powered-By: ASP.NET Set-Cookie: COMPANYID=271;path=/ Content-Language: en-US Content-Type: text/html; charset=UTF-8 If you do the decode using 'utf-8', it will work for you (or, at least, is did for me): import urllib html = urllib.urlopen('http://www.coopamerica.org/programs/responsibleshopper/company.cfm?id=271').read() h = html.decode('utf-8') soup = BeautifulSoup(h) ps = soup.body("p") p = ps[52] print p A: It's actually UTF-8 misencoded as CP1252: >>> print u'Oxfam International\xe2€™s report entitled \xe2€œOffside!'.encode('cp1252').decode('utf8') Oxfam International’s report entitled “Offside!
BeautifulSoup gives me unicode+html symbols, rather than straight up unicode. Is this a bug or misunderstanding?
I'm using BeautifulSoup to scrape a website. The website's page renders fine in my browser: Oxfam International’s report entitled “Offside! http://www.coopamerica.org/programs/responsibleshopper/company.cfm?id=271 In particular, the single and double quotes look fine. They look html symbols rather than ascii, though strangely when I view source in FF3 they appear to be normal ascii. Unfortunately, when I scrape I get something like this u'Oxfam International\xe2€™s report entitled \xe2€œOffside! oops, I mean this: u'Oxfam International\xe2€™s report entitled \xe2€œOffside! The page's meta data indicates 'iso-88959-1' encoding. I've tried different encodings, played with unicode->ascii and html->ascii third party functions, and looked at the MS/iso-8859-1 discrepancy, but the fact of the matter is that ™ has nothing to do with a single quote, and I can't seem to turn the unicode+htmlsymbol combo into the right ascii or html symbol--in my limited knowledge, which is why I'm seeking help. I'd be happy with an ascii double quote, " or " The problem the following is that I'm concerned there are other funny symbols decoded incorrectly. \xe2€™ Below is some python to reproduce what I'm seeing, followed by the things I've tried. import twill from twill import get_browser from twill.commands import go from BeautifulSoup import BeautifulSoup as BSoup url = 'http://www.coopamerica.org/programs/responsibleshopper/company.cfm?id=271' twill.commands.go(url) soup = BSoup(twill.commands.get_browser().get_html()) ps = soup.body("p") p = ps[52] >>> p Traceback (most recent call last): File "<stdin>", line 1, in <module> UnicodeEncodeError: 'ascii' codec can't encode character u'\xe2' in position 22: ordinal not in range(128) >>> p.string u'Oxfam International\xe2€™s report entitled \xe2€œOffside!<elided>\r\n' http://groups.google.com/group/comp.lang.python/browse_frm/thread/9b7bb3f621b4b8e4/3b00a890cf3a5e46?q=htmlentitydefs&rnum=3&hl=en#3b00a890cf3a5e46 http://www.fourmilab.ch/webtools/demoroniser/ http://www.crummy.com/software/BeautifulSoup/documentation.html http://www.cs.tut.fi/~jkorpela/www/windows-chars.html >>> AsciiDammit.asciiDammit(p.decode()) u'<p>Oxfam International\xe2€™s report entitled \xe2€œOffside! >>> handle_html_entities(p.decode()) u'<p>Oxfam International\xe2\u20ac\u2122s report entitled \xe2\u20ac\u0153Offside! >>> unicodedata.normalize('NFKC', p.decode()).encode('ascii','ignore') '<p>Oxfam International€™s report entitled €œOffside! >>> htmlStripEscapes(p.string) u'Oxfam International\xe2TMs report entitled \xe2Offside! EDIT: I've tried using a different BS parser: import html5lib bsoup_parser = html5lib.HTMLParser(tree=html5lib.treebuilders.getTreeBuilder("beautifulsoup")) soup = bsoup_parser.parse(twill.commands.get_browser().get_html()) ps = soup.body("p") ps[55].decode() which gives me this u'<p>Oxfam International\xe2\u20ac\u2122s report entitled \xe2\u20ac\u0153Offside! the best case decode seems to give me the same results: unicodedata.normalize('NFKC', p.decode()).encode('ascii','ignore') '<p>Oxfam InternationalTMs report entitled Offside! EDIT 2: I am running Mac OS X 4 with FF 3.0.7 and Firebug Python 2.5 (wow, can't believe I didn't state this from the beginning)
[ "That's one seriously messed up page, encoding-wise :-)\nThere's nothing really wrong with your approach at all. I would probably tend to do the conversion before passing it to BeautifulSoup, just because I'm persnickity:\nimport urllib\nhtml = urllib.urlopen('http://www.coopamerica.org/programs/responsibleshopper/company.cfm?id=271').read()\nh = html.decode('iso-8859-1')\nsoup = BeautifulSoup(h)\n\nIn this case, the page's meta tag is lying about the encoding. The page is actually in utf-8... Firefox's page info reveals the real encoding, and you can actually see this charset in the response headers returned by the server:\ncurl -i http://www.coopamerica.org/programs/responsibleshopper/company.cfm?id=271\nHTTP/1.1 200 OK\nConnection: close\nDate: Tue, 10 Mar 2009 13:14:29 GMT\nServer: Microsoft-IIS/6.0\nX-Powered-By: ASP.NET\nSet-Cookie: COMPANYID=271;path=/\nContent-Language: en-US\nContent-Type: text/html; charset=UTF-8\n\nIf you do the decode using 'utf-8', it will work for you (or, at least, is did for me):\nimport urllib\nhtml = urllib.urlopen('http://www.coopamerica.org/programs/responsibleshopper/company.cfm?id=271').read()\nh = html.decode('utf-8')\nsoup = BeautifulSoup(h)\nps = soup.body(\"p\")\np = ps[52]\nprint p\n\n", "It's actually UTF-8 misencoded as CP1252:\n>>> print u'Oxfam International\\xe2€™s report entitled \\xe2€œOffside!'.encode('cp1252').decode('utf8')\nOxfam International’s report entitled “Offside!\n\n" ]
[ 8, 4 ]
[]
[]
[ "beautifulsoup", "html", "python", "unicode" ]
stackoverflow_0000629999_beautifulsoup_html_python_unicode.txt
Q: How can I use python's telnetlib to fetch data from a device for a fixed period of time? I'm connecting to a hardware device via telnet. That device is pretty simple in terms of I/O. So I submit a command to it, and after that the device pumps out data one line at a time, once per second. Each line just contains a number. So my question is this: if I connect to this device using python's telnetlib, how can I fetch data for a fixed period of time (or a fixed number of lines of data)? I've tried using all the various read_ commands, but they all seem to block indefinitely, apart from read_until, which I can't use as the output can't be used to determine when to stop. (I'm running python 2.5 under Cygwin, btw). Edit: Maybe the real question is, should I be using telnetlib at all for this, or should I just use the socket module? A: From your description I'm not clear if you're using telnetlib because the device you're connecting to requires terminal setup provided by telnet or because it seemed like the right thing to do. If the device is as simple as you describe--i.e. not negotiating terminal options on connection--have you considered the asynchat module? It would be appropriate for the "send command, read lines" sort of IO pattern you are describing. Alternatively, for something lower-level, you could use the socket module to open the connection to the device and then sit in a timed loop and read() the incoming data. If the lines are newline-terminated it should be simple for you to identify each individual number. If you are concerned with blocking, stick this loop in its own thread. A: In my experience, most such devices use some prompt, in which case Telnet.read_until() is appropriate: Telnet.read_until(expected[, timeout]) Read until a given string, expected, is encountered or until timeout seconds have passed. When no match is found, return whatever is available instead, possibly the empty string. Raise EOFError if the connection is closed and no cooked data is available. If no usable (repetitive) prompt is presented by the device, try Telnet.read_very_eager(), or Telnet.read_very_lazy(): Telnet.read_very_eager() Read everything that can be without blocking in I/O (eager). Raise EOFError if connection closed and no cooked data available. Return '' if no cooked data available otherwise. Do not block unless in the midst of an IAC sequence. A: It sounds like blocking isn't really your problem, since you know that you'll only be blocking for a second. Why not do something like: lines_to_read = 10 for i in range(lines_to_read): line = tel.read_until("\n") A: Read lines in a loop until you have either read the required number of lines or the time limit has been reached. However, it doesn't sound like you actual need a telnet library. Why not just use a simple TCP socket for the connection?
How can I use python's telnetlib to fetch data from a device for a fixed period of time?
I'm connecting to a hardware device via telnet. That device is pretty simple in terms of I/O. So I submit a command to it, and after that the device pumps out data one line at a time, once per second. Each line just contains a number. So my question is this: if I connect to this device using python's telnetlib, how can I fetch data for a fixed period of time (or a fixed number of lines of data)? I've tried using all the various read_ commands, but they all seem to block indefinitely, apart from read_until, which I can't use as the output can't be used to determine when to stop. (I'm running python 2.5 under Cygwin, btw). Edit: Maybe the real question is, should I be using telnetlib at all for this, or should I just use the socket module?
[ "From your description I'm not clear if you're using telnetlib because the device you're connecting to requires terminal setup provided by telnet or because it seemed like the right thing to do.\nIf the device is as simple as you describe--i.e. not negotiating terminal options on connection--have you considered the asynchat module? It would be appropriate for the \"send command, read lines\" sort of IO pattern you are describing.\nAlternatively, for something lower-level, you could use the socket module to open the connection to the device and then sit in a timed loop and read() the incoming data. If the lines are newline-terminated it should be simple for you to identify each individual number. If you are concerned with blocking, stick this loop in its own thread.\n", "In my experience, most such devices use some prompt, in which case Telnet.read_until() is appropriate:\n\nTelnet.read_until(expected[, timeout])\nRead until a given string, expected, is encountered or until timeout seconds have passed.\n When no match is found, return whatever is available instead, possibly the empty string. Raise EOFError if the connection is closed and no cooked data is available.\n\nIf no usable (repetitive) prompt is presented by the device, try Telnet.read_very_eager(), or Telnet.read_very_lazy():\n\nTelnet.read_very_eager()\nRead everything that can be without blocking in I/O (eager).\nRaise EOFError if connection closed and no cooked data available. Return '' if no cooked data available otherwise. Do not block unless in the midst of an IAC sequence.\n\n", "It sounds like blocking isn't really your problem, since you know that you'll only be blocking for a second. Why not do something like:\nlines_to_read = 10\nfor i in range(lines_to_read):\n line = tel.read_until(\"\\n\")\n\n", "Read lines in a loop until you have either read the required number of lines or the time limit has been reached. However, it doesn't sound like you actual need a telnet library. Why not just use a simple TCP socket for the connection? \n" ]
[ 5, 2, 2, 1 ]
[]
[]
[ "python", "telnet" ]
stackoverflow_0000630217_python_telnet.txt
Q: Why avoid CGI for Python with LAMP hosting? I have been using PHP for years. Lately I've come across numerous forum posts stating that PHP is outdated, that modern programming languages are easier, more secure, etc. etc. So, I decided to start learning Python. Since I'm used to using PHP, I just started building pages by uploading an .htaccess file with: addtype text/html py addhandler cgi-script .py Then, my sample pages look like: #!/usr/bin/python print "content-type: text/html\n\n" print "html tags, more stuff, etc." This works fine. But, I came across a comment in a post that said that CGI isn't the best way to use Python. Of course, it didn't mention what is the best way. Why is it that using CGI is not the best way to use Python? What is the alternative? Is there some totally other way to set up a simple Python site? Is there some completely different paradigm I should be looking at outside of .htaccess and .py files? Related Pros and Cons of different approaches to web programming in Python What’s a good lightweight Python MVC framework? (esp., @Kevin Dangoor's answer) How do I use python for web development without relying on a framework? Python Web Framework - Not App Framework or CMS Framework Python web programming A: Classic CGI isn't the best way to use anything at all. With classic CGI server has to spawn a new process for every request. As for Python, you have few alternatives: mod_wsgi mod_python fastcgi standalone Python web server (built-in, CherryPy, Tracd ) standalone Python web server on non-standard port and mod_proxy in Apache A: Why is it that using CGI is not the best way to use Python? I will stick up for CGI a little. It's good for development environments. It's simple to wire up and you don't have to worry about module reloading problems. Naturally performance is terrible, but for dev you don't care. Of course you should really be writing to the WSGI interface rather than CGI directly. You can then deploy through CGI using: wsgiref.handlers.CGIHandler().run(application) and use the same application object to deploy through mod_wsgi other whatever other WSGI server you prefer in the production environment where speed matters (and the testing environment where you want it to be as close to production as possible). A: mod_wsgi is the proper alternative. It is preferable over CGI in almost all aspects. A: Really it's just an efficiency thing - CGI spawns an entire new process for every request, which is quite heavyweight for what it does. PHP can be run through CGI as well, but mod_php embeds the interpreter within apache. There's a mod_python which does the same job, and mod_wsgi as Yuval says. A: Aside from the suggestions others make, you should really consider using a framework of some kind. You can and should be using FastCGI, mod_python, or mod_wsgi, but they weren't really intended for you to write code directly against. Might I suggest one of the following? django (my favorite for practical applications) pylons cherrypy (my favorite for not-so-practical applications) web.py A: There is a page in the Python documentation that describes the advantages and disadvantages of the various possibilities. mod_python (…) These are the reasons why mod_python should be avoided when writing new programs. WSGI The Web Server Gateway Interface or WSGI for short is currently the best possible way to Python web programming. While it is great for programmers writing frameworks, the normal person does not need to get in direct contact with it. FastCGI and stuff These days, FastCGI is never used directly.
Why avoid CGI for Python with LAMP hosting?
I have been using PHP for years. Lately I've come across numerous forum posts stating that PHP is outdated, that modern programming languages are easier, more secure, etc. etc. So, I decided to start learning Python. Since I'm used to using PHP, I just started building pages by uploading an .htaccess file with: addtype text/html py addhandler cgi-script .py Then, my sample pages look like: #!/usr/bin/python print "content-type: text/html\n\n" print "html tags, more stuff, etc." This works fine. But, I came across a comment in a post that said that CGI isn't the best way to use Python. Of course, it didn't mention what is the best way. Why is it that using CGI is not the best way to use Python? What is the alternative? Is there some totally other way to set up a simple Python site? Is there some completely different paradigm I should be looking at outside of .htaccess and .py files? Related Pros and Cons of different approaches to web programming in Python What’s a good lightweight Python MVC framework? (esp., @Kevin Dangoor's answer) How do I use python for web development without relying on a framework? Python Web Framework - Not App Framework or CMS Framework Python web programming
[ "Classic CGI isn't the best way to use anything at all. With classic CGI server has to spawn a new process for every request.\nAs for Python, you have few alternatives:\n\nmod_wsgi\nmod_python\nfastcgi\nstandalone Python web server (built-in, CherryPy, Tracd )\nstandalone Python web server on non-standard port and mod_proxy in Apache\n\n", "\nWhy is it that using CGI is not the best way to use Python?\n\nI will stick up for CGI a little. It's good for development environments.\nIt's simple to wire up and you don't have to worry about module reloading problems. Naturally performance is terrible, but for dev you don't care.\nOf course you should really be writing to the WSGI interface rather than CGI directly. You can then deploy through CGI using:\nwsgiref.handlers.CGIHandler().run(application)\n\nand use the same application object to deploy through mod_wsgi other whatever other WSGI server you prefer in the production environment where speed matters (and the testing environment where you want it to be as close to production as possible).\n", "mod_wsgi is the proper alternative. It is preferable over CGI in almost all aspects.\n", "Really it's just an efficiency thing - CGI spawns an entire new process for every request, which is quite heavyweight for what it does.\nPHP can be run through CGI as well, but mod_php embeds the interpreter within apache.\nThere's a mod_python which does the same job, and mod_wsgi as Yuval says.\n", "Aside from the suggestions others make, you should really consider using a framework of some kind. You can and should be using FastCGI, mod_python, or mod_wsgi, but they weren't really intended for you to write code directly against. Might I suggest one of the following?\n\ndjango (my favorite for practical applications)\npylons\ncherrypy (my favorite for not-so-practical applications)\nweb.py\n\n", "There is a page in the Python documentation that describes the advantages and disadvantages of the various possibilities.\nmod_python\n\n(…) These are the reasons why mod_python should be avoided when writing new programs.\n\nWSGI\n\nThe Web Server Gateway Interface or\n WSGI for short is currently the best\n possible way to Python web\n programming. While it is great for\n programmers writing frameworks, the\n normal person does not need to get in\n direct contact with it.\n\nFastCGI and stuff\n\nThese days, FastCGI is never used directly.\n\n" ]
[ 13, 5, 3, 3, 2, 2 ]
[]
[]
[ ".htaccess", "cgi", "php", "python" ]
stackoverflow_0000629919_.htaccess_cgi_php_python.txt
Q: Detect whether charset exists in python Is it possible to check in Python whether a given charset exists/is installed. For example: check('iso-8859-1') -> True check('bla') -> False A: You can use the lookup() function in the codecs module. It throws an exception if a codec does not exist: import codecs def exists_encoding(enc): try: codecs.lookup(enc) except LookupError: return False return True exists_encoding('latin1')
Detect whether charset exists in python
Is it possible to check in Python whether a given charset exists/is installed. For example: check('iso-8859-1') -> True check('bla') -> False
[ "You can use the lookup() function in the codecs module. It throws an exception if a codec does not exist:\nimport codecs\ndef exists_encoding(enc):\n try:\n codecs.lookup(enc)\n except LookupError:\n return False\n return True\nexists_encoding('latin1')\n\n" ]
[ 4 ]
[]
[]
[ "character_encoding", "python" ]
stackoverflow_0000630938_character_encoding_python.txt
Q: figure out whether python module is installed or in develop mode programmatically I tend to develop my apps in 'setup.py develop' -mode. I'd want the configuration to switch automagically on production mode when the program gets 'setup.py install'ed. This can be done by poor hacks, like checking whether installation directory contains 'setup.py', but I wonder whether pkg_resources can do this for me somehow. A: Isn't it easier, and cleaner, to just set an environment variable on your development machine, and test for os.environ['development_mode'] (or a setting of your choice)? A: Indeed, pkg_resources will do that: dist = pkg_resources.get_distribution('your-app') if dist.precedence == pkg_resources.DEVELOP_DIST: # package is in development mode ... A: Another option is to use virtualenv. Then your development environment could be identical to your production environment. Setuptools is a pretty heavy thing to depend on, in my opinion.
figure out whether python module is installed or in develop mode programmatically
I tend to develop my apps in 'setup.py develop' -mode. I'd want the configuration to switch automagically on production mode when the program gets 'setup.py install'ed. This can be done by poor hacks, like checking whether installation directory contains 'setup.py', but I wonder whether pkg_resources can do this for me somehow.
[ "Isn't it easier, and cleaner, to just set an environment variable on your development machine, and test for os.environ['development_mode'] (or a setting of your choice)?\n", "Indeed, pkg_resources will do that:\ndist = pkg_resources.get_distribution('your-app')\nif dist.precedence == pkg_resources.DEVELOP_DIST:\n # package is in development mode\n ...\n\n", "Another option is to use virtualenv. Then your development environment could be identical to your production environment. Setuptools is a pretty heavy thing to depend on, in my opinion.\n" ]
[ 5, 4, 0 ]
[]
[]
[ "packaging", "python" ]
stackoverflow_0000631996_packaging_python.txt
Q: base64 png in python on Windows How do you encode a png image into base64 using python on Windows? iconfile = open("icon.png") icondata = iconfile.read() icondata = base64.b64encode(icondata) The above works fine in Linux and OSX, but on Windows it will encode the first few characters then cut short. Why is this? A: Open the file in binary mode: open("icon.png", "rb") I'm not very familiar with Windows, but I'd imagine what's happening is that the file contains a character (0x1A) that Windows is interpreting as the end of the file (for legacy reasons) when it is opened in text mode. The other issue is that opening a file in text mode (without the 'b') on Windows will cause line endings to be rewritten, which will generally break binary files where those characters don't actually indicate the end of a line. A: To augment the answer from Miles, the first eight bytes in a PNG file are specially designed: 89 - the first byte is a check that bit 8 hasn't been stripped "PNG" - let someone read that it's a PNG format 0d 0a - the DOS end-of-line indicator, to check if there was DOS->unix conversion 1a - the DOS end-of-file character, to check that the file was opened in binary mode 0a - unix end-of-line character, to check if there was a unix->DOS conversion Your code stops at the 1a, as designed.
base64 png in python on Windows
How do you encode a png image into base64 using python on Windows? iconfile = open("icon.png") icondata = iconfile.read() icondata = base64.b64encode(icondata) The above works fine in Linux and OSX, but on Windows it will encode the first few characters then cut short. Why is this?
[ "Open the file in binary mode:\nopen(\"icon.png\", \"rb\")\n\nI'm not very familiar with Windows, but I'd imagine what's happening is that the file contains a character (0x1A) that Windows is interpreting as the end of the file (for legacy reasons) when it is opened in text mode. The other issue is that opening a file in text mode (without the 'b') on Windows will cause line endings to be rewritten, which will generally break binary files where those characters don't actually indicate the end of a line.\n", "To augment the answer from Miles, the first eight bytes in a PNG file are specially designed:\n\n89 - the first byte is a check that\nbit 8 hasn't been stripped\n\"PNG\" - let someone read that it's a\nPNG format\n0d 0a - the DOS end-of-line\nindicator, to check if there was\nDOS->unix conversion\n1a - the DOS end-of-file character,\nto check that the file was opened in\nbinary mode\n0a - unix end-of-line character, to\ncheck if there was a unix->DOS\nconversion\n\nYour code stops at the 1a, as designed.\n" ]
[ 26, 9 ]
[]
[]
[ "base64", "python", "windows" ]
stackoverflow_0000631884_base64_python_windows.txt
Q: Nested loop syntax in python server pages I am just trying to write a small web page that can parse some text using a regular expression and return the resulting matches in a table. This is the first I've used python for web development, and I have to say, it looks messy. My question is why do I only get output for the last match in my data set? I figure it has to be because the nested loops aren't formatted correctly. Here's the data I provide: groups is just an id correspoding to the regex group, and it's name to provide the header for the table. pattern is something like: (\d+)\s(\S+)\s(\S+)$ and data: 12345 SOME USER 09876 SOMEONE ELSE 54678 ANOTHER USER My simple page: <% import re pattern = form['pattern'] p = re.compile(pattern) data = form['data'] matches = p.finditer(data) lines = form['groups'].split("\n") groupids ={} for line in lines: key, val = line.split(' ') groupids[int(key.strip())] = val.strip() %> <html> <table style="border-width:1px;border-style:solid;width:60%;"> <tr> <% for k,v in groupids.iteritems():%> <th style="width:30px;text-align:center"><%= v %></th> <% # end %> </tr> <% for match in matches: #begin %><tr> <% for i in range(1, len(match.groups())+1): #begin %> <td style="border-style:solid;border-width:1px;border-spacing:0px;text-align:center;"><%= match.group(i) %></td> <% #end # end %> </tr> </table> </html> Edit Below is the test I ran Code: import re pattern = "(\d\d\d\d\d)\s(\S+)\s(\S+)" p = re.compile(pattern) data = """12345 TESTS USERS 34567 TESTS USERS 56789 TESTS USERS""" groups = """1 PIN 2 FNAME 3 LNAME""" matches = p.finditer(data) lines = groups.split("\n") print lines groupids ={} for line in lines: key, val = line.split(' ') groupids[int(key.strip())] = val.strip() for k,v in groupids.iteritems(): print "%s\t" % v, print '' for match in matches: for i in range(1, len(match.groups())+1): print "%s\t" % match.group(i), print '' Output: PIN FNAME LNAME 12345 TESTS USERS 34567 TESTS USERS 56789 TESTS USERS A: <% for match in matches: #begin %><tr> <% for i in range(1, len(match.groups())+1): #begin %> <td style="border-style:solid;border-width:1px;border-spacing:0px;text-align:center;"><%= match.group(i) %></td> <% #end # end %> Yeah, you haven't got a nested loop there. Instead you've got a loop over matches that outputs “<tr>\n”, then a second loop over range(...) that only runs after the first has finished. The second is not inside the first because it isn't indented to say so. From the doc, I think what you need to be saying is: <% for match in matches: # begin %><tr><% for group in match.groups(): # begin %><td style="border-style:solid;border-width:1px;border-spacing:0px;text-align:center;"><%= group %></td><% # end %></tr><% # end %> But I can only agree with your “messy” comment: if PSP is requiring that you torture the indenting of your HTML to fit the structure of your Python like this, it is really Doing It Wrong and you should look for another, less awful templating syntax. There are many, many templating languages for Python that have a more sensible syntax for control structures. As an example, in the one I use the above would look like: <px:for item="match" in="matches"><tr> <px:for item="group" in="match.groups()"> <td style="border-style:solid;border-width:1px;border-spacing:0px;text-align:center;"> <?_ group ?> </td> </px:for> </tr></px:for> A: I'm not sure about the interaction with the templating engine, but python would expect the inner loop to be indented under the containing loop. Try formatting it that way and see if it works. <% for match in matches: %><tr><% for i in range(1, len(match.groups())+1): %><td style="border-style:solid;border-width:1px;border-spacing:0px;text-align:center;"><%= match.group(i) %></td><% %> Or some such. The above produces "IndentationError: unindent does not match any outer indentation level" so try: <% for match in matches: %><tr><% for i in range(1, len(match.groups())+1): %><td style="border-style:solid;border-width:1px;border-spacing:0px;text-align:center;"><%= match.group(i) %></td><% %> or <% for match in matches: %><tr><% for i in range(1, len(match.groups())+1): %><td style="border-style:solid;border-width:1px;border-spacing:0px;text-align:center;"><%= match.group(i) %></td><% pass %> or some combination. Your problem is in indicating to python where the loop ends. To do this you must figure out a way to make the templating engine produce valid python with the right indentation. Also, if you can get at the generated code you could split the problem in half: first tinker with the generated code to find out what python will accept and then tinker wit the template to get it produce that.
Nested loop syntax in python server pages
I am just trying to write a small web page that can parse some text using a regular expression and return the resulting matches in a table. This is the first I've used python for web development, and I have to say, it looks messy. My question is why do I only get output for the last match in my data set? I figure it has to be because the nested loops aren't formatted correctly. Here's the data I provide: groups is just an id correspoding to the regex group, and it's name to provide the header for the table. pattern is something like: (\d+)\s(\S+)\s(\S+)$ and data: 12345 SOME USER 09876 SOMEONE ELSE 54678 ANOTHER USER My simple page: <% import re pattern = form['pattern'] p = re.compile(pattern) data = form['data'] matches = p.finditer(data) lines = form['groups'].split("\n") groupids ={} for line in lines: key, val = line.split(' ') groupids[int(key.strip())] = val.strip() %> <html> <table style="border-width:1px;border-style:solid;width:60%;"> <tr> <% for k,v in groupids.iteritems():%> <th style="width:30px;text-align:center"><%= v %></th> <% # end %> </tr> <% for match in matches: #begin %><tr> <% for i in range(1, len(match.groups())+1): #begin %> <td style="border-style:solid;border-width:1px;border-spacing:0px;text-align:center;"><%= match.group(i) %></td> <% #end # end %> </tr> </table> </html> Edit Below is the test I ran Code: import re pattern = "(\d\d\d\d\d)\s(\S+)\s(\S+)" p = re.compile(pattern) data = """12345 TESTS USERS 34567 TESTS USERS 56789 TESTS USERS""" groups = """1 PIN 2 FNAME 3 LNAME""" matches = p.finditer(data) lines = groups.split("\n") print lines groupids ={} for line in lines: key, val = line.split(' ') groupids[int(key.strip())] = val.strip() for k,v in groupids.iteritems(): print "%s\t" % v, print '' for match in matches: for i in range(1, len(match.groups())+1): print "%s\t" % match.group(i), print '' Output: PIN FNAME LNAME 12345 TESTS USERS 34567 TESTS USERS 56789 TESTS USERS
[ "<%\nfor match in matches:\n #begin\n%><tr>\n<%\nfor i in range(1, len(match.groups())+1):\n #begin\n%>\n <td style=\"border-style:solid;border-width:1px;border-spacing:0px;text-align:center;\"><%= match.group(i) %></td>\n<%\n #end\n# end\n%>\n\nYeah, you haven't got a nested loop there. Instead you've got a loop over matches that outputs “<tr>\\n”, then a second loop over range(...) that only runs after the first has finished. The second is not inside the first because it isn't indented to say so.\nFrom the doc, I think what you need to be saying is:\n<%\nfor match in matches:\n # begin\n%><tr><%\n for group in match.groups():\n # begin\n%><td style=\"border-style:solid;border-width:1px;border-spacing:0px;text-align:center;\"><%= group %></td><%\n # end\n%></tr><%\n# end\n%>\n\nBut I can only agree with your “messy” comment: if PSP is requiring that you torture the indenting of your HTML to fit the structure of your Python like this, it is really Doing It Wrong and you should look for another, less awful templating syntax. There are many, many templating languages for Python that have a more sensible syntax for control structures. As an example, in the one I use the above would look like:\n<px:for item=\"match\" in=\"matches\"><tr>\n <px:for item=\"group\" in=\"match.groups()\">\n <td style=\"border-style:solid;border-width:1px;border-spacing:0px;text-align:center;\">\n <?_ group ?>\n </td>\n </px:for>\n</tr></px:for>\n\n", "I'm not sure about the interaction with the templating engine, but python would expect the inner loop to be indented under the containing loop.\nTry formatting it that way and see if it works.\n<%\nfor match in matches:\n %><tr><%\n for i in range(1, len(match.groups())+1):\n %><td style=\"border-style:solid;border-width:1px;border-spacing:0px;text-align:center;\"><%= match.group(i) %></td><%\n%>\n\nOr some such. The above produces \"IndentationError: unindent does not match any outer indentation level\" so try:\n<%\nfor match in matches:\n %><tr><%\n for i in range(1, len(match.groups())+1):\n %><td style=\"border-style:solid;border-width:1px;border-spacing:0px;text-align:center;\"><%= match.group(i) %></td><%\n\n%>\n\nor \n<%\nfor match in matches:\n %><tr><%\n for i in range(1, len(match.groups())+1):\n %><td style=\"border-style:solid;border-width:1px;border-spacing:0px;text-align:center;\"><%= match.group(i) %></td><%\npass\n%>\n\nor some combination. Your problem is in indicating to python where the loop ends. To do this you must figure out a way to make the templating engine produce valid python with the right indentation.\nAlso, if you can get at the generated code you could split the problem in half: first tinker with the generated code to find out what python will accept and then tinker wit the template to get it produce that.\n" ]
[ 1, 0 ]
[]
[]
[ "python", "python_server_pages" ]
stackoverflow_0000632624_python_python_server_pages.txt
Q: What is the best method to read a double from a Binary file created in C? A C program spits out consecutive doubles into a binary file. I wish to read them into Python. I tried using struct.unpack('d',f.read(8)) EDIT: I used the following in C to write a random double number r = drand48(); fwrite((void*)&r, sizeof(double), 1, data); The Errors are now fixed but I cannot read the first value. for an all 0.000.. number it reads it as 3.90798504668055 but the rest are fine. A: I think you are actually reading the number correctly, but are getting confused by the display. When I read the number from your provided file, I get "3.907985046680551e-14" - this is almost but not quite zero (0.000000000000039 in expanded form). I suspect your C code is just printing it with less precision than python is. [Edit] I've just tried reading the file in C, and I get the same result (though slightly less precision: 3.90799e-14) (using printf("%g", val)), so I think if this value is incorrect, it's happened on the writing side, rather than the reading. A: Could you please elaborate on "didn't work"? Did the command crash? Did the data come out wrong? What actually happened? If the command crashed: Please share the error output of the command If the data simply came out wrong: Do the systems that create and read the data have the same endianness? If one is big-endian, and the other is little-endian, then you need to specify an endianness conversion in your format string. If the endianness of the two computers are the same, how was the data written to the file, exactly? Do you know? If you do, then what was the value written to the file and what was the incorrect value you got out? A: First, have you tried pickle? No one has shown any Python code yet... Here is some code for reading in binary in python: import Numeric as N import array filename = "tmp.bin" file = open(filename, mode='rb') binvalues = array.array('f') binvalues.read(file, num_lon * num_lat) data = N.array(binvalues, typecode=N.Float) file.close() Where the f here specified single-precision, 4-byte floating, numbers. Find whatever size your data is per entry and use that. For non binary data you could do something simple like this: tmp=[] for line in open("data.dat"): tmp.append(float(line)) A: f.read(8) might return less than 8 bytes Data might have different alignment and/or endianness: >>> for c in '@=<>': ... print repr(struct.pack(c+'d', -1.05)) ... '\xcd\xcc\xcc\xcc\xcc\xcc\xf0\xbf' '\xcd\xcc\xcc\xcc\xcc\xcc\xf0\xbf' '\xcd\xcc\xcc\xcc\xcc\xcc\xf0\xbf' '\xbf\xf0\xcc\xcc\xcc\xcc\xcc\xcd' >>> struct.unpack('<d', '\xbf\xf0\xcc\xcc\xcc\xcc\xcc\xcd') (-6.0659880001157799e+066,) >>> struct.unpack('>d', '\xbf\xf0\xcc\xcc\xcc\xcc\xcc\xcd') (-1.05,) A: The best method would be to use an ASCII text file: 0.0 3.1416 3.90798504668055 in that it would be portable and work with any kind of floating point implementation to a degree. Reading raw binary data from a double's memory address is not portable at all, and is bound to fail in some different implementation. You may of course use a binary format for compactness, but a portable C function writing in that format would not look like your snippet at all. At the very least, the code should be surrounded by a series of ifs/ifdefs checking that the memory representation of doubles used by the current machine exactly matches the one expected by the Python interpreter. Writing such code would be difficult, which is why I'm suggesting the easy, clean, portable and human-readable solution of ASCII text. This would be my definition of "best".
What is the best method to read a double from a Binary file created in C?
A C program spits out consecutive doubles into a binary file. I wish to read them into Python. I tried using struct.unpack('d',f.read(8)) EDIT: I used the following in C to write a random double number r = drand48(); fwrite((void*)&r, sizeof(double), 1, data); The Errors are now fixed but I cannot read the first value. for an all 0.000.. number it reads it as 3.90798504668055 but the rest are fine.
[ "I think you are actually reading the number correctly, but are getting confused by the display. When I read the number from your provided file, I get \"3.907985046680551e-14\" - this is almost but not quite zero (0.000000000000039 in expanded form). I suspect your C code is just printing it with less precision than python is.\n[Edit] I've just tried reading the file in C, and I get the same result (though slightly less precision: 3.90799e-14) (using printf(\"%g\", val)), so I think if this value is incorrect, it's happened on the writing side, rather than the reading.\n", "Could you please elaborate on \"didn't work\"? Did the command crash? Did the data come out wrong? What actually happened?\nIf the command crashed:\n\nPlease share the error output of the command\n\nIf the data simply came out wrong:\n\nDo the systems that create and read the data have the same endianness? If one is big-endian, and the other is little-endian, then you need to specify an endianness conversion in your format string.\nIf the endianness of the two computers are the same, how was the data written to the file, exactly? Do you know? If you do, then what was the value written to the file and what was the incorrect value you got out?\n\n", "First, have you tried pickle? \nNo one has shown any Python code yet... Here is some code for reading in binary in python:\nimport Numeric as N\nimport array\nfilename = \"tmp.bin\"\nfile = open(filename, mode='rb')\nbinvalues = array.array('f')\nbinvalues.read(file, num_lon * num_lat) \ndata = N.array(binvalues, typecode=N.Float) \n\nfile.close()\n\nWhere the f here specified single-precision, 4-byte floating, numbers. Find whatever size your data is per entry and use that. \nFor non binary data you could do something simple like this:\n tmp=[]\n for line in open(\"data.dat\"):\n tmp.append(float(line))\n\n", "\nf.read(8) might return less than 8 bytes\nData might have different alignment and/or endianness:\n>>> for c in '@=<>':\n... print repr(struct.pack(c+'d', -1.05))\n...\n'\\xcd\\xcc\\xcc\\xcc\\xcc\\xcc\\xf0\\xbf'\n'\\xcd\\xcc\\xcc\\xcc\\xcc\\xcc\\xf0\\xbf'\n'\\xcd\\xcc\\xcc\\xcc\\xcc\\xcc\\xf0\\xbf'\n'\\xbf\\xf0\\xcc\\xcc\\xcc\\xcc\\xcc\\xcd'\n>>> struct.unpack('<d', '\\xbf\\xf0\\xcc\\xcc\\xcc\\xcc\\xcc\\xcd')\n(-6.0659880001157799e+066,)\n>>> struct.unpack('>d', '\\xbf\\xf0\\xcc\\xcc\\xcc\\xcc\\xcc\\xcd')\n(-1.05,)\n\n\n", "The best method would be to use an ASCII text file:\n\n0.0\n 3.1416\n 3.90798504668055 \n\nin that it would be portable and work with any kind of floating point implementation to a degree.\nReading raw binary data from a double's memory address is not portable at all, and is bound to fail in some different implementation.\nYou may of course use a binary format for compactness, but a portable C function writing in that format would not look like your snippet at all.\nAt the very least, the code should be surrounded by a series of ifs/ifdefs checking that the memory representation of doubles used by the current machine exactly matches the one expected by the Python interpreter.\nWriting such code would be difficult, which is why I'm suggesting the easy, clean, portable and human-readable solution of ASCII text.\nThis would be my definition of \"best\".\n" ]
[ 2, 1, 1, 0, 0 ]
[]
[]
[ "c", "double", "python" ]
stackoverflow_0000631607_c_double_python.txt
Q: Python, Evaluate a Variable value as a Variable I'd like to do something like below: particularly the 'f.eval(field)' part, such that it evaluates the value of the variable as the field name. How does one accomplish this in Python? def punctuated_object_list(objects, field): field_list = [f.eval(field) for f in objects] if len(field_list) > 0: if len(field_list) == 1: return field_list[0] else: return ', '.join(field_list[:-1]) + ' & ' + field_list[-1] else: return u'' A: getattr(f, field), if I understand you correctly (that is, if you might have field = "foo", and want f.foo). If not, you might want to clarify. Python has an eval(), and I don't know what other languages' eval() you want the equivalent of. A: getattr( object, 'field' ) #note that field is a string f = 'field_name' #... getattr( object, f ) #to get a list of fields in an object, you can use dir() dir( object ) For more details, see: http://www.diveintopython.org/power_of_introspection/index.html Don't use eval, even if the strings are safe in this particular case! Just don't get yourself used to it. If you're getting the string from the user it could be malicious code. Murphy's law: if things can go wrong, they will. A: The python equivalent of eval() is eval() x = 9 eval("x*2") will give you 18. v = "x" eval(v+"*2") works too. A: To get at a list of all the fields in a Python object you can access its __dict__ property. class Testing(): def __init__(self): self.name = "Joe" self.age = 30 test = Testing() print test.__dict__ results: {'age': 30, 'name': 'Joe'}
Python, Evaluate a Variable value as a Variable
I'd like to do something like below: particularly the 'f.eval(field)' part, such that it evaluates the value of the variable as the field name. How does one accomplish this in Python? def punctuated_object_list(objects, field): field_list = [f.eval(field) for f in objects] if len(field_list) > 0: if len(field_list) == 1: return field_list[0] else: return ', '.join(field_list[:-1]) + ' & ' + field_list[-1] else: return u''
[ "getattr(f, field), if I understand you correctly (that is, if you might have field = \"foo\", and want f.foo). If not, you might want to clarify. Python has an eval(), and I don't know what other languages' eval() you want the equivalent of.\n", "getattr( object, 'field' ) #note that field is a string\n\nf = 'field_name'\n#...\ngetattr( object, f )\n\n\n#to get a list of fields in an object, you can use dir()\ndir( object )\n\nFor more details, see: http://www.diveintopython.org/power_of_introspection/index.html\nDon't use eval, even if the strings are safe in this particular case! Just don't get yourself used to it. If you're getting the string from the user it could be malicious code. \nMurphy's law: if things can go wrong, they will.\n", "The python equivalent of eval() is eval()\nx = 9\neval(\"x*2\")\n\nwill give you 18.\nv = \"x\"\neval(v+\"*2\")\n\nworks too.\n", "To get at a list of all the fields in a Python object you can access its __dict__ property.\nclass Testing():\n def __init__(self):\n self.name = \"Joe\"\n self.age = 30\n\ntest = Testing()\nprint test.__dict__\n\nresults:\n{'age': 30, 'name': 'Joe'}\n\n" ]
[ 13, 4, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000632856_python.txt
Q: Automatically fetching latest version of a file on import I have a module that I want to keep up to date, and I'm wondering if this is a bad idea: Have a module (mod1.py) in the site-packages directory that copies a different module from some other location into the site-packages directory, and then imports * from that module. import shutil from distutils.sysconfig import get_python_lib p_source = r'\\SourceSafeServer\mod1_current.py' p_local = get_python_lib() + r'\mod1_current.py' shutil.copyfile(p_source, p_local) from mod1_current import * Now I can do this in any module, and it will always be the latest version: from mod1 import function1 This works.... but is there a better way of doing this? Update Here is the current process... there is a project under source-control that has a single module: mod1.py There is also a setup.py Running setup.py copies mod1.py to the site-packages directory. Developers that use the module must run setup.py to update the module. Sometimes, they don't and not having the latest version causes problems. I want to be able to just check-in the a new version, and any code that imports that module will automatically grab the latest version every time, without anyone having to run setup.py A: Do you really want to do this? This means you could very easily roll code to a production app simply by committing to source control. I would consider this a nasty side-effect for someone who isn't aware of your setup. That being said this seems like a pretty good solution - you may want to add some exception-handling around the network file calls as those are prone to failure. A: In some cases, we put .pth files in the Python site-packages directory. The .pth files name our various SVN checkout directories. No install. No copy. .pth files are described here. A: The original strategy of having other developers copy mod1.py into their site-packages in order to use the module sounds like it's the real problem. Why aren't they just using the same source control are you are? This auto-copying will make it hard to do rollbacks, especially if other developers copy your strategy. Imagine this same system used for dozens and dozens of files. And then imagine you actually do want to use a version of mod1.py that is not the latest for something.
Automatically fetching latest version of a file on import
I have a module that I want to keep up to date, and I'm wondering if this is a bad idea: Have a module (mod1.py) in the site-packages directory that copies a different module from some other location into the site-packages directory, and then imports * from that module. import shutil from distutils.sysconfig import get_python_lib p_source = r'\\SourceSafeServer\mod1_current.py' p_local = get_python_lib() + r'\mod1_current.py' shutil.copyfile(p_source, p_local) from mod1_current import * Now I can do this in any module, and it will always be the latest version: from mod1 import function1 This works.... but is there a better way of doing this? Update Here is the current process... there is a project under source-control that has a single module: mod1.py There is also a setup.py Running setup.py copies mod1.py to the site-packages directory. Developers that use the module must run setup.py to update the module. Sometimes, they don't and not having the latest version causes problems. I want to be able to just check-in the a new version, and any code that imports that module will automatically grab the latest version every time, without anyone having to run setup.py
[ "Do you really want to do this? This means you could very easily roll code to a production app simply by committing to source control. I would consider this a nasty side-effect for someone who isn't aware of your setup.\nThat being said this seems like a pretty good solution - you may want to add some exception-handling around the network file calls as those are prone to failure.\n", "In some cases, we put .pth files in the Python site-packages directory. The .pth files name our various SVN checkout directories. \nNo install. No copy.\n.pth files are described here.\n", "The original strategy of having other developers copy mod1.py into their site-packages in order to use the module sounds like it's the real problem. Why aren't they just using the same source control are you are?\nThis auto-copying will make it hard to do rollbacks, especially if other developers copy your strategy. Imagine this same system used for dozens and dozens of files. And then imagine you actually do want to use a version of mod1.py that is not the latest for something.\n" ]
[ 2, 1, 0 ]
[]
[]
[ "python", "version_control", "visual_sourcesafe" ]
stackoverflow_0000632171_python_version_control_visual_sourcesafe.txt
Q: why am i getting errors while installing pysqlite2.5.3 Am trying build pysqlite 2.5.3 package on SLSE 9, and am getting all sorts of compilation errors i.e. ... src/module.c:290: error: initializer element is not constant src/module.c:290: error: (near initialization for `_int_constants[27].constant_value') src/module.c:290: error: initializer element is not constant src/module.c:290: error: (near initialization for `_int_constants[27]') src/module.c:291: error: `SQLITE_ATTACH' undeclared here (not in a function) src/module.c:291: error: initializer element is not constant src/module.c:291: error: (near initialization for `_int_constants[28].constant_value') src/module.c:291: error: initializer element is not constant src/module.c:291: error: (near initialization for `_int_constants[28]') src/module.c:292: error: `SQLITE_DETACH' undeclared here (not in a function) src/module.c:292: error: initializer element is not constant src/module.c:292: error: (near initialization for `_int_constants[29].constant_value') src/module.c:292: error: initializer element is not constant src/module.c:292: error: (near initialization for `_int_constants[29]') src/module.c:300: error: initializer element is not constant src/module.c:300: error: (near initialization for `_int_constants[30]') src/module.c: In function `init_sqlite': src/module.c:419: warning: implicit declaration of function `sqlite3_libversion' src/module.c:419: warning: passing arg 1 of `PyString_FromString' makes pointer from integer without a cast error: command 'gcc' failed with exit status 1 the things fails this is my setup.cfg file: [build_ext] #define= #include_dirs=/usr/local/include #library_dirs=/usr/local/lib libraries=sqlite3 define= SQLlite is running... when i do sqlite3, i get the command interface. What am i missing out? Gath A: Do you have the sqlite development headers installed? error: SQLITE_DETACH' undeclared here Looks like you need sqlite3-dev (or whatever your distro named it, perhaps sqlite3-devel?) Edit: After a good natured soul cleaned up your error trace a bit more, I'm quite sure you are missing the sqlite3 development headers. You have the library, just not the headers: src/module.c:419: warning: implicit declaration of function `sqlite3_libversion' If there is no header, there is no prototype. If there is no prototype, you'll see a warning complaining about an implicit declaration (if the compiler is set to issue sensible warnings).
why am i getting errors while installing pysqlite2.5.3
Am trying build pysqlite 2.5.3 package on SLSE 9, and am getting all sorts of compilation errors i.e. ... src/module.c:290: error: initializer element is not constant src/module.c:290: error: (near initialization for `_int_constants[27].constant_value') src/module.c:290: error: initializer element is not constant src/module.c:290: error: (near initialization for `_int_constants[27]') src/module.c:291: error: `SQLITE_ATTACH' undeclared here (not in a function) src/module.c:291: error: initializer element is not constant src/module.c:291: error: (near initialization for `_int_constants[28].constant_value') src/module.c:291: error: initializer element is not constant src/module.c:291: error: (near initialization for `_int_constants[28]') src/module.c:292: error: `SQLITE_DETACH' undeclared here (not in a function) src/module.c:292: error: initializer element is not constant src/module.c:292: error: (near initialization for `_int_constants[29].constant_value') src/module.c:292: error: initializer element is not constant src/module.c:292: error: (near initialization for `_int_constants[29]') src/module.c:300: error: initializer element is not constant src/module.c:300: error: (near initialization for `_int_constants[30]') src/module.c: In function `init_sqlite': src/module.c:419: warning: implicit declaration of function `sqlite3_libversion' src/module.c:419: warning: passing arg 1 of `PyString_FromString' makes pointer from integer without a cast error: command 'gcc' failed with exit status 1 the things fails this is my setup.cfg file: [build_ext] #define= #include_dirs=/usr/local/include #library_dirs=/usr/local/lib libraries=sqlite3 define= SQLlite is running... when i do sqlite3, i get the command interface. What am i missing out? Gath
[ "Do you have the sqlite development headers installed?\n\nerror: SQLITE_DETACH' undeclared here \n\nLooks like you need sqlite3-dev (or whatever your distro named it, perhaps sqlite3-devel?)\nEdit:\nAfter a good natured soul cleaned up your error trace a bit more, I'm quite sure you are missing the sqlite3 development headers. You have the library, just not the headers:\n\nsrc/module.c:419: warning: implicit\n declaration of function\n `sqlite3_libversion'\n\nIf there is no header, there is no prototype. If there is no prototype, you'll see a warning complaining about an implicit declaration (if the compiler is set to issue sensible warnings).\n" ]
[ 4 ]
[]
[]
[ "linux", "python", "sqlite" ]
stackoverflow_0000633601_linux_python_sqlite.txt
Q: How do I upgrade python 2.5.2 to python 2.6rc2 on ubuntu linux 8.04? I'd like to how to upgrade the default python installation(2.5.2) supplied with ubuntu 8.04 to python 2.6rc2. I'd like to make 2.6 the default python version on the system and migrate all the other useful installed python libraries installed on 2.5.2 to python 2.6rc2. Please let me know how I can achieve this. Thanks Dirk A: With the warning that I think it's a tremendously bad idea to replace the default Python with an unreleased beta version: First, install 2.6rc2. You can download the source from the Python website. Standard ./configure && make && sudo make install installation style. Next, remove the /usr/bin/python symlink. Do not remove /usr/bin/python2.5. Add a symlink to 2.6 with ln -s /usr/local/bin/python2.6 /usr/bin/python. Once again, I think this is a terrible idea. There is almost certainly a better way to do whatever you're trying to accomplish. Migrating installed libraries is a much longer process. Look in the /usr/lib/python2.5/site-packages/ and /usr/local/lib/python2.5/site-packages/ directories. Any libraries installed to them will need to be re-installed with 2.6. Since you're not using a packaged Python version, you cannot use Ubuntu's packages -- you'll have to manually upgrade all the libraries yourself. Most of them can probably be installed with sudo easy_install <name>, but some like PyGTK+ are not so easy. You'll have to follow custom installation procedures for each such library. A: I have the same issue, and apparently pre-built binaries can be found here: # Python 2.6 deb http://ppa.launchpad.net/doko/ubuntu intrepid main deb-src http://ppa.launchpad.net/doko/ubuntu intrepid main A: Is there any need to? Ubuntu in general doesn't package RC releases. 2.6 will not be available in Ubuntu until Jaunty Jackalope. However,, if you insist that you need to install it, then, you'll have to do so without a package manager. Download the package, and unzip it to a directory run the following commands (waiting for each to finish as you do so) ./configure make sudo make install There, you have it installed. It's better to wait for it to be packaged first, espescially as Python is used in a lot of ubuntu internals, so may break your system horribly A: It would not be wise to change the default version of Python, i.e. what you get when you type "python" into a shell. However, you can have multiple versions of python installed. The trick is to make sure that the program named "python" on the path is the system supplied version. If you want to run your install of Python 2.6 you'd then type python2.6 into a shell to start it. Download the package and unzip it, then run: ./configure make sudo make install ls -l /usr/local/bin You should see a python and a python2.6 file, both created on the day you ran make install; delete the python file. Then when python is launched the standard system Python version from /usr/bin will be run, and when python2.6 is run you get your shiny new python 2.6rc2. Python displays the version when it starts an interactive interpreter.
How do I upgrade python 2.5.2 to python 2.6rc2 on ubuntu linux 8.04?
I'd like to how to upgrade the default python installation(2.5.2) supplied with ubuntu 8.04 to python 2.6rc2. I'd like to make 2.6 the default python version on the system and migrate all the other useful installed python libraries installed on 2.5.2 to python 2.6rc2. Please let me know how I can achieve this. Thanks Dirk
[ "With the warning that I think it's a tremendously bad idea to replace the default Python with an unreleased beta version:\nFirst, install 2.6rc2. You can download the source from the Python website. Standard ./configure && make && sudo make install installation style.\nNext, remove the /usr/bin/python symlink. Do not remove /usr/bin/python2.5. Add a symlink to 2.6 with ln -s /usr/local/bin/python2.6 /usr/bin/python.\nOnce again, I think this is a terrible idea. There is almost certainly a better way to do whatever you're trying to accomplish.\n\nMigrating installed libraries is a much longer process. Look in the /usr/lib/python2.5/site-packages/ and /usr/local/lib/python2.5/site-packages/ directories. Any libraries installed to them will need to be re-installed with 2.6. Since you're not using a packaged Python version, you cannot use Ubuntu's packages -- you'll have to manually upgrade all the libraries yourself. Most of them can probably be installed with sudo easy_install <name>, but some like PyGTK+ are not so easy. You'll have to follow custom installation procedures for each such library.\n", "I have the same issue, and apparently pre-built binaries can be found here:\n# Python 2.6\ndeb http://ppa.launchpad.net/doko/ubuntu intrepid main\ndeb-src http://ppa.launchpad.net/doko/ubuntu intrepid main\n\n", "Is there any need to?\nUbuntu in general doesn't package RC releases. 2.6 will not be available in Ubuntu until Jaunty Jackalope.\nHowever,, if you insist that you need to install it, then, you'll have to do so without a package manager.\nDownload the package, and unzip it to a directory\nrun the following commands (waiting for each to finish as you do so)\n./configure\nmake\nsudo make install\n\nThere, you have it installed.\nIt's better to wait for it to be packaged first, espescially as Python is used in a lot of ubuntu internals, so may break your system horribly\n", "It would not be wise to change the default version of Python, i.e. what you get when you type \"python\" into a shell. However, you can have multiple versions of python installed. The trick is to make sure that the program named \"python\" on the path is the system supplied version. If you want to run your install of Python 2.6 you'd then type python2.6 into a shell to start it.\nDownload the package and unzip it, then run:\n./configure\nmake\nsudo make install\nls -l /usr/local/bin\n\nYou should see a python and a python2.6 file, both created on the day you ran make install; delete the python file. Then when python is launched the standard system Python version from /usr/bin will be run, and when python2.6 is run you get your shiny new python 2.6rc2. Python displays the version when it starts an interactive interpreter.\n" ]
[ 14, 6, 1, 1 ]
[]
[]
[ "installation", "linux", "python", "ubuntu" ]
stackoverflow_0000142764_installation_linux_python_ubuntu.txt
Q: What is the feasibility of porting a legacy C program to Python? I have a program in C that communicates via UDP with another program (in Java) and then does process manipulation (start/stop) based on the UDP pkt exchange. Now this C program has been legacy and I want to convert it to Python - do you think Python will be a good choice for the tasks mentioned? A: Yes, I do think that Python would be a good replacement. I understand that the Twisted Python framework is quite popular. A: I'd say that if: Your C code contains no platform specific requirements You are sure speed is not going to be an issue going from C to python You have a desire to not compile anymore You would like to try utilise exception handling You want to dabble in OO You might choose to run on many platforms without porting You are curious about dynamic typing You want memory handled for you You know or want to learn python Then sure, why not. There doesn't seem to be any technical reason you shouldn't use python here, so it's a preference in this case. A: Remember as well, you can leave parts of your program in C, turn them into Python modules and build python code around them - you don't need to re-write everything up-front. A: Assuming that you have control over the environment which this application will run, and that the performance of interpreted language (python) compared to a compiled one (C) can be ignored, I believe Python is a great choice for this. A: If I was faced with a similar situation I'd ask myself a couple of questions: Is there anything more important I could be working on? Does Python bring anything to the table that is currently handled poorly by the current application? Will this allow me to add functionality that was previously too difficult to implement? Is this going to disrupt service in any way? If I can't answer those satisfactorily, then I'd put off the rewrite. A: Yes, I think Python is a good choice, if all your platforms support it. Since this is a network program, I'm assuming the network is your runtime bottleneck? That's likely to still be the case in Python. If you really do need to speed it up, you can include your long-since-debugged, speedy C as Python modules. A: If this is an embedded program, then it might be a problem to port it since Python programs typically rely on the Python runtime and library, and those are fairly large. Especially when compared to a C program doing a well-defined task. Of course, it's likely you've already considered that aspect, but I wanted to mention it in the context of the question anyway, since I feel it's an important aspect when doing this type of comparison.
What is the feasibility of porting a legacy C program to Python?
I have a program in C that communicates via UDP with another program (in Java) and then does process manipulation (start/stop) based on the UDP pkt exchange. Now this C program has been legacy and I want to convert it to Python - do you think Python will be a good choice for the tasks mentioned?
[ "Yes, I do think that Python would be a good replacement. I understand that the Twisted Python framework is quite popular.\n", "I'd say that if:\n\nYour C code contains no platform specific requirements\nYou are sure speed is not going to be an issue going from C to python\nYou have a desire to not compile anymore\nYou would like to try utilise exception handling\nYou want to dabble in OO\nYou might choose to run on many platforms without porting\nYou are curious about dynamic typing\nYou want memory handled for you\nYou know or want to learn python\n\nThen sure, why not. \nThere doesn't seem to be any technical reason you shouldn't use python here, so it's a preference in this case.\n", "Remember as well, you can leave parts of your program in C, turn them into Python modules and build python code around them - you don't need to re-write everything up-front.\n", "Assuming that you have control over the environment which this application will run, and that the performance of interpreted language (python) compared to a compiled one (C) can be ignored, I believe Python is a great choice for this.\n", "If I was faced with a similar situation I'd ask myself a couple of questions:\n\nIs there anything more important I could be working on?\nDoes Python bring anything to the table that is currently handled poorly by the current application?\nWill this allow me to add functionality that was previously too difficult to implement?\nIs this going to disrupt service in any way?\n\nIf I can't answer those satisfactorily, then I'd put off the rewrite. \n", "Yes, I think Python is a good choice, if all your platforms support it. Since this is a network program, I'm assuming the network is your runtime bottleneck? That's likely to still be the case in Python. If you really do need to speed it up, you can include your long-since-debugged, speedy C as Python modules.\n", "If this is an embedded program, then it might be a problem to port it since Python programs typically rely on the Python runtime and library, and those are fairly large. Especially when compared to a C program doing a well-defined task. Of course, it's likely you've already considered that aspect, but I wanted to mention it in the context of the question anyway, since I feel it's an important aspect when doing this type of comparison.\n" ]
[ 9, 4, 2, 1, 1, 1, 0 ]
[]
[]
[ "c", "python" ]
stackoverflow_0000632730_c_python.txt
Q: Why do Python's frameworks return dictionaries from controllers? Why (for example web2py) do you return data from a controller in a dictionary instead of variables (see Rails)? For example: return dict(sape=4139, guido=4127, jack=4098) instead of (that's the way Rails does it) @var1 = "jello" @var2 = "hihi" Is there any advantage using dictionaries over plain variables (speed-wise/code-wise)? Update: The above way is actually a correct way for creating a dictionary (at least in Python 2.6.1). The other way (that many people say it's the correct one) return {"var1": "jello", "var2": "hihi"} is not used a lot by python frameworks. From Python's documentation: "When the keys are simple strings, it is sometimes easier to specify pairs using keyword arguments:" dict(sape=4139, guido=4127, jack=4098) A: The main advantage is that this is the only way in python to return a) more than a single value and b) give that value a name. Other options would be to use a class (extra code), return a tuple (no names, so you'd have to use indexes to access the values) or allow to return only a single value which would probably mean that everyone would return a dictionary since that's the most simple solution. It also allows to wrap several methods and join/merge their results. Lastly, it allows to return different sets of value/name pairs for each call easily, for example, omit optional values or return additional hints. A: You can use local variables if you'd like: def hello(): var1 = "whatever you like" var2 = "another value" return locals() # or vars() hello.html: <html><body> <p>var1 {{=var1}}</p> <p>var2 {{=var2}}</p> </body></html> from PHP to web2py: In web2py an HTTP request for "/app/c/f" is mapped into a call to the function f() in file (controller) c.py in the application "app". The file c.py is written in Python. The output of the function f() can be a string (in this case it is returned), or a set of variables (implemented as a python dictionary). In the latter case the variables are rendered into HTML by a file c/f.html, called a view.
Why do Python's frameworks return dictionaries from controllers?
Why (for example web2py) do you return data from a controller in a dictionary instead of variables (see Rails)? For example: return dict(sape=4139, guido=4127, jack=4098) instead of (that's the way Rails does it) @var1 = "jello" @var2 = "hihi" Is there any advantage using dictionaries over plain variables (speed-wise/code-wise)? Update: The above way is actually a correct way for creating a dictionary (at least in Python 2.6.1). The other way (that many people say it's the correct one) return {"var1": "jello", "var2": "hihi"} is not used a lot by python frameworks. From Python's documentation: "When the keys are simple strings, it is sometimes easier to specify pairs using keyword arguments:" dict(sape=4139, guido=4127, jack=4098)
[ "The main advantage is that this is the only way in python to return a) more than a single value and b) give that value a name. Other options would be to use a class (extra code), return a tuple (no names, so you'd have to use indexes to access the values) or allow to return only a single value which would probably mean that everyone would return a dictionary since that's the most simple solution.\nIt also allows to wrap several methods and join/merge their results. Lastly, it allows to return different sets of value/name pairs for each call easily, for example, omit optional values or return additional hints.\n", "You can use local variables if you'd like:\ndef hello():\n var1 = \"whatever you like\"\n var2 = \"another value\"\n return locals() # or vars()\n\nhello.html:\n<html><body>\n <p>var1 {{=var1}}</p>\n <p>var2 {{=var2}}</p>\n</body></html>\n\nfrom PHP to web2py:\n\nIn web2py an HTTP request for\n \"/app/c/f\" is mapped into a call to\n the function f() in file (controller)\n c.py in the application \"app\". The\n file c.py is written in Python. The\n output of the function f() can be a\n string (in this case it is returned),\n or a set of variables (implemented as\n a python dictionary). In the latter\n case the variables are rendered into\n HTML by a file c/f.html, called a\n view.\n\n" ]
[ 5, 3 ]
[ "The nice thing is that a template engine like Jinja2 treats an object and a dict similarly, so if:\nd = {'color': 'red'}\no = Color(red)\n\nthen these all work in the template syntax:\nd.color d['color'] o.color o['color']\n\n" ]
[ -1 ]
[ "python", "ruby_on_rails", "web2py" ]
stackoverflow_0000634024_python_ruby_on_rails_web2py.txt
Q: How to debug a file upload? I'm trying to upload a PDF file to a website using Hot Banana's content management system using a Python script. I've successfully logged into the site and can log out, but I can't seem to get file uploads to work. The file upload is part of a large complicated web form that submits the form data and PDF file though a POST. Using Firefox along with the Firebug and Tamper Data extensions I took a peek at what the browser was sending in the POST and where it was going. I believe I mimicked the data the browser was sending in the code, but I'm still having trouble. I'm importing cookielib to handle cookies, poster to encode the PDF, and urllib and urllib2 to build the request and send it to the URL. Is it possible that registering the poster openers is clobbering the cookie processor openers? Am I doing this completely wrong? Edit: What's a good way to debug the process? At the moment, I'm just dumping out the urllib2 response to a text file and examining the output to see if it matches what I get when I do a file upload manually. Edit 2: Chris Lively suggested I post the error I'm getting. The response from urllib2 doesn't generate an exception, but just returns: <script> if (parent != window) { parent.document.location.reload(); } else { parent.document.location = 'login.cfm'; } </script> I'll keep at it. A: A tool like WireShark will give you a more complete trace at a much lower-level than the firefox plugins. Often this can be something as simple as not setting the content-type correctly, or failing to include content-length. A: You might be better off instrumenting the server to see why this is failing, rather than trying to debug this on the client side. A: "What's a good way to debug [a web services] process?" At the moment, I'm just dumping out the urllib2 response to a text file and examining the output to see if it matches what I get when I do a file upload manually. Correct. That's about all there is. HTTP is a very simple protocol -- you make a request (POST, in this case) and the server responds. Not much else involved and not much more you can do while debugging. What else would you like? Seriously. What kind of debugger are you imagining might exist for this kind of stateless protocol?
How to debug a file upload?
I'm trying to upload a PDF file to a website using Hot Banana's content management system using a Python script. I've successfully logged into the site and can log out, but I can't seem to get file uploads to work. The file upload is part of a large complicated web form that submits the form data and PDF file though a POST. Using Firefox along with the Firebug and Tamper Data extensions I took a peek at what the browser was sending in the POST and where it was going. I believe I mimicked the data the browser was sending in the code, but I'm still having trouble. I'm importing cookielib to handle cookies, poster to encode the PDF, and urllib and urllib2 to build the request and send it to the URL. Is it possible that registering the poster openers is clobbering the cookie processor openers? Am I doing this completely wrong? Edit: What's a good way to debug the process? At the moment, I'm just dumping out the urllib2 response to a text file and examining the output to see if it matches what I get when I do a file upload manually. Edit 2: Chris Lively suggested I post the error I'm getting. The response from urllib2 doesn't generate an exception, but just returns: <script> if (parent != window) { parent.document.location.reload(); } else { parent.document.location = 'login.cfm'; } </script> I'll keep at it.
[ "A tool like WireShark will give you a more complete trace at a much lower-level than the firefox plugins.\nOften this can be something as simple as not setting the content-type correctly, or failing to include content-length.\n", "You might be better off instrumenting the server to see why this is failing, rather than trying to debug this on the client side.\n", "\"What's a good way to debug [a web services] process?\"\nAt the moment, I'm just dumping out the urllib2 response to a text file and examining the output to see if it matches what I get when I do a file upload manually.\nCorrect. That's about all there is.\nHTTP is a very simple protocol -- you make a request (POST, in this case) and the server responds. Not much else involved and not much more you can do while debugging.\nWhat else would you like? Seriously. What kind of debugger are you imagining might exist for this kind of stateless protocol? \n" ]
[ 1, 0, 0 ]
[]
[]
[ "post", "python", "upload", "urllib2" ]
stackoverflow_0000632577_post_python_upload_urllib2.txt
Q: Django: Calling custom Model method from Form clean method. "Unbound Method"? I'm having a problem while trying to call a custom Model method from my Form clean method. Here is [part of] my model: http://dpaste.com/hold/12695/ Here is my Form: http://dpaste.com/hold/12699/ I'm specifically having a problem with line 11 in my Form: nzb_data = File.get_nzb_data(nzb_absolute) This raises the following error: TypeError at /admin/main/file/add/ unbound method get_nzb_data() must be called with File instance as first argument (got str instance instead) By this error I can assume I have to pass the method something (a File instance), however I don't really know what that means and how I can do it. Can you let me know what I'm doing wrong here, and what can be done to resolve the issue? Solved by making the get_nzb_data method a class method using the @classmethod decorator. A: You can't call nzb_data = File.get_nzb_data(nzb_absolute) because your using the class, not an object. You have two choices. Make get_nzb_data a @classmethod. See http://docs.python.org/library/functions.html#classmethod Create an instance of File and use that. temp_f= File(...). Then temp_f.get_dnb_data. A: I may be missing something here, but I think that your method ´get_nzb_data´ should have a @classmethod decorator. Otherwise, it expects the ´self´ argument of the type File, and this gives that error.
Django: Calling custom Model method from Form clean method. "Unbound Method"?
I'm having a problem while trying to call a custom Model method from my Form clean method. Here is [part of] my model: http://dpaste.com/hold/12695/ Here is my Form: http://dpaste.com/hold/12699/ I'm specifically having a problem with line 11 in my Form: nzb_data = File.get_nzb_data(nzb_absolute) This raises the following error: TypeError at /admin/main/file/add/ unbound method get_nzb_data() must be called with File instance as first argument (got str instance instead) By this error I can assume I have to pass the method something (a File instance), however I don't really know what that means and how I can do it. Can you let me know what I'm doing wrong here, and what can be done to resolve the issue? Solved by making the get_nzb_data method a class method using the @classmethod decorator.
[ "You can't call \nnzb_data = File.get_nzb_data(nzb_absolute)\n\nbecause your using the class, not an object.\nYou have two choices.\n\nMake get_nzb_data a @classmethod. See http://docs.python.org/library/functions.html#classmethod\nCreate an instance of File and use that. temp_f= File(...). Then temp_f.get_dnb_data.\n\n", "I may be missing something here, but I think that your method ´get_nzb_data´ should have a @classmethod decorator. Otherwise, it expects the ´self´ argument of the type File, and this gives that error.\n" ]
[ 3, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000634857_django_python.txt
Q: Looking to get started with Apache, PHP, MySQL, Python, Django on a fresh Mac I've looked for other questions, but could not find any... I have freshly installed my Mac with OSX 10.5. I need to learn Python/Django for a new job, so want to set it all up correctly, ready to develop and run from my browser using http://localhost/ I come from a PHP background and always used MAMP before. But I want to get everything working together... Apache, PHP, MySQL, Python, Django. Using MAMP is easy to install a local development server, but I want to get Python and Django running nicely too. So I can just start developing and also following tutorials on Python/Django. Please give me some steps (with MAMP or not) to get a nicely working environment for Apache, PHP, MySQL, Python and Django. Thank you, all have great days! James A: Why not try the official installation instructions? Really all you need to do is install Django. You can use its built-in server (http://localhost:8000 by default) for testing: ./manage.py runserver A: Your Mac should come pre-installed with Python 2.4 (or later) which is fine for Django 1.0.2. A: 10.5 comes with Apache installed by default System Preferences > Sharing > Web Sharing. To enable Apache php module edit the Apache conf (/etc/Apache/httpd.conf) file and uncomment the php module line. LoadModule php5_module libexec/apache2/libphp5.so. Restart Apache after by disabling & enabling web sharing Mysql package can be downloaded form the official website and is easy to install A: The fastest way to get started with Django, will be to use TurnKey linux Django appliance. Link: http://www.turnkeylinux.org/appliances/django A: I also came from PHP a few months ago. I'm not sure if this will get moderated up or down because my answer changes your question: Do not use MySQL and Apache for local development on your Mac. Use Sqlite3 and the development server that is bundled with Django - this allows for inline debugging, etc... Sqlite3 is basically the same as MySQL except you need to use .schema instead of describe. If you start having problems, get MacPython. This has helped me instantly solve problems faster than trying to work with the stock Python on Leopard. Try to use pip instead of easy_install where possible. When you are ready for real deployment, then you'll need MySQL/Apache/Nginx, etc... but those will be on a Linux system and you'll be better prepared at that point to make a good production installation than you are now. Getting a production-quality stack running on the Mac is more of a pain than it's worth. BTW, when you do install Apache, use wsgi, not mod_python.
Looking to get started with Apache, PHP, MySQL, Python, Django on a fresh Mac
I've looked for other questions, but could not find any... I have freshly installed my Mac with OSX 10.5. I need to learn Python/Django for a new job, so want to set it all up correctly, ready to develop and run from my browser using http://localhost/ I come from a PHP background and always used MAMP before. But I want to get everything working together... Apache, PHP, MySQL, Python, Django. Using MAMP is easy to install a local development server, but I want to get Python and Django running nicely too. So I can just start developing and also following tutorials on Python/Django. Please give me some steps (with MAMP or not) to get a nicely working environment for Apache, PHP, MySQL, Python and Django. Thank you, all have great days! James
[ "Why not try the official installation instructions? Really all you need to do is install Django. You can use its built-in server (http://localhost:8000 by default) for testing:\n./manage.py runserver\n\n", "Your Mac should come pre-installed with Python 2.4 (or later) which is fine for Django 1.0.2.\n", "10.5 comes with Apache installed by default System Preferences > Sharing > Web Sharing. \nTo enable Apache php module edit the Apache conf (/etc/Apache/httpd.conf) file and uncomment the php module line.\nLoadModule php5_module libexec/apache2/libphp5.so. \n\nRestart Apache after by disabling & enabling web sharing\nMysql package can be downloaded form the official website and is easy to install\n", "The fastest way to get started with Django, will be to use TurnKey linux Django appliance.\nLink: http://www.turnkeylinux.org/appliances/django\n", "I also came from PHP a few months ago. I'm not sure if this will get moderated up or down because my answer changes your question:\n\nDo not use MySQL and Apache for local development on your Mac. Use Sqlite3 and the development server that is bundled with Django - this allows for inline debugging, etc...\nSqlite3 is basically the same as MySQL except you need to use .schema instead of describe.\nIf you start having problems, get MacPython. This has helped me instantly solve problems faster than trying to work with the stock Python on Leopard.\nTry to use pip instead of easy_install where possible.\n\nWhen you are ready for real deployment, then you'll need MySQL/Apache/Nginx, etc... but those will be on a Linux system and you'll be better prepared at that point to make a good production installation than you are now. Getting a production-quality stack running on the Mac is more of a pain than it's worth. \nBTW, when you do install Apache, use wsgi, not mod_python.\n" ]
[ 6, 1, 0, 0, 0 ]
[ "Okay. I'd just install MySQL from their site and stick with what's already on my Mac as of 10.5, then install Django and the Python MySQL driver. But since you like MAMP, install MAMP or XAMPP and read something like this which summarized says:\nMac OS X 10.5 comes with \"Python 2.5.1, thus you won’t have to install it. You can verify this by running python in the Terminal.\" \nCheckout Django cd $HOME/Code; svn co http://code.djangoproject.com/svn/django/trunk django_trunk\nTell Python where Django is echo \"$HOME/Code/django_trunk\">/Library/Python/2.5/site-packages/django.pth\nAdd django-admin.py to your PATH\nInstall the MySQLdb driver from sf.net this probably requires GCC which means you might want the set with Xcode from Apple's Dev Tools.\nDo a source code edit\n\"At this point, edit the _mysql.c file\nand comment out lines 37, 38 and 39 as\nfollows:\"\n//#ifndef uint\n//#define uint unsigned int\n//#endif\n\nrun\npython setup.py build\nsudo python setup.py install\n\nVerify the installation\n" ]
[ -1 ]
[ "django", "macos", "osx_leopard", "php", "python" ]
stackoverflow_0000632046_django_macos_osx_leopard_php_python.txt
Q: Visual Studio 2005 Build of Python with Debug .lib I am looking for the Visual Studio 2005 build of Python 2.4, 2.5 or 2.6, I also need the python2x_d.lib (the debug version of the .lib) since I embed the interpreter into my app and the python libs implicitly link to the python2x_d.lib with pragmas (grrr). Any hints where I can find those builds ? Regards, Paul A: I would recommend that you download the Python source (tgz and tar.bz2 zipped versions available) and compile it yourself. It comes with a VS2005 solution so it isn't difficult. I had to do this for a SWIG project I was working on. A: If you have trouble finding the debug builds, you can try and build your own. Browse the build directory, for project files like python.vcproj - to locate versions that will work with Visual Studio 2005. A: I recall, some time ago, giving IronPython a 'whirl' in VS2005. I ran into all kinds of 'esoteric' errors until I figured out that to compile and run I had to add the C++ libraries and tools of VS2005 as well (add/remove). Maybe this is something similar ?
Visual Studio 2005 Build of Python with Debug .lib
I am looking for the Visual Studio 2005 build of Python 2.4, 2.5 or 2.6, I also need the python2x_d.lib (the debug version of the .lib) since I embed the interpreter into my app and the python libs implicitly link to the python2x_d.lib with pragmas (grrr). Any hints where I can find those builds ? Regards, Paul
[ "I would recommend that you download the Python source (tgz and tar.bz2 zipped versions available) and compile it yourself. It comes with a VS2005 solution so it isn't difficult. I had to do this for a SWIG project I was working on.\n", "If you have trouble finding the debug builds, you can try and build your own. Browse the build directory, for project files like python.vcproj - to locate versions that will work with Visual Studio 2005.\n", "I recall, some time ago, giving IronPython a 'whirl' in VS2005. I ran into all kinds of 'esoteric' errors until I figured out that to compile and run I had to add the C++ libraries and tools of VS2005 as well (add/remove).\nMaybe this is something similar ?\n" ]
[ 1, 0, 0 ]
[]
[]
[ "python", "visual_studio_2005" ]
stackoverflow_0000635200_python_visual_studio_2005.txt
Q: Django: Open uploaded file while still in memory; In the Form Clean method? I need to validate the contents of an uploaded XML file in my Form clean method, but I'm unable to open the file for validation. It seams, in the clean method, the file hasn't yet been moved from memory (or the temporary directory) to the destination directory. For example the following code doesn't work because the file hasn't been moved to that destination yet. It's still in memory (or the temporary directory): xml_file = cleaned_data.get('xml_file') xml_file_absolute = '%(1)s%(2)s' % {'1': settings.MEDIA_ROOT, '2': xml_file} xml_size = str(os.path.getsize(xml_file_absolute)) When I look at the "cleaned_data" variable it shows this: {'xml_file': <InMemoryUploadedFile: texting.nzb (application/octet-stream)>} cleaned_data.get('xml_file') only returns "texting.nzb" as a string. Is there another way to access the the file in memory (or the temporary directory)? Again, this is in my Form's clean method that's tied into the default administration view. I've been told time and time again that all validation should be handled in a Form, not the view. Correct? A: I'm assuming that you've bound your form to the files using: my_form = MyFormClass(request.POST, request.FILES) If you have, once the form has been validated, you can access the file content itself using the request.FILES dictionary: if my_form.is_valid(): data = request.FILES['myfile'].read() The request.FILES['myfile'] object is an UploadedFile object, so it supports file-like read/write operations. If you need to access the file contents from within the form's clean method (or any method of the cleaning machinery), you are doing it right. cleaned_data.get('xml_file') returns an UploadedFile object. The __str__ method of that object just prints out the string, which is why you see only the file name. However, you can get access to the entire contents: xml_file = myform.cleaned_data.get('xml_file') print xml_file.read() This section of the docs has some great examples: http://docs.djangoproject.com/en/dev/topics/http/file-uploads/
Django: Open uploaded file while still in memory; In the Form Clean method?
I need to validate the contents of an uploaded XML file in my Form clean method, but I'm unable to open the file for validation. It seams, in the clean method, the file hasn't yet been moved from memory (or the temporary directory) to the destination directory. For example the following code doesn't work because the file hasn't been moved to that destination yet. It's still in memory (or the temporary directory): xml_file = cleaned_data.get('xml_file') xml_file_absolute = '%(1)s%(2)s' % {'1': settings.MEDIA_ROOT, '2': xml_file} xml_size = str(os.path.getsize(xml_file_absolute)) When I look at the "cleaned_data" variable it shows this: {'xml_file': <InMemoryUploadedFile: texting.nzb (application/octet-stream)>} cleaned_data.get('xml_file') only returns "texting.nzb" as a string. Is there another way to access the the file in memory (or the temporary directory)? Again, this is in my Form's clean method that's tied into the default administration view. I've been told time and time again that all validation should be handled in a Form, not the view. Correct?
[ "I'm assuming that you've bound your form to the files using:\nmy_form = MyFormClass(request.POST, request.FILES)\n\nIf you have, once the form has been validated, you can access the file content itself using the request.FILES dictionary:\nif my_form.is_valid():\n data = request.FILES['myfile'].read()\n\nThe request.FILES['myfile'] object is an UploadedFile object, so it supports file-like read/write operations.\nIf you need to access the file contents from within the form's clean method (or any method of the cleaning machinery), you are doing it right. cleaned_data.get('xml_file') returns an UploadedFile object. The __str__ method of that object just prints out the string, which is why you see only the file name. However, you can get access to the entire contents:\nxml_file = myform.cleaned_data.get('xml_file')\nprint xml_file.read()\n\nThis section of the docs has some great examples: http://docs.djangoproject.com/en/dev/topics/http/file-uploads/\n" ]
[ 30 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000635524_django_python.txt
Q: How do you deploy your WSGI application? (and why it is the best way) I am deploying a WSGI application. There are many ways to skin this cat. I am currently using apache2 with mod-wsgi, but I can see some potential problems with this. So how can it be done? Apache Mod-wsgi (the other mod-wsgi's seem to not be worth it) Pure Python web server eg paste, cherrypy, Spawning, Twisted.web as 2 but with reverse proxy from nginx, apache2 etc, with good static file handling Conversion to other protocol such as FCGI with a bridge (eg Flup) and running in a conventional web server. More? I want to know how you do it, and why it is the best way to do it. I would absolutely love you to bore me with details about the whats and the whys, application specific stuff, etc. A: As always: It depends ;-) When I don't need any apache features I am going with a pure python webserver like paste etc. Which one exactly depends on your application I guess and can be decided by doing some benchmarks. I always wanted to do some but never came to it. I guess Spawning might have some advantages in using non blocking IO out of the box but I had sometimes problems with it because of the patching it's doing. You are always free to put a varnish in front as well of course. If an Apache is required I am usually going with solution 3 so that I can keep processes separate. You can also more easily move processes to other servers etc. I simply like to keep things separate. For static files I am using right now a separate server for a project which just serves static images/css/js. I am using lighttpd as webserver which has great performance (in this case I don't have a varnish in front anymore). Another useful tool is supervisord for controlling and monitoring these services. I am additionally using buildout for managing my deployments and development sandboxes (together with virtualenv). A: The absolute easiest thing to deploy is CherryPy. Your web application can also become a standalone webserver. CherryPy is also a fairly fast server considering that it's written in pure Python. With that said, it's not Apache. Thus, I find that CherryPy is a good choice for lower volume webapps. Other than that, I don't think there's any right or wrong answer to this question. Lots of high-volume websites have been built on the technologies you talk about, and I don't think you can go too wrong any of those ways (although I will say that I agree with mod-wsgi not being up to snuff on every non-apache server). Also, I've been using isapi_wsgi to deploy python apps under IIS. It's a less than ideal setup, but it works and you don't always get to choose otherwise when you live in a windows-centric world. A: I would absolutely love you to bore me with details about the whats and the whys, application specific stuff, etc Ho. Well you asked for it! Like Daniel I personally use Apache with mod_wsgi. It is still new enough that deploying it in some environments can be a struggle, but if you're compiling everything yourself anyway it's pretty easy. I've found it very reliable, even the early versions. Props to Graham Dumpleton for keeping control of it pretty much by himself. However for me it's essential that WSGI applications work across all possible servers. There is a bit of a hole at the moment in this area: you have the WSGI standard telling you what a WSGI callable (application) does, but there's no standardisation of deployment; no single way to tell the web server where to find the application. There's also no standardised way to make the server reload the application when you've updated it. The approach I've adopted is to put: all application logic in modules/packages, preferably in classes all website-specific customisations to be done by subclassing the main Application and overriding members all server-specific deployment settings (eg. database connection factory, mail relay settings) as class __init__() parameters one top-level ‘application.py’ script that initialises the Application class with the correct deployment settings for the current server, then runs the application in such a way that it can work deployed as a CGI script, a mod_wsgi WSGIScriptAlias (or Passenger, which apparently works the same way), or can be interacted with from the command line a helper module that takes care of above deployment issues and allows the application to be reloaded when the modules the application is relying on change So what the application.py looks like in the end is something like: #!/usr/bin/env python import os.path basedir= os.path.dirname(__file__) import MySQLdb def dbfactory(): return MySQLdb.connect(db= 'myappdb', unix_socket= '/var/mysql/socket', user= 'u', passwd= 'p') def appfactory(): import myapplication return myapplication.Application(basedir, dbfactory, debug= False) import wsgiwrap ismain= __name__=='__main__' libdir= os.path.join(basedir, 'system', 'lib') application= wsgiwrap.Wrapper(appfactory, libdir, 10, ismain) The wsgiwrap.Wrapper checks every 10 seconds to see if any of the application modules in libdir have been updated, and if so does some nasty sys.modules magic to unload them all reliably. Then appfactory() will be called again to get a new instance of the updated application. (You can also use command line tools such as ./application.py setup ./application.py daemon to run any setup and background-tasks hooks provided by the application callable — a bit like how distutils works. It also responds to start/stop/restart like an init script.) Another trick I use is to put the deployment settings for multiple servers (development/testing/production) in the same application.py script, and sniff ‘socket.gethostname()’ to decide which server-specific bunch of settings to use. At some point I might package wsgiwrap up and release it properly (possibly under a different name). In the meantime if you're interested, you can see a dogfood-development version at http://www.doxdesk.com/file/software/py/v/wsgiwrap-0.5.py. A: Nginx reverse proxy and static file sharing + XSendfile + uploadprogress_module. Nothing beats it for the purpose. On the WSGI side either Apache + mod_wsgi or cherrypy server. I like to use cherrypy wsgi server for applications on servers with less memory and less requests. Reasoning: I've done benchmarks with different tools for different popular solutions. I have more experience with lower level TCP/IP than web development, especially http implementations. I'm more confident that I can recognize a good http server than I can recognize a good web framework. I know Twisted much more than Django or Pylons. The http stack in Twisted is still not up to this but it will be there. A: I'm using Google App Engine for an application I'm developing. It runs WSGI applications. Here's a couple bits of info on it. This is the first web-app I've ever really worked on, so I don't have a basis for comparison, but if you're a Google fan, you might want to look into it. I've had a lot of fun using it as my framework for learning. A: TurboGears (2.0) TurboGears 2.0 is leaving Beta within the next month (has been in it for plenty of time). 2.0 improves upon 1.0 series and attempts to give you best-of-breed WSGI stack, so it makes some default choices for you, if you want the least fuss. it has the tg* tools for testing and deployment in 1.x series, but now transformed to paster equivalents in 2.0 series, which shoud seem familiar if you've expermiented with pylons. tg-admin quickstart —> paster quickstart tg-admin info —> paster tginfo tg-admin toolbox –> paster toolbox tg-admin shell –> paster shell tg-admin sql create –> paster setup-app development.ini Pylons It you'd like to be more flexible in your WSGI stack (choice of ORM, choice of templater, choice of form-ing), Pylons is becoming the consolidated choice. This would be my recommended choice, since it offers excellent documentation and allows you to experiment with different components. It is a pleasure to work with as a result, and works on under Apache (production deployment) or stand-alone (helpful for testing and experimenting stage). so it follows, you can do both with Pylons: 2 option for testing stage (python standalone) 4 for scalable production purposes (FastCGI, assuming the database you choose can keep up) The Pylons admin interface is very similar to TurboGears. Here's a toy standalone example: $ paster create -t pylons helloworld $ cd helloworld $ paster serve --reload development.ini for production-class deployment, you could refer to the setup guide of Apache + FastCGI + mod_rewrite is available here. this would scale up to most needs. A: Apache httpd + mod_fcgid using web.py (which is a wsgi application). Works like a charm. A: We are using pure Paste for some of our web services. It is easy to deploy (with our internal deployment mechanism; we're not using Paste Deploy or anything like that) and it is nice to minimize the difference between production systems and what's running on developers' workstations. Caveat: we don't expect low latency out of Paste itself because of the heavyweight nature of our requests. In some crude benchmarking we did we weren't getting fantastic results; it just ended up being moot due to the expense of our typical request handler. So far it has worked fine. Static data has been handled by completely separate (and somewhat "organically" grown) stacks, including the use of S3, Akamai, Apache and IIS, in various ways. A: Apache+mod_wsgi, Simple, clean. (only four lines of webserver config), easy for other sysadimns to get their head around.
How do you deploy your WSGI application? (and why it is the best way)
I am deploying a WSGI application. There are many ways to skin this cat. I am currently using apache2 with mod-wsgi, but I can see some potential problems with this. So how can it be done? Apache Mod-wsgi (the other mod-wsgi's seem to not be worth it) Pure Python web server eg paste, cherrypy, Spawning, Twisted.web as 2 but with reverse proxy from nginx, apache2 etc, with good static file handling Conversion to other protocol such as FCGI with a bridge (eg Flup) and running in a conventional web server. More? I want to know how you do it, and why it is the best way to do it. I would absolutely love you to bore me with details about the whats and the whys, application specific stuff, etc.
[ "As always: It depends ;-)\nWhen I don't need any apache features I am going with a pure python webserver like paste etc. Which one exactly depends on your application I guess and can be decided by doing some benchmarks. I always wanted to do some but never came to it. I guess Spawning might have some advantages in using non blocking IO out of the box but I had sometimes problems with it because of the patching it's doing. \nYou are always free to put a varnish in front as well of course.\nIf an Apache is required I am usually going with solution 3 so that I can keep processes separate. You can also more easily move processes to other servers etc. I simply like to keep things separate.\nFor static files I am using right now a separate server for a project which just serves static images/css/js. I am using lighttpd as webserver which has great performance (in this case I don't have a varnish in front anymore).\nAnother useful tool is supervisord for controlling and monitoring these services.\nI am additionally using buildout for managing my deployments and development sandboxes (together with virtualenv).\n", "The absolute easiest thing to deploy is CherryPy. Your web application can also become a standalone webserver. CherryPy is also a fairly fast server considering that it's written in pure Python. With that said, it's not Apache. Thus, I find that CherryPy is a good choice for lower volume webapps.\nOther than that, I don't think there's any right or wrong answer to this question. Lots of high-volume websites have been built on the technologies you talk about, and I don't think you can go too wrong any of those ways (although I will say that I agree with mod-wsgi not being up to snuff on every non-apache server).\nAlso, I've been using isapi_wsgi to deploy python apps under IIS. It's a less than ideal setup, but it works and you don't always get to choose otherwise when you live in a windows-centric world.\n", "\nI would absolutely love you to bore me with details about the whats and the whys, application specific stuff, etc\n\nHo. Well you asked for it!\nLike Daniel I personally use Apache with mod_wsgi. It is still new enough that deploying it in some environments can be a struggle, but if you're compiling everything yourself anyway it's pretty easy. I've found it very reliable, even the early versions. Props to Graham Dumpleton for keeping control of it pretty much by himself.\nHowever for me it's essential that WSGI applications work across all possible servers. There is a bit of a hole at the moment in this area: you have the WSGI standard telling you what a WSGI callable (application) does, but there's no standardisation of deployment; no single way to tell the web server where to find the application. There's also no standardised way to make the server reload the application when you've updated it.\nThe approach I've adopted is to put:\n\nall application logic in modules/packages, preferably in classes\nall website-specific customisations to be done by subclassing the main Application and overriding members\nall server-specific deployment settings (eg. database connection factory, mail relay settings) as class __init__() parameters\none top-level ‘application.py’ script that initialises the Application class with the correct deployment settings for the current server, then runs the application in such a way that it can work deployed as a CGI script, a mod_wsgi WSGIScriptAlias (or Passenger, which apparently works the same way), or can be interacted with from the command line\na helper module that takes care of above deployment issues and allows the application to be reloaded when the modules the application is relying on change\n\nSo what the application.py looks like in the end is something like:\n#!/usr/bin/env python\n\nimport os.path\nbasedir= os.path.dirname(__file__)\n\nimport MySQLdb\ndef dbfactory():\n return MySQLdb.connect(db= 'myappdb', unix_socket= '/var/mysql/socket', user= 'u', passwd= 'p')\n\ndef appfactory():\n import myapplication\n return myapplication.Application(basedir, dbfactory, debug= False)\n\nimport wsgiwrap\nismain= __name__=='__main__'\nlibdir= os.path.join(basedir, 'system', 'lib')\napplication= wsgiwrap.Wrapper(appfactory, libdir, 10, ismain)\n\nThe wsgiwrap.Wrapper checks every 10 seconds to see if any of the application modules in libdir have been updated, and if so does some nasty sys.modules magic to unload them all reliably. Then appfactory() will be called again to get a new instance of the updated application.\n(You can also use command line tools such as\n./application.py setup\n./application.py daemon\n\nto run any setup and background-tasks hooks provided by the application callable — a bit like how distutils works. It also responds to start/stop/restart like an init script.)\nAnother trick I use is to put the deployment settings for multiple servers (development/testing/production) in the same application.py script, and sniff ‘socket.gethostname()’ to decide which server-specific bunch of settings to use.\nAt some point I might package wsgiwrap up and release it properly (possibly under a different name). In the meantime if you're interested, you can see a dogfood-development version at http://www.doxdesk.com/file/software/py/v/wsgiwrap-0.5.py.\n", "Nginx reverse proxy and static file sharing + XSendfile + uploadprogress_module. Nothing beats it for the purpose.\nOn the WSGI side either Apache + mod_wsgi or cherrypy server. I like to use cherrypy wsgi server for applications on servers with less memory and less requests.\nReasoning:\nI've done benchmarks with different tools for different popular solutions.\nI have more experience with lower level TCP/IP than web development, especially http implementations. I'm more confident that I can recognize a good http server than I can recognize a good web framework.\nI know Twisted much more than Django or Pylons. The http stack in Twisted is still not up to this but it will be there.\n", "I'm using Google App Engine for an application I'm developing. It runs WSGI applications.\nHere's a couple bits of info on it. \nThis is the first web-app I've ever really worked on, so I don't have a basis for comparison, but if you're a Google fan, you might want to look into it. I've had a lot of fun using it as my framework for learning. \n", "TurboGears (2.0)\nTurboGears 2.0 is leaving Beta within the next month (has been in it for plenty of time). 2.0 improves upon 1.0 series and attempts to give you best-of-breed WSGI stack, so it makes some default choices for you, if you want the least fuss.\nit has the tg* tools for testing and deployment in 1.x series, but now transformed to paster equivalents in 2.0 series, which shoud seem familiar if you've expermiented with pylons.\n\ntg-admin quickstart —> paster quickstart\ntg-admin info —> paster tginfo\ntg-admin toolbox –> paster toolbox\ntg-admin shell –> paster shell\ntg-admin sql create –> paster setup-app development.ini\n\nPylons\nIt you'd like to be more flexible in your WSGI stack (choice of ORM, choice of templater, choice of form-ing), Pylons is becoming the consolidated choice. This would be my recommended choice, since it offers excellent documentation and allows you to experiment with different components.\nIt is a pleasure to work with as a result, and works on under Apache (production deployment) or stand-alone (helpful for testing and experimenting stage).\nso it follows, you can do both with Pylons:\n\n2 option for testing stage (python standalone)\n\n4 for scalable production purposes (FastCGI, assuming the database you choose can keep up)\n\n\nThe Pylons admin interface is very similar to TurboGears. Here's a toy standalone example:\n\n$ paster create -t pylons helloworld\n$ cd helloworld\n$ paster serve --reload development.ini\nfor production-class deployment, you could refer to the setup guide of Apache + FastCGI + mod_rewrite is available here. this would scale up to most needs.\n", "Apache httpd + mod_fcgid using web.py (which is a wsgi application).\nWorks like a charm.\n", "We are using pure Paste for some of our web services. It is easy to deploy (with our internal deployment mechanism; we're not using Paste Deploy or anything like that) and it is nice to minimize the difference between production systems and what's running on developers' workstations. Caveat: we don't expect low latency out of Paste itself because of the heavyweight nature of our requests. In some crude benchmarking we did we weren't getting fantastic results; it just ended up being moot due to the expense of our typical request handler. So far it has worked fine.\nStatic data has been handled by completely separate (and somewhat \"organically\" grown) stacks, including the use of S3, Akamai, Apache and IIS, in various ways.\n", "Apache+mod_wsgi,\nSimple, clean. (only four lines of webserver config), easy for other sysadimns to get their head around.\n" ]
[ 26, 13, 13, 6, 4, 4, 3, 1, 1 ]
[]
[]
[ "deployment", "python", "wsgi" ]
stackoverflow_0000574068_deployment_python_wsgi.txt
Q: tell whether a character is a combining diacritic mark if you're looping though the chars a unicode string in python (2.x), say: ak.sɛp.tɑ̃ How can you tell whether the current char is a combining diacritic mark? For instance, the last char in the above string is actually a combining mark: ak.sɛp.tɑ̃ --> ̃ A: Use the unicodedata module: import unicodedata if unicodedata.combining(u'a'): print "is combining character" else: print "is not combining" these posts are also relevant How do I reverse Unicode decomposition using Python? What is the best way to remove accents in a Python unicode string?
tell whether a character is a combining diacritic mark
if you're looping though the chars a unicode string in python (2.x), say: ak.sɛp.tɑ̃ How can you tell whether the current char is a combining diacritic mark? For instance, the last char in the above string is actually a combining mark: ak.sɛp.tɑ̃ --> ̃
[ "Use the unicodedata module:\nimport unicodedata\nif unicodedata.combining(u'a'):\n print \"is combining character\"\nelse:\n print \"is not combining\"\n\nthese posts are also relevant\nHow do I reverse Unicode decomposition using Python?\nWhat is the best way to remove accents in a Python unicode string?\n" ]
[ 9 ]
[]
[]
[ "diacritics", "python", "unicode" ]
stackoverflow_0000635643_diacritics_python_unicode.txt