content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
sequence
answers_scores
sequence
non_answers
sequence
non_answers_scores
sequence
tags
sequence
name
stringlengths
35
137
Q: Can you do LINQ-like queries in a language like Python or Boo? Take this simple C# LINQ query, and imagine that db.Numbers is an SQL table with one column Number: var result = from n in db.Numbers where n.Number < 5 select n.Number; This will run very efficiently in C#, because it generates an SQL query something like select Number from Numbers where Number < 5 What it doesn't do is select all the numbers from the database, and then filter them in C#, as it might appear to do at first. Python supports a similar syntax: result = [n.Number for n in Numbers if n.Number < 5] But it the if clause here does the filtering on the client side, rather than the server side, which is much less efficient. Is there something as efficient as LINQ in Python? (I'm currently evaluating Python vs. IronPython vs. Boo, so an answer that works in any of those languages is fine.) A: sqlsoup in sqlalchemy gives you the quickest solution in python I think if you want a clear(ish) one liner . Look at the page to see. It should be something like... result = [n.Number for n in db.Numbers.filter(db.Numbers.Number < 5).all()] A: Look closely at SQLAlchemy. This can probably do much of what you want. It gives you Python syntax for plain-old SQL that runs on the server. A: LINQ is a language feature of C# and VB.NET. It is a special syntax recognized by the compiler and treated specially. It is also dependent on another language feature called expression trees. Expression trees are a little different in that they are not special syntax. They are written just like any other class instantiation, but the compiler does treat them specially under the covers by turning a lambda into an instantiation of a run-time abstract syntax tree. These can be manipulated at run-time to produce a command in another language (i.e. SQL). The C# and VB.NET compilers take LINQ syntax, and turn it into lambdas, then pass those into expression tree instantiations. Then there are a bunch of framework classes that manipulate these trees to produce SQL. You can also find other libraries, both MS-produced and third party, that offer "LINQ providers", which basically pop a different AST processer in to produce something from the LINQ other than SQL. So one obstacle to doing these things in another language is the question whether they support run-time AST building/manipulation. I don't know whether any implementations of Python or Boo do, but I haven't heard of any such features. A: I believe that when IronPython 2.0 is complete, it will have LINQ support (see this thread for some example discussion). Right now you should be able to write something like: Queryable.Select(Queryable.Where(someInputSequence, somePredicate), someFuncThatReturnsTheSequenceElement) Something better might have made it into IronPython 2.0b4 - there's a lot of current discussion about how naming conflicts were handled. A: Boo supports list generator expressions using the same syntax as python. For more information on that, check out the Boo documentation on Generator expressions and List comprehensions. A: A key factor for LINQ is the ability of the compiler to generate expression trees. I am using a macro in Nemerle that converts a given Nemerle expression into an Expression tree object. I can then pass this to the Where/Select/etc extension methods on IQueryables. It's not quite the syntax of C# and VB, but it's close enough for me. I got the Nemerle macro via a link on this post: http://groups.google.com/group/nemerle-dev/browse_thread/thread/99b9dcfe204a578e It should be possible to create a similar macro for Boo. It's quite a bit of work however, given the large set of possible expressions you need to support. Ayende has given a proof of concept here: http://ayende.com/Blog/archive/2008/08/05/Ugly-Linq.aspx
Can you do LINQ-like queries in a language like Python or Boo?
Take this simple C# LINQ query, and imagine that db.Numbers is an SQL table with one column Number: var result = from n in db.Numbers where n.Number < 5 select n.Number; This will run very efficiently in C#, because it generates an SQL query something like select Number from Numbers where Number < 5 What it doesn't do is select all the numbers from the database, and then filter them in C#, as it might appear to do at first. Python supports a similar syntax: result = [n.Number for n in Numbers if n.Number < 5] But it the if clause here does the filtering on the client side, rather than the server side, which is much less efficient. Is there something as efficient as LINQ in Python? (I'm currently evaluating Python vs. IronPython vs. Boo, so an answer that works in any of those languages is fine.)
[ "sqlsoup in sqlalchemy gives you the quickest solution in python I think if you want a clear(ish) one liner . Look at the page to see.\nIt should be something like...\nresult = [n.Number for n in db.Numbers.filter(db.Numbers.Number < 5).all()]\n\n", "Look closely at SQLAlchemy. This can probably do much of what you want. It gives you Python syntax for plain-old SQL that runs on the server.\n", "LINQ is a language feature of C# and VB.NET. It is a special syntax recognized by the compiler and treated specially. It is also dependent on another language feature called expression trees.\nExpression trees are a little different in that they are not special syntax. They are written just like any other class instantiation, but the compiler does treat them specially under the covers by turning a lambda into an instantiation of a run-time abstract syntax tree. These can be manipulated at run-time to produce a command in another language (i.e. SQL).\nThe C# and VB.NET compilers take LINQ syntax, and turn it into lambdas, then pass those into expression tree instantiations. Then there are a bunch of framework classes that manipulate these trees to produce SQL. You can also find other libraries, both MS-produced and third party, that offer \"LINQ providers\", which basically pop a different AST processer in to produce something from the LINQ other than SQL.\nSo one obstacle to doing these things in another language is the question whether they support run-time AST building/manipulation. I don't know whether any implementations of Python or Boo do, but I haven't heard of any such features.\n", "I believe that when IronPython 2.0 is complete, it will have LINQ support (see this thread for some example discussion). Right now you should be able to write something like:\nQueryable.Select(Queryable.Where(someInputSequence, somePredicate), someFuncThatReturnsTheSequenceElement) \n\nSomething better might have made it into IronPython 2.0b4 - there's a lot of current discussion about how naming conflicts were handled.\n", "Boo supports list generator expressions using the same syntax as python. For more information on that, check out the Boo documentation on Generator expressions and List comprehensions.\n", "A key factor for LINQ is the ability of the compiler to generate expression trees.\nI am using a macro in Nemerle that converts a given Nemerle expression into an Expression tree object.\nI can then pass this to the Where/Select/etc extension methods on IQueryables.\nIt's not quite the syntax of C# and VB, but it's close enough for me. \nI got the Nemerle macro via a link on this post: \nhttp://groups.google.com/group/nemerle-dev/browse_thread/thread/99b9dcfe204a578e\nIt should be possible to create a similar macro for Boo. It's quite a bit of work however, given the large set of possible expressions you need to support.\nAyende has given a proof of concept here:\nhttp://ayende.com/Blog/archive/2008/08/05/Ugly-Linq.aspx\n" ]
[ 6, 5, 4, 4, 1, 0 ]
[]
[]
[ "boo", "ironpython", "linq", "linq_to_sql", "python" ]
stackoverflow_0000117732_boo_ironpython_linq_linq_to_sql_python.txt
Q: Python re.findall with groupdicts I kind of wish that there were a version of re.findall that returned groupdicts instead of just groups. Am I missing some simple way to accomplish the same result? Does anybody know of a reason that this function doesn't exist? A: You could use the finditer() function. This will give you a sequence of match objects, so you can get the groupdict for each with: [m.groupdict() for m in regex.finditer(search_string)]
Python re.findall with groupdicts
I kind of wish that there were a version of re.findall that returned groupdicts instead of just groups. Am I missing some simple way to accomplish the same result? Does anybody know of a reason that this function doesn't exist?
[ "You could use the finditer() function. This will give you a sequence of match objects, so you can get the groupdict for each with:\n[m.groupdict() for m in regex.finditer(search_string)]\n\n" ]
[ 31 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0000255332_python_regex.txt
Q: Determine if a named parameter was passed I would like to know if it is possible to determine if a function parameter with a default value was passed in Python. For example, how does dict.pop work? >>> {}.pop('test') Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'pop(): dictionary is empty' >>> {}.pop('test',None) >>> {}.pop('test',3) 3 >>> {}.pop('test',NotImplemented) NotImplemented How does the pop method determine that the first time a default return value was not passed? Is this something that can only be done in C? Thanks A: The convention is often to use arg=None and use def foo(arg=None): if arg is None: arg = "default value" # other stuff # ... to check if it was passed or not. Allowing the user to pass None, which would be interpreted as if the argument was not passed. A: I guess you mean "keyword argument", when you say "named parameter". dict.pop() does not accept keyword argument, so this part of the question is moot. >>> {}.pop('test', d=None) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: pop() takes no keyword arguments That said, the way to detect whether an argument was provided is to use the *args or **kwargs syntax. For example: def foo(first, *rest): if len(rest) > 1: raise TypeError("foo() expected at most 2 arguments, got %d" % (len(rest) + 1)) print 'first =', first if rest: print 'second =', rest[0] With some work, and using the **kwargs syntax too it is possible to completely emulate the python calling convention, where arguments can be either provided by position or by name, and arguments provided multiple times (by position and name) cause an error. A: You can do it like this: def isdefarg(*args): if len(args) > 0: print len(args), "arguments" else: print "no arguments" isdefarg() isdefarg(None) isdefarg(5, 7) See the Python documentation on calls for full information. A: I am not certain if I fully understand what is it you want; however: def fun(arg=Ellipsis): if arg is Ellipsis: print "No arg provided" else: print "arg provided:", repr(arg) does that do what you want? If not, then as others have suggested, you should declare your function with the *args, **kwargs syntax and check in the kwargs dict for the parameter existence. A: def f(one, two=2): print "I wonder if", two, "has been passed or not..." f(1, 2) If this is the exact meaning of your question, I think that there is no way to distinguish between a 2 that was in the default value and a 2 that has been passed. I didn't find how to accomplish such distinction even in the inspect module.
Determine if a named parameter was passed
I would like to know if it is possible to determine if a function parameter with a default value was passed in Python. For example, how does dict.pop work? >>> {}.pop('test') Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'pop(): dictionary is empty' >>> {}.pop('test',None) >>> {}.pop('test',3) 3 >>> {}.pop('test',NotImplemented) NotImplemented How does the pop method determine that the first time a default return value was not passed? Is this something that can only be done in C? Thanks
[ "The convention is often to use arg=None and use\ndef foo(arg=None):\n if arg is None:\n arg = \"default value\"\n # other stuff\n # ...\n\nto check if it was passed or not. Allowing the user to pass None, which would be interpreted as if the argument was not passed.\n", "I guess you mean \"keyword argument\", when you say \"named parameter\". dict.pop() does not accept keyword argument, so this part of the question is moot.\n>>> {}.pop('test', d=None)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: pop() takes no keyword arguments\n\nThat said, the way to detect whether an argument was provided is to use the *args or **kwargs syntax. For example:\ndef foo(first, *rest):\n if len(rest) > 1:\n raise TypeError(\"foo() expected at most 2 arguments, got %d\"\n % (len(rest) + 1))\n print 'first =', first\n if rest:\n print 'second =', rest[0]\n\nWith some work, and using the **kwargs syntax too it is possible to completely emulate the python calling convention, where arguments can be either provided by position or by name, and arguments provided multiple times (by position and name) cause an error.\n", "You can do it like this:\ndef isdefarg(*args):\n if len(args) > 0:\n print len(args), \"arguments\"\n else:\n print \"no arguments\"\n\nisdefarg()\nisdefarg(None)\nisdefarg(5, 7)\n\nSee the Python documentation on calls for full information.\n", "I am not certain if I fully understand what is it you want; however:\ndef fun(arg=Ellipsis):\n if arg is Ellipsis:\n print \"No arg provided\"\n else:\n print \"arg provided:\", repr(arg)\n\ndoes that do what you want? If not, then as others have suggested, you should declare your function with the *args, **kwargs syntax and check in the kwargs dict for the parameter existence.\n", "def f(one, two=2):\n print \"I wonder if\", two, \"has been passed or not...\"\n\nf(1, 2)\n\nIf this is the exact meaning of your question, I think that there is no way to distinguish between a 2 that was in the default value and a 2 that has been passed. I didn't find how to accomplish such distinction even in the inspect module.\n" ]
[ 17, 12, 4, 2, 1 ]
[]
[]
[ "default_value", "named_parameters", "python" ]
stackoverflow_0000255429_default_value_named_parameters_python.txt
Q: Python packages and egg-info directories Can someone explain how egg-info directories are tied to their respective modules? For example, I have the following: /usr/local/lib/python2.5/site-packages/quodlibet/ /usr/local/lib/python2.5/site-packages/quodlibet-2.0.egg-info/ I'm assuming the egg-info directory is to make the corresponding module visible to setuptools (easy_install), right? If so, how does setuptools tie the egg-info directory to the module directory? Assuming that I'm on the right track, and for the sake of example... If I wanted to make an existing package of mine visible to setuptools, could I just symlink the module directory and the egg-info directory to the site-packages directory? I would have just tried this myself, but I'm not sure how to test if the package is visible to setuptools. Bonus points if you can also tell me how to test this :) The main reason I'm trying to understand all this is because I would like to symlink some of my modules into site-packages so that I can make changes to them and have the changes visible to the scripts that use them without having to reinstall the egg from PyPI after each change. A: The .egg-info directories get only created if --single-version-externally-managed was used to install the egg. "Normally", installing an egg would create a single directory (or zip file), containing both the code and the metadata. pkg_resources (which is the library that reads the metadata) has a function require which can be used to request a specific version of the package. For "old-style", regular imports, easy_install hacks a .pth file to get the egg directory onto sys.path. For --single-version-externally-managed, this hacking is not necessary, because there will only be a single version installed (by the system's pacakging infrastructure, e.g. rpm or dpkg). The egg-info is still included, for applications that use require (or any of the other pkg_resources binding mechanisms). If you want to install a package by hard-linking, I recommend to use "setup.py develop". This is a command from setuptools which doesn't actually install the egg, but makes it available site-wide. To do so, it creates an egg-link file so that pkg_resources can find it, and it manipulates a .pth file, so that regular import can find it.
Python packages and egg-info directories
Can someone explain how egg-info directories are tied to their respective modules? For example, I have the following: /usr/local/lib/python2.5/site-packages/quodlibet/ /usr/local/lib/python2.5/site-packages/quodlibet-2.0.egg-info/ I'm assuming the egg-info directory is to make the corresponding module visible to setuptools (easy_install), right? If so, how does setuptools tie the egg-info directory to the module directory? Assuming that I'm on the right track, and for the sake of example... If I wanted to make an existing package of mine visible to setuptools, could I just symlink the module directory and the egg-info directory to the site-packages directory? I would have just tried this myself, but I'm not sure how to test if the package is visible to setuptools. Bonus points if you can also tell me how to test this :) The main reason I'm trying to understand all this is because I would like to symlink some of my modules into site-packages so that I can make changes to them and have the changes visible to the scripts that use them without having to reinstall the egg from PyPI after each change.
[ "The .egg-info directories get only created if --single-version-externally-managed was used to install the egg. \"Normally\", installing an egg would create a single directory (or zip file), containing both the code and the metadata. \npkg_resources (which is the library that reads the metadata) has a function require which can be used to request a specific version of the package. For \"old-style\", regular imports, easy_install hacks a .pth file to get the egg directory onto sys.path. For --single-version-externally-managed, this hacking is not necessary, because there will only be a single version installed (by the system's pacakging infrastructure, e.g. rpm or dpkg). The egg-info is still included, for applications that use require (or any of the other pkg_resources binding mechanisms).\nIf you want to install a package by hard-linking, I recommend to use \"setup.py develop\". This is a command from setuptools which doesn't actually install the egg, but makes it available site-wide. To do so, it creates an egg-link file so that pkg_resources can find it, and it manipulates a .pth file, so that regular import can find it.\n" ]
[ 75 ]
[]
[]
[ "egg", "python", "setuptools" ]
stackoverflow_0000256417_egg_python_setuptools.txt
Q: How to override HTTP request verb in GAE In the context of a Google App Engine Webapp framework application: I want to changed the request verb of a request in the case a parameter _method is provided, for example if a POST request comes in with a parameter _method=PUT, I need to change the request to call the put method of the handler. This is to cope with the way prototype.js works with verbs like PUT and DELETE(workaround for IE). Here is my first attempt: class MyRequestHandler(webapp.RequestHandler): def initialize(self, request, response): m = request.get('_method') if m: request.method = m.upper() webapp.RequestHandler.initialize(self, request, response) The problem is, for some reason whenever the redirect is done, the self.request.params are emptied by the time the handling method(put or delete) is called, even though they were populated when initialize was called. Anyone have a clue why this is? As a workaround I thought I could clone the params at initialize() time, but .copy() did not work, and I haven't found a way to do that either. Update: I received a very helpful response from Arachnid. The solution I ended up with uses a metaclass. It is found below. A: Calling the handler from initialize isn't the right way anyway - if you do that, the webapp will then call the original handler as well. Instead, you have a couple of options: You can subclass webapp.WSGIApplication and override call to select the method based on _method when it exists. You can check for the existence of _method in initialize, and if it exists, modify the request object's 'REQUEST_METHOD' environment variable accordingly. That will cause the WSGIApplication class to execute the method you choose. Either way, take a look at google/appengine/ext/webapp/init.py in the SDK so you can see how it works. A: Thats Arachnid for your response. Pointing me to the source of the framework was really helpful. Last I looked the source wasn't there(there was only .pyc), maybe it changed with the new version of the SDK. For my situation I think overriding WSGIApplication would have been the right thing to do. However, I chose to use a metaclass instead, because it didn't require me to cargo-cult(copy) a bunch of the framework code into my code and then modifying it. This is my solution: class RequestHandlerMetaclass(type): def __init__(cls, name, bases, dct): super(RequestHandlerMetaclass, cls).__init__(name, bases, dct) org_post = getattr(cls, 'post') def post(self, *params, **kws): verb = self.request.get('_method') if verb: verb = verb.upper() if verb == 'DELETE': self.delete(*params, **kws) elif verb == 'PUT': self.put(*params, **kws) else: org_post(self, *params, **kws) setattr(cls, 'post', post) class MyRequestHandler(webapp.RequestHandler): __metaclass__ = RequestHandlerMetaclass
How to override HTTP request verb in GAE
In the context of a Google App Engine Webapp framework application: I want to changed the request verb of a request in the case a parameter _method is provided, for example if a POST request comes in with a parameter _method=PUT, I need to change the request to call the put method of the handler. This is to cope with the way prototype.js works with verbs like PUT and DELETE(workaround for IE). Here is my first attempt: class MyRequestHandler(webapp.RequestHandler): def initialize(self, request, response): m = request.get('_method') if m: request.method = m.upper() webapp.RequestHandler.initialize(self, request, response) The problem is, for some reason whenever the redirect is done, the self.request.params are emptied by the time the handling method(put or delete) is called, even though they were populated when initialize was called. Anyone have a clue why this is? As a workaround I thought I could clone the params at initialize() time, but .copy() did not work, and I haven't found a way to do that either. Update: I received a very helpful response from Arachnid. The solution I ended up with uses a metaclass. It is found below.
[ "Calling the handler from initialize isn't the right way anyway - if you do that, the webapp will then call the original handler as well.\nInstead, you have a couple of options:\n\nYou can subclass webapp.WSGIApplication and override call to select the method based on _method when it exists.\nYou can check for the existence of _method in initialize, and if it exists, modify the request object's 'REQUEST_METHOD' environment variable accordingly. That will cause the WSGIApplication class to execute the method you choose.\n\nEither way, take a look at google/appengine/ext/webapp/init.py in the SDK so you can see how it works.\n", "Thats Arachnid for your response. Pointing me to the source of the framework was really helpful. Last I looked the source wasn't there(there was only .pyc), maybe it changed with the new version of the SDK. For my situation I think overriding WSGIApplication would have been the right thing to do. However, I chose to use a metaclass instead, because it didn't require me to cargo-cult(copy) a bunch of the framework code into my code and then modifying it. This is my solution:\n\nclass RequestHandlerMetaclass(type):\n def __init__(cls, name, bases, dct):\n super(RequestHandlerMetaclass, cls).__init__(name, bases, dct)\n org_post = getattr(cls, 'post')\n def post(self, *params, **kws):\n verb = self.request.get('_method')\n if verb:\n verb = verb.upper()\n if verb == 'DELETE':\n self.delete(*params, **kws)\n elif verb == 'PUT':\n self.put(*params, **kws)\n else:\n org_post(self, *params, **kws)\n setattr(cls, 'post', post)\n\nclass MyRequestHandler(webapp.RequestHandler):\n __metaclass__ = RequestHandlerMetaclass\n\n" ]
[ 3, 2 ]
[]
[]
[ "google_app_engine", "metaclass", "python", "rest" ]
stackoverflow_0000255157_google_app_engine_metaclass_python_rest.txt
Q: Storage transactions in Redland's Python bindings? I've currently skimming through the Python-bindings for Redland and haven't found a clean way to do transactions on the storage engine via it. I found some model-transactions within the low-level Redland module: import RDF, Redland storage = RDF.Storage(...) model = RDF.Model(storage) Redland.librdf_model_transaction_start(model._model) try: # Do something Redland.librdf_model_transaction_commit(model._model) model.sync() except: Redland.librdf_model_transaction_rollback(model._model) Do these also translate down to the storage layer? Thanks :-) A: Yes, this should work. There are no convenience functions for the model class in the python wrapper right now but they would be similar to what you wrote: class Model(object): ... def transaction_start(self): return Redland.librdf_model_transaction_start(self._model)
Storage transactions in Redland's Python bindings?
I've currently skimming through the Python-bindings for Redland and haven't found a clean way to do transactions on the storage engine via it. I found some model-transactions within the low-level Redland module: import RDF, Redland storage = RDF.Storage(...) model = RDF.Model(storage) Redland.librdf_model_transaction_start(model._model) try: # Do something Redland.librdf_model_transaction_commit(model._model) model.sync() except: Redland.librdf_model_transaction_rollback(model._model) Do these also translate down to the storage layer? Thanks :-)
[ "Yes, this should work. There are no convenience functions for the model class in the python wrapper right now but they would be similar to what you wrote:\nclass Model(object):\n ...\n def transaction_start(self):\n return Redland.librdf_model_transaction_start(self._model) \n\n" ]
[ 4 ]
[]
[]
[ "python", "rdf", "rdfstore", "redland", "transactions" ]
stackoverflow_0000255263_python_rdf_rdfstore_redland_transactions.txt
Q: Java equivalent to pyftpdlib? Is there a good Java alternative to pyftpdlib? I am looking for an easy to setup and run embedded ftp server. A: Check out Apache's FTPServer. They have an example of how to embed it in a Java application.
Java equivalent to pyftpdlib?
Is there a good Java alternative to pyftpdlib? I am looking for an easy to setup and run embedded ftp server.
[ "Check out Apache's FTPServer.\nThey have an example of how to embed it in a Java application.\n" ]
[ 0 ]
[]
[]
[ "ftp", "java", "python" ]
stackoverflow_0000257956_ftp_java_python.txt
Q: Python: wrapping method invocations with pre and post methods I am instantiating a class A (which I am importing from somebody else, so I can't modify it) into my class X. Is there a way I can intercept or wrap calls to methods in A? I.e., in the code below can I call x.a.p1() and get the output X.pre A.p1 X.post Many TIA! class A: # in my real application, this is an imported class # that I cannot modify def p1(self): print 'A.p1' class X: def __init__(self): self.a=A() def pre(self): print 'X.pre' def post(self): print 'X.post' x=X() x.a.p1() A: Here is the solution I and my colleagues came up with: from types import MethodType class PrePostCaller: def __init__(self, other): self.other = other def pre(self): print 'pre' def post(self): print 'post' def __getattr__(self, name): if hasattr(self.other, name): func = getattr(self.other, name) return lambda *args, **kwargs: self._wrap(func, args, kwargs) raise AttributeError(name) def _wrap(self, func, args, kwargs): self.pre() if type(func) == MethodType: result = func( *args, **kwargs) else: result = func(self.other, *args, **kwargs) self.post() return result #Examples of use class Foo: def stuff(self): print 'stuff' a = PrePostCaller(Foo()) a.stuff() a = PrePostCaller([1,2,3]) print a.count() Gives: pre stuff post pre post 0 So when creating an instance of your object, wrap it with the PrePostCaller object. After that you continue using the object as if it was an instance of the wrapped object. With this solution you can do the wrapping on a per instance basis. A: The no-whistles-or-bells solution would be to write a wrapper class for class A that does just that. A: You could just modify the A instance and replace the p1 function with a wrapper function: def wrapped(pre, post, f): def wrapper(*args, **kwargs): pre() retval = f(*args, **kwargs) post() return retval return wrapper class Y: def __init__(self): self.a=A() self.a.p1 = wrapped(self.pre, self.post, self.a.p1) def pre(self): print 'X.pre' def post(self): print 'X.post' A: I've just recently read about decorators in python, I'm not understanding them yet but it seems to me that they can be a solution to your problem. see Bruce Eckel intro to decorators at: http://www.artima.com/weblogs/viewpost.jsp?thread=240808 He has a few more posts on that topic there. Edit: Three days later I stumble upon this article, which shows how to do a similar task without decorators, what's the problems with it and then introduces decorators and develop a quite full solution: http://wordaligned.org/articles/echo A: As others have mentioned, the wrapper/decorator solution is probably be the easiest one. I don't recommend modifyng the wrapped class itself, for the same reasons that you point out. If you have many external classes you can write a code generator to generate the wrapper classes for you. Since you are doing this in Python you can probably even implement the generator as a part of the program, generating the wrappers at startup, or something. A: Here's what I've received from Steven D'Aprano on comp.lang.python. # Define two decorator factories. def precall(pre): def decorator(f): def newf(*args, **kwargs): pre() return f(*args, **kwargs) return newf return decorator def postcall(post): def decorator(f): def newf(*args, **kwargs): x = f(*args, **kwargs) post() return x return newf return decorator Now you can monkey patch class A if you want. It's probably not a great idea to do this in production code, as it will effect class A everywhere. [this is ok for my application, as it is basically a protocol converter and there's exactly one instance of each class being processed.] class A: # in my real application, this is an imported class # that I cannot modify def p1(self): print 'A.p1' class X: def __init__(self): self.a=A() A.p1 = precall(self.pre)(postcall(self.post)(A.p1)) def pre(self): print 'X.pre' def post(self): print 'X.post' x=X() x.a.p1() Gives the desired result. X.pre A.p1 X.post
Python: wrapping method invocations with pre and post methods
I am instantiating a class A (which I am importing from somebody else, so I can't modify it) into my class X. Is there a way I can intercept or wrap calls to methods in A? I.e., in the code below can I call x.a.p1() and get the output X.pre A.p1 X.post Many TIA! class A: # in my real application, this is an imported class # that I cannot modify def p1(self): print 'A.p1' class X: def __init__(self): self.a=A() def pre(self): print 'X.pre' def post(self): print 'X.post' x=X() x.a.p1()
[ "Here is the solution I and my colleagues came up with:\nfrom types import MethodType\n\nclass PrePostCaller:\n def __init__(self, other):\n self.other = other\n\n def pre(self): print 'pre'\n def post(self): print 'post'\n\n def __getattr__(self, name):\n if hasattr(self.other, name):\n func = getattr(self.other, name)\n return lambda *args, **kwargs: self._wrap(func, args, kwargs)\n raise AttributeError(name)\n\n def _wrap(self, func, args, kwargs):\n self.pre()\n if type(func) == MethodType:\n result = func( *args, **kwargs)\n else:\n result = func(self.other, *args, **kwargs)\n self.post()\n return result\n\n#Examples of use\nclass Foo:\n def stuff(self):\n print 'stuff'\n\na = PrePostCaller(Foo())\na.stuff()\n\na = PrePostCaller([1,2,3])\nprint a.count()\n\nGives:\npre\nstuff\npost\npre\npost\n0\n\nSo when creating an instance of your object, wrap it with the PrePostCaller object. After that you continue using the object as if it was an instance of the wrapped object. With this solution you can do the wrapping on a per instance basis.\n", "The no-whistles-or-bells solution would be to write a wrapper class for class A that does just that.\n", "You could just modify the A instance and replace the p1 function with a wrapper function:\ndef wrapped(pre, post, f):\n def wrapper(*args, **kwargs):\n pre()\n retval = f(*args, **kwargs)\n post()\n return retval\n return wrapper\n\nclass Y:\n def __init__(self):\n self.a=A()\n self.a.p1 = wrapped(self.pre, self.post, self.a.p1)\n\n def pre(self): print 'X.pre'\n def post(self): print 'X.post'\n\n", "I've just recently read about decorators in python, I'm not understanding them yet but it seems to me that they can be a solution to your problem. see Bruce Eckel intro to decorators at:\nhttp://www.artima.com/weblogs/viewpost.jsp?thread=240808\nHe has a few more posts on that topic there.\nEdit: Three days later I stumble upon this article, which shows how to do a similar task without decorators, what's the problems with it and then introduces decorators and develop a quite full solution:\nhttp://wordaligned.org/articles/echo\n", "As others have mentioned, the wrapper/decorator solution is probably be the easiest one. I don't recommend modifyng the wrapped class itself, for the same reasons that you point out.\nIf you have many external classes you can write a code generator to generate the wrapper classes for you. Since you are doing this in Python you can probably even implement the generator as a part of the program, generating the wrappers at startup, or something.\n", "Here's what I've received from Steven D'Aprano on comp.lang.python.\n# Define two decorator factories.\ndef precall(pre):\n def decorator(f):\n def newf(*args, **kwargs):\n pre()\n return f(*args, **kwargs)\n return newf\n return decorator\n\ndef postcall(post):\n def decorator(f):\n def newf(*args, **kwargs):\n x = f(*args, **kwargs)\n post()\n return x\n return newf\n return decorator\n\nNow you can monkey patch class A if you want. It's probably not a great\nidea to do this in production code, as it will effect class A everywhere.\n[this is ok for my application, as it is basically a protocol converter and there's exactly one instance of each class being processed.]\nclass A:\n # in my real application, this is an imported class\n # that I cannot modify\n def p1(self): print 'A.p1'\n\nclass X:\n def __init__(self):\n self.a=A()\n A.p1 = precall(self.pre)(postcall(self.post)(A.p1))\n def pre(self): print 'X.pre'\n def post(self): print 'X.post'\n\n\nx=X()\nx.a.p1()\n\nGives the desired result.\nX.pre\nA.p1\nX.post\n\n" ]
[ 7, 1, 1, 1, 1, 0 ]
[]
[]
[ "metaprogramming", "python" ]
stackoverflow_0000258119_metaprogramming_python.txt
Q: Python filter/remove URLs from a list I have a text file of URLs, about 14000. Below is a couple of examples: http://www.domainname.com/pagename?CONTENT_ITEM_ID=100&param2=123 http://www.domainname.com/images?IMAGE_ID=10 http://www.domainname.com/pagename?CONTENT_ITEM_ID=101&param2=123 http://www.domainname.com/images?IMAGE_ID=11 http://www.domainname.com/pagename?CONTENT_ITEM_ID=102&param2=123 I have loaded the text file into a Python list and I am trying to get all the URLs with CONTENT_ITEM_ID separated off into a list of their own. What would be the best way to do this in Python? Cheers A: Here's another alternative to Graeme's, using the newer list comprehension syntax: list2= [line for line in file if 'CONTENT_ITEM_ID' in line] Which you prefer is a matter of taste! A: I liked @bobince's answer (+1), but will up the ante. Since you have a rather large starting set, you may wish to avoid loading the entire list into memory. Unless you need the whole list for something else, you could use a Python generator expression to perform the same task by building up the filtered list item by item as they're requested: for filtered_url in (line for line in file if 'CONTENT_ITEM_ID' in line): do_something_with_filtered_url(filtered_url) A: list2 = filter( lambda x: x.find( 'CONTENT_ITEM_ID ') != -1, list1 ) The filter calls the function (first parameter) on each element of list1 (second parameter). If the function returns true (non-zero), the element is copied to the output list. The lambda basically creates a temporary unnamed function. This is just to avoid having to create a function and then pass it, like this: function look_for_content_item_id( elem ): if elem.find( 'CONTENT_ITEM_ID') == -1: return 0 return 1 list2 = filter( look_for_content_item_id, list1 ) A: For completeness; You can also use ifilter. It is like filter, but doesn't build up a list. from itertools import ifilter for line in ifilter(lambda line: 'CONTENT_ITEM_ID' in line, urls): do_something(line)
Python filter/remove URLs from a list
I have a text file of URLs, about 14000. Below is a couple of examples: http://www.domainname.com/pagename?CONTENT_ITEM_ID=100&param2=123 http://www.domainname.com/images?IMAGE_ID=10 http://www.domainname.com/pagename?CONTENT_ITEM_ID=101&param2=123 http://www.domainname.com/images?IMAGE_ID=11 http://www.domainname.com/pagename?CONTENT_ITEM_ID=102&param2=123 I have loaded the text file into a Python list and I am trying to get all the URLs with CONTENT_ITEM_ID separated off into a list of their own. What would be the best way to do this in Python? Cheers
[ "Here's another alternative to Graeme's, using the newer list comprehension syntax:\nlist2= [line for line in file if 'CONTENT_ITEM_ID' in line]\n\nWhich you prefer is a matter of taste!\n", "I liked @bobince's answer (+1), but will up the ante.\nSince you have a rather large starting set, you may wish to avoid loading the entire list into memory. Unless you need the whole list for something else, you could use a Python generator expression to perform the same task by building up the filtered list item by item as they're requested:\nfor filtered_url in (line for line in file if 'CONTENT_ITEM_ID' in line):\n do_something_with_filtered_url(filtered_url)\n\n", "list2 = filter( lambda x: x.find( 'CONTENT_ITEM_ID ') != -1, list1 )\n\nThe filter calls the function (first parameter) on each element of list1 (second parameter). If the function returns true (non-zero), the element is copied to the output list.\nThe lambda basically creates a temporary unnamed function. This is just to avoid having to create a function and then pass it, like this:\nfunction look_for_content_item_id( elem ):\n if elem.find( 'CONTENT_ITEM_ID') == -1:\n return 0\n return 1\nlist2 = filter( look_for_content_item_id, list1 )\n\n", "For completeness; You can also use ifilter. It is like filter, but doesn't build up a list.\nfrom itertools import ifilter\n\nfor line in ifilter(lambda line: 'CONTENT_ITEM_ID' in line, urls):\n do_something(line)\n\n" ]
[ 21, 6, 5, 5 ]
[]
[]
[ "filter", "list", "python", "url" ]
stackoverflow_0000258390_filter_list_python_url.txt
Q: Why are Exceptions iterable? I have been bitten by something unexpected recently. I wanted to make something like that: try : thing.merge(iterable) # this is an iterable so I add it to the list except TypeError : thing.append(iterable) # this is not iterable, so I add it Well, It was working fine until I passed an object inheriting from Exception which was supposed to be added. Unfortunetly, an Exception is iterable. The following code does not raise any TypeError: for x in Exception() : print 1 Does anybody know why? A: Note that what is happening is not related to any kind of implicit string conversion etc, but because the Exception class implements ___getitem__ to return the values from the args tuple (ex.args). You can see this by the fact that you get the whole string as your first and only item in the iteration, rather than the character-by-character result you'd get if you iterate over the string. This surprised me too, but thinking about it, I'm guessing it is for backwards compatibility reasons. Python used to (pre-1.5) lack the current class hierarchy of exceptions. Instead, strings were thrown, with (usually) a tuple argument for any details that should be passed to the handling block, i.e: try: raise "something failed", (42, "some other details") except "something failed", args: errCode, msg = args print "something failed. error code %d: %s" % (errCode, msg) It looks like this behavior was put in to avoid breaking pre-1.5 code expecting a tuple of arguments, rather than a non-iterable exception object. There are a couple of examples of this with IOError in the Fatal Breakage section of the above link String exceptions have been deprecated for a while, and are gone in Python 3. Exception objects are no longer iterable in Python 3: >>> list(Exception("test")) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'Exception' object is not iterable A: NOT VALID. Check Brian anwser. Ok, I just got it : for x in Exception("test") : print x ....: ....: test Don't bother ;-) Anyway, it's good to know. EDIT : looking to the comments, I feel like adding some explanations. An exception contains a message you passed to during instantiation : raise Exception("test") Traceback (most recent call last): File "<stdin>", line 1, in <module> Exception: test It's fair to say that the message is what defines the Exception the best, so str() returns it : print Exception("test") test Now, it happens that Exceptions are implicitly converted to string when used in something else than an Exception context. So when I do : for x in Exception("test") : print x I am iterating over the string "test". And when I do : for x in Exception() : print x I do iterate over an empty string. Tricky. Because when it comes to my issue : try : thing.merge(ExceptionLikeObject) except TypeError : ... This won't raise anything since ExceptionLikeObject is considered as a string. Well now, we know the HOW, but I still not the WHY. Maybe the built-in Exception inherit from the built-in String ? Because as far as I know : adding str does not make any object iterable. I bypassed the problem by overloding iter, making it raising TypeError ! Not a problem anymore, but still a mystery.
Why are Exceptions iterable?
I have been bitten by something unexpected recently. I wanted to make something like that: try : thing.merge(iterable) # this is an iterable so I add it to the list except TypeError : thing.append(iterable) # this is not iterable, so I add it Well, It was working fine until I passed an object inheriting from Exception which was supposed to be added. Unfortunetly, an Exception is iterable. The following code does not raise any TypeError: for x in Exception() : print 1 Does anybody know why?
[ "Note that what is happening is not related to any kind of implicit string conversion etc, but because the Exception class implements ___getitem__ to return the values from the args tuple (ex.args). You can see this by the fact that you get the whole string as your first and only item in the iteration, rather than the character-by-character result you'd get if you iterate over the string.\nThis surprised me too, but thinking about it, I'm guessing it is for backwards compatibility reasons. Python used to (pre-1.5) lack the current class hierarchy of exceptions. Instead, strings were thrown, with (usually) a tuple argument for any details that should be passed to the handling block, i.e:\ntry:\n raise \"something failed\", (42, \"some other details\")\nexcept \"something failed\", args:\n errCode, msg = args\n print \"something failed. error code %d: %s\" % (errCode, msg)\n\nIt looks like this behavior was put in to avoid breaking pre-1.5 code expecting a tuple of arguments, rather than a non-iterable exception object. There are a couple of examples of this with IOError in the Fatal Breakage section of the above link\nString exceptions have been deprecated for a while, and are gone in Python 3. Exception objects are no longer iterable in Python 3:\n>>> list(Exception(\"test\"))\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: 'Exception' object is not iterable\n\n", "NOT VALID. Check Brian anwser.\nOk, I just got it :\nfor x in Exception(\"test\") :\n print x\n ....: \n ....: \ntest\n\nDon't bother ;-)\nAnyway, it's good to know.\nEDIT : looking to the comments, I feel like adding some explanations.\nAn exception contains a message you passed to during instantiation :\nraise Exception(\"test\") \n\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nException: test\n\nIt's fair to say that the message is what defines the Exception the best, so str() returns it :\nprint Exception(\"test\") \ntest\n\nNow, it happens that Exceptions are implicitly converted to string when used in something else than an Exception context.\nSo when I do :\nfor x in Exception(\"test\") :\n print x\n\nI am iterating over the string \"test\".\nAnd when I do : \nfor x in Exception() :\n print x\n\nI do iterate over an empty string. Tricky. Because when it comes to my issue :\ntry :\n thing.merge(ExceptionLikeObject)\nexcept TypeError :\n ...\n\nThis won't raise anything since ExceptionLikeObject is considered as a string.\nWell now, we know the HOW, but I still not the WHY. Maybe the built-in Exception inherit from the built-in String ? Because as far as I know :\n\nadding str does not make any object iterable.\nI bypassed the problem by overloding iter, making it raising TypeError !\n\nNot a problem anymore, but still a mystery.\n" ]
[ 13, 2 ]
[]
[]
[ "exception", "python" ]
stackoverflow_0000258228_exception_python.txt
Q: Django: Overriding verbose_name for AutoField without dropping the model I am using 0.97-pre-SVN-unknown release of Django. I have a model for which I have not given any primary_key. Django, consequently, automatically provides an AutoField that is called "id". Everything's fine with that. But now, I have to change the "verbose_name" of that AutoField to something other than "id". I cannot override the "id" field the usual way, because that would require dropping/resetting the entire model and its data (which is strictly not an option). I cannot find another way around it. Does what I want even possible to achieve? If you may suggest any alternatives that would get me away with what I want without having to drop the model/table, I'd be happy. A: Hmm... and what about explicitly write id field in the model definition? Like this for example: class Entry(models.Model): id = models.AutoField(verbose_name="custom name") # and other fields... It doesn't require any underlying database changes. A: Look into the command-line options for manage.py; there's a command to dump all of the model data to JSON, and another command to load it back in from JSON. You can export all of your model data, add your new field to the model, then import your data back in. Just make sure that you set the db_column option to 'id' so you don't break your existing data. Edit: Specifically, you want the commands dumpdata and loaddata.
Django: Overriding verbose_name for AutoField without dropping the model
I am using 0.97-pre-SVN-unknown release of Django. I have a model for which I have not given any primary_key. Django, consequently, automatically provides an AutoField that is called "id". Everything's fine with that. But now, I have to change the "verbose_name" of that AutoField to something other than "id". I cannot override the "id" field the usual way, because that would require dropping/resetting the entire model and its data (which is strictly not an option). I cannot find another way around it. Does what I want even possible to achieve? If you may suggest any alternatives that would get me away with what I want without having to drop the model/table, I'd be happy.
[ "Hmm... and what about explicitly write id field in the model definition? Like this for example:\nclass Entry(models.Model):\n id = models.AutoField(verbose_name=\"custom name\")\n # and other fields...\n\nIt doesn't require any underlying database changes.\n", "Look into the command-line options for manage.py; there's a command to dump all of the model data to JSON, and another command to load it back in from JSON. You can export all of your model data, add your new field to the model, then import your data back in. Just make sure that you set the db_column option to 'id' so you don't break your existing data.\nEdit: Specifically, you want the commands dumpdata and loaddata.\n" ]
[ 4, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000258767_django_python.txt
Q: python, functions running from a list and adding to a list through functions How do I run a function on a loop so all the results go straight into a list and is there a way to run a function which acts on all the values in a list? A: Theres a couple ways to run a function on a loop like that - You can either use a list comprehension test = list('asdf') [function(x) for x in test] and use that result Or you could use the map function test = list('asdf') map(function, test) The first answer is more "pythonic", while the second is more functional. EDIT: The second way is also a lot faster, as it's not running arbitrary code to call a function, but directly calling a function using map, which is implemented in C. A: Your question needs clarification. run a function on a loop new_list= [yourfunction(item) for item in a_sequence] run a function acting on all values in a list Your function should have some form of iteration in its code to process all items of a sequence, something like: def yourfunction(sequence): for item in sequence: … Then you just call it with a sequence (i.e. a list, a string, an iterator etc) yourfunction(range(10)) yourfunction("a string") YMMV. A: This example shows how to do it (run it in an interpreter) >>> def square(x): ... return x*x ... >>> a = [1,2,3,4,5,6,7,8,9] >>> map(square,a) [1, 4, 9, 16, 25, 36, 49, 64, 81]
python, functions running from a list and adding to a list through functions
How do I run a function on a loop so all the results go straight into a list and is there a way to run a function which acts on all the values in a list?
[ "Theres a couple ways to run a function on a loop like that - You can either use a list comprehension\ntest = list('asdf')\n[function(x) for x in test]\n\nand use that result\nOr you could use the map function\ntest = list('asdf')\nmap(function, test)\n\nThe first answer is more \"pythonic\", while the second is more functional. \nEDIT: The second way is also a lot faster, as it's not running arbitrary code to call a function, but directly calling a function using map, which is implemented in C.\n", "Your question needs clarification.\nrun a function on a loop\nnew_list= [yourfunction(item) for item in a_sequence]\n\nrun a function acting on all values in a list\nYour function should have some form of iteration in its code to process all items of a sequence, something like:\ndef yourfunction(sequence):\n for item in sequence:\n …\n\nThen you just call it with a sequence (i.e. a list, a string, an iterator etc)\nyourfunction(range(10))\nyourfunction(\"a string\")\n\nYMMV.\n", "This example shows how to do it (run it in an interpreter)\n>>> def square(x):\n... return x*x\n...\n>>> a = [1,2,3,4,5,6,7,8,9]\n\n>>> map(square,a)\n[1, 4, 9, 16, 25, 36, 49, 64, 81]\n\n" ]
[ 8, 1, 0 ]
[]
[]
[ "function", "list", "python" ]
stackoverflow_0000259234_function_list_python.txt
Q: Turning a GqlQuery result set into a python dictionary Let's say I have a model like this class Foo(db.Model): id = db.StringProperty() bar = db.StringProperty() baz = db.StringProperty() And I'm going a GqlQuery like this foos = db.GqlQuery("SELECT * FROM Foo") I want to take the results of the GqlQuery and turn into some sort of JSON string that I can manipulate from different languages. Here's how I'm doing it now Add a method to the Foo class that converts it into a dictionary def toDict(self): return { 'id': self.id, 'bar': self.bar, 'baz': self'baz } Loop through the GqlQuery results and manually add each Foo instance to a dictionary fooDict = {} for foo in foos: fooDict[foo.id] = foo.toDict() return simplejson.dumps(fooDict) My approach above works but it feels kind of gross. Is there a cleaner, more "Pythonic" way to handle this? The end format doesn't have to be exactly what I've done above. It just has to be something that converts nicely to JSON so I can deal with it from Javascript/PHP/whatever. A: Take a look at google.appengine.api.datastore. It's the lower level datastore API that google.appengine.ext.db builds on, and it returns Entity objects, which subclass dict. You can query it using GQL with google.appengine.ext.gql, or (my personal preference) use the Query class, which avoids the need for you to construct text strings for the GQL parser to parse. The Query class in api.datastore behaves exactly like the one documented here (but returns the lower level Entity objects instead of Model instances). As an example, your query above can be reformulated as "datastore.Query("Foo").all()". A: I can't do too much better than that, but here are a couple of ideas: class Foo: id = db.StringProperty() # etc. json_attrs = 'id bar baz'.split() # Depending on how easy it is to identify string properties, there # might also be a way to assign json_attrs programmatically after the # definition of Foo, like this Foo.json_attrs = [attr for attr in dir(Foo) if isStringProperty(getattr(Foo, attr))] fooDict=dict((foo.id,dict(getattr(foo, attr) for attr in Foo.json_attrs)) for foo in foos) A: http://code.google.com/p/google-app-engine-samples/source/browse/trunk/geochat/json.py?r=55 The encoder method will solve your GQL-to-JSON needs nicely. I'd recommend getting rid of some of the excessive datetime options....out time as an epoch? really?
Turning a GqlQuery result set into a python dictionary
Let's say I have a model like this class Foo(db.Model): id = db.StringProperty() bar = db.StringProperty() baz = db.StringProperty() And I'm going a GqlQuery like this foos = db.GqlQuery("SELECT * FROM Foo") I want to take the results of the GqlQuery and turn into some sort of JSON string that I can manipulate from different languages. Here's how I'm doing it now Add a method to the Foo class that converts it into a dictionary def toDict(self): return { 'id': self.id, 'bar': self.bar, 'baz': self'baz } Loop through the GqlQuery results and manually add each Foo instance to a dictionary fooDict = {} for foo in foos: fooDict[foo.id] = foo.toDict() return simplejson.dumps(fooDict) My approach above works but it feels kind of gross. Is there a cleaner, more "Pythonic" way to handle this? The end format doesn't have to be exactly what I've done above. It just has to be something that converts nicely to JSON so I can deal with it from Javascript/PHP/whatever.
[ "Take a look at google.appengine.api.datastore. It's the lower level datastore API that google.appengine.ext.db builds on, and it returns Entity objects, which subclass dict. You can query it using GQL with google.appengine.ext.gql, or (my personal preference) use the Query class, which avoids the need for you to construct text strings for the GQL parser to parse. The Query class in api.datastore behaves exactly like the one documented here (but returns the lower level Entity objects instead of Model instances).\nAs an example, your query above can be reformulated as \"datastore.Query(\"Foo\").all()\".\n", "I can't do too much better than that, but here are a couple of ideas:\nclass Foo:\n id = db.StringProperty() # etc.\n json_attrs = 'id bar baz'.split()\n\n# Depending on how easy it is to identify string properties, there\n# might also be a way to assign json_attrs programmatically after the\n# definition of Foo, like this\nFoo.json_attrs = [attr for attr in dir(Foo)\n if isStringProperty(getattr(Foo, attr))]\n\nfooDict=dict((foo.id,dict(getattr(foo, attr)\n for attr in Foo.json_attrs))\n for foo in foos)\n\n", "http://code.google.com/p/google-app-engine-samples/source/browse/trunk/geochat/json.py?r=55\nThe encoder method will solve your GQL-to-JSON needs nicely. I'd recommend getting rid of some of the excessive datetime options....out time as an epoch? really?\n" ]
[ 2, 1, 0 ]
[ "You can use web2py on GAE and do:\ndb.define_table('foo',SQLField('bar'),SQLField('baz'))\nrows=db(db.foo.id>0).select()\n### rows is a list, rows.response is a list of tuples\nfor row in rows: print dict(row)\n\nRuns on Oracle, Postgresql, Mssql, mysql, etc... too.\n" ]
[ -1 ]
[ "google_app_engine", "gqlquery", "python" ]
stackoverflow_0000212125_google_app_engine_gqlquery_python.txt
Q: exceptions.AttributeError : SMTP instance has no attribute 'login' : Hey I have a windows server running python CGI scripts and I'm having a little trouble with smtplib. The server is running python 2.1 (unfortunately and I can not upgrade it). Anyway I have the following code: session = smtplib.SMTP("smtp-auth.ourhosting.com", 587) session.login(smtpuser, smtppass) and it's giving me this error: exceptions.AttributeError : SMTP instance has no attribute 'login' : <traceback object at 006BB1D0> I'm assuming this is because the login() method was added after python 2.1. so how do I fix this? I have to either add the module by uploading the files to the same directory as the cgi script (though I believe smtplib is written in C and needs to be compiled which we can't do on this server) OR Do it whatever way is expected by the libsmtp in python 2.1. A: login() was introduced in Python 2.2, unluckily for you! The only way to do it in Python 2.1's own smtplib would be to issue the AUTH commands manually, which wouldn't be much fun. I haven't tested it fully but it seems Python 2.2's smtplib should more or less work on 2.1 if you copy it across as you describe (perhaps call it smtplib2.py). It's only a Python module, no C compilation should be necessary. However you will at least need to copy the hmac.py library it relies on from 2.2's lib as well. If you use a later Python version to steal from it starts requiring the email package too which might be more work. A: Do it whatever way is expected by the libsmtp in python 2.1
exceptions.AttributeError : SMTP instance has no attribute 'login' :
Hey I have a windows server running python CGI scripts and I'm having a little trouble with smtplib. The server is running python 2.1 (unfortunately and I can not upgrade it). Anyway I have the following code: session = smtplib.SMTP("smtp-auth.ourhosting.com", 587) session.login(smtpuser, smtppass) and it's giving me this error: exceptions.AttributeError : SMTP instance has no attribute 'login' : <traceback object at 006BB1D0> I'm assuming this is because the login() method was added after python 2.1. so how do I fix this? I have to either add the module by uploading the files to the same directory as the cgi script (though I believe smtplib is written in C and needs to be compiled which we can't do on this server) OR Do it whatever way is expected by the libsmtp in python 2.1.
[ "login() was introduced in Python 2.2, unluckily for you! The only way to do it in Python 2.1's own smtplib would be to issue the AUTH commands manually, which wouldn't be much fun.\nI haven't tested it fully but it seems Python 2.2's smtplib should more or less work on 2.1 if you copy it across as you describe (perhaps call it smtplib2.py). It's only a Python module, no C compilation should be necessary. However you will at least need to copy the hmac.py library it relies on from 2.2's lib as well. If you use a later Python version to steal from it starts requiring the email package too which might be more work.\n", "\nDo it whatever way is expected by the libsmtp in python 2.1\n\n" ]
[ 4, 0 ]
[]
[]
[ "python", "python_2.1", "smtp", "smtplib" ]
stackoverflow_0000259314_python_python_2.1_smtp_smtplib.txt
Q: How do I make Windows aware of a service I have written in Python? In another question I posted yesterday, I got very good advice on how a Python script could be run as a service in Windows. What I'm left wondering is: How is Windows aware of the services that can be managed in the native tools ("services" window in "administrative tools"). I. e. what is the Windows equivalent of putting a start/stop script in /etc/init.d under Linux? A: Don't muck with the registry directly. User the SC command-line tool. Namely, SC CREATE DESCRIPTION: SC is a command line program used for communicating with the NT Service Controller and services. USAGE: sc [command] [service name] ... The option has the form "\\ServerName" Further help on commands can be obtained by typing: "sc [command]" Commands: query-----------Queries the status for a service, or enumerates the status for types of services. queryex---------Queries the extended status for a service, or enumerates the status for types of services. start-----------Starts a service. pause-----------Sends a PAUSE control request to a service. interrogate-----Sends an INTERROGATE control request to a service. continue--------Sends a CONTINUE control request to a service. stop------------Sends a STOP request to a service. config----------Changes the configuration of a service (persistant). description-----Changes the description of a service. failure---------Changes the actions taken by a service upon failure. qc--------------Queries the configuration information for a service. qdescription----Queries the description for a service. qfailure--------Queries the actions taken by a service upon failure. delete----------Deletes a service (from the registry). create----------Creates a service. (adds it to the registry). control---------Sends a control to a service. sdshow----------Displays a service's security descriptor. sdset-----------Sets a service's security descriptor. GetDisplayName--Gets the DisplayName for a service. GetKeyName------Gets the ServiceKeyName for a service. EnumDepend------Enumerates Service Dependencies. The following commands don't require a service name: sc boot------------(ok | bad) Indicates whether the last boot should be saved as the last-known-good boot configuration Lock------------Locks the Service Database QueryLock-------Queries the LockStatus for the SCManager Database EXAMPLE: sc start MyService A: Here is code to install a python-script as a service, written in python :) http://code.activestate.com/recipes/551780/ This post could also help you out: http://essiene.blogspot.com/2005/04/python-windows-services.html A: As with most "aware" things in Windows, the answer is "Registry". Take a look at this Microsoft Knowledge Base article: http://support.microsoft.com/kb/103000 Search for "A Win32 program that can be started by the Service Controller and that obeys the service control protocol." This is the kind of service you're interested in. The service registration (contents of KEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services \myservice) carries information about the service, including things like its executable location, what to do when it fails (halt the OS?), what services must be started before this one, what user it runs as. As to service control protocol, main() of your program is supposed to invoke a Windows API call, setting up callbacks for start, stop, pause for your service. What you do in those callbacks is all up to you. A: You can use srvany.exe from Windows NT Resource Kit to create a user defined service that will show up in the admin tools... http://support.microsoft.com/kb/137890 I am using this method to run tracd (a python script / server) for trac. Here are some very clear instructions: http://www.tacktech.com/display.cfm?ttid=197 It does require some registry editing (very minimal and easy) but will allow you to make any command line / script a windows service.
How do I make Windows aware of a service I have written in Python?
In another question I posted yesterday, I got very good advice on how a Python script could be run as a service in Windows. What I'm left wondering is: How is Windows aware of the services that can be managed in the native tools ("services" window in "administrative tools"). I. e. what is the Windows equivalent of putting a start/stop script in /etc/init.d under Linux?
[ "Don't muck with the registry directly. User the SC command-line tool. Namely, SC CREATE\n\n DESCRIPTION:\n SC is a command line program used for communicating with the\n NT Service Controller and services.\n USAGE:\n sc [command] [service name] ...\n\n The option has the form \"\\\\ServerName\"\n Further help on commands can be obtained by typing: \"sc [command]\"\n Commands:\n query-----------Queries the status for a service, or\n enumerates the status for types of services.\n queryex---------Queries the extended status for a service, or\n enumerates the status for types of services.\n start-----------Starts a service.\n pause-----------Sends a PAUSE control request to a service.\n interrogate-----Sends an INTERROGATE control request to a service.\n continue--------Sends a CONTINUE control request to a service.\n stop------------Sends a STOP request to a service.\n config----------Changes the configuration of a service (persistant).\n description-----Changes the description of a service.\n failure---------Changes the actions taken by a service upon failure.\n qc--------------Queries the configuration information for a service.\n qdescription----Queries the description for a service.\n qfailure--------Queries the actions taken by a service upon failure.\n delete----------Deletes a service (from the registry).\n create----------Creates a service. (adds it to the registry).\n control---------Sends a control to a service.\n sdshow----------Displays a service's security descriptor.\n sdset-----------Sets a service's security descriptor.\n GetDisplayName--Gets the DisplayName for a service.\n GetKeyName------Gets the ServiceKeyName for a service.\n EnumDepend------Enumerates Service Dependencies.\n\n The following commands don't require a service name:\n sc \n boot------------(ok | bad) Indicates whether the last boot should\n be saved as the last-known-good boot configuration\n Lock------------Locks the Service Database\n QueryLock-------Queries the LockStatus for the SCManager Database\n EXAMPLE:\n sc start MyService\n\n", "Here is code to install a python-script as a service, written in python :)\nhttp://code.activestate.com/recipes/551780/\nThis post could also help you out:\nhttp://essiene.blogspot.com/2005/04/python-windows-services.html\n", "As with most \"aware\" things in Windows, the answer is \"Registry\".\nTake a look at this Microsoft Knowledge Base article: http://support.microsoft.com/kb/103000\nSearch for \"A Win32 program that can be started by the Service Controller and that obeys the service control protocol.\" This is the kind of service you're interested in.\nThe service registration (contents of KEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\n\\myservice) carries information about the service, including things like its executable location, what to do when it fails (halt the OS?), what services must be started before this one, what user it runs as.\nAs to service control protocol, main() of your program is supposed to invoke a Windows API call, setting up callbacks for start, stop, pause for your service. What you do in those callbacks is all up to you.\n", "You can use srvany.exe from Windows NT Resource Kit to create a user defined service that will show up in the admin tools...\nhttp://support.microsoft.com/kb/137890\nI am using this method to run tracd (a python script / server) for trac. \nHere are some very clear instructions: http://www.tacktech.com/display.cfm?ttid=197\nIt does require some registry editing (very minimal and easy) but will allow you to make any command line / script a windows service. \n" ]
[ 8, 7, 3, 0 ]
[]
[]
[ "cross_platform", "python", "windows" ]
stackoverflow_0000034328_cross_platform_python_windows.txt
Q: Is it safe to make an old-style class into a new-style class using Multiple Inheritance? In a program that I'm writing, I wanted to make a ConfigParser that's read only so that it can safely be used globally. I didn't realize this, but apparently the SafeConfigParser is an old-style class, thus I had to subclass it like this: class ConstParser(SafeConfigParser, object): """This is a implementation of the SafeConfigParser that can't write any values. This is to ensure that it can only be filled once and won't get messy with multiple modules writing to it.""" def __init__(self, files, defaults={}): super(ConstParser, self).__init__(defaults) self.read(files) def set(self, *args, **argd): raise NotImplementedError() def write(self, *args, **argd): raise NotImplementedError() def remove_option(self, *args, **argd): raise NotImplementedError() def remove_section(self, *args, **argd): raise NotImplementedError() If I didn't use object as a mixin, the call to SafeConfigParser's __init__ method didn't work. Now, I'm sure that there are better ways to do what I want to do, but now I'm curious: is this ok to do in general? I mean, I can't think of any reason why this would be a bad thing, but it still gives me bad feelings. Are they justified, or am I just being paranoid? A: Replace the call: super(ConstParser, self).__init__(defaults) with: SafeConfigParser.__init__(self, defaults) and it works just fine without multiple Inheritance.
Is it safe to make an old-style class into a new-style class using Multiple Inheritance?
In a program that I'm writing, I wanted to make a ConfigParser that's read only so that it can safely be used globally. I didn't realize this, but apparently the SafeConfigParser is an old-style class, thus I had to subclass it like this: class ConstParser(SafeConfigParser, object): """This is a implementation of the SafeConfigParser that can't write any values. This is to ensure that it can only be filled once and won't get messy with multiple modules writing to it.""" def __init__(self, files, defaults={}): super(ConstParser, self).__init__(defaults) self.read(files) def set(self, *args, **argd): raise NotImplementedError() def write(self, *args, **argd): raise NotImplementedError() def remove_option(self, *args, **argd): raise NotImplementedError() def remove_section(self, *args, **argd): raise NotImplementedError() If I didn't use object as a mixin, the call to SafeConfigParser's __init__ method didn't work. Now, I'm sure that there are better ways to do what I want to do, but now I'm curious: is this ok to do in general? I mean, I can't think of any reason why this would be a bad thing, but it still gives me bad feelings. Are they justified, or am I just being paranoid?
[ "Replace the call:\nsuper(ConstParser, self).__init__(defaults)\n\nwith:\nSafeConfigParser.__init__(self, defaults)\n\nand it works just fine without multiple Inheritance.\n" ]
[ 2 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0000259578_oop_python.txt
Q: Does Python 2.5 include a package to natively transform an XML document? In my Python app, I have an XML document that I'd like to transform using my XSL file. I'm currently using xml.etree to generate the XML document, but I haven't found anything within Python 2.5 that will allow me to natively transform my XML document. I've already found one library (libxslt) which can execute the transformation, but I figured Python would have a native library that achieves the desired result. Any thoughts? A: If you have libxml2 and libxslt installed, then also install lxml. It provides a nice, easy-to-use binding for libxml2 and libxslt, and it also implements the ElementTree API. libxml2/libxslt also come with their own, much lower-level Python bindings, but lxml is much more straightforward and pythonic, and it seems to have great performance as well. A: There is no XSLT processor in Python 2.5.
Does Python 2.5 include a package to natively transform an XML document?
In my Python app, I have an XML document that I'd like to transform using my XSL file. I'm currently using xml.etree to generate the XML document, but I haven't found anything within Python 2.5 that will allow me to natively transform my XML document. I've already found one library (libxslt) which can execute the transformation, but I figured Python would have a native library that achieves the desired result. Any thoughts?
[ "If you have libxml2 and libxslt installed, then also install lxml. It provides a nice, easy-to-use binding for libxml2 and libxslt, and it also implements the ElementTree API.\nlibxml2/libxslt also come with their own, much lower-level Python bindings, but lxml is much more straightforward and pythonic, and it seems to have great performance as well.\n", "There is no XSLT processor in Python 2.5.\n" ]
[ 5, 4 ]
[]
[]
[ "elementtree", "python", "xml", "xslt" ]
stackoverflow_0000259782_elementtree_python_xml_xslt.txt
Q: How can I make a fake "active session" for gconf? I've automated my Ubuntu installation - I've got Python code that runs automatically (after a clean install, but before the first user login - it's in a temporary /etc/init.d/ script) that sets up everything from Apache & its configuration to my personal Gnome preferences. It's the latter that's giving me trouble. This worked fine in Ubuntu 8.04 (Hardy), but when I use this with 8.10 (Intrepid), the first time I try to access gconf, I get this exception: Failed to contact configuration server; some possible causes are that you need to enable TCP/IP networking for ORBit, or you have stale NFS locks due to a system crash. See http://www.gnome.org/projects/gconf/ for information. (Details - 1: Not running within active session) Yes, right, there's no Gnome session when this is running, because the user hasn't logged in yet - however, this worked before; this appears to be new with Intrepid's Gnome (2.24?). Short of modifying the gconf's XML files directly, is there a way to make some sort of proxy Gnome session? Or, any other suggestions? (More details: this is python code that runs as root, but setuid's & setgid's to be me before setting my preferences using the "gconf" module from the python-gconf package.) A: I can reproduce this by installing GConf 2.24 on my machine. GConf 2.22 works fine, but 2.24 breaks it. GConf is failing to launch because D-Bus is not running. Manually spawning D-Bus and the GConf daemon makes this work again. I tried to spawn the D-Bus session bus by doing the following: import dbus dummy_bus = dbus.SessionBus() ...but got this: dbus.exceptions.DBusException: org.freedesktop.DBus.Error.Spawn.ExecFailed: dbus-launch failed to autolaunch D-Bus session: Autolaunch error: X11 initialization failed. Weird. Looks like it doesn't like to come up if X isn't running. To work around that, start dbus-launch manually (IIRC use the os.system() call): $ dbus-launch DBUS_SESSION_BUS_ADDRESS=unix:abstract=/tmp/dbus-eAmT3q94u0,guid=c250f62d3c4739dcc9a12d48490fc268 DBUS_SESSION_BUS_PID=15836 You'll need to parse the output somehow and inject them into environment variables (you'll probably want to use os.putenv). For my testing, I just used the shell, and set the environment vars manually with export DBUS_SESSION_BUS_ADDRESS=blahblah..., etc. Next, you need to launch gconftool-2 --spawn with those environment variables you received from dbus-launch. This will launch the GConf daemon. If the D-Bus environment vars are not set, the daemon will not launch. Then, run your GConf code. Provided you set the D-Bus session bus environment variables for your own script, you will now be able to communicate with the GConf daemon. I know it's complicated. gconftool-2 provides a --direct option that enables you to set GConf variables without needing to communicate with the server, but I haven't been able to find an equivalent option for the Python bindings (short of outputting XML manually). Edit: For future reference, if anybody wants to run dbus-launch from within a normal bash script (as opposed to a Python script, as this thread is discussing), it is quite easy to retrieve the session bus address for use within the script: #!/bin/bash eval `dbus-launch --sh-syntax` export DBUS_SESSION_BUS_ADDRESS export DBUS_SESSION_BUS_PID do_other_stuff_here A: Well, I think I understand the question. Looks like your script just needs to start the dbus daemon, or make sure its started. I believe "session" here refers to a dbus session. (here is some evidence), not a Gnome session. Dbus and gconf both run fine without Gnome. Either way, faking an "active session" sounds like a pretty bad idea. It would only look for it if it needed it. Perhaps we could see the script in a pastebin? I should have really seen it before making any comment. A: Thanks, Ali & Jeremy - both your answers were a big help. I'm still working on this (though I've stopped for the evening). First, I took the hint from Ali and was trying part of Jeremy's suggestion: I was using dbus-launch to run "gconftool-2 --spawn". It didn't work for me; I now understand why (thx, Jeremy) -- I was trying to use gconf from within the same python program that was launching dbus & gconftool, but its environment didn't have the environment variables - duh. I set that strategy aside when I noticed gconftool-2's --direct option; internally, gconftool-2 is using API that isn't exposed by the gconf python bindings. So, I modified python-gconf to expose the extra method, and once that builds (I had some unrelated problems getting this to work), we'll see if that fixes things - if it doesn't (and maybe if it does, because building those bindings seems to build all of gnome!), I'll find a better way to manage the environment variables in that first strategy. (I'll add another answer here tomorrow either way) And it's the next day: I ran into a little trouble with my modified python-gconf, which inspired me to try Jeremy's simpler idea, which worked fine - before doing the first gconf operation, I simply ran "dbus-launch", parsed the resulting name-value pairs, and added them directly to python's environment. Having done that, I ran "gconftool-2 --spawn". Problem solved.
How can I make a fake "active session" for gconf?
I've automated my Ubuntu installation - I've got Python code that runs automatically (after a clean install, but before the first user login - it's in a temporary /etc/init.d/ script) that sets up everything from Apache & its configuration to my personal Gnome preferences. It's the latter that's giving me trouble. This worked fine in Ubuntu 8.04 (Hardy), but when I use this with 8.10 (Intrepid), the first time I try to access gconf, I get this exception: Failed to contact configuration server; some possible causes are that you need to enable TCP/IP networking for ORBit, or you have stale NFS locks due to a system crash. See http://www.gnome.org/projects/gconf/ for information. (Details - 1: Not running within active session) Yes, right, there's no Gnome session when this is running, because the user hasn't logged in yet - however, this worked before; this appears to be new with Intrepid's Gnome (2.24?). Short of modifying the gconf's XML files directly, is there a way to make some sort of proxy Gnome session? Or, any other suggestions? (More details: this is python code that runs as root, but setuid's & setgid's to be me before setting my preferences using the "gconf" module from the python-gconf package.)
[ "I can reproduce this by installing GConf 2.24 on my machine. GConf 2.22 works fine, but 2.24 breaks it.\nGConf is failing to launch because D-Bus is not running. Manually spawning D-Bus and the GConf daemon makes this work again.\nI tried to spawn the D-Bus session bus by doing the following:\nimport dbus\ndummy_bus = dbus.SessionBus()\n\n...but got this:\ndbus.exceptions.DBusException: org.freedesktop.DBus.Error.Spawn.ExecFailed: dbus-launch failed to autolaunch D-Bus session: Autolaunch error: X11 initialization failed.\n\nWeird. Looks like it doesn't like to come up if X isn't running. To work around that, start dbus-launch manually (IIRC use the os.system() call):\n$ dbus-launch \nDBUS_SESSION_BUS_ADDRESS=unix:abstract=/tmp/dbus-eAmT3q94u0,guid=c250f62d3c4739dcc9a12d48490fc268\nDBUS_SESSION_BUS_PID=15836\n\nYou'll need to parse the output somehow and inject them into environment variables (you'll probably want to use os.putenv). For my testing, I just used the shell, and set the environment vars manually with export DBUS_SESSION_BUS_ADDRESS=blahblah..., etc.\nNext, you need to launch gconftool-2 --spawn with those environment variables you received from dbus-launch. This will launch the GConf daemon. If the D-Bus environment vars are not set, the daemon will not launch.\nThen, run your GConf code. Provided you set the D-Bus session bus environment variables for your own script, you will now be able to communicate with the GConf daemon.\nI know it's complicated.\ngconftool-2 provides a --direct option that enables you to set GConf variables without needing to communicate with the server, but I haven't been able to find an equivalent option for the Python bindings (short of outputting XML manually).\nEdit: For future reference, if anybody wants to run dbus-launch from within a normal bash script (as opposed to a Python script, as this thread is discussing), it is quite easy to retrieve the session bus address for use within the script:\n#!/bin/bash\n\neval `dbus-launch --sh-syntax`\n\nexport DBUS_SESSION_BUS_ADDRESS\nexport DBUS_SESSION_BUS_PID\n\ndo_other_stuff_here\n\n", "Well, I think I understand the question. Looks like your script just needs to start the dbus daemon, or make sure its started. I believe \"session\" here refers to a dbus session. (here is some evidence), not a Gnome session. Dbus and gconf both run fine without Gnome.\nEither way, faking an \"active session\" sounds like a pretty bad idea. It would only look for it if it needed it.\nPerhaps we could see the script in a pastebin? I should have really seen it before making any comment.\n", "Thanks, Ali & Jeremy - both your answers were a big help. I'm still working on this (though I've stopped for the evening).\nFirst, I took the hint from Ali and was trying part of Jeremy's suggestion: I was using dbus-launch to run \"gconftool-2 --spawn\". It didn't work for me; I now understand why (thx, Jeremy) -- I was trying to use gconf from within the same python program that was launching dbus & gconftool, but its environment didn't have the environment variables - duh.\nI set that strategy aside when I noticed gconftool-2's --direct option; internally, gconftool-2 is using API that isn't exposed by the gconf python bindings. So, I modified python-gconf to expose the extra method, and once that builds (I had some unrelated problems getting this to work), we'll see if that fixes things - if it doesn't (and maybe if it does, because building those bindings seems to build all of gnome!), I'll find a better way to manage the environment variables in that first strategy.\n(I'll add another answer here tomorrow either way)\nAnd it's the next day: I ran into a little trouble with my modified python-gconf, which inspired me to try Jeremy's simpler idea, which worked fine - before doing the first gconf operation, I simply ran \"dbus-launch\", parsed the resulting name-value pairs, and added them directly to python's environment. Having done that, I ran \"gconftool-2 --spawn\". Problem solved.\n" ]
[ 8, 1, 1 ]
[]
[]
[ "gconf", "python", "ubuntu", "ubuntu_8.10" ]
stackoverflow_0000257658_gconf_python_ubuntu_ubuntu_8.10.txt
Q: What is the simplest way to find the difference between 2 times in python? I have 2 time values which have the type datetime.time. I want to find their difference. The obvious thing to do is t1 - t2, but this doesn't work. It works for objects of type datetime.datetime but not for datetime.time. So what is the best way to do this? A: Also a little silly, but you could try picking an arbitrary day and embedding each time in it, using datetime.datetime.combine, then subtracting: >>> import datetime >>> t1 = datetime.time(2,3,4) >>> t2 = datetime.time(18,20,59) >>> dummydate = datetime.date(2000,1,1) >>> datetime.datetime.combine(dummydate,t2) - datetime.datetime.combine(dummydate,t1) datetime.timedelta(0, 58675) A: You could transform both into timedelta objects and subtract these from each other, which will take care to of the carry-overs. For example: >>> import datetime as dt >>> t1 = dt.time(23, 5, 5, 5) >>> t2 = dt.time(10, 5, 5, 5) >>> dt1 = dt.timedelta(hours=t1.hour, minutes=t1.minute, seconds=t1.second, microseconds=t1.microsecond) >>> dt2 = dt.timedelta(hours=t2.hour, minutes=t2.minute, seconds=t2.second, microseconds=t2.microsecond) >>> print(dt1-dt2) 13:00:00 >>> print(dt2-dt1) -1 day, 11:00:00 >>> print(abs(dt2-dt1)) 13:00:00 Negative timedelta objects in Python get a negative day field, with the other fields positive. You could check beforehand: comparison works on both time objects and timedelta objects: >>> dt2 < dt1 True >>> t2 < t1 True A: Python has pytz (http://pytz.sourceforge.net) module which can be used for arithmetic of 'time' objects. It takes care of DST offsets as well. The above page has a number of examples that illustrate the usage of pytz. A: It seems that this isn't supported, since there wouldn't be a good way to deal with overflows in datetime.time. I know this isn't an answer directly, but maybe someone with more python experience than me can take this a little further. For more info, see this: http://bugs.python.org/issue3250 A: Firstly, note that a datetime.time is a time of day, independent of a given day, and so the different between any two datetime.time values is going to be less than 24 hours. One approach is to convert both datetime.time values into comparable values (such as milliseconds), and find the difference. t1, t2 = datetime.time(...), datetime.time(...) t1_ms = (t1.hour*60*60 + t1.minute*60 + t1.second)*1000 + t1.microsecond t2_ms = (t2.hour*60*60 + t2.minute*60 + t2.second)*1000 + t2.microsecond delta_ms = max([t1_ms, t2_ms]) - min([t1_ms, t2_ms]) It's a little lame, but it works.
What is the simplest way to find the difference between 2 times in python?
I have 2 time values which have the type datetime.time. I want to find their difference. The obvious thing to do is t1 - t2, but this doesn't work. It works for objects of type datetime.datetime but not for datetime.time. So what is the best way to do this?
[ "Also a little silly, but you could try picking an arbitrary day and embedding each time in it, using datetime.datetime.combine, then subtracting:\n>>> import datetime\n>>> t1 = datetime.time(2,3,4)\n>>> t2 = datetime.time(18,20,59)\n>>> dummydate = datetime.date(2000,1,1)\n>>> datetime.datetime.combine(dummydate,t2) - datetime.datetime.combine(dummydate,t1)\ndatetime.timedelta(0, 58675)\n\n", "You could transform both into timedelta objects and subtract these from each other, which will take care to of the carry-overs. For example:\n>>> import datetime as dt\n>>> t1 = dt.time(23, 5, 5, 5)\n>>> t2 = dt.time(10, 5, 5, 5)\n>>> dt1 = dt.timedelta(hours=t1.hour, minutes=t1.minute, seconds=t1.second, microseconds=t1.microsecond)\n>>> dt2 = dt.timedelta(hours=t2.hour, minutes=t2.minute, seconds=t2.second, microseconds=t2.microsecond)\n>>> print(dt1-dt2)\n13:00:00\n>>> print(dt2-dt1)\n-1 day, 11:00:00\n>>> print(abs(dt2-dt1))\n13:00:00\n\nNegative timedelta objects in Python get a negative day field, with the other fields positive. You could check beforehand: comparison works on both time objects and timedelta objects:\n>>> dt2 < dt1\nTrue\n>>> t2 < t1\nTrue\n\n", "Python has pytz (http://pytz.sourceforge.net) module which can be used for arithmetic of 'time' objects. It takes care of DST offsets as well. The above page has a number of examples that illustrate the usage of pytz.\n", "It seems that this isn't supported, since there wouldn't be a good way to deal with overflows in datetime.time. I know this isn't an answer directly, but maybe someone with more python experience than me can take this a little further. For more info, see this: http://bugs.python.org/issue3250\n", "Firstly, note that a datetime.time is a time of day, independent of a given day, and so the different between any two datetime.time values is going to be less than 24 hours.\nOne approach is to convert both datetime.time values into comparable values (such as milliseconds), and find the difference.\nt1, t2 = datetime.time(...), datetime.time(...)\n\nt1_ms = (t1.hour*60*60 + t1.minute*60 + t1.second)*1000 + t1.microsecond\nt2_ms = (t2.hour*60*60 + t2.minute*60 + t2.second)*1000 + t2.microsecond\n\ndelta_ms = max([t1_ms, t2_ms]) - min([t1_ms, t2_ms])\n\nIt's a little lame, but it works.\n" ]
[ 16, 7, 3, 1, -1 ]
[ "Retrieve the times in milliseconds and then do the subtraction.\n", "Environment.TickCount seems to work well if you need something quick.\nint start = Environment.TickCount\n...DoSomething()\nint elapsedtime = Environment.TickCount - start\nJon\n" ]
[ -1, -3 ]
[ "datetime", "python", "time" ]
stackoverflow_0000051010_datetime_python_time.txt
Q: launching VS2008 build from python if I paste this into the command prompt by hand, it works, but if I run it from python, I get The filename, directgory name, or volume label syntax is incorrect. os.system('%comspec% /k ""C:\Program Files\Microsoft Visual Studio 9.0\VC\vcvarsall.bat"" x86') os.system('devenv Immersica.sln /rebuild Debug /Out last-build.txt') A: I think the backslashes are messing you up. You need to use an R string (raw) r"string" See https://docs.python.org/2/reference/lexical_analysis.html#string-literals for reference
launching VS2008 build from python
if I paste this into the command prompt by hand, it works, but if I run it from python, I get The filename, directgory name, or volume label syntax is incorrect. os.system('%comspec% /k ""C:\Program Files\Microsoft Visual Studio 9.0\VC\vcvarsall.bat"" x86') os.system('devenv Immersica.sln /rebuild Debug /Out last-build.txt')
[ "I think the backslashes are messing you up. You need to use an R string (raw)\nr\"string\"\nSee https://docs.python.org/2/reference/lexical_analysis.html#string-literals for reference\n" ]
[ 1 ]
[]
[]
[ "build_automation", "python", "visual_studio_2008", "windows" ]
stackoverflow_0000263690_build_automation_python_visual_studio_2008_windows.txt
Q: How can I ask for root password but perform the action at a later time? I have a python script that I would like to add a "Shutdown when done" feature to. I know I can use gksudo (when the user clicks on "shutdown when done") to ask the user for root privileges but how can I use those privileges at a later time (when the script is actually finished). I have thought about chmod u+s on the shutdown command so I don't need a password but I really don't want to do that. Any ideas how I can achieve this? Thanks in advance, Ashy. A: Instead of chmod u+sing the shutdown command, allowing passwordless sudo access to that command would be better.. As for allowing shutdown at the end of the script, I suppose you could run the entire script with sudo, then drop privileges to the initial user at the start of the script? A: gksudo should have a timeout, I believe it's from the time you last executed a gksudo command. So I think I'd just throw out a "gksudo echo meh" or something every minute. Should reset the timer and keep you active until you reboot. A: Escalate priority, spawn (fork (2)) a separate process that will wait (2), and drop priority in the main process.
How can I ask for root password but perform the action at a later time?
I have a python script that I would like to add a "Shutdown when done" feature to. I know I can use gksudo (when the user clicks on "shutdown when done") to ask the user for root privileges but how can I use those privileges at a later time (when the script is actually finished). I have thought about chmod u+s on the shutdown command so I don't need a password but I really don't want to do that. Any ideas how I can achieve this? Thanks in advance, Ashy.
[ "Instead of chmod u+sing the shutdown command, allowing passwordless sudo access to that command would be better..\nAs for allowing shutdown at the end of the script, I suppose you could run the entire script with sudo, then drop privileges to the initial user at the start of the script?\n", "gksudo should have a timeout, I believe it's from the time you last executed a gksudo command.\nSo I think I'd just throw out a \"gksudo echo meh\" or something every minute. Should reset the timer and keep you active until you reboot.\n", "Escalate priority, spawn (fork (2)) a separate process that will wait (2), and drop priority in the main process.\n" ]
[ 4, 3, 1 ]
[]
[]
[ "linux", "python", "ubuntu" ]
stackoverflow_0000263773_linux_python_ubuntu.txt
Q: We have a graphical designer, now they want a text based designer. Suggestions? I'm sorry I could not think of a better title. The problem is the following: For our customer we have created (as part of a larger application) a graphical designer which they can use to build "scenario's". These scenario's consist of "Composites" which in turn consist of "Commands". These command objects all derive from CommandBase and implement an interface called ICompilable. The scenario class also implements ICompilable. When Compile() is called on a command an array of bytes is returned which can then be send to the device for which they are intended (can't disclose to much info about that hardware, sorry) Just to give you an idea: var scenario = new Scenario(); scenario.Add(new DelayCommand(1)); scenario.Add(new CountWithValueCommand(1,ActionEnum.Add,1)); scenario.Add(new DirectPowerCommand(23,false,150)); scenario.Add(new WaitCommand(3)); scenario.Add(new DirectPowerCommand(23,false,150)); scenario.Add(new SkipIfCommand(1,OperatorEnum.SmallerThan,10)); scenario.Add(new JumpCommand(2)); byte[] compiledData = scenario.Compile(); The graphical designer abstracts all this from the user and allows him (or her) to simply drag en drop composites onto the designer surface. (Composites can group commands so we can provide building blocks for returning tasks) Recently our customer came to us and said, "well the designer is really cool, but we have some people who would rather have some kind of programming language, just something simple." (Simple to them of course) I would very much like to provide them with a simple language, that can call various commmands and also replace SkipIfCommand with a nicer structure, etc... I have no idea where to start or what my options are (without breaking what we have) I have heard about people embedding languages such as Python, people writing their own language an parsers, etc... Any suggestions? PS: Users only work with composites, never with commands. Composites are loaded dynamically at runtime (along with their graphical designer) and may be provided by third parties in seperate assemblies. A: From what i think i've understood you have two options you could either use an XML style "markup" to let them define entities and their groupings, but that may not be best. Your alternatives are yes, yoou could embedd a language, but do you really need to, wouldnt that be overkill, and how can you control it? If you only need really simple syntax then perhaps write your own language. Its actually not that hard to create a simple interpreter, as long as you have a strict, unambiguous language. Have a look for some examples of compilers in whatever youre using, c#? I wrote a very simple interperter in java at uni, it wasnt as hard as you'd think. A: This looks like a perfect scenario for a simple DSL. See http://msdn.microsoft.com/en-us/library/bb126235(VS.80).aspx for some information. You could also use a scripting language such as lua.Net. A: If you really just want a dirt simple language, you want a 'recursive descent parser'. For example, a language like this: SCENARIO MyScenario DELAY 1 COUNT 1 ADD 1 DIRECT_POWER 23, False, 150 WAIT 3 ... END_SCENARIO You might have a grammar like: scenario :: 'SCENARIO' label newline _cmds END_SCENARIO cmds:: _delay or _count or _direct_power or... delay:: 'DELAY' number Which gives code like: def scenario(): match_word('SCENARIO') scenario_name = match_label() emit('var scenario = new Scenario();') cmds() match_word('END_SCENARIO') emit('byte[] ' + scenario_name + ' = scenario.Compile();') def delay(): match_word('DELAY') length = match_number() emit('scenario.Add(new DelayCommand('+ length +'))') def cmds(): word = peek_next_word() if word == 'DELAY': delay() elif ... A: Here's a Pythonic solution for building a DSL that you can use to compile and create byte code arrays. Write a simple module that makes your C# structures available to Python. The goal is to define each C# class that users are allowed to work with (Composites or Commands or whatever) as a Python class. Usually, this involves implementing a minimal set of methods with different conversions from C# types to native Python types and vice versa. Write some nice demos showing how to use these Python class definitions to create their scripts. You should be able to create things like this in Python. import * from someInterfaceModule scenario= Scenario( Delay(1), Repeat( Range(10), DirectPower( 23, False, 150), Wait(3), DirectPower( 23, False, 150) ) ) scenario.compile() These are relatively simple classes to define. Each class here be reasonably easy to implement as Python modules that directly call your base C# modules. The syntax is pure Python with no additional parsing or lexical scanning required. A: To add to S.Lott's comment, here's how you eval a Python script from C# A: While it might be great fun to create this mini-language and code it all up, the real questions you need to ask are: What is the business case for adding this feature / facility? Who is going to pay for this feature? Who is going to "sign off" on this feature if you build it? "Really neat" features have a way of getting built when the reality might indicate the true answer to such a request is "no". See if you have a stakeholder willing to sponsor this before proceeding. Then check with the end users to see what they really want before committing to the project. Cheers, -R
We have a graphical designer, now they want a text based designer. Suggestions?
I'm sorry I could not think of a better title. The problem is the following: For our customer we have created (as part of a larger application) a graphical designer which they can use to build "scenario's". These scenario's consist of "Composites" which in turn consist of "Commands". These command objects all derive from CommandBase and implement an interface called ICompilable. The scenario class also implements ICompilable. When Compile() is called on a command an array of bytes is returned which can then be send to the device for which they are intended (can't disclose to much info about that hardware, sorry) Just to give you an idea: var scenario = new Scenario(); scenario.Add(new DelayCommand(1)); scenario.Add(new CountWithValueCommand(1,ActionEnum.Add,1)); scenario.Add(new DirectPowerCommand(23,false,150)); scenario.Add(new WaitCommand(3)); scenario.Add(new DirectPowerCommand(23,false,150)); scenario.Add(new SkipIfCommand(1,OperatorEnum.SmallerThan,10)); scenario.Add(new JumpCommand(2)); byte[] compiledData = scenario.Compile(); The graphical designer abstracts all this from the user and allows him (or her) to simply drag en drop composites onto the designer surface. (Composites can group commands so we can provide building blocks for returning tasks) Recently our customer came to us and said, "well the designer is really cool, but we have some people who would rather have some kind of programming language, just something simple." (Simple to them of course) I would very much like to provide them with a simple language, that can call various commmands and also replace SkipIfCommand with a nicer structure, etc... I have no idea where to start or what my options are (without breaking what we have) I have heard about people embedding languages such as Python, people writing their own language an parsers, etc... Any suggestions? PS: Users only work with composites, never with commands. Composites are loaded dynamically at runtime (along with their graphical designer) and may be provided by third parties in seperate assemblies.
[ "From what i think i've understood you have two options\nyou could either use an XML style \"markup\" to let them define entities and their groupings, but that may not be best.\nYour alternatives are yes, yoou could embedd a language, but do you really need to, wouldnt that be overkill, and how can you control it?\nIf you only need really simple syntax then perhaps write your own language. Its actually not that hard to create a simple interpreter, as long as you have a strict, unambiguous language. Have a look for some examples of compilers in whatever youre using, c#?\nI wrote a very simple interperter in java at uni, it wasnt as hard as you'd think.\n", "This looks like a perfect scenario for a simple DSL. See http://msdn.microsoft.com/en-us/library/bb126235(VS.80).aspx for some information.\nYou could also use a scripting language such as lua.Net. \n", "If you really just want a dirt simple language, you want a 'recursive descent parser'.\nFor example, a language like this:\nSCENARIO MyScenario\nDELAY 1\nCOUNT 1 ADD 1\nDIRECT_POWER 23, False, 150\nWAIT 3\n...\nEND_SCENARIO\n\nYou might have a grammar like:\nscenario :: 'SCENARIO' label newline _cmds END_SCENARIO\ncmds:: _delay or _count or _direct_power or...\ndelay:: 'DELAY' number\n\nWhich gives code like:\ndef scenario():\n match_word('SCENARIO')\n scenario_name = match_label()\n emit('var scenario = new Scenario();')\n cmds()\n match_word('END_SCENARIO')\n emit('byte[] ' + scenario_name + ' = scenario.Compile();')\n\ndef delay():\n match_word('DELAY')\n length = match_number()\n emit('scenario.Add(new DelayCommand('+ length +'))')\n\ndef cmds():\n word = peek_next_word()\n if word == 'DELAY':\n delay()\n elif ...\n\n", "Here's a Pythonic solution for building a DSL that you can use to compile and create byte code arrays.\n\nWrite a simple module that makes your C# structures available to Python. The goal is to define each C# class that users are allowed to work with (Composites or Commands or whatever) as a Python class.\nUsually, this involves implementing a minimal set of methods with different conversions from C# types to native Python types and vice versa.\nWrite some nice demos showing how to use these Python class definitions to create their scripts. You should be able to create things like this in Python.\nimport * from someInterfaceModule\nscenario= Scenario(\n Delay(1),\n Repeat( Range(10),\n DirectPower( 23, False, 150),\n Wait(3),\n DirectPower( 23, False, 150)\n )\n)\nscenario.compile()\n\n\nThese are relatively simple classes to define. Each class here be reasonably easy to implement as Python modules that directly call your base C# modules.\nThe syntax is pure Python with no additional parsing or lexical scanning required.\n", "To add to S.Lott's comment, here's how you eval a Python script from C# \n", "While it might be great fun to create this mini-language and code it all up, the real questions you need to ask are:\n\nWhat is the business case for adding this feature / facility?\nWho is going to pay for this feature?\nWho is going to \"sign off\" on this feature if you build it?\n\n\"Really neat\" features have a way of getting built when the reality might indicate the true answer to such a request is \"no\".\nSee if you have a stakeholder willing to sponsor this before proceeding. Then check with the end users to see what they really want before committing to the project.\nCheers,\n-R\n" ]
[ 4, 2, 2, 1, 1, 0 ]
[]
[]
[ "c#", "embedding", "parsing", "python", "scripting" ]
stackoverflow_0000263550_c#_embedding_parsing_python_scripting.txt
Q: making a programme run indefinitely in python Is there any way to make a function (the ones I'm thinking of are in the style of the simple ones I've made which generate the fibonnacci sequence from 0 to a point, and all the primes between two points) run indefinitely. E.g. until I press a certain key or until a time has passed, rather than until a number reaches a certain point? Also, if it is based on time then is there any way I could just extend the time and start it going from that point again, rather than having to start again from 0? I am aware there is a time module, i just don't know much about it. A: The simplest way is just to write a program with an infinite loop, and then hit control-C to stop it. Without more description it's hard to know if this works for you. If you do it time-based, you don't need a generator. You can just have it pause for user input, something like a "Continue? [y/n]", read from stdin, and depending on what you get either exit the loop or not. A: If you really want your function to run and still wants user (or system) input, you have two solutions: multi-thread multi-process It will depend on how fine the interaction. If you just want to interrupt the function and don't care about the exit, then multi-process is fine. In both cases, you can rely on some shared resources (file or shared memory for multi-thread, variable with associated mutex for multi-thread) and check for the state of that resource regularly in your function. If it is set up to tell you to quit, just do it. Example on multi-thread: from threading import Thread, Lock from time import sleep class MyFct(Thread): def __init__(self): Thread.__init__(self) self.mutex = Lock() self._quit = False def stopped(self): self.mutex.acquire() val = self._quit self.mutex.release() return val def stop(self): self.mutex.acquire() self._quit = True self.mutex.release() def run(self): i = 1 j = 1 print i print j while True: if self.stopped(): return i,j = j,i+j print j def main_fct(): t = MyFct() t.start() sleep(1) t.stop() t.join() print "Exited" if __name__ == "__main__": main_fct() A: You could use a generator for this: def finished(): "Define your exit condition here" return ... def count(i=0): while not finished(): yield i i += 1 for i in count(): print i If you want to change the exit condition you could pass a value back into the generator function and use that value to determine when to exit. A: As in almost all languages: while True: # check what you want and eventually break print nextValue() The second part of your question is more interesting: Also, if it is based on time then is there anyway I could just extend the time and start it going from that point again rather than having to start again from 0 you can use a yield instead of return in the function nextValue() A: If you use a child thread to run the function while the main thread waits for character input it should work. Just remember to have something that stops the child thread (in the example below the global runthread) For example: import threading, time runthread = 1 def myfun(): while runthread: print "A" time.sleep(.1) t = threading.Thread(target=myfun) t.start() raw_input("") runthread = 0 t.join() does just that A: If you want to exit based on time, you can use the signal module's alarm(time) function, and the catch the SIGALRM - here's an example http://docs.python.org/library/signal.html#example You can let the user interrupt the program in a sane manner by catching KeyboardInterrupt. Simply catch the KeyboardInterrupt exception from outside you main loop, and do whatever cleanup you want. If you want to continue later where you left off, you will have to add some sort persistence. I would pickle a data structure to disk, that you could read back in to continue the operations. I haven't tried anything like this, but you could look into using something like memoizing, and caching to the disk. A: You could do something like this to generate fibonnacci numbers for 1 second then stop. fibonnacci = [1,1] stoptime = time.time() + 1 # set stop time to 1 second in the future while time.time() < stoptime: fibonnacci.append(fibonnacci[-1]+fibonnacci[-2]) print "Generated %s numbers, the last one was %s." % (len(fibonnacci),fibonnacci[-1]) I'm not sure how efficient it is to call time.time() in every loop - depending on the what you are doing inside the loop, it might end up taking a lot of the performance away.
making a programme run indefinitely in python
Is there any way to make a function (the ones I'm thinking of are in the style of the simple ones I've made which generate the fibonnacci sequence from 0 to a point, and all the primes between two points) run indefinitely. E.g. until I press a certain key or until a time has passed, rather than until a number reaches a certain point? Also, if it is based on time then is there any way I could just extend the time and start it going from that point again, rather than having to start again from 0? I am aware there is a time module, i just don't know much about it.
[ "The simplest way is just to write a program with an infinite loop, and then hit control-C to stop it. Without more description it's hard to know if this works for you.\nIf you do it time-based, you don't need a generator. You can just have it pause for user input, something like a \"Continue? [y/n]\", read from stdin, and depending on what you get either exit the loop or not.\n", "If you really want your function to run and still wants user (or system) input, you have two solutions:\n\nmulti-thread\nmulti-process\n\nIt will depend on how fine the interaction. If you just want to interrupt the function and don't care about the exit, then multi-process is fine.\nIn both cases, you can rely on some shared resources (file or shared memory for multi-thread, variable with associated mutex for multi-thread) and check for the state of that resource regularly in your function. If it is set up to tell you to quit, just do it.\nExample on multi-thread:\nfrom threading import Thread, Lock\nfrom time import sleep\n\nclass MyFct(Thread):\n def __init__(self):\n Thread.__init__(self)\n self.mutex = Lock()\n self._quit = False\n\n def stopped(self):\n self.mutex.acquire()\n val = self._quit\n self.mutex.release()\n return val\n\n def stop(self):\n self.mutex.acquire()\n self._quit = True\n self.mutex.release()\n\n def run(self):\n i = 1\n j = 1\n print i\n print j\n while True:\n if self.stopped():\n return\n i,j = j,i+j\n print j\n\ndef main_fct():\n t = MyFct()\n t.start()\n sleep(1)\n t.stop()\n t.join()\n print \"Exited\"\n\nif __name__ == \"__main__\":\n main_fct()\n\n", "You could use a generator for this:\ndef finished():\n \"Define your exit condition here\"\n return ...\n\ndef count(i=0):\n while not finished():\n yield i\n i += 1\n\nfor i in count():\n print i\n\nIf you want to change the exit condition you could pass a value back into the generator function and use that value to determine when to exit.\n", "As in almost all languages:\nwhile True:\n # check what you want and eventually break\n print nextValue()\n\nThe second part of your question is more interesting:\n\nAlso, if it is based on time then is there anyway I could just extend the time and start it going from that point again rather than having to start again from 0\n\nyou can use a yield instead of return in the function nextValue()\n", "If you use a child thread to run the function while the main thread waits for character input it should work. Just remember to have something that stops the child thread (in the example below the global runthread)\nFor example:\nimport threading, time\nrunthread = 1\ndef myfun():\n while runthread:\n print \"A\"\n time.sleep(.1)\n\nt = threading.Thread(target=myfun)\nt.start()\nraw_input(\"\")\nrunthread = 0\nt.join()\n\ndoes just that\n", "If you want to exit based on time, you can use the signal module's alarm(time) function, and the catch the SIGALRM - here's an example http://docs.python.org/library/signal.html#example\nYou can let the user interrupt the program in a sane manner by catching KeyboardInterrupt. Simply catch the KeyboardInterrupt exception from outside you main loop, and do whatever cleanup you want.\nIf you want to continue later where you left off, you will have to add some sort persistence. I would pickle a data structure to disk, that you could read back in to continue the operations. \nI haven't tried anything like this, but you could look into using something like memoizing, and caching to the disk.\n", "You could do something like this to generate fibonnacci numbers for 1 second then stop.\nfibonnacci = [1,1]\nstoptime = time.time() + 1 # set stop time to 1 second in the future\nwhile time.time() < stoptime:\n fibonnacci.append(fibonnacci[-1]+fibonnacci[-2])\n\nprint \"Generated %s numbers, the last one was %s.\" % (len(fibonnacci),fibonnacci[-1])\n\nI'm not sure how efficient it is to call time.time() in every loop - depending on the what you are doing inside the loop, it might end up taking a lot of the performance away.\n" ]
[ 2, 2, 2, 1, 1, 0, 0 ]
[]
[]
[ "indefinite", "key", "python", "time" ]
stackoverflow_0000262460_indefinite_key_python_time.txt
Q: Python - one variable equals another variable when it shouldn't Here is my sample code. It is meant to be an iterative procedure for gauss seidel (matrix solver). Essentially when the error is small enough it breaks out of the while loop. i=1 while (i>0): x_past = x_present j=0 while(j<3): value=0 k=0 while(k<3): if(k!=j): if(i==1): if(k>j): value=value+0 else: value=value+x_present[k]*eqn[j][k] else: value=value+x_present[k]*eqn[j][k] else: value=value+eqn[j][k] k=k+1 x_present[j:j+1]=[value] j=j+1 print "X_PAST" print x_past print "X_PRESENT" print x_present if(error(x_past, x_present)<10**-2): break; i=i+1 I've reduced the code so its more manageable. if you don't understand what its doing its not really that important to solving this problem. Here is the issue. Everytime x_present[j:j+1]=[value] is run, x_past is made equal to x_present. I don't know why this is the case as the only place i have set x_past equal to x_present is at the top of the loop. If I take away the x_past=x_present sentence, x_past is never made equal to x_present. This leads me to think it is some combination of the two statements that is causing the issue. This is a big problem cause if x_past = x_present the error = 0 every time and the loop breaks after the first iteration. The code does work, for example if I tell the code to run for 8 iterations and the break it gives me the answer its supposed to. I've been trying to figure this out for the last 4 hours and am completely stumped. I haven't been working with python long, so my trouble shooting skills syntax wise aren't that great. Any help would be appreciated!! A: Yes, I think the answers here show your problem. Just to try and clarify a little bit. You're referencing a list, so when the list changes any reference to that list will reflect that change. To demonstrate: >>> x_present = [4,5,6] >>> >>> x_past = x_present >>> >>> x_past [4, 5, 6] >>> >>> x_present.append(7) >>> >>> x_past [4, 5, 6, 7] >>> If you want a copy of the list you have to do do this, listcopy = mylist[:]. (or import copy;listcopy = copy.copy(mylist) >>> x_past = x_present[:] >>> x_past [4, 5, 6, 7] >>> >>> x_present.append(8) >>> >>> x_past [4, 5, 6, 7] A: What are x_past and x_present? I don't know much Python, but from a .NET/Java perspective, if they're references to some data structure (a map or whatever) then making them references to the same object (as you do at the start) will mean that any changes made through one variable will be visible through the other. It sounds like you need to take a copy of the data structure instead of just doing a reference assignment. Does the data structure you're working with have any kind of "clone" functionality available? As I say though, I don't know much Python so this could be totally wrong... A: As others pointed out the answer is to replace: x_past = x_present by x_past = x_present[:]. In general you could use a copy module to copy an object in Python. >>> import copy >>> a = range(10) >>> a [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> b = a >>> a += 10, 11 >>> a [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] >>> b [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] >>> c = copy.copy(a) # shallow copy >>> c [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] >>> del a[3:] >>> a [0, 1, 2] >>> b [0, 1, 2] >>> c [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] Your code is unpythonic to say the least. It could be replaced by something like the following code: import copy # assert(len(x_present) >= len(eqn)) first = True while True: x_past = copy.copy(x_present) # copy for j, eqj in enumerate(eqn): x_present[j] = sum(x_present[k] * eqj[k] for k in range(j if first else len(eqj)) if k != j) x_present[j] += eqj[j] print "X_PAST\n%s\nX_PRESENT\n%s" % (x_past, x_present) if allequal(x_past, x_present, tolerance=10**-2): break first = False Here's a definition of allequal() (using an absolute error. It might or might not be a good idea in your case (you could use a relative error instead)): def allequal(x, y, tolerance): return (len(x) == len(y) and all(-tolerance < (xx - yy) < tolerance for xx, yy in zip(x, y))) A: In Python, everything is an object. So the statement x_past = x_present point to the same reference. A: It looks as if x_present is a list. I suspect that this means that the assignment x_last = x_present makes x_last into an alias, i.e. they reference the same variable. Might this be the case? A: try changing the x_past = x_present line to x_past = [x for x in x_present] and see if it helps. the list copy shorthand is my favorite python feature since i can do one-liners that are not possible in other languages: greaterthan100 = [x for x in number if x > 100] notinblacklist = [x for x in mylist if x not in blacklist] firstchildofbigfamily = [x.child[0] for x in familylist if len(x.child) > 10]
Python - one variable equals another variable when it shouldn't
Here is my sample code. It is meant to be an iterative procedure for gauss seidel (matrix solver). Essentially when the error is small enough it breaks out of the while loop. i=1 while (i>0): x_past = x_present j=0 while(j<3): value=0 k=0 while(k<3): if(k!=j): if(i==1): if(k>j): value=value+0 else: value=value+x_present[k]*eqn[j][k] else: value=value+x_present[k]*eqn[j][k] else: value=value+eqn[j][k] k=k+1 x_present[j:j+1]=[value] j=j+1 print "X_PAST" print x_past print "X_PRESENT" print x_present if(error(x_past, x_present)<10**-2): break; i=i+1 I've reduced the code so its more manageable. if you don't understand what its doing its not really that important to solving this problem. Here is the issue. Everytime x_present[j:j+1]=[value] is run, x_past is made equal to x_present. I don't know why this is the case as the only place i have set x_past equal to x_present is at the top of the loop. If I take away the x_past=x_present sentence, x_past is never made equal to x_present. This leads me to think it is some combination of the two statements that is causing the issue. This is a big problem cause if x_past = x_present the error = 0 every time and the loop breaks after the first iteration. The code does work, for example if I tell the code to run for 8 iterations and the break it gives me the answer its supposed to. I've been trying to figure this out for the last 4 hours and am completely stumped. I haven't been working with python long, so my trouble shooting skills syntax wise aren't that great. Any help would be appreciated!!
[ "Yes, I think the answers here show your problem.\nJust to try and clarify a little bit.\nYou're referencing a list, so when the list changes any reference to that list will reflect that change. To demonstrate:\n>>> x_present = [4,5,6]\n>>>\n>>> x_past = x_present\n>>>\n>>> x_past\n[4, 5, 6]\n>>>\n>>> x_present.append(7)\n>>>\n>>> x_past\n[4, 5, 6, 7]\n>>>\n\nIf you want a copy of the list you have to do do this, listcopy = mylist[:]. (or import copy;listcopy = copy.copy(mylist)\n>>> x_past = x_present[:]\n>>> x_past\n[4, 5, 6, 7]\n>>>\n>>> x_present.append(8)\n>>>\n>>> x_past\n[4, 5, 6, 7]\n\n", "What are x_past and x_present? I don't know much Python, but from a .NET/Java perspective, if they're references to some data structure (a map or whatever) then making them references to the same object (as you do at the start) will mean that any changes made through one variable will be visible through the other. It sounds like you need to take a copy of the data structure instead of just doing a reference assignment. Does the data structure you're working with have any kind of \"clone\" functionality available?\nAs I say though, I don't know much Python so this could be totally wrong...\n", "As others pointed out the answer is to replace: x_past = x_present by x_past = x_present[:]. In general you could use a copy module to copy an object in Python.\n>>> import copy\n>>> a = range(10)\n>>> a\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n>>> b = a\n>>> a += 10, 11\n>>> a\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]\n>>> b\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]\n>>> c = copy.copy(a) # shallow copy\n>>> c\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]\n>>> del a[3:]\n>>> a\n[0, 1, 2]\n>>> b\n[0, 1, 2]\n>>> c\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]\n\nYour code is unpythonic to say the least.\nIt could be replaced by something like the following code:\nimport copy\n# assert(len(x_present) >= len(eqn))\n\nfirst = True\nwhile True:\n x_past = copy.copy(x_present) # copy\n\n for j, eqj in enumerate(eqn):\n x_present[j] = sum(x_present[k] * eqj[k] \n for k in range(j if first else len(eqj)) \n if k != j)\n x_present[j] += eqj[j] \n\n print \"X_PAST\\n%s\\nX_PRESENT\\n%s\" % (x_past, x_present)\n if allequal(x_past, x_present, tolerance=10**-2):\n break\n first = False\n\nHere's a definition of allequal() (using an absolute error. It might or might not be a good idea in your case (you could use a relative error instead)):\ndef allequal(x, y, tolerance):\n return (len(x) == len(y) and \n all(-tolerance < (xx - yy) < tolerance\n for xx, yy in zip(x, y)))\n\n", "In Python, everything is an object.\nSo the statement x_past = x_present point to the same reference.\n", "It looks as if x_present is a list. I suspect that this means that the assignment x_last = x_present makes x_last into an alias, i.e. they reference the same variable. Might this be the case?\n", "try changing the x_past = x_present line to x_past = [x for x in x_present] and see if it helps.\nthe list copy shorthand is my favorite python feature since i can do one-liners that are not possible in other languages:\ngreaterthan100 = [x for x in number if x > 100]\nnotinblacklist = [x for x in mylist if x not in blacklist]\nfirstchildofbigfamily = [x.child[0] for x in familylist if len(x.child) > 10]\n" ]
[ 31, 4, 3, 1, 0, 0 ]
[]
[]
[ "python", "variables" ]
stackoverflow_0000264575_python_variables.txt
Q: How can I optimize this Google App Engine code? I'm relatively new to the Python world, but this seems very straight forward. Google is yelling at me that this code needs to be optimized: class AddLinks(webapp.RequestHandler): def post(self): # Hash the textarea input to generate pseudo-unique value hash = md5.new(self.request.get('links')).hexdigest() # Seperate the input by line allLinks = self.request.get('links').splitlines() # For each line in the input, add to the database for x in allLinks: newGroup = LinkGrouping() newGroup.reference = hash newGroup.link = x newGroup.put() # testing vs live #baseURL = 'http://localhost:8080' baseURL = 'http://linkabyss.appspot.com' # Build template parameters template_values = { 'all_links': allLinks, 'base_url': baseURL, 'reference': hash, } # Output the template path = os.path.join(os.path.dirname(__file__), 'addLinks.html') self.response.out.write(template.render(path, template_values)) The dashboard is telling me that this is using a ton of CPU. Where should I look for improvements? A: The main overhead here is the multiple individual puts to the datastore. If you can, store the links as a single entity, as Andre suggests. You can always split the links into an array and store it in a ListProperty. If you do need an entity for each link, try this: # For each line in the input, add to the database groups = [] for x in allLinks: newGroup = LinkGrouping() newGroup.reference = hash newGroup.link = x groups.append(newGroup) db.put(groups) It will reduce the datastore roundtrips to one, and it's the roundtrips that are really killing your high CPU cap. A: Looks pretty tight to me. I see one thing that may make a small improvement. Your calling, "self.request.get('links')" twice. So adding: unsplitlinks = self.request.get('links') And referencing, "unsplitlinks" could help. Other than that the loop is the only area I see that would be a target for optimization. Is it possible to prep the data and then add it to the db at once, instead of doing a db add per link? (I assume the .put() command adds the link to the database) A: You can dramatically reduce the interaction between your app and the database by just storing the complete self.request.get('links') in a text field in the database. only one put() per post(self) the hash isn't stored n-times (for every link, which makes no sense and is really a waste of space) And you save yourself the parsing of the textfield when someone actually calls the page.... A: How frequently is this getting called? This doesn't look that bad... especially after removing the duplicate request. A: Can I query against the ListProperty? Something like SELECT * FROM LinkGrouping WHERE links.contains('http://www.google.com') I have future plans where I would need that functionality. I'll definitely implement the single db.put() to reduce usage. A: no/ you can not use something like "links.contains('http://www.google.com')" GQL not support this
How can I optimize this Google App Engine code?
I'm relatively new to the Python world, but this seems very straight forward. Google is yelling at me that this code needs to be optimized: class AddLinks(webapp.RequestHandler): def post(self): # Hash the textarea input to generate pseudo-unique value hash = md5.new(self.request.get('links')).hexdigest() # Seperate the input by line allLinks = self.request.get('links').splitlines() # For each line in the input, add to the database for x in allLinks: newGroup = LinkGrouping() newGroup.reference = hash newGroup.link = x newGroup.put() # testing vs live #baseURL = 'http://localhost:8080' baseURL = 'http://linkabyss.appspot.com' # Build template parameters template_values = { 'all_links': allLinks, 'base_url': baseURL, 'reference': hash, } # Output the template path = os.path.join(os.path.dirname(__file__), 'addLinks.html') self.response.out.write(template.render(path, template_values)) The dashboard is telling me that this is using a ton of CPU. Where should I look for improvements?
[ "The main overhead here is the multiple individual puts to the datastore. If you can, store the links as a single entity, as Andre suggests. You can always split the links into an array and store it in a ListProperty.\nIf you do need an entity for each link, try this:\n# For each line in the input, add to the database\ngroups = []\nfor x in allLinks:\n newGroup = LinkGrouping()\n newGroup.reference = hash\n newGroup.link = x\n groups.append(newGroup)\ndb.put(groups)\n\nIt will reduce the datastore roundtrips to one, and it's the roundtrips that are really killing your high CPU cap.\n", "Looks pretty tight to me.\nI see one thing that may make a small improvement.\nYour calling, \"self.request.get('links')\" twice.\nSo adding:\nunsplitlinks = self.request.get('links')\n\nAnd referencing, \"unsplitlinks\" could help.\nOther than that the loop is the only area I see that would be a target for optimization.\nIs it possible to prep the data and then add it to the db at once, instead of doing a db add per link? (I assume the .put() command adds the link to the database)\n", "You can dramatically reduce the interaction between your app and the database by just storing the complete self.request.get('links') in a text field in the database.\n\nonly one put() per post(self)\nthe hash isn't stored n-times (for every link, which makes no sense and is really a waste of space)\n\nAnd you save yourself the parsing of the textfield when someone actually calls the page....\n", "How frequently is this getting called? This doesn't look that bad... especially after removing the duplicate request.\n", "Can I query against the ListProperty?\nSomething like \nSELECT * FROM LinkGrouping WHERE links.contains('http://www.google.com')\n\nI have future plans where I would need that functionality.\nI'll definitely implement the single db.put() to reduce usage.\n", "no/ you can not use something like \"links.contains('http://www.google.com')\"\nGQL not support this\n" ]
[ 7, 3, 2, 0, 0, 0 ]
[]
[]
[ "google_app_engine", "optimization", "python" ]
stackoverflow_0000250209_google_app_engine_optimization_python.txt
Q: How do I process a string such as this using regular expressions? How can I create a regex for a string such as this: <SERVER> <SERVERKEY> <COMMAND> <FOLDERPATH> <RETENTION> <TRANSFERMODE> <OUTPUTPATH> <LOGTO> <OPTIONAL-MAXSIZE> <OPTIONAL-OFFSET> Most of these fields are just simple words, but some of them can be paths, such as FOLDERPATH, OUTPUTPATH, these paths can also be paths with a filename and wildcard appended. Retention is a number, and transfer mode can be bin or ascii. The issue is, LOGTO which can be a path with the logfile name appended to it or can be NO, which means no log file. The main issue, is the optional arguments, they are both numbers, and OFFSET can't exist without MAXSIZE, but MAXSIZE can exist without offset. Heres some examples: loveserver love copy /muffin* 20 bin C:\Puppies\ NO 256 300 loveserver love copy /muffin* 20 bin C:\Puppies\ NO 256 loveserver love copy /hats* 300 ascii C:\Puppies\no\ C:\log\love.log 256 Now the main issue, is that paths can have spaces in them, so if I use . to match everything, the regex ends up breaking, when parsing the optional arguments where the LOG destination ends up getting attached to the outputpath. Also if I end up using . and start removing parts of it, the regex will start putting things where it shouldn't. Heres my regex: ^(\s+)?(?P<SRCHOST>.+)(\s+)(?P<SRCKEY>.+)(\s+)(?P<COMMAND>COPY)(\s+)(?P<SRCDIR>.+)(\s+)(?P<RETENTION>\d+)(\s+)(?P<TRANSFER_MODE>BIN|ASC|BINARY|ASCII)(\s+)(?P<DSTDIR>.+)(\s+)(?P<LOGFILE>.+)(\s+)?(?P<SIZE>\d+)?(\s+)?(?P<OFFSET>\d+)?$ A: The problem is that because you're allowing spaces in filenames and using spaces to separate fields, the solution is ambiguous. You either need to use a different field separator character that can't appear in filenames, or use some other method of representing filenames with spaces in them, e.g. putting them in quotation marks. A: it is theoretically possible, but you are making things incredibly difficult for yourself. You have a number of problems here: 1) You are using space as a separator and you are also allowing spaces in the path names. You can avoid this by forcing the application to use paths without spaces in them. 2) You have 2 optional parameters on the end. This means that with the line ending "C:\LogTo Path 256 300" you have no idea if the path is C:\LogTo Path 256 300 with no optional parameters or C:\Log To Path 256 with one optional parameter or C:\LogTo Path with 2 optional parameters. This would be easily remedied with a replacement algorithm on the output. Replacing spaces with underscore and underscore with double underscore. Therefore you could reverse this reliably after you have split the log file on spaces. Even as a human you could not reliably perform this function 100%. If you presume that all paths either end with a asterisk, a backslash or .log you could use positive lookahead to find the end of the paths, but without some kind of rules regarding this you are stuffed. I get the feeling that a single regex would be too difficult for this and would make anyone trying to maintain the code insane. I am a regex whore, using them whenever possible and I would not attempt this. A: Just splitting on whitespace is never going to work. But if you can make some assumptions on the data it could be made to work. Some assumptions I had in mind: SERVER, SERVERKEY and COMMAND not containing any spaces: \S+ FOLDERPATH beginning with a slash: /.*? RETENTION being a number: \d+ TRANSFERMODE not containing any spaces: \S+ OUTPUTPATH beginning with a drive and ending with a slash: [A-Z]:\\.*?\\ LOGTO either being the word "NO", or a path beginning with a drive: [A-Z]:\\.*? MAXSIZE and OFFSET being a number: \d+ Putting it all together: ^\s* (?P<SERVER>\S+)\s+ (?P<SERVERKEY>\S+)\s+ (?P<COMMAND>\S+)\s+ (?P<FOLDERPATH>/.*?)\s+ # Slash not that important, but should start with non-whitespace (?P<RETENTION>\d+)\s+ (?P<TRANSFERMODE>\S+)\s+ (?P<OUTPUTPATH>[A-Z]:\\.*?\\)\s+ # Could also support network paths (?P<LOGTO>NO|[A-Z]:\\.*?) (?: \s+(?P<MAXSIZE>\d+) (?: \s+(?P<OFFSET>\d+) )? )? \s*$ In one line: ^\s*(?P<SERVER>\S+)\s+(?P<SERVERKEY>\S+)\s+(?P<COMMAND>\S+)\s+(?P<FOLDERPATH>/.*?)\s+(?P<RETENTION>\d+)\s+(?P<TRANSFERMODE>\S+)\s+(?P<OUTPUTPATH>[A-Z]:\\.*?\\)\s+(?P<LOGTO>NO|[A-Z]:\\.*?)(?:\s+(?P<MAXSIZE>\d+)(?:\s+(?P<OFFSET>\d+))?)?\s*$ Testing: >>> import re >>> p = re.compile(r'^(?P<SERVER>\S+)\s+(?P<SERVERKEY>\S+)\s+(?P<COMMAND>\S+)\s+(?P<FOLDERPATH>/.*?)\s+(?P<RETENTION>\d+)\s+(?P<TRANSFERMODE>\S+)\s+(?P<OUTPUTPATH>[A-Z]:\\.*?\\)\s+(?P<LOGTO>NO|[A-Z]:\\.*?)(?:\s+(?P<MAXSIZE>\d+)(?:\s+(?P<OFFSET>\d+))?)?\s*$',re.M) >>> data = r"""loveserver love copy /muffin* 20 bin C:\Puppies\ NO 256 300 ... loveserver love copy /muffin* 20 bin C:\Puppies\ NO 256 ... loveserver love copy /hats* 300 ascii C:\Puppies\no\ C:\log\love.log 256""" >>> import pprint >>> for match in p.finditer(data): ... print pprint.pprint(match.groupdict()) ... {'COMMAND': 'copy', 'FOLDERPATH': '/muffin*', 'LOGTO': 'NO', 'MAXSIZE': '256', 'OFFSET': '300', 'OUTPUTPATH': 'C:\\Puppies\\', 'RETENTION': '20', 'SERVER': 'loveserver', 'SERVERKEY': 'love', 'TRANSFERMODE': 'bin'} {'COMMAND': 'copy', 'FOLDERPATH': '/muffin*', 'LOGTO': 'NO', 'MAXSIZE': '256', 'OFFSET': None, 'OUTPUTPATH': 'C:\\Puppies\\', 'RETENTION': '20', 'SERVER': 'loveserver', 'SERVERKEY': 'love', 'TRANSFERMODE': 'bin'} {'COMMAND': 'copy', 'FOLDERPATH': '/hats*', 'LOGTO': 'C:\\log\\love.log', 'MAXSIZE': '256', 'OFFSET': None, 'OUTPUTPATH': 'C:\\Puppies\\no\\', 'RETENTION': '300', 'SERVER': 'loveserver', 'SERVERKEY': 'love', 'TRANSFERMODE': 'ascii'} >>> A: You need to restrict the fields between the paths in a way that the regexp can distinct them from the pathnames. So unless you put in a special separator, the sequence <OUTPUTPATH> <LOGTO> with optional spaces will not work. And if a path can look like those fields, you might get surprising results. e.g. c:\ 12 bin \ 250 bin \output for <FOLDERPATH> <RETENTION> <TRANSFERMODE> <OUTPUTPATH> is indistinguishable. So, let's try to restrict allowed characters a bit: <SERVER>, <SERVERKEY>, <COMMAND> no spaces -> [^]+ <FOLDERPATH> allow anything -> .+ <RETENTION> integer -> [0-9]+ <TRANSFERMODE> allow only bin and ascii -> (bin|ascii) <OUTPUTPATH> allow anything -> .+ <LOGTO> allow anything -> .+ <OPTIONAL-MAXSIZE>[0-9]* <OPTIONAL-OFFSET>[0-9]* So, i'd go with something along the lines of [^]+ [^]+ [^]+ .+ [0-9]+ (bin|ascii) .+ \> .+( [0-9]* ( [0-9]*)?)? With a ">" to separate the two pathes. You might want to quote the pathnames instead. NB: This was done in a hurry.
How do I process a string such as this using regular expressions?
How can I create a regex for a string such as this: <SERVER> <SERVERKEY> <COMMAND> <FOLDERPATH> <RETENTION> <TRANSFERMODE> <OUTPUTPATH> <LOGTO> <OPTIONAL-MAXSIZE> <OPTIONAL-OFFSET> Most of these fields are just simple words, but some of them can be paths, such as FOLDERPATH, OUTPUTPATH, these paths can also be paths with a filename and wildcard appended. Retention is a number, and transfer mode can be bin or ascii. The issue is, LOGTO which can be a path with the logfile name appended to it or can be NO, which means no log file. The main issue, is the optional arguments, they are both numbers, and OFFSET can't exist without MAXSIZE, but MAXSIZE can exist without offset. Heres some examples: loveserver love copy /muffin* 20 bin C:\Puppies\ NO 256 300 loveserver love copy /muffin* 20 bin C:\Puppies\ NO 256 loveserver love copy /hats* 300 ascii C:\Puppies\no\ C:\log\love.log 256 Now the main issue, is that paths can have spaces in them, so if I use . to match everything, the regex ends up breaking, when parsing the optional arguments where the LOG destination ends up getting attached to the outputpath. Also if I end up using . and start removing parts of it, the regex will start putting things where it shouldn't. Heres my regex: ^(\s+)?(?P<SRCHOST>.+)(\s+)(?P<SRCKEY>.+)(\s+)(?P<COMMAND>COPY)(\s+)(?P<SRCDIR>.+)(\s+)(?P<RETENTION>\d+)(\s+)(?P<TRANSFER_MODE>BIN|ASC|BINARY|ASCII)(\s+)(?P<DSTDIR>.+)(\s+)(?P<LOGFILE>.+)(\s+)?(?P<SIZE>\d+)?(\s+)?(?P<OFFSET>\d+)?$
[ "The problem is that because you're allowing spaces in filenames and using spaces to separate fields, the solution is ambiguous. You either need to use a different field separator character that can't appear in filenames, or use some other method of representing filenames with spaces in them, e.g. putting them in quotation marks.\n", "it is theoretically possible, but you are making things incredibly difficult for yourself. You have a number of problems here:\n1) You are using space as a separator and you are also allowing spaces in the path names. You can avoid this by forcing the application to use paths without spaces in them.\n2) You have 2 optional parameters on the end. This means that with the line ending \"C:\\LogTo Path 256 300\" you have no idea if the path is C:\\LogTo Path 256 300 with no optional parameters or C:\\Log To Path 256 with one optional parameter or C:\\LogTo Path with 2 optional parameters.\nThis would be easily remedied with a replacement algorithm on the output. Replacing spaces with underscore and underscore with double underscore. Therefore you could reverse this reliably after you have split the log file on spaces.\nEven as a human you could not reliably perform this function 100%. \nIf you presume that all paths either end with a asterisk, a backslash or .log you could use positive lookahead to find the end of the paths, but without some kind of rules regarding this you are stuffed.\nI get the feeling that a single regex would be too difficult for this and would make anyone trying to maintain the code insane. I am a regex whore, using them whenever possible and I would not attempt this. \n", "Just splitting on whitespace is never going to work. But if you can make some assumptions on the data it could be made to work.\nSome assumptions I had in mind:\n\nSERVER, SERVERKEY and COMMAND not containing any spaces: \\S+\nFOLDERPATH beginning with a slash: /.*?\nRETENTION being a number: \\d+\nTRANSFERMODE not containing any spaces: \\S+\nOUTPUTPATH beginning with a drive and ending with a slash: [A-Z]:\\\\.*?\\\\\nLOGTO either being the word \"NO\", or a path beginning with a drive: [A-Z]:\\\\.*?\nMAXSIZE and OFFSET being a number: \\d+\n\nPutting it all together:\n^\\s*\n(?P<SERVER>\\S+)\\s+\n(?P<SERVERKEY>\\S+)\\s+\n(?P<COMMAND>\\S+)\\s+\n(?P<FOLDERPATH>/.*?)\\s+ # Slash not that important, but should start with non-whitespace\n(?P<RETENTION>\\d+)\\s+\n(?P<TRANSFERMODE>\\S+)\\s+\n(?P<OUTPUTPATH>[A-Z]:\\\\.*?\\\\)\\s+ # Could also support network paths\n(?P<LOGTO>NO|[A-Z]:\\\\.*?)\n(?:\n \\s+(?P<MAXSIZE>\\d+)\n (?:\n \\s+(?P<OFFSET>\\d+)\n )?\n)?\n\\s*$\n\nIn one line:\n^\\s*(?P<SERVER>\\S+)\\s+(?P<SERVERKEY>\\S+)\\s+(?P<COMMAND>\\S+)\\s+(?P<FOLDERPATH>/.*?)\\s+(?P<RETENTION>\\d+)\\s+(?P<TRANSFERMODE>\\S+)\\s+(?P<OUTPUTPATH>[A-Z]:\\\\.*?\\\\)\\s+(?P<LOGTO>NO|[A-Z]:\\\\.*?)(?:\\s+(?P<MAXSIZE>\\d+)(?:\\s+(?P<OFFSET>\\d+))?)?\\s*$\n\nTesting:\n>>> import re\n>>> p = re.compile(r'^(?P<SERVER>\\S+)\\s+(?P<SERVERKEY>\\S+)\\s+(?P<COMMAND>\\S+)\\s+(?P<FOLDERPATH>/.*?)\\s+(?P<RETENTION>\\d+)\\s+(?P<TRANSFERMODE>\\S+)\\s+(?P<OUTPUTPATH>[A-Z]:\\\\.*?\\\\)\\s+(?P<LOGTO>NO|[A-Z]:\\\\.*?)(?:\\s+(?P<MAXSIZE>\\d+)(?:\\s+(?P<OFFSET>\\d+))?)?\\s*$',re.M)\n>>> data = r\"\"\"loveserver love copy /muffin* 20 bin C:\\Puppies\\ NO 256 300\n... loveserver love copy /muffin* 20 bin C:\\Puppies\\ NO 256\n... loveserver love copy /hats* 300 ascii C:\\Puppies\\no\\ C:\\log\\love.log 256\"\"\"\n>>> import pprint\n>>> for match in p.finditer(data):\n... print pprint.pprint(match.groupdict())\n...\n{'COMMAND': 'copy',\n 'FOLDERPATH': '/muffin*',\n 'LOGTO': 'NO',\n 'MAXSIZE': '256',\n 'OFFSET': '300',\n 'OUTPUTPATH': 'C:\\\\Puppies\\\\',\n 'RETENTION': '20',\n 'SERVER': 'loveserver',\n 'SERVERKEY': 'love',\n 'TRANSFERMODE': 'bin'}\n{'COMMAND': 'copy',\n 'FOLDERPATH': '/muffin*',\n 'LOGTO': 'NO',\n 'MAXSIZE': '256',\n 'OFFSET': None,\n 'OUTPUTPATH': 'C:\\\\Puppies\\\\',\n 'RETENTION': '20',\n 'SERVER': 'loveserver',\n 'SERVERKEY': 'love',\n 'TRANSFERMODE': 'bin'}\n{'COMMAND': 'copy',\n 'FOLDERPATH': '/hats*',\n 'LOGTO': 'C:\\\\log\\\\love.log',\n 'MAXSIZE': '256',\n 'OFFSET': None,\n 'OUTPUTPATH': 'C:\\\\Puppies\\\\no\\\\',\n 'RETENTION': '300',\n 'SERVER': 'loveserver',\n 'SERVERKEY': 'love',\n 'TRANSFERMODE': 'ascii'}\n>>>\n\n", "You need to restrict the fields between the paths in a way that the regexp can distinct them from the pathnames.\nSo unless you put in a special separator, the sequence\n<OUTPUTPATH> <LOGTO>\n\nwith optional spaces will not work.\nAnd if a path can look like those fields, you might get surprising results.\ne.g.\nc:\\ 12 bin \\ 250 bin \\output\n\nfor \n<FOLDERPATH> <RETENTION> <TRANSFERMODE> <OUTPUTPATH>\n\nis indistinguishable.\nSo, let's try to restrict allowed characters a bit:\n<SERVER>, <SERVERKEY>, <COMMAND> no spaces -> [^]+\n<FOLDERPATH> allow anything -> .+\n<RETENTION> integer -> [0-9]+\n<TRANSFERMODE> allow only bin and ascii -> (bin|ascii)\n<OUTPUTPATH> allow anything -> .+\n<LOGTO> allow anything -> .+\n<OPTIONAL-MAXSIZE>[0-9]*\n<OPTIONAL-OFFSET>[0-9]*\n\nSo, i'd go with something along the lines of\n[^]+ [^]+ [^]+ .+ [0-9]+ (bin|ascii) .+ \\> .+( [0-9]* ( [0-9]*)?)?\n\nWith a \">\" to separate the two pathes. You might want to quote the pathnames instead.\nNB: This was done in a hurry.\n" ]
[ 4, 3, 1, 0 ]
[ "Are less than/greater than allowed inside the values? Because if not you have a very simple solution:\nJust replace ever occurance of \"> \" with just \">\", split on \"><\", and strip out all less than/greater than from each item. It's probably longer than the regex code, but it will be clearer what's going on.\n" ]
[ -1 ]
[ "python", "regex" ]
stackoverflow_0000265814_python_regex.txt
Q: Why the Global Interpreter Lock? What is exactly the function of Python's Global Interpreter Lock? Do other languages that are compiled to bytecode employ a similar mechanism? A: In general, for any thread safety problem you will need to protect your internal data structures with locks. This can be done with various levels of granularity. You can use fine-grained locking, where every separate structure has its own lock. You can use coarse-grained locking where one lock protects everything (the GIL approach). There are various pros and cons of each method. Fine-grained locking allows greater parallelism - two threads can execute in parallel when they don't share any resources. However there is a much larger administrative overhead. For every line of code, you may need to acquire and release several locks. The coarse grained approach is the opposite. Two threads can't run at the same time, but an individual thread will run faster because its not doing so much bookkeeping. Ultimately it comes down to a tradeoff between single-threaded speed and parallelism. There have been a few attempts to remove the GIL in python, but the extra overhead for single threaded machines was generally too large. Some cases can actually be slower even on multi-processor machines due to lock contention. Do other languages that are compiled to bytecode employ a similar mechanism? It varies, and it probably shouldn't be considered a language property so much as an implementation property. For instance, there are Python implementations such as Jython and IronPython which use the threading approach of their underlying VM, rather than a GIL approach. Additionally, the next version of Ruby looks to be moving towards introducing a GIL. A: The following is from the official Python/C API Reference Manual: The Python interpreter is not fully thread safe. In order to support multi-threaded Python programs, there's a global lock that must be held by the current thread before it can safely access Python objects. Without the lock, even the simplest operations could cause problems in a multi-threaded program: for example, when two threads simultaneously increment the reference count of the same object, the reference count could end up being incremented only once instead of twice. Therefore, the rule exists that only the thread that has acquired the global interpreter lock may operate on Python objects or call Python/C API functions. In order to support multi-threaded Python programs, the interpreter regularly releases and reacquires the lock -- by default, every 100 bytecode instructions (this can be changed with sys.setcheckinterval()). The lock is also released and reacquired around potentially blocking I/O operations like reading or writing a file, so that other threads can run while the thread that requests the I/O is waiting for the I/O operation to complete. I think it sums up the issue pretty well. A: The global interpreter lock is a big mutex-type lock that protects reference counters from getting hosed. If you are writing pure python code, this all happens behind the scenes, but if you embedding Python into C, then you might have to explicitly take/release the lock. This mechanism is not related to Python being compiled to bytecode. It's not needed for Java. In fact, it's not even needed for Jython (python compiled to jvm). see also this question A: Python, like perl 5, was not designed from the ground up to be thread safe. Threads were grafted on after the fact, so the global interpreter lock is used to maintain mutual exclusion to where only one thread is executing code at a given time in the bowels of the interpreter. Individual Python threads are cooperatively multitasked by the interpreter itself by cycling the lock every so often. Grabbing the lock yourself is needed when you are talking to Python from C when other Python threads are active to 'opt in' to this protocol and make sure that nothing unsafe happens behind your back. Other systems that have a single-threaded heritage that later evolved into mulithreaded systems often have some mechanism of this sort. For instance, the Linux kernel has the "Big Kernel Lock" from its early SMP days. Gradually over time as multi-threading performance becomes an issue there is a tendency to try to break these sorts of locks up into smaller pieces or replace them with lock-free algorithms and data structures where possible to maximize throughput. A: Regarding your second question, not all scripting languages use this, but it only makes them less powerful. For instance, the threads in Ruby are green and not native. In Python, the threads are native and the GIL only prevents them from running on different cores. In Perl, the threads are even worse. They just copy the whole interpreter, and are far from being as usable as in Python. A: Maybe this article by the BDFL will help.
Why the Global Interpreter Lock?
What is exactly the function of Python's Global Interpreter Lock? Do other languages that are compiled to bytecode employ a similar mechanism?
[ "In general, for any thread safety problem you will need to protect your internal data structures with locks.\nThis can be done with various levels of granularity.\n\nYou can use fine-grained locking, where every separate structure has its own lock.\nYou can use coarse-grained locking where one lock protects everything (the GIL approach).\n\nThere are various pros and cons of each method. Fine-grained locking allows greater parallelism - two threads can\nexecute in parallel when they don't share any resources. However there is a much larger administrative overhead. For\nevery line of code, you may need to acquire and release several locks.\nThe coarse grained approach is the opposite. Two threads can't run at the same time, but an individual thread will run faster because its not doing so much bookkeeping. Ultimately it comes down to a tradeoff between single-threaded speed and parallelism.\nThere have been a few attempts to remove the GIL in python, but the extra overhead for single threaded machines was generally too large. Some cases can actually be slower even on multi-processor machines\ndue to lock contention. \n\nDo other languages that are compiled to bytecode employ a similar mechanism?\n\nIt varies, and it probably shouldn't be considered a language property so much as an implementation property.\nFor instance, there are Python implementations such as Jython and IronPython which use the threading approach of their underlying VM, rather than a GIL approach. Additionally, the next version of Ruby looks to be moving towards introducing a GIL.\n", "The following is from the official Python/C API Reference Manual:\n\nThe Python interpreter is not fully\n thread safe. In order to support\n multi-threaded Python programs,\n there's a global lock that must be\n held by the current thread before it\n can safely access Python objects.\n Without the lock, even the simplest\n operations could cause problems in a\n multi-threaded program: for example,\n when two threads simultaneously\n increment the reference count of the\n same object, the reference count could\n end up being incremented only once\n instead of twice. \nTherefore, the rule exists that only\n the thread that has acquired the\n global interpreter lock may operate on\n Python objects or call Python/C API\n functions. In order to support\n multi-threaded Python programs, the\n interpreter regularly releases and\n reacquires the lock -- by default,\n every 100 bytecode instructions (this\n can be changed with\n sys.setcheckinterval()). The lock is\n also released and reacquired around\n potentially blocking I/O operations\n like reading or writing a file, so\n that other threads can run while the\n thread that requests the I/O is\n waiting for the I/O operation to\n complete.\n\nI think it sums up the issue pretty well.\n", "The global interpreter lock is a big mutex-type lock that protects reference counters from getting hosed. If you are writing pure python code, this all happens behind the scenes, but if you embedding Python into C, then you might have to explicitly take/release the lock.\nThis mechanism is not related to Python being compiled to bytecode. It's not needed for Java. In fact, it's not even needed for Jython (python compiled to jvm).\nsee also this question\n", "Python, like perl 5, was not designed from the ground up to be thread safe. Threads were grafted on after the fact, so the global interpreter lock is used to maintain mutual exclusion to where only one thread is executing code at a given time in the bowels of the interpreter.\nIndividual Python threads are cooperatively multitasked by the interpreter itself by cycling the lock every so often.\nGrabbing the lock yourself is needed when you are talking to Python from C when other Python threads are active to 'opt in' to this protocol and make sure that nothing unsafe happens behind your back.\nOther systems that have a single-threaded heritage that later evolved into mulithreaded systems often have some mechanism of this sort. For instance, the Linux kernel has the \"Big Kernel Lock\" from its early SMP days. Gradually over time as multi-threading performance becomes an issue there is a tendency to try to break these sorts of locks up into smaller pieces or replace them with lock-free algorithms and data structures where possible to maximize throughput.\n", "Regarding your second question, not all scripting languages use this, but it only makes them less powerful. For instance, the threads in Ruby are green and not native.\nIn Python, the threads are native and the GIL only prevents them from running on different cores.\nIn Perl, the threads are even worse. They just copy the whole interpreter, and are far from being as usable as in Python.\n", "Maybe this article by the BDFL will help.\n" ]
[ 72, 34, 20, 12, 7, 2 ]
[]
[]
[ "bytecode", "locking", "multithreading", "python", "scripting" ]
stackoverflow_0000265687_bytecode_locking_multithreading_python_scripting.txt
Q: What is a Ruby equivalent for Python's "zip" builtin? Is there any Ruby equivalent for Python's builtin zip function? If not, what is a concise way of doing the same thing? A bit of context: this came up when I was trying to find a clean way of doing a check involving two arrays. If I had zip, I could have written something like: zip(a, b).all? {|pair| pair[0] === pair[1]} I'd also accept a clean way of doing this without anything resembling zip (where "clean" means "without an explicit loop"). A: Ruby has a zip function: [1,2].zip([3,4]) => [[1,3],[2,4]] so your code example is actually: a.zip(b).all? {|pair| pair[0] === pair[1]} or perhaps more succinctly: a.zip(b).all? {|a,b| a === b } A: Could you not do: a.eql?(b) Edited to add an example: a = %w[a b c] b = %w[1 2 3] c = ['a', 'b', 'c'] a.eql?(b) # => false a.eql?(c) # => true a.eql?(c.reverse) # => false
What is a Ruby equivalent for Python's "zip" builtin?
Is there any Ruby equivalent for Python's builtin zip function? If not, what is a concise way of doing the same thing? A bit of context: this came up when I was trying to find a clean way of doing a check involving two arrays. If I had zip, I could have written something like: zip(a, b).all? {|pair| pair[0] === pair[1]} I'd also accept a clean way of doing this without anything resembling zip (where "clean" means "without an explicit loop").
[ "Ruby has a zip function:\n[1,2].zip([3,4]) => [[1,3],[2,4]]\n\nso your code example is actually:\na.zip(b).all? {|pair| pair[0] === pair[1]}\n\nor perhaps more succinctly:\na.zip(b).all? {|a,b| a === b }\n\n", "Could you not do:\na.eql?(b)\n\nEdited to add an example:\na = %w[a b c]\nb = %w[1 2 3]\nc = ['a', 'b', 'c']\n\na.eql?(b) # => false\na.eql?(c) # => true\na.eql?(c.reverse) # => false\n\n" ]
[ 28, 0 ]
[ "This is from the ruby spec:\nit \"returns true if other has the same length and each pair of corresponding elements are eql\" do\n a = [1, 2, 3, 4]\n b = [1, 2, 3, 4]\n a.should eql(b)\n [].should eql([])\nend\n\nSo you should it should work for the example you mentioned.\nIf you're not using integers, but custom objects I think you need to override eql?.\nThe spec for this method is here:\nhttp://github.com/rubyspec/rubyspec/tree/master/1.8/core/array/eql_spec.rb\n" ]
[ -2 ]
[ "python", "ruby", "translation" ]
stackoverflow_0000263623_python_ruby_translation.txt
Q: using jython and open office 2.4 to convert docs to pdf I completed a python script using pyuno which successfully converted a document/ xls / rtf etc to a pdf. Then I needed to update a mssql database, due to open office currently supporting python 2.3, it's ancientness, lacks support for decent database libs. So I have resorted to using Jython, this way im not burdened down by running inside OO python environment using an old pyuno. This also means that my conversion code is broken, and I need to now make use of the java libraries instead of the pyuno libs. import com.sun.star.beans.PropertyValue as PropertyValue import com.sun.star.bridge.XUnoUrlResolver as XUnoUrlResolver import com.sun.star.comp.helper.Bootstrap as Bootstrap ->> import com.sun.star.frame.XComponentLoader as XComponentLoader ->> import com.sun.star.frame.XStorable as XStorable import com.sun.star.lang.XMultiComponentFactory as XMultiComponentFactory import com.sun.star.uno.UnoRuntime as UnoRuntime import com.sun.star.uno.XComponentContext as XComponentContext The includes with the '->>' do not import the compiler does not recognise the com.sun.star.frame cant see the 'frame' bit. These are the libs I have included. alt text http://www.freeimagehosting.net/uploads/eda5cda76d.jpg Some advice on this matter would be well received context = XComponentContext xMultiCompFactory = XMultiComponentFactory xcomponentloader = XComponentLoader //used in python ctx = None smgr = None doc = None url = None context = Bootstrap.bootstrap() xMultiCompFactory = self.context.getServiceManager() xcomponentloader = UnoRuntime.queryInterface(XComponentLoader.class, ....xMultiCompFactory.createInstanceWithContext("com.sun.star.frame.Desktop", context)) file = "file:\\" + file // also what is the equivalent of url = uno.systemPathToFileUrl(file) in Java so that I can make use of it to nicely format my path properties = [] p = PropertyValue() p.Name = "Hidden" p.Value = True properties.append(p) properties = tuple(properties) doc = xcomponentloader.loadComponentFromURL(file, "_blank",0, properties) A: And so it goes, according to this guy, you need some oil.... and it works like a charm http://www.oooforum.org/forum/viewtopic.phtml?p=304263#304263 include this lib C:\OpenOffice_24\program\classes\unoil.jar A: Using Jython is a great idea for this I think. But why could you not use two scripts, one with pyuno/2.3 and one with pymssql/2.5 (or whatever db adapter you are using)?. The intermediate format could be anything like a pickle, or json, or XML. Edit: I should add that I have used pyuno quite extensively, and I feel your pain.
using jython and open office 2.4 to convert docs to pdf
I completed a python script using pyuno which successfully converted a document/ xls / rtf etc to a pdf. Then I needed to update a mssql database, due to open office currently supporting python 2.3, it's ancientness, lacks support for decent database libs. So I have resorted to using Jython, this way im not burdened down by running inside OO python environment using an old pyuno. This also means that my conversion code is broken, and I need to now make use of the java libraries instead of the pyuno libs. import com.sun.star.beans.PropertyValue as PropertyValue import com.sun.star.bridge.XUnoUrlResolver as XUnoUrlResolver import com.sun.star.comp.helper.Bootstrap as Bootstrap ->> import com.sun.star.frame.XComponentLoader as XComponentLoader ->> import com.sun.star.frame.XStorable as XStorable import com.sun.star.lang.XMultiComponentFactory as XMultiComponentFactory import com.sun.star.uno.UnoRuntime as UnoRuntime import com.sun.star.uno.XComponentContext as XComponentContext The includes with the '->>' do not import the compiler does not recognise the com.sun.star.frame cant see the 'frame' bit. These are the libs I have included. alt text http://www.freeimagehosting.net/uploads/eda5cda76d.jpg Some advice on this matter would be well received context = XComponentContext xMultiCompFactory = XMultiComponentFactory xcomponentloader = XComponentLoader //used in python ctx = None smgr = None doc = None url = None context = Bootstrap.bootstrap() xMultiCompFactory = self.context.getServiceManager() xcomponentloader = UnoRuntime.queryInterface(XComponentLoader.class, ....xMultiCompFactory.createInstanceWithContext("com.sun.star.frame.Desktop", context)) file = "file:\\" + file // also what is the equivalent of url = uno.systemPathToFileUrl(file) in Java so that I can make use of it to nicely format my path properties = [] p = PropertyValue() p.Name = "Hidden" p.Value = True properties.append(p) properties = tuple(properties) doc = xcomponentloader.loadComponentFromURL(file, "_blank",0, properties)
[ "And so it goes, according to this guy, you need some oil.... and it works like a charm\nhttp://www.oooforum.org/forum/viewtopic.phtml?p=304263#304263\ninclude this lib C:\\OpenOffice_24\\program\\classes\\unoil.jar\n", "Using Jython is a great idea for this I think. But why could you not use two scripts, one with pyuno/2.3 and one with pymssql/2.5 (or whatever db adapter you are using)?.\nThe intermediate format could be anything like a pickle, or json, or XML.\nEdit: I should add that I have used pyuno quite extensively, and I feel your pain.\n" ]
[ 1, 0 ]
[]
[]
[ "jython", "openoffice.org", "python" ]
stackoverflow_0000264540_jython_openoffice.org_python.txt
Q: How to create a picture with animated aspects programmatically Background I have been asked by a client to create a picture of the world which has animated arrows/rays that come from one part of the world to another. The rays will be randomized, will represent a transaction, will fade out after they happen and will increase in frequency as time goes on. The rays will start in one country's boundary and end in another's. As each animated transaction happens a continuously updating sum of the amounts of all the transactions will be shown at the bottom of the image. The amounts of the individual transactions will be randomized. There will also be a year showing on the image that will increment every n seconds. The randomization, summation and incrementing are not a problem for me, but I am at a loss as to how to approach the animation of the arrows/rays. My question is what is the best way to do this? What frameworks/libraries are best suited for this job? I am most fluent in python so python suggestions are most easy for me, but I am open to any elegant way to do this. The client will present this as a slide in a presentation in a windows machine. A: The client will present this as a slide in a presentation in a windows machine I think this is the key to your answer. Before going to a 3d implementation and writing all the code in the world to create this feature, you need to look at the presentation software. Chances are, your options will boil down to two things: Animated Gif Custom Presentation Scripts Obviously, an animated gif is not ideal due to the fact that it repeats when it is done rendering, and to make it last a long time would make a large gif. Custom Presentation Scripts would probably be the other way to allow him to bring it up in a presentation without running any side-programs, or doing anything strange. I'm not sure which presentation application is the target, but this could be valuable information. He sounds like he's more non-technical and requesting something he doesn't realize will be difficult. I think you should come up with some options, explain the difficulty in implementing them, and suggest another solution that falls into the 'bang for your buck' range. A: It depends largely on the effort you want to expend on this, but the basic outline of an easy way. Would be to load an image of an arrow, and use a drawing library to color and rotate it in the direction you want to point(or draw it using shapes/curves). Finally to actually animate it interpolate between the coordinates based on time. If its just for a presentation though, I would use Macromedia Flash, or a similar animation program.(would do the same as above but you don't need to program anything) A: If you are adventurous use OpenGL :) You can draw bezier curves in 3d space on top of a textured plane (earth map), you can specify a thickness for them and you can draw a point (small cone) at the end. It's easy and it looks nice, problem is learning the basics of OpenGL if you haven't used it before but that would be fun and probably useful if your in to programing graphics. You can use OpenGL from python either with pyopengl or pyglet. If you make the animation this way you can capture it to an avi file (using camtasia or something similar) that can be put onto a presentation slide.
How to create a picture with animated aspects programmatically
Background I have been asked by a client to create a picture of the world which has animated arrows/rays that come from one part of the world to another. The rays will be randomized, will represent a transaction, will fade out after they happen and will increase in frequency as time goes on. The rays will start in one country's boundary and end in another's. As each animated transaction happens a continuously updating sum of the amounts of all the transactions will be shown at the bottom of the image. The amounts of the individual transactions will be randomized. There will also be a year showing on the image that will increment every n seconds. The randomization, summation and incrementing are not a problem for me, but I am at a loss as to how to approach the animation of the arrows/rays. My question is what is the best way to do this? What frameworks/libraries are best suited for this job? I am most fluent in python so python suggestions are most easy for me, but I am open to any elegant way to do this. The client will present this as a slide in a presentation in a windows machine.
[ "\nThe client will present this as a slide in a presentation in a windows machine\n\nI think this is the key to your answer. Before going to a 3d implementation and writing all the code in the world to create this feature, you need to look at the presentation software. Chances are, your options will boil down to two things:\n\nAnimated Gif\nCustom Presentation Scripts\n\nObviously, an animated gif is not ideal due to the fact that it repeats when it is done rendering, and to make it last a long time would make a large gif.\nCustom Presentation Scripts would probably be the other way to allow him to bring it up in a presentation without running any side-programs, or doing anything strange. I'm not sure which presentation application is the target, but this could be valuable information.\nHe sounds like he's more non-technical and requesting something he doesn't realize will be difficult. I think you should come up with some options, explain the difficulty in implementing them, and suggest another solution that falls into the 'bang for your buck' range.\n", "It depends largely on the effort you want to expend on this, but the basic outline of an easy way. Would be to load an image of an arrow, and use a drawing library to color and rotate it in the direction you want to point(or draw it using shapes/curves).\nFinally to actually animate it interpolate between the coordinates based on time.\nIf its just for a presentation though, I would use Macromedia Flash, or a similar animation program.(would do the same as above but you don't need to program anything)\n", "If you are adventurous use OpenGL :)\nYou can draw bezier curves in 3d space on top of a textured plane (earth map), you can specify a thickness for them and you can draw a point (small cone) at the end. It's easy and it looks nice, problem is learning the basics of OpenGL if you haven't used it before but that would be fun and probably useful if your in to programing graphics.\nYou can use OpenGL from python either with pyopengl or pyglet.\nIf you make the animation this way you can capture it to an avi file (using camtasia or something similar) that can be put onto a presentation slide.\n" ]
[ 2, 1, 1 ]
[]
[]
[ "animation", "drawing", "graphics", "image", "python" ]
stackoverflow_0000267660_animation_drawing_graphics_image_python.txt
Q: apache user can not write to .python-eggs I have read that I need to set the PYTHON_EGG_CACHE environment variable, or install the python library as an uncompressed .egg Which do you suggest? A: It totally depends on if you want to make the egg available as a generally available library or just for a single (or a handful of applications). Are you talking about a Trac installation? If so, there are also a handful of alternatives to make the egg available per instance: http://trac.edgewall.org/wiki/TracPlugins
apache user can not write to .python-eggs
I have read that I need to set the PYTHON_EGG_CACHE environment variable, or install the python library as an uncompressed .egg Which do you suggest?
[ "It totally depends on if you want to make the egg available as a generally available library or just for a single (or a handful of applications). Are you talking about a Trac installation? If so, there are also a handful of alternatives to make the egg available per instance:\nhttp://trac.edgewall.org/wiki/TracPlugins\n" ]
[ 1 ]
[]
[]
[ "apache", "egg", "python", "python_egg_cache" ]
stackoverflow_0000268015_apache_egg_python_python_egg_cache.txt
Q: C++ string diff (a la Python's difflib) I'm trying to diff two strings to determine whether or not they solely vary in one numerical subset of the string structure; for example, varies_in_single_number_field('foo7bar', 'foo123bar') # Returns True, because 7 != 123, and there's only one varying # number region between the two strings. In Python I can use the difflib to accomplish this: import difflib, doctest def varies_in_single_number_field(str1, str2): """ A typical use case is as follows: >>> varies_in_single_number_field('foo7bar00', 'foo123bar00') True Numerical variation in two dimensions is no good: >>> varies_in_single_number_field('foo7bar00', 'foo123bar01') False Varying in a nonexistent field is okay: >>> varies_in_single_number_field('foobar00', 'foo123bar00') True Identical strings don't *vary* in any number field: >>> varies_in_single_number_field('foobar00', 'foobar00') False """ in_differing_substring = False passed_differing_substring = False # There should be only one. differ = difflib.Differ() for letter_diff in differ.compare(str1, str2): letter = letter_diff[2:] if letter_diff.startswith(('-', '+')): if passed_differing_substring: # Already saw a varying field. return False in_differing_substring = True if not letter.isdigit(): return False # Non-digit diff character. elif in_differing_substring: # Diff character not found - end of diff. in_differing_substring = False passed_differing_substring = True return passed_differing_substring # No variation if no diff was passed. if __name__ == '__main__': doctest.testmod() But I have no idea how to find something like difflib for C++. Alternative approaches welcome. :) A: This might work, it at least passes your demonstration test: EDIT: I've made some modifications to deal with some string indexing issues. I believe it should be good now. #include <iostream> #include <string> #include <vector> #include <algorithm> #include <cctype> bool starts_with(const std::string &s1, const std::string &s2) { return (s1.length() <= s2.length()) && (s2.substr(0, s1.length()) == s1); } bool ends_with(const std::string &s1, const std::string &s2) { return (s1.length() <= s2.length()) && (s2.substr(s2.length() - s1.length()) == s1); } bool is_numeric(const std::string &s) { for(std::string::const_iterator it = s.begin(); it != s.end(); ++it) { if(!std::isdigit(*it)) { return false; } } return true; } bool varies_in_single_number_field(std::string s1, std::string s2) { size_t index1 = 0; size_t index2 = s1.length() - 1; if(s1 == s2) { return false; } if((s1.empty() && is_numeric(s2)) || (s2.empty() && is_numeric(s1))) { return true; } if(s1.length() < s2.length()) { s1.swap(s2); } while(index1 < s1.length() && starts_with(s1.substr(0, index1), s2)) { index1++; } while(ends_with(s1.substr(index2), s2)) { index2--; } return is_numeric(s1.substr(index1 - 1, (index2 + 1) - (index1 - 1))); } int main() { std::cout << std::boolalpha << varies_in_single_number_field("foo7bar00", "foo123bar00") << std::endl; std::cout << std::boolalpha << varies_in_single_number_field("foo7bar00", "foo123bar01") << std::endl; std::cout << std::boolalpha << varies_in_single_number_field("foobar00", "foo123bar00") << std::endl; std::cout << std::boolalpha << varies_in_single_number_field("foobar00", "foobar00") << std::endl; std::cout << std::boolalpha << varies_in_single_number_field("7aaa", "aaa") << std::endl; std::cout << std::boolalpha << varies_in_single_number_field("aaa7", "aaa") << std::endl; std::cout << std::boolalpha << varies_in_single_number_field("aaa", "7aaa") << std::endl; std::cout << std::boolalpha << varies_in_single_number_field("aaa", "aaa7") << std::endl; } Basically, it looks for a string which has 3 parts, string2 begins with part1, string2 ends with part3 and part2 is only digits. A: It's probably a bit of overkill, but you could use boost to interface to python. At the worst, difflib is implemented in pure python, and it's not too long. It should be possible to port from python to C... A: You could do an ad hoc approach: You're looking to match strings s and s', where s=abc and s'=ab'c, and the b and b' should be two distinct numbers (possible empty). So: Compare the strings from the left, char by char, until you hit different characters, and then stop. You Similarly, compare the strings from the right until you hit different characters, OR hit that left marker. Then check the remainders in the middle to see if they're both numbers. A: @Evan Teran: looks like we did this in parallel -- I have a markedly less readable O(n) implementation: #include <cassert> #include <cctype> #include <string> #include <sstream> #include <iostream> using namespace std; ostringstream debug; const bool DEBUG = true; bool varies_in_single_number_field(const string &str1, const string &str2) { bool in_difference = false; bool passed_difference = false; string str1_digits, str2_digits; size_t str1_iter = 0, str2_iter = 0; while (str1_iter < str1.size() && str2_iter < str2.size()) { const char &str1_char = str1.at(str1_iter); const char &str2_char = str2.at(str2_iter); debug << "str1: " << str1_char << "; str2: " << str2_char << endl; if (str1_char == str2_char) { if (in_difference) { in_difference = false; passed_difference = true; } ++str1_iter, ++str2_iter; continue; } in_difference = true; if (passed_difference) { /* Already passed a difference. */ debug << "Already passed a difference." << endl; return false; } bool str1_char_is_digit = isdigit(str1_char); bool str2_char_is_digit = isdigit(str2_char); if (str1_char_is_digit && !str2_char_is_digit) { ++str1_iter; str1_digits.push_back(str1_char); } else if (!str1_char_is_digit && str2_char_is_digit) { ++str2_iter; str2_digits.push_back(str2_char); } else if (str1_char_is_digit && str2_char_is_digit) { ++str1_iter, ++str2_iter; str1_digits.push_back(str1_char); str2_digits.push_back(str2_char); } else { /* Both are non-digits and they're different. */ return false; } } if (in_difference) { in_difference = false; passed_difference = true; } string str1_remainder = str1.substr(str1_iter); string str2_remainder = str2.substr(str2_iter); debug << "Got to exit point; passed difference: " << passed_difference << "; str1 digits: " << str1_digits << "; str2 digits: " << str2_digits << "; str1 remainder: " << str1_remainder << "; str2 remainder: " << str2_remainder << endl; return passed_difference && (str1_digits != str2_digits) && (str1_remainder == str2_remainder); } int main() { assert(varies_in_single_number_field("foo7bar00", "foo123bar00") == true); assert(varies_in_single_number_field("foo7bar00", "foo123bar01") == false); assert(varies_in_single_number_field("foobar00", "foo123bar00") == true); assert(varies_in_single_number_field("foobar00", "foobar00") == false); assert(varies_in_single_number_field("foobar00", "foobaz00") == false); assert(varies_in_single_number_field("foo00bar", "foo01barz") == false); assert(varies_in_single_number_field("foo01barz", "foo00bar") == false); if (DEBUG) { cout << debug.str(); } return 0; } A: How about using something like boost::regex? // pseudo code, may or may not compile bool match_except_numbers(const std::string& s1, const std::string& s2) { static const boost::regex fooNumberBar("foo\\d+bar"); return boost::match(s1, fooNumberBar) && boost::match(s2, fooNumberBar); }
C++ string diff (a la Python's difflib)
I'm trying to diff two strings to determine whether or not they solely vary in one numerical subset of the string structure; for example, varies_in_single_number_field('foo7bar', 'foo123bar') # Returns True, because 7 != 123, and there's only one varying # number region between the two strings. In Python I can use the difflib to accomplish this: import difflib, doctest def varies_in_single_number_field(str1, str2): """ A typical use case is as follows: >>> varies_in_single_number_field('foo7bar00', 'foo123bar00') True Numerical variation in two dimensions is no good: >>> varies_in_single_number_field('foo7bar00', 'foo123bar01') False Varying in a nonexistent field is okay: >>> varies_in_single_number_field('foobar00', 'foo123bar00') True Identical strings don't *vary* in any number field: >>> varies_in_single_number_field('foobar00', 'foobar00') False """ in_differing_substring = False passed_differing_substring = False # There should be only one. differ = difflib.Differ() for letter_diff in differ.compare(str1, str2): letter = letter_diff[2:] if letter_diff.startswith(('-', '+')): if passed_differing_substring: # Already saw a varying field. return False in_differing_substring = True if not letter.isdigit(): return False # Non-digit diff character. elif in_differing_substring: # Diff character not found - end of diff. in_differing_substring = False passed_differing_substring = True return passed_differing_substring # No variation if no diff was passed. if __name__ == '__main__': doctest.testmod() But I have no idea how to find something like difflib for C++. Alternative approaches welcome. :)
[ "This might work, it at least passes your demonstration test:\nEDIT: I've made some modifications to deal with some string indexing issues. I believe it should be good now.\n#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\n#include <cctype>\n\nbool starts_with(const std::string &s1, const std::string &s2) {\n return (s1.length() <= s2.length()) && (s2.substr(0, s1.length()) == s1);\n}\n\nbool ends_with(const std::string &s1, const std::string &s2) {\n return (s1.length() <= s2.length()) && (s2.substr(s2.length() - s1.length()) == s1);\n}\n\nbool is_numeric(const std::string &s) {\n for(std::string::const_iterator it = s.begin(); it != s.end(); ++it) {\n if(!std::isdigit(*it)) {\n return false;\n }\n }\n return true;\n}\n\nbool varies_in_single_number_field(std::string s1, std::string s2) {\n\n size_t index1 = 0;\n size_t index2 = s1.length() - 1;\n\n if(s1 == s2) {\n return false;\n }\n\n if((s1.empty() && is_numeric(s2)) || (s2.empty() && is_numeric(s1))) {\n return true;\n }\n\n if(s1.length() < s2.length()) {\n s1.swap(s2);\n }\n\n while(index1 < s1.length() && starts_with(s1.substr(0, index1), s2)) { index1++; }\n while(ends_with(s1.substr(index2), s2)) { index2--; }\n\n return is_numeric(s1.substr(index1 - 1, (index2 + 1) - (index1 - 1)));\n\n}\n\nint main() {\n std::cout << std::boolalpha << varies_in_single_number_field(\"foo7bar00\", \"foo123bar00\") << std::endl;\n std::cout << std::boolalpha << varies_in_single_number_field(\"foo7bar00\", \"foo123bar01\") << std::endl;\n std::cout << std::boolalpha << varies_in_single_number_field(\"foobar00\", \"foo123bar00\") << std::endl;\n std::cout << std::boolalpha << varies_in_single_number_field(\"foobar00\", \"foobar00\") << std::endl;\n std::cout << std::boolalpha << varies_in_single_number_field(\"7aaa\", \"aaa\") << std::endl;\n std::cout << std::boolalpha << varies_in_single_number_field(\"aaa7\", \"aaa\") << std::endl;\n std::cout << std::boolalpha << varies_in_single_number_field(\"aaa\", \"7aaa\") << std::endl;\n std::cout << std::boolalpha << varies_in_single_number_field(\"aaa\", \"aaa7\") << std::endl;\n}\n\nBasically, it looks for a string which has 3 parts, string2 begins with part1, string2 ends with part3 and part2 is only digits.\n", "It's probably a bit of overkill, but you could use boost to interface to python. At the worst, difflib is implemented in pure python, and it's not too long. It should be possible to port from python to C...\n", "You could do an ad hoc approach: You're looking to match strings s and s', where s=abc and s'=ab'c, and the b and b' should be two distinct numbers (possible empty). So:\n\nCompare the strings from the left, char by char, until you hit different characters, and then stop. You \nSimilarly, compare the strings from the right until you hit different characters, OR hit that left marker.\nThen check the remainders in the middle to see if they're both numbers.\n\n", "@Evan Teran: looks like we did this in parallel -- I have a markedly less readable O(n) implementation:\n#include <cassert>\n#include <cctype>\n#include <string>\n#include <sstream>\n#include <iostream>\n\nusing namespace std;\n\nostringstream debug;\nconst bool DEBUG = true;\n\nbool varies_in_single_number_field(const string &str1, const string &str2) {\n bool in_difference = false;\n bool passed_difference = false;\n string str1_digits, str2_digits;\n size_t str1_iter = 0, str2_iter = 0;\n while (str1_iter < str1.size() && str2_iter < str2.size()) {\n const char &str1_char = str1.at(str1_iter);\n const char &str2_char = str2.at(str2_iter);\n debug << \"str1: \" << str1_char << \"; str2: \" << str2_char << endl;\n if (str1_char == str2_char) {\n if (in_difference) {\n in_difference = false;\n passed_difference = true;\n }\n ++str1_iter, ++str2_iter;\n continue;\n }\n in_difference = true;\n if (passed_difference) { /* Already passed a difference. */\n debug << \"Already passed a difference.\" << endl;\n return false;\n }\n bool str1_char_is_digit = isdigit(str1_char);\n bool str2_char_is_digit = isdigit(str2_char);\n if (str1_char_is_digit && !str2_char_is_digit) {\n ++str1_iter;\n str1_digits.push_back(str1_char);\n } else if (!str1_char_is_digit && str2_char_is_digit) {\n ++str2_iter;\n str2_digits.push_back(str2_char);\n } else if (str1_char_is_digit && str2_char_is_digit) {\n ++str1_iter, ++str2_iter;\n str1_digits.push_back(str1_char);\n str2_digits.push_back(str2_char);\n } else { /* Both are non-digits and they're different. */\n return false;\n }\n }\n if (in_difference) {\n in_difference = false;\n passed_difference = true;\n }\n string str1_remainder = str1.substr(str1_iter);\n string str2_remainder = str2.substr(str2_iter);\n debug << \"Got to exit point; passed difference: \" << passed_difference\n << \"; str1 digits: \" << str1_digits\n << \"; str2 digits: \" << str2_digits\n << \"; str1 remainder: \" << str1_remainder\n << \"; str2 remainder: \" << str2_remainder\n << endl;\n return passed_difference\n && (str1_digits != str2_digits)\n && (str1_remainder == str2_remainder);\n}\n\nint main() {\n assert(varies_in_single_number_field(\"foo7bar00\", \"foo123bar00\") == true);\n assert(varies_in_single_number_field(\"foo7bar00\", \"foo123bar01\") == false);\n assert(varies_in_single_number_field(\"foobar00\", \"foo123bar00\") == true);\n assert(varies_in_single_number_field(\"foobar00\", \"foobar00\") == false);\n assert(varies_in_single_number_field(\"foobar00\", \"foobaz00\") == false);\n assert(varies_in_single_number_field(\"foo00bar\", \"foo01barz\") == false);\n assert(varies_in_single_number_field(\"foo01barz\", \"foo00bar\") == false);\n if (DEBUG) {\n cout << debug.str();\n }\n return 0;\n}\n\n", "How about using something like boost::regex?\n\n// pseudo code, may or may not compile\nbool match_except_numbers(const std::string& s1, const std::string& s2)\n{\n static const boost::regex fooNumberBar(\"foo\\\\d+bar\");\n return boost::match(s1, fooNumberBar) && boost::match(s2, fooNumberBar);\n}\n\n" ]
[ 2, 1, 1, 0, 0 ]
[]
[]
[ "algorithm", "c++", "diff", "python" ]
stackoverflow_0000269918_algorithm_c++_diff_python.txt
Q: How do I validate xml against a DTD file in Python I need to validate an XML string (and not a file) against a DTD description file. How can that be done in python? A: Another good option is lxml's validation which I find quite pleasant to use. A simple example taken from the lxml site: from StringIO import StringIO from lxml import etree dtd = etree.DTD(StringIO("""<!ELEMENT foo EMPTY>""")) root = etree.XML("<foo/>") print(dtd.validate(root)) # True root = etree.XML("<foo>bar</foo>") print(dtd.validate(root)) # False print(dtd.error_log.filter_from_errors()) # <string>:1:0:ERROR:VALID:DTD_NOT_EMPTY: Element foo was declared EMPTY this one has content A: from the examples directory in the libxml2 python bindings: #!/usr/bin/python -u import libxml2 import sys # Memory debug specific libxml2.debugMemory(1) dtd="""<!ELEMENT foo EMPTY>""" instance="""<?xml version="1.0"?> <foo></foo>""" dtd = libxml2.parseDTD(None, 'test.dtd') ctxt = libxml2.newValidCtxt() doc = libxml2.parseDoc(instance) ret = doc.validateDtd(ctxt, dtd) if ret != 1: print "error doing DTD validation" sys.exit(1) doc.freeDoc() dtd.freeDtd() del dtd del ctxt
How do I validate xml against a DTD file in Python
I need to validate an XML string (and not a file) against a DTD description file. How can that be done in python?
[ "Another good option is lxml's validation which I find quite pleasant to use.\nA simple example taken from the lxml site:\nfrom StringIO import StringIO\n\nfrom lxml import etree\n\ndtd = etree.DTD(StringIO(\"\"\"<!ELEMENT foo EMPTY>\"\"\"))\nroot = etree.XML(\"<foo/>\")\nprint(dtd.validate(root))\n# True\n\nroot = etree.XML(\"<foo>bar</foo>\")\nprint(dtd.validate(root))\n# False\nprint(dtd.error_log.filter_from_errors())\n# <string>:1:0:ERROR:VALID:DTD_NOT_EMPTY: Element foo was declared EMPTY this one has content\n\n", "from the examples directory in the libxml2 python bindings:\n#!/usr/bin/python -u\nimport libxml2\nimport sys\n\n# Memory debug specific\nlibxml2.debugMemory(1)\n\ndtd=\"\"\"<!ELEMENT foo EMPTY>\"\"\"\ninstance=\"\"\"<?xml version=\"1.0\"?>\n<foo></foo>\"\"\"\n\ndtd = libxml2.parseDTD(None, 'test.dtd')\nctxt = libxml2.newValidCtxt()\ndoc = libxml2.parseDoc(instance)\nret = doc.validateDtd(ctxt, dtd)\nif ret != 1:\n print \"error doing DTD validation\"\n sys.exit(1)\n\ndoc.freeDoc()\ndtd.freeDtd()\ndel dtd\ndel ctxt\n\n" ]
[ 32, 7 ]
[]
[]
[ "dtd", "python", "validation", "xml" ]
stackoverflow_0000015798_dtd_python_validation_xml.txt
Q: Using Python to authenticate against raw username, hash, salt in DB created by ASP.NET roles/membership We have a current application where user login credentials are stored in a SQL Server DB. These are, basically, stored as a plain text username, a password hash, and an associated salt for this hash. These were all created by built in functions in ASP.NET's membership/role system. Here's a row for a user named 'joe' and a password of 'password': joe,kDP0Py2QwEdJYtUX9cJABg==,OJF6H4KdxFLgLu+oTDNFodCEfMA= I've dumped this stuff into a CSV file and I'm attempting to get it into a usable format for Django which stores its passwords in this format: [algo]$[salt]$[hash] Where the salt is a plain string and the hash is the hex digest of an SHA1 hash. So far I've been able to ascertain that ASP is storing these hashes and salts in a base64 format. Those values above decode into binary strings. We've used reflector to glean how ASP authenticates against these values: internal string EncodePassword(string pass, int passwordFormat, string salt) { if (passwordFormat == 0) { return pass; } byte[] bytes = Encoding.Unicode.GetBytes(pass); byte[] src = Convert.FromBase64String(salt); byte[] dst = new byte[src.Length + bytes.Length]; byte[] inArray = null; Buffer.BlockCopy(src, 0, dst, 0, src.Length); Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length); if (passwordFormat == 1) { HashAlgorithm algorithm = HashAlgorithm.Create(Membership.HashAlgorithmType); if ((algorithm == null) && Membership.IsHashAlgorithmFromMembershipConfig) { RuntimeConfig.GetAppConfig().Membership.ThrowHashAlgorithmException(); } inArray = algorithm.ComputeHash(dst); } else { inArray = this.EncryptPassword(dst); } return Convert.ToBase64String(inArray); } Eseentially, pulls in the salt from the DB and b64 decodes it into a binary representation. It does a "GetBytes" on the raw password and then it concatinates them, salt first. It then runs the SHA1 algorithm on this new string, base64 encodes it, and compares it against the value stored in the database. I've attempted to write some code to try and reproduce these hashes in Python and I'm failing. I won't be able to use them in Django until I can figure out how this translates over. Here's how I'm testing: import hashlib from base64 import b64decode, b64encode b64salt = "kDP0Py2QwEdJYtUX9cJABg==" b64hash = "OJF6H4KdxFLgLu+oTDNFodCEfMA=" binsalt = b64decode(b64salt) password_string = 'password' m1 = hashlib.sha1() # Pass in salt m1.update(binsalt) # Pass in password m1.update(password_string) # B64 encode the binary digest if b64encode(m1.digest()) == b64hash: print "Logged in!" else: print "Didn't match" print b64hash print b64encode(m1.digest()) I'm wondering if anyone can see any flaws in my approach or can suggest an alternate method. Perhaps you can take the algorithms above and the known password and salt above and produce the hash on your system? A: It appears python is inserting a byte order marker when you convert a UTF16 string to binary. The .NET byte array contains no BOM, so I did some ghetto python that turns the UTF16 into hex, removes the first 4 characters, then decodes it to binary. There may be a better way to rip out the BOM, but this works for me! Here's one that passes: import hashlib from base64 import b64decode, b64encode def utf16tobin(s): return s.encode('hex')[4:].decode('hex') b64salt = "kDP0Py2QwEdJYtUX9cJABg==" b64hash = "OJF6H4KdxFLgLu+oTDNFodCEfMA=" binsalt = b64decode(b64salt) password_string = 'password'.encode("utf16") password_string = utf16tobin(password_string) m1 = hashlib.sha1() # Pass in salt m1.update(binsalt + password_string) # Pass in password # B64 encode the binary digest if b64encode(m1.digest()) == b64hash: print "Logged in!" else: print "Didn't match" print b64hash print b64encode(m1.digest()) A: Two thoughts as to what could be going wrong. First the code from the reflection has three paths: If passwordFormat is 0 it returns the password as is. If passwordFormat is 1 it creates the hash as your python code does. If passwordFormat is anything other than 0 or 1 it calls this.EncryptPassword() How do you know you are hashing the password, and not encrypting the password with this.EncryptPassword()? You may need to reverse the EncryptPassword() member function and replicate that. That is unless you have some information which ensures that you are hashing the password and not encrypting it. Second if it is indeed hashing the password you may want to see what the Encoding.Unicode.GetBytes() function returns for the string "password", as you may be getting something back like: 0x00 0x70 0x00 0x61 0x00 0x73 0x00 0x73 0x00 0x77 0x00 0x6F 0x00 0x72 0x00 0x64 instead of: 0x70 0x61 0x73 0x73 0x77 0x6F 0x72 0x64 I hope this helps.
Using Python to authenticate against raw username, hash, salt in DB created by ASP.NET roles/membership
We have a current application where user login credentials are stored in a SQL Server DB. These are, basically, stored as a plain text username, a password hash, and an associated salt for this hash. These were all created by built in functions in ASP.NET's membership/role system. Here's a row for a user named 'joe' and a password of 'password': joe,kDP0Py2QwEdJYtUX9cJABg==,OJF6H4KdxFLgLu+oTDNFodCEfMA= I've dumped this stuff into a CSV file and I'm attempting to get it into a usable format for Django which stores its passwords in this format: [algo]$[salt]$[hash] Where the salt is a plain string and the hash is the hex digest of an SHA1 hash. So far I've been able to ascertain that ASP is storing these hashes and salts in a base64 format. Those values above decode into binary strings. We've used reflector to glean how ASP authenticates against these values: internal string EncodePassword(string pass, int passwordFormat, string salt) { if (passwordFormat == 0) { return pass; } byte[] bytes = Encoding.Unicode.GetBytes(pass); byte[] src = Convert.FromBase64String(salt); byte[] dst = new byte[src.Length + bytes.Length]; byte[] inArray = null; Buffer.BlockCopy(src, 0, dst, 0, src.Length); Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length); if (passwordFormat == 1) { HashAlgorithm algorithm = HashAlgorithm.Create(Membership.HashAlgorithmType); if ((algorithm == null) && Membership.IsHashAlgorithmFromMembershipConfig) { RuntimeConfig.GetAppConfig().Membership.ThrowHashAlgorithmException(); } inArray = algorithm.ComputeHash(dst); } else { inArray = this.EncryptPassword(dst); } return Convert.ToBase64String(inArray); } Eseentially, pulls in the salt from the DB and b64 decodes it into a binary representation. It does a "GetBytes" on the raw password and then it concatinates them, salt first. It then runs the SHA1 algorithm on this new string, base64 encodes it, and compares it against the value stored in the database. I've attempted to write some code to try and reproduce these hashes in Python and I'm failing. I won't be able to use them in Django until I can figure out how this translates over. Here's how I'm testing: import hashlib from base64 import b64decode, b64encode b64salt = "kDP0Py2QwEdJYtUX9cJABg==" b64hash = "OJF6H4KdxFLgLu+oTDNFodCEfMA=" binsalt = b64decode(b64salt) password_string = 'password' m1 = hashlib.sha1() # Pass in salt m1.update(binsalt) # Pass in password m1.update(password_string) # B64 encode the binary digest if b64encode(m1.digest()) == b64hash: print "Logged in!" else: print "Didn't match" print b64hash print b64encode(m1.digest()) I'm wondering if anyone can see any flaws in my approach or can suggest an alternate method. Perhaps you can take the algorithms above and the known password and salt above and produce the hash on your system?
[ "It appears python is inserting a byte order marker when you convert a UTF16 string to binary. The .NET byte array contains no BOM, so I did some ghetto python that turns the UTF16 into hex, removes the first 4 characters, then decodes it to binary.\nThere may be a better way to rip out the BOM, but this works for me!\nHere's one that passes:\nimport hashlib\nfrom base64 import b64decode, b64encode\n\ndef utf16tobin(s):\n return s.encode('hex')[4:].decode('hex')\n\nb64salt = \"kDP0Py2QwEdJYtUX9cJABg==\"\nb64hash = \"OJF6H4KdxFLgLu+oTDNFodCEfMA=\"\nbinsalt = b64decode(b64salt)\npassword_string = 'password'.encode(\"utf16\")\npassword_string = utf16tobin(password_string)\n\nm1 = hashlib.sha1()\n# Pass in salt\nm1.update(binsalt + password_string)\n# Pass in password\n# B64 encode the binary digest\nif b64encode(m1.digest()) == b64hash:\n print \"Logged in!\"\nelse:\n print \"Didn't match\"\n print b64hash\n print b64encode(m1.digest())\n\n", "Two thoughts as to what could be going wrong.\nFirst the code from the reflection has three paths:\n\nIf passwordFormat is 0 it returns the password as is.\nIf passwordFormat is 1 it creates the hash as your python code does.\nIf passwordFormat is anything other than 0 or 1 it calls this.EncryptPassword()\n\nHow do you know you are hashing the password, and not encrypting the password with this.EncryptPassword()? You may need to reverse the EncryptPassword() member function and replicate that. That is unless you have some information which ensures that you are hashing the password and not encrypting it.\nSecond if it is indeed hashing the password you may want to see what the Encoding.Unicode.GetBytes() function returns for the string \"password\", as you may be getting something back like:\n0x00 0x70 0x00 0x61 0x00 0x73 0x00 0x73 0x00 0x77 0x00 0x6F 0x00 0x72 0x00 0x64\n\ninstead of:\n0x70 0x61 0x73 0x73 0x77 0x6F 0x72 0x64\n\nI hope this helps.\n" ]
[ 8, 0 ]
[]
[]
[ "asp.net", "hash", "passwords", "python" ]
stackoverflow_0000269713_asp.net_hash_passwords_python.txt
Q: How can I apply authenticated proxy exceptions to an opener using urllib2? When using urllib2 (and maybe urllib) on windows python seems to magically pick up the authenticated proxy setting applied to InternetExplorer. However, it doesn't seem to check and process the Advance setting "Exceptions" list. Is there a way I can get it to process the exceptions list? Or, ignore the IE proxy setting and apply my own proxy opener to address this issue? I played with creating a proxy opener before, but couldn't get it to work. Here's what I managed to dig out, but I still don't see how/where to apply any exceptions and I'm not even sure if this is right: proxy_info = { 'host':'myproxy.com', 'user':Username, 'pass':Password, 'port':1080 } http_str = "http://%(user)s:%(pass)s@%(host)s:%(port)d" % proxy_info authInfo = urllib2.HTTPBasicAuthHandler() authInfo.add_password() proxy_dict = {'http':http_str} proxyHandler = urllib2.ProxyHandler(proxy_dict) # apply the handler to an opener proxy_opener = urllib2.build_opener(proxyHandler, urllib2.HTTPHandler) urllib2.install_opener(proxy_opener) A: By default urllib2 gets the proxy settings from the environment variable, which is why it is using the IE settings. This is very handy, because you don't need to setup authentication yourself. You can't apply exceptions like you want to, the easiest way to do this would be to have two openers and decide which one to use depending on whether the domain is in your exception list or not. Use the default opener for when you want to use the proxy, and one without a proxy for when you don't need it: >>> no_proxy = urllib2.ProxyHandler({}) >>> opener = urllib2.build_opener(no_proxy) >>> urllib2.install_opener(opener) From here. Edit: Here's how I'd do it: exclusion_list = ['http://www.google.com/', 'http://localhost/'] no_proxy = urllib2.ProxyHandler({}) no_proxy_opener = urllib2.build_opener(no_proxy) default_proxy_opener = urllib2.build_opener() url = 'http://www.example.com/' if url in exclusion_list: opener = no_proxy_opener else: opener = default_proxy_opener page = opener.open(url) print page Your biggest problem will be matching the url to the exclusion list, but that's a whole new question.
How can I apply authenticated proxy exceptions to an opener using urllib2?
When using urllib2 (and maybe urllib) on windows python seems to magically pick up the authenticated proxy setting applied to InternetExplorer. However, it doesn't seem to check and process the Advance setting "Exceptions" list. Is there a way I can get it to process the exceptions list? Or, ignore the IE proxy setting and apply my own proxy opener to address this issue? I played with creating a proxy opener before, but couldn't get it to work. Here's what I managed to dig out, but I still don't see how/where to apply any exceptions and I'm not even sure if this is right: proxy_info = { 'host':'myproxy.com', 'user':Username, 'pass':Password, 'port':1080 } http_str = "http://%(user)s:%(pass)s@%(host)s:%(port)d" % proxy_info authInfo = urllib2.HTTPBasicAuthHandler() authInfo.add_password() proxy_dict = {'http':http_str} proxyHandler = urllib2.ProxyHandler(proxy_dict) # apply the handler to an opener proxy_opener = urllib2.build_opener(proxyHandler, urllib2.HTTPHandler) urllib2.install_opener(proxy_opener)
[ "By default urllib2 gets the proxy settings from the environment variable, which is why it is using the IE settings. This is very handy, because you don't need to setup authentication yourself.\nYou can't apply exceptions like you want to, the easiest way to do this would be to have two openers and decide which one to use depending on whether the domain is in your exception list or not.\nUse the default opener for when you want to use the proxy, and one without a proxy for when you don't need it:\n>>> no_proxy = urllib2.ProxyHandler({})\n>>> opener = urllib2.build_opener(no_proxy)\n>>> urllib2.install_opener(opener)\n\nFrom here.\nEdit:\nHere's how I'd do it:\nexclusion_list = ['http://www.google.com/', 'http://localhost/']\n\nno_proxy = urllib2.ProxyHandler({})\nno_proxy_opener = urllib2.build_opener(no_proxy)\n\ndefault_proxy_opener = urllib2.build_opener()\n\nurl = 'http://www.example.com/'\n\nif url in exclusion_list:\n opener = no_proxy_opener\nelse:\n opener = default_proxy_opener\n\npage = opener.open(url)\nprint page\n\nYour biggest problem will be matching the url to the exclusion list, but that's a whole new question.\n" ]
[ 2 ]
[]
[]
[ "proxy", "python", "windows" ]
stackoverflow_0000270983_proxy_python_windows.txt
Q: Replacing multiple occurrences in nested arrays I've got this python dictionary "mydict", containing arrays, here's what it looks like : mydict = dict( one=['foo', 'bar', 'foobar', 'barfoo', 'example'], two=['bar', 'example', 'foobar'], three=['foo', 'example']) i'd like to replace all the occurrences of "example" by "someotherword". While I can already think of a few ways to do it, is there a most "pythonic" method to achieve this ? A: for arr in mydict.values(): for i, s in enumerate(arr): if s == 'example': arr[i] = 'someotherword' A: If you want to leave the original untouched, and just return a new dictionary with the modifications applied, you can use: replacements = {'example' : 'someotherword'} newdict = dict((k, [replacements.get(x,x) for x in v]) for (k,v) in mydict.iteritems()) This also has the advantage that its easy to extend with new words just by adding them to the replacements dict. If you want to mutate an existing dict in place, you can use the same approach: for l in mydict.values(): l[:]=[replacements.get(x,x) for x in l] However it's probably going to be slower than J.F Sebastian's solution, as it rebuilds the whole list rather than just modifying the changed elements in place. A: Here's another take: for key, val in mydict.items(): mydict[key] = ["someotherword" if x == "example" else x for x in val] I've found that building lists is very fast, but of course profile if performance is important.
Replacing multiple occurrences in nested arrays
I've got this python dictionary "mydict", containing arrays, here's what it looks like : mydict = dict( one=['foo', 'bar', 'foobar', 'barfoo', 'example'], two=['bar', 'example', 'foobar'], three=['foo', 'example']) i'd like to replace all the occurrences of "example" by "someotherword". While I can already think of a few ways to do it, is there a most "pythonic" method to achieve this ?
[ "for arr in mydict.values():\n for i, s in enumerate(arr):\n if s == 'example':\n arr[i] = 'someotherword'\n\n", "If you want to leave the original untouched, and just return a new dictionary with the modifications applied, you can use:\nreplacements = {'example' : 'someotherword'}\n\nnewdict = dict((k, [replacements.get(x,x) for x in v]) \n for (k,v) in mydict.iteritems())\n\nThis also has the advantage that its easy to extend with new words just by adding them to the replacements dict. If you want to mutate an existing dict in place, you can use the same approach:\nfor l in mydict.values():\n l[:]=[replacements.get(x,x) for x in l]\n\nHowever it's probably going to be slower than J.F Sebastian's solution, as it rebuilds the whole list rather than just modifying the changed elements in place.\n", "Here's another take:\nfor key, val in mydict.items():\n mydict[key] = [\"someotherword\" if x == \"example\" else x for x in val]\n\nI've found that building lists is very fast, but of course profile if performance is important.\n" ]
[ 2, 2, 1 ]
[]
[]
[ "arrays", "dictionary", "python", "replace" ]
stackoverflow_0000268891_arrays_dictionary_python_replace.txt
Q: How to scan a webpage and get images and youtube embeds? I am building a web app where I need to get all the images and any flash videos that are embedded (e.g. youtube) on a given URL. I'm using Python. I've googled, but have not found any good information about this (probably because I don't know what this is called to search for), does anyone have any experience with this and knows how it can be done? I'd love to see some code examples if there are any available. Thanks! A: BeautifulSoup is a great screen-scraping library. Use urllib2 to fetch the page, and BeautifulSoup to parse it apart. Here's a code sample from their docs: import urllib2 from BeautifulSoup import BeautifulSoup page = urllib2.urlopen("http://www.icc-ccs.org/prc/piracyreport.php") soup = BeautifulSoup(page) for incident in soup('td', width="90%"): where, linebreak, what = incident.contents[:3] print where.strip() print what.strip() print
How to scan a webpage and get images and youtube embeds?
I am building a web app where I need to get all the images and any flash videos that are embedded (e.g. youtube) on a given URL. I'm using Python. I've googled, but have not found any good information about this (probably because I don't know what this is called to search for), does anyone have any experience with this and knows how it can be done? I'd love to see some code examples if there are any available. Thanks!
[ "BeautifulSoup is a great screen-scraping library. Use urllib2 to fetch the page, and BeautifulSoup to parse it apart. Here's a code sample from their docs:\nimport urllib2\nfrom BeautifulSoup import BeautifulSoup\n\npage = urllib2.urlopen(\"http://www.icc-ccs.org/prc/piracyreport.php\")\nsoup = BeautifulSoup(page)\nfor incident in soup('td', width=\"90%\"):\n where, linebreak, what = incident.contents[:3]\n print where.strip()\n print what.strip()\n print\n\n" ]
[ 7 ]
[]
[]
[ "python", "screen_scraping", "web_applications" ]
stackoverflow_0000271855_python_screen_scraping_web_applications.txt
Q: What mime-type should I return for a python string I have a web API that returns python dictionaries or lists as a response that I eval() in python scripts that use the API, for completness I wanted to set a proper content-type but not sure what would be best to use "text/x-python" or maybe "application/python", or something else? [edit] I'm also outputting JSON, I'm doing Python as an option mainly for internal use.[/edit] A: I doubt there's an established MIME type. Have you considered using JSON instead, it is almost the same as a Python dict, and has a better established culture of tools and techniques. A: The authoritative registry is at IANA and, no, there is no standard subtype for Python. So, do not use type like "application/python" but you may use private subtypes such as "text/x-python" (the one I find in the mime-support package on my Debian).
What mime-type should I return for a python string
I have a web API that returns python dictionaries or lists as a response that I eval() in python scripts that use the API, for completness I wanted to set a proper content-type but not sure what would be best to use "text/x-python" or maybe "application/python", or something else? [edit] I'm also outputting JSON, I'm doing Python as an option mainly for internal use.[/edit]
[ "I doubt there's an established MIME type. Have you considered using JSON instead, it is almost the same as a Python dict, and has a better established culture of tools and techniques.\n", "The authoritative registry is at IANA and, no, there is no standard subtype for Python. So, do not use type like \"application/python\" but you may use private subtypes such as \"text/x-python\" (the one I find in the mime-support package on my Debian).\n" ]
[ 8, 3 ]
[]
[]
[ "http", "mime_types", "python" ]
stackoverflow_0000269292_http_mime_types_python.txt
Q: "File -X: does not exist" message from ipy.exe in Windows PowerShell If I type this line in an MS-DOS command prompt window: ipy -X:ColorfulConsole IronPython starts up as expected with the colorful console option enabled. However, if I type the same line in Windows PowerShell I get the message: File -X: does not exist Can someone explain what I'm doing wrong? A: Try this code: ipy '-X:ColorfulConsole' Or whatever quoting mechanism is supported in Windows PowerShell - the shell is splitting your argument. Typing ipy -X: ColorfulConsole in MS-DOS command prompt window returns the same response: File -X: does not exist.
"File -X: does not exist" message from ipy.exe in Windows PowerShell
If I type this line in an MS-DOS command prompt window: ipy -X:ColorfulConsole IronPython starts up as expected with the colorful console option enabled. However, if I type the same line in Windows PowerShell I get the message: File -X: does not exist Can someone explain what I'm doing wrong?
[ "Try this code:\nipy '-X:ColorfulConsole'\n\nOr whatever quoting mechanism is supported in Windows PowerShell - the shell is splitting your argument. \nTyping\nipy -X: ColorfulConsole\n\nin MS-DOS command prompt window returns the same response:\nFile -X: does not exist.\n" ]
[ 5 ]
[]
[]
[ "ironpython", "powershell", "python" ]
stackoverflow_0000272233_ironpython_powershell_python.txt
Q: User Authentication in Django is there any way of making sure that, one user is logged in only once? I would like to avoid two different persons logging into the system with the same login/password. I guess I could do it myself by checking in the django_session table before logging in the user, but I rather prefer using the framework, if there is already such functionality. Cheers, Thanks for the responses! A: Logged in twice is ambiguous over HTTP. There's no "disconnecting" signal that's sent. You can frustrate people if you're not careful. If I shut down my browser and drop the cookies -- accidentally -- I might be prevented from logging in again. How would the server know it was me trying to re-login vs. me trying to login twice? You can try things like checking the IP address. And what if the accidental disconnect was my router crashing, releasing my DHCP lease? Now I'm trying to re-login, but I have a new address and no established cookie. I'm not trying to create a second session, I'm just trying to get back on after my current session got disconnected. the point is that there's no well-established rule for "single session" that can be installed in a framework. You have to make up a rule appropriate to your application and figure out how to enforce it. A: A site I did last year was concerned that usernames/passwords might be posted to a forum. I dealt with this by adding a model and a check to the login view that looked at how many unique IPs the name had been used from in the last X hours. I gave the site admins two values in settings.py to adjust the number of hours and the number of unique IPs. If a name was being "overused" it was blocked for logins from new IPs until enough time had passed to fall below the threshold. Much to their surprise, they have had only one name trigger the blocking in the last year and that turned out to be the company president who was on a business trip and kept logging in from new locations. Ps. The code is straightforward. Email me at peter at techbuddy dot us if you would like it.
User Authentication in Django
is there any way of making sure that, one user is logged in only once? I would like to avoid two different persons logging into the system with the same login/password. I guess I could do it myself by checking in the django_session table before logging in the user, but I rather prefer using the framework, if there is already such functionality. Cheers, Thanks for the responses!
[ "Logged in twice is ambiguous over HTTP. There's no \"disconnecting\" signal that's sent. You can frustrate people if you're not careful.\nIf I shut down my browser and drop the cookies -- accidentally -- I might be prevented from logging in again. \nHow would the server know it was me trying to re-login vs. me trying to login twice? \nYou can try things like checking the IP address. And what if the accidental disconnect was my router crashing, releasing my DHCP lease? Now I'm trying to re-login, but I have a new address and no established cookie. I'm not trying to create a second session, I'm just trying to get back on after my current session got disconnected.\nthe point is that there's no well-established rule for \"single session\" that can be installed in a framework. You have to make up a rule appropriate to your application and figure out how to enforce it.\n", "A site I did last year was concerned that usernames/passwords might be posted to a forum. I dealt with this by adding a model and a check to the login view that looked at how many unique IPs the name had been used from in the last X hours. I gave the site admins two values in settings.py to adjust the number of hours and the number of unique IPs. If a name was being \"overused\" it was blocked for logins from new IPs until enough time had passed to fall below the threshold.\nMuch to their surprise, they have had only one name trigger the blocking in the last year and that turned out to be the company president who was on a business trip and kept logging in from new locations.\nPs. The code is straightforward. Email me at peter at techbuddy dot us if you would like it.\n" ]
[ 5, 4 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000272042_django_python.txt
Q: Python memory debugging with GDB We have a Linux application that makes use of OpenSSL's Python bindings and I suspect it is causing random crashes. Occasionally, we see it crash with the message: Python Fatal Error: GC Object already tracked which would appear to be either a programming error on the part of the library, or a symptom of memory corruption. Is there any way to know the last line of Python source code it executed, given a core file? Or if it is attached in GDB? I realize it is probably all compiled bytecode, but I'm hoping there someone out there may have dealt with this. Currently it is running with the trace module active and we're hoping it will happen again, but it could be a long while. A: Yes, you can do this kind of thing: (gdb) print PyRun_SimpleString("import traceback; traceback.print_stack()") File "<string>", line 1, in <module> File "/var/tmp/foo.py", line 2, in <module> i**2 File "<string>", line 1, in <module> $1 = 0 It should also be possible to use the pystack command defined in the python gdbinit file, but it's not working for me. It's discussed here if you want to look into it. Also, if you suspect memory issues, it's worth noting that you can use valgrind with python, if you're prepared to recompile it. The procedure is described here. A: If you have mac or sun box kicking around you could use dtrace and a version of python compiled with dtrace to figure out what the application was doing at the time. Note: in 10.5 python is pre-compiled with dtrace which is really nice and handy. If that isn't available to you, then you can import gc and enable debugging which you can then put out to a log file. To specifically answer your question regarding debugging with GDB you might want to read "Debugging With GDB" on the python wiki. A: If you're using CDLL to wrap a C library in python, and this is 64-bit linux, there's a good chance that you're CDLL wrapper is misconfigured. CDLL defaults to int return types on all platforms (should be a long long on 64-bit systems) and just expects you to pass the right arguments in. You may need to verify the CDLL wrapper in this case... A: In addition to all above one can quickly implement an adhoc tracer via the trace module.
Python memory debugging with GDB
We have a Linux application that makes use of OpenSSL's Python bindings and I suspect it is causing random crashes. Occasionally, we see it crash with the message: Python Fatal Error: GC Object already tracked which would appear to be either a programming error on the part of the library, or a symptom of memory corruption. Is there any way to know the last line of Python source code it executed, given a core file? Or if it is attached in GDB? I realize it is probably all compiled bytecode, but I'm hoping there someone out there may have dealt with this. Currently it is running with the trace module active and we're hoping it will happen again, but it could be a long while.
[ "Yes, you can do this kind of thing:\n(gdb) print PyRun_SimpleString(\"import traceback; traceback.print_stack()\")\n File \"<string>\", line 1, in <module>\n File \"/var/tmp/foo.py\", line 2, in <module>\n i**2\n File \"<string>\", line 1, in <module>\n$1 = 0\n\nIt should also be possible to use the pystack command defined in the python gdbinit file, but it's not working for me. It's discussed here if you want to look into it.\nAlso, if you suspect memory issues, it's worth noting that you can use valgrind with python, if you're prepared to recompile it. The procedure is described here.\n", "If you have mac or sun box kicking around you could use dtrace and a version of python compiled with dtrace to figure out what the application was doing at the time. Note: in 10.5 python is pre-compiled with dtrace which is really nice and handy.\nIf that isn't available to you, then you can import gc and enable debugging which you can then put out to a log file.\nTo specifically answer your question regarding debugging with GDB you might want to read \"Debugging With GDB\" on the python wiki.\n", "If you're using CDLL to wrap a C library in python, and this is 64-bit linux, there's a good chance that you're CDLL wrapper is misconfigured. CDLL defaults to int return types on all platforms (should be a long long on 64-bit systems) and just expects you to pass the right arguments in. You may need to verify the CDLL wrapper in this case...\n", "In addition to all above one can quickly implement an adhoc tracer via the trace module.\n" ]
[ 5, 1, 0, 0 ]
[]
[]
[ "debugging", "linux", "openssl", "python" ]
stackoverflow_0000273043_debugging_linux_openssl_python.txt
Q: Is there a Python library function which attempts to guess the character-encoding of some bytes? I'm writing some mail-processing software in Python that is encountering strange bytes in header fields. I suspect this is just malformed mail; the message itself claims to be us-ascii, so I don't think there is a true encoding, but I'd like to get out a unicode string approximating the original one without throwing a UnicodeDecodeError. So, I'm looking for a function that takes a str and optionally some hints and does its darndest to give me back a unicode. I could write one of course, but if such a function exists its author has probably thought a bit deeper about the best way to go about this. I also know that Python's design prefers explicit to implicit and that the standard library is designed to avoid implicit magic in decoding text. I just want to explicitly say "go ahead and guess". A: +1 for the chardet module (suggested by @insin). It is not in the standard library, but you can easily install it with the following command: $ pip install chardet Example: >>> import chardet >>> import urllib >>> detect = lambda url: chardet.detect(urllib.urlopen(url).read()) >>> detect('http://stackoverflow.com') {'confidence': 0.85663169917190185, 'encoding': 'ISO-8859-2'} >>> detect('https://stackoverflow.com/questions/269060/is-there-a-python-lib') {'confidence': 0.98999999999999999, 'encoding': 'utf-8'} See Installing Pip if you don't have one. A: As far as I can tell, the standard library doesn't have a function, though it's not too difficult to write one as suggested above. I think the real thing I was looking for was a way to decode a string and guarantee that it wouldn't throw an exception. The errors parameter to string.decode does that. def decode(s, encodings=('ascii', 'utf8', 'latin1')): for encoding in encodings: try: return s.decode(encoding) except UnicodeDecodeError: pass return s.decode('ascii', 'ignore') A: The best way to do this that I've found is to iteratively try decoding a prospective with each of the most common encodings inside of a try except block.
Is there a Python library function which attempts to guess the character-encoding of some bytes?
I'm writing some mail-processing software in Python that is encountering strange bytes in header fields. I suspect this is just malformed mail; the message itself claims to be us-ascii, so I don't think there is a true encoding, but I'd like to get out a unicode string approximating the original one without throwing a UnicodeDecodeError. So, I'm looking for a function that takes a str and optionally some hints and does its darndest to give me back a unicode. I could write one of course, but if such a function exists its author has probably thought a bit deeper about the best way to go about this. I also know that Python's design prefers explicit to implicit and that the standard library is designed to avoid implicit magic in decoding text. I just want to explicitly say "go ahead and guess".
[ "+1 for the chardet module (suggested by @insin).\nIt is not in the standard library, but you can easily install it with the following command:\n$ pip install chardet\n\nExample:\n>>> import chardet\n>>> import urllib\n>>> detect = lambda url: chardet.detect(urllib.urlopen(url).read())\n>>> detect('http://stackoverflow.com')\n{'confidence': 0.85663169917190185, 'encoding': 'ISO-8859-2'} \n>>> detect('https://stackoverflow.com/questions/269060/is-there-a-python-lib')\n{'confidence': 0.98999999999999999, 'encoding': 'utf-8'}\n\nSee Installing Pip if you don't have one.\n", "As far as I can tell, the standard library doesn't have a function, though it's not too difficult to write one as suggested above. I think the real thing I was looking for was a way to decode a string and guarantee that it wouldn't throw an exception. The errors parameter to string.decode does that.\ndef decode(s, encodings=('ascii', 'utf8', 'latin1')):\n for encoding in encodings:\n try:\n return s.decode(encoding)\n except UnicodeDecodeError:\n pass\n return s.decode('ascii', 'ignore')\n\n", "The best way to do this that I've found is to iteratively try decoding a prospective with each of the most common encodings inside of a try except block.\n" ]
[ 27, 15, 1 ]
[]
[]
[ "character_encoding", "email", "invalid_characters", "python" ]
stackoverflow_0000269060_character_encoding_email_invalid_characters_python.txt
Q: Is there a cross-platform way of getting information from Python's OSError? On a simple directory creation operation for example, I can make an OSError like this: (Ubuntu Linux) >>> import os >>> os.mkdir('foo') >>> os.mkdir('foo') Traceback (most recent call last): File "<stdin>", line 1, in <module> OSError: [Errno 17] File exists: 'foo' Now I can catch that error like this: >>> import os >>> os.mkdir('foo') >>> try: ... os.mkdir('foo') ... except OSError, e: ... print e.args ... (17, 'File exists') Is there a cross-platform way that I can know that that the 17 or the 'File Exists' will always mean the same thing so that I can act differently depending on the situation? (This came up during another question.) A: The errno attribute on the error should be the same on all platforms. You will get WindowsError exceptions on Windows, but since this is a subclass of OSError the same "except OSError:" block will catch it. Windows does have its own error codes, and these are accessible as .winerror, but the .errno attribute should still be present, and usable in a cross-platform way. Symbolic names for the various error codes can be found in the errno module. For example, import os, errno try: os.mkdir('test') except OSError, e: if e.errno == errno.EEXIST: # Do something You can also perform the reverse lookup (to find out what code you should be using) with errno.errorcode. That is: >>> errno.errorcode[17] 'EEXIST'
Is there a cross-platform way of getting information from Python's OSError?
On a simple directory creation operation for example, I can make an OSError like this: (Ubuntu Linux) >>> import os >>> os.mkdir('foo') >>> os.mkdir('foo') Traceback (most recent call last): File "<stdin>", line 1, in <module> OSError: [Errno 17] File exists: 'foo' Now I can catch that error like this: >>> import os >>> os.mkdir('foo') >>> try: ... os.mkdir('foo') ... except OSError, e: ... print e.args ... (17, 'File exists') Is there a cross-platform way that I can know that that the 17 or the 'File Exists' will always mean the same thing so that I can act differently depending on the situation? (This came up during another question.)
[ "The errno attribute on the error should be the same on all platforms. You will get WindowsError exceptions on Windows, but since this is a subclass of OSError the same \"except OSError:\" block will catch it. Windows does have its own error codes, and these are accessible as .winerror, but the .errno attribute should still be present, and usable in a cross-platform way.\nSymbolic names for the various error codes can be found in the errno module.\nFor example,\nimport os, errno\ntry:\n os.mkdir('test')\nexcept OSError, e:\n if e.errno == errno.EEXIST:\n # Do something\n\nYou can also perform the reverse lookup (to find out what code you should be using) with errno.errorcode. That is:\n>>> errno.errorcode[17]\n'EEXIST'\n\n" ]
[ 60 ]
[]
[]
[ "cross_platform", "exception", "python" ]
stackoverflow_0000273698_cross_platform_exception_python.txt
Q: Python's os.execvp equivalent for PHP I've got a PHP command line program running. And I want to connect to a mysql shell straight from PHP. I've done this before in Python using os.execvp But I can't get the same thing to work in PHP. I've tried the following functions: system passthru exec shell_exec example: system('mysql -u root -pxxxx db_name'); But they all seem to wait for mysql to exit and return something. What I really want is for PHP to launch the mysql shell and then exit it self. any ideas? A: If you want shell commands to be interactive, use: system("mysql -uroot -p db_name > `tty`"); That will work for most cases, but will break if you aren't in a terminal. A: Give MySQL a script to run that's separate from the PHP script: system('mysql -u root -pxxxx db_name < script.mysql'); A: In addition to what acrosman said, you can also use the -e switch to pass SQL from the command line. $sql = "....."; system("mysql -u root -pxxxx db_name -e \"$sql\""); Also, I hope your not actually connecting to the database as root from a PHP application.
Python's os.execvp equivalent for PHP
I've got a PHP command line program running. And I want to connect to a mysql shell straight from PHP. I've done this before in Python using os.execvp But I can't get the same thing to work in PHP. I've tried the following functions: system passthru exec shell_exec example: system('mysql -u root -pxxxx db_name'); But they all seem to wait for mysql to exit and return something. What I really want is for PHP to launch the mysql shell and then exit it self. any ideas?
[ "If you want shell commands to be interactive, use:\nsystem(\"mysql -uroot -p db_name > `tty`\");\n\nThat will work for most cases, but will break if you aren't in a terminal.\n", "Give MySQL a script to run that's separate from the PHP script:\nsystem('mysql -u root -pxxxx db_name < script.mysql');\n\n", "In addition to what acrosman said, you can also use the -e switch to pass SQL from the command line.\n$sql = \".....\";\nsystem(\"mysql -u root -pxxxx db_name -e \\\"$sql\\\"\");\n\nAlso, I hope your not actually connecting to the database as root from a PHP application.\n" ]
[ 3, 0, 0 ]
[]
[]
[ "command_line_interface", "php", "python", "shell" ]
stackoverflow_0000272826_command_line_interface_php_python_shell.txt
Q: How do I Create an instance of a class in another class in Python I am trying to learn Python and WxPython. I have been a SAS programmer for years. This OOP stuff is slowly coming together but I am still fuzzy on a lot of the concepts. Below is a section of code. I am trying to use a button click to create an instance of another class. Specifically-I have my main panel in one class and I wanted to instance a secondary panel when a user clicked on one of the menu items on the main panel. I made all of this work when the secondary panel was just a function. I can't seem to get ti to work as a class. Here is the code import wx class mainPanel(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, 'directEDGAR Supplemental Tools', size=(450, 450)) wx.Panel(self,-1) wx.StaticText(self,-1, "This is where I will describe\n the purpose of these tools",(100,10)) menubar = wx.MenuBar() parser = wx.Menu() one =wx.MenuItem(parser,1,'&Extract Tables with One Heading or Label') two =wx.MenuItem(parser,1,'&Extract Tables with Two Headings or Labels') three =wx.MenuItem(parser,1,'&Extract Tables with Three Headings or Labels') four =wx.MenuItem(parser,1,'&Extract Tables with Four Headings or Labels') quit = wx.MenuItem(parser, 2, '&Quit\tCtrl+Q') parser.AppendItem(one) parser.AppendItem(two) parser.AppendItem(three) parser.AppendItem(four) parser.AppendItem(quit) menubar.Append(parser, '&Table Parsers') textRip = wx.Menu() section =wx.MenuItem(parser,1,'&Extract Text With Section Headings') textRip.AppendItem(section) menubar.Append(textRip, '&Text Rippers') dataHandling = wx.Menu() deHydrate =wx.MenuItem(dataHandling,1,'&Extract Data from Tables') dataHandling.AppendItem(deHydrate) menubar.Append(dataHandling, '&Data Extraction') self.Bind(wx.EVT_MENU, self.OnQuit, id=2) this is where I think I am being clever by using a button click to create an instance of subPanel. self.Bind(wx.EVT_MENU, self.subPanel(None, -1, 'TEST'),id=1) self.SetMenuBar(menubar) self.Centre() self.Show(True) def OnQuit(self, event): self.Close() class subPanel(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, 'directEDGAR Supplemental Tools', size=(450, 450)) wx.Panel(self,-1) wx.StaticText(self,-1, "This is where I will describe\n the purpose of these tools",(100,10)) getDirectory = wx.Button(panel, -1, "Get Directory Path", pos=(20,350)) getDirectory.SetDefault() getTerm1 = wx.Button(panel, -1, "Get Search Term", pos=(20,400)) getTerm1.SetDefault() #getDirectory.Bind(wx.EVT_BUTTON, getDirectory.OnClick, getDirectory.button) self.Centre() self.Show(True) app = wx.App() mainPanel(None, -1, '') app.MainLoop() A: I don't know wxWidgets, but based on what I know of Python, I'm guessing that you need to change: self.Bind(wx.EVT_MENU, self.subPanel(None, -1, 'TEST'),id=1) to: self.Bind(wx.EVT_MENU, subPanel(None, -1, 'TEST'),id=1) "subPanel" is a globally defined class, not a member of "self" (which is a mainPanel). Edit: Ah, "Bind" seems to bind an action to a function, so you need to give it a function that creates the other class. Try the following. It still doesn't work, but at least it now crashes during the subPanel creation. self.Bind(wx.EVT_MENU, lambda(x): subPanel(None, -1, 'TEST'),id=1) A: You should handle the button click event, and create the panel in your button handler (like you already do with your OnQuit method). I think the following code basically does what you're after -- creates a new Frame when the button is clicked/menu item is selected. import wx class MyFrame(wx.Frame): def __init__(self, parent, title="My Frame", num=1): self.num = num wx.Frame.__init__(self, parent, -1, title) panel = wx.Panel(self) button = wx.Button(panel, -1, "New Panel") button.SetPosition((15, 15)) self.Bind(wx.EVT_BUTTON, self.OnNewPanel, button) self.Bind(wx.EVT_CLOSE, self.OnCloseWindow) # Now create a menu menubar = wx.MenuBar() self.SetMenuBar(menubar) # Panel menu panel_menu = wx.Menu() # The menu item menu_newpanel = wx.MenuItem(panel_menu, wx.NewId(), "&New Panel", "Creates a new panel", wx.ITEM_NORMAL) panel_menu.AppendItem(menu_newpanel) menubar.Append(panel_menu, "&Panels") # Bind the menu event self.Bind(wx.EVT_MENU, self.OnNewPanel, menu_newpanel) def OnNewPanel(self, event): panel = MyFrame(self, "Panel %s" % self.num, self.num+1) panel.Show() def OnCloseWindow(self, event): self.Destroy() def main(): application = wx.PySimpleApp() frame = MyFrame(None) frame.Show() application.MainLoop() if __name__ == "__main__": main() Edit: Added code to do this from a menu. A: You need an event handler in your bind expression self.bind(wx.EVT_MENU, subPanel(None, -1, 'TEST'),id=1) needs to be changed to: self.bind(wx.EVT_MENU, <event handler>, <id of menu item>) where your event handler responds to the event and instantiates the subpanel: def OnMenuItem(self, evt): #don't forget the evt sp = SubPanel(self, wx.ID_ANY, 'TEST') #I assume you will add it to a sizer #if you aren't... you should test_sizer.Add(sp, 1, wx.EXPAND) #force the frame to refresh the sizers: self.Layout() Alternatively, you can instantiate the subpanel in your frame's __init__ and call a subpanel.Hide() after instantiation, and then your menuitem event handler and call a show on the panel subpanel.Show() Edit: Here is some code that will do what I think that you are asking: #!usr/bin/env python import wx class TestFrame(wx.Frame): def __init__(self, parent, *args, **kwargs): wx.Frame.__init__(self, parent, *args, **kwargs) framesizer = wx.BoxSizer(wx.VERTICAL) mainpanel = MainPanel(self, wx.ID_ANY) self.subpanel = SubPanel(self, wx.ID_ANY) self.subpanel.Hide() framesizer.Add(mainpanel, 1, wx.EXPAND) framesizer.Add(self.subpanel, 1, wx.EXPAND) self.SetSizerAndFit(framesizer) class MainPanel(wx.Panel): def __init__(self, parent, *args, **kwargs): wx.Panel.__init__(self, parent, *args, **kwargs) panelsizer = wx.BoxSizer(wx.VERTICAL) but = wx.Button(self, wx.ID_ANY, "Add") self.Bind(wx.EVT_BUTTON, self.OnAdd, but) self.panel_shown = False panelsizer.Add(but, 0) self.SetSizer(panelsizer) def OnAdd(self, evt): if not self.panel_shown: self.GetParent().subpanel.Show() self.GetParent().Fit() self.GetParent().Layout() self.panel_shown = True else: self.GetParent().subpanel.Hide() self.GetParent().Fit() self.GetParent().Layout() self.panel_shown = False class SubPanel(wx.Panel): def __init__(self, parent, *args, **kwargs): wx.Panel.__init__(self, parent, *args, **kwargs) spsizer = wx.BoxSizer(wx.VERTICAL) text = wx.StaticText(self, wx.ID_ANY, label='I am a subpanel') spsizer.Add(text, 1, wx.EXPAND) self.SetSizer(spsizer) if __name__ == '__main__': app = wx.App() frame = TestFrame(None, wx.ID_ANY, "Test Frame") frame.Show() app.MainLoop()
How do I Create an instance of a class in another class in Python
I am trying to learn Python and WxPython. I have been a SAS programmer for years. This OOP stuff is slowly coming together but I am still fuzzy on a lot of the concepts. Below is a section of code. I am trying to use a button click to create an instance of another class. Specifically-I have my main panel in one class and I wanted to instance a secondary panel when a user clicked on one of the menu items on the main panel. I made all of this work when the secondary panel was just a function. I can't seem to get ti to work as a class. Here is the code import wx class mainPanel(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, 'directEDGAR Supplemental Tools', size=(450, 450)) wx.Panel(self,-1) wx.StaticText(self,-1, "This is where I will describe\n the purpose of these tools",(100,10)) menubar = wx.MenuBar() parser = wx.Menu() one =wx.MenuItem(parser,1,'&Extract Tables with One Heading or Label') two =wx.MenuItem(parser,1,'&Extract Tables with Two Headings or Labels') three =wx.MenuItem(parser,1,'&Extract Tables with Three Headings or Labels') four =wx.MenuItem(parser,1,'&Extract Tables with Four Headings or Labels') quit = wx.MenuItem(parser, 2, '&Quit\tCtrl+Q') parser.AppendItem(one) parser.AppendItem(two) parser.AppendItem(three) parser.AppendItem(four) parser.AppendItem(quit) menubar.Append(parser, '&Table Parsers') textRip = wx.Menu() section =wx.MenuItem(parser,1,'&Extract Text With Section Headings') textRip.AppendItem(section) menubar.Append(textRip, '&Text Rippers') dataHandling = wx.Menu() deHydrate =wx.MenuItem(dataHandling,1,'&Extract Data from Tables') dataHandling.AppendItem(deHydrate) menubar.Append(dataHandling, '&Data Extraction') self.Bind(wx.EVT_MENU, self.OnQuit, id=2) this is where I think I am being clever by using a button click to create an instance of subPanel. self.Bind(wx.EVT_MENU, self.subPanel(None, -1, 'TEST'),id=1) self.SetMenuBar(menubar) self.Centre() self.Show(True) def OnQuit(self, event): self.Close() class subPanel(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, 'directEDGAR Supplemental Tools', size=(450, 450)) wx.Panel(self,-1) wx.StaticText(self,-1, "This is where I will describe\n the purpose of these tools",(100,10)) getDirectory = wx.Button(panel, -1, "Get Directory Path", pos=(20,350)) getDirectory.SetDefault() getTerm1 = wx.Button(panel, -1, "Get Search Term", pos=(20,400)) getTerm1.SetDefault() #getDirectory.Bind(wx.EVT_BUTTON, getDirectory.OnClick, getDirectory.button) self.Centre() self.Show(True) app = wx.App() mainPanel(None, -1, '') app.MainLoop()
[ "I don't know wxWidgets, but based on what I know of Python, I'm guessing that you need to change:\nself.Bind(wx.EVT_MENU, self.subPanel(None, -1, 'TEST'),id=1)\n\nto:\nself.Bind(wx.EVT_MENU, subPanel(None, -1, 'TEST'),id=1)\n\n\"subPanel\" is a globally defined class, not a member of \"self\" (which is a mainPanel).\nEdit: Ah, \"Bind\" seems to bind an action to a function, so you need to give it a function that creates the other class. Try the following. It still doesn't work, but at least it now crashes during the subPanel creation.\nself.Bind(wx.EVT_MENU, lambda(x): subPanel(None, -1, 'TEST'),id=1)\n\n", "You should handle the button click event, and create the panel in your button handler (like you already do with your OnQuit method).\nI think the following code basically does what you're after -- creates a new Frame when the button is clicked/menu item is selected.\nimport wx\n\nclass MyFrame(wx.Frame):\n def __init__(self, parent, title=\"My Frame\", num=1):\n\n self.num = num\n wx.Frame.__init__(self, parent, -1, title)\n panel = wx.Panel(self)\n\n button = wx.Button(panel, -1, \"New Panel\")\n button.SetPosition((15, 15))\n self.Bind(wx.EVT_BUTTON, self.OnNewPanel, button)\n self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)\n\n # Now create a menu\n menubar = wx.MenuBar()\n self.SetMenuBar(menubar)\n\n # Panel menu\n panel_menu = wx.Menu()\n\n # The menu item\n menu_newpanel = wx.MenuItem(panel_menu,\n wx.NewId(),\n \"&New Panel\",\n \"Creates a new panel\",\n wx.ITEM_NORMAL)\n panel_menu.AppendItem(menu_newpanel)\n\n menubar.Append(panel_menu, \"&Panels\")\n # Bind the menu event\n self.Bind(wx.EVT_MENU, self.OnNewPanel, menu_newpanel)\n\n def OnNewPanel(self, event):\n panel = MyFrame(self, \"Panel %s\" % self.num, self.num+1)\n panel.Show()\n\n def OnCloseWindow(self, event):\n self.Destroy()\n\ndef main():\n application = wx.PySimpleApp()\n frame = MyFrame(None)\n frame.Show()\n application.MainLoop()\n\nif __name__ == \"__main__\":\n main()\n\n\nEdit: Added code to do this from a menu.\n", "You need an event handler in your bind expression\nself.bind(wx.EVT_MENU, subPanel(None, -1, 'TEST'),id=1)\n\nneeds to be changed to:\nself.bind(wx.EVT_MENU, <event handler>, <id of menu item>)\n\nwhere your event handler responds to the event and instantiates the subpanel:\ndef OnMenuItem(self, evt): #don't forget the evt\n sp = SubPanel(self, wx.ID_ANY, 'TEST')\n #I assume you will add it to a sizer\n #if you aren't... you should\n test_sizer.Add(sp, 1, wx.EXPAND)\n #force the frame to refresh the sizers:\n self.Layout()\n\nAlternatively, you can instantiate the subpanel in your frame's __init__ and call a subpanel.Hide() after instantiation, and then your menuitem event handler and call a show on the panel subpanel.Show()\nEdit: Here is some code that will do what I think that you are asking:\n#!usr/bin/env python\n\nimport wx\n\nclass TestFrame(wx.Frame):\n def __init__(self, parent, *args, **kwargs):\n wx.Frame.__init__(self, parent, *args, **kwargs)\n framesizer = wx.BoxSizer(wx.VERTICAL)\n mainpanel = MainPanel(self, wx.ID_ANY)\n self.subpanel = SubPanel(self, wx.ID_ANY)\n self.subpanel.Hide()\n framesizer.Add(mainpanel, 1, wx.EXPAND)\n framesizer.Add(self.subpanel, 1, wx.EXPAND)\n self.SetSizerAndFit(framesizer)\n\nclass MainPanel(wx.Panel):\n def __init__(self, parent, *args, **kwargs):\n wx.Panel.__init__(self, parent, *args, **kwargs)\n panelsizer = wx.BoxSizer(wx.VERTICAL)\n but = wx.Button(self, wx.ID_ANY, \"Add\")\n self.Bind(wx.EVT_BUTTON, self.OnAdd, but)\n self.panel_shown = False\n panelsizer.Add(but, 0)\n self.SetSizer(panelsizer)\n\n def OnAdd(self, evt):\n if not self.panel_shown:\n self.GetParent().subpanel.Show()\n self.GetParent().Fit()\n self.GetParent().Layout()\n self.panel_shown = True\n else:\n self.GetParent().subpanel.Hide()\n self.GetParent().Fit()\n self.GetParent().Layout()\n self.panel_shown = False\n\nclass SubPanel(wx.Panel):\n def __init__(self, parent, *args, **kwargs):\n wx.Panel.__init__(self, parent, *args, **kwargs)\n spsizer = wx.BoxSizer(wx.VERTICAL)\n text = wx.StaticText(self, wx.ID_ANY, label='I am a subpanel')\n spsizer.Add(text, 1, wx.EXPAND)\n self.SetSizer(spsizer)\n\nif __name__ == '__main__':\n app = wx.App()\n frame = TestFrame(None, wx.ID_ANY, \"Test Frame\")\n frame.Show()\n app.MainLoop()\n\n" ]
[ 1, 1, 0 ]
[]
[]
[ "oop", "python", "wxpython" ]
stackoverflow_0000273937_oop_python_wxpython.txt
Q: UTF-8 latin-1 conversion issues, python django ok so my issue is i have the string '\222\222\223\225' which is stored as latin-1 in the db. What I get from django (by printing it) is the following string, 'ââââ¢' which I assume is the UTF conversion of it. Now I need to pass the string into a function that does this operation: strdecryptedPassword + chr(ord(c) - 3 - intCounter - 30) I get this error: chr() arg not in range(256) If I try to encode the string as latin-1 first I get this error: 'latin-1' codec can't encode characters in position 0-3: ordinal not in range(256) I have read a bunch on how character encoding works, and there is something I am missing because I just don't get it! A: Your first error 'chr() arg not in range(256)' probably means you have underflowed the value, because chr cannot take negative numbers. I don't know what the encryption algorithm is supposed to do when the inputcounter + 33 is more than the actual character representation, you'll have to check what to do in that case. About the second error. you must decode() and not encode() a regular string object to get a proper representation of your data. encode() takes a unicode object (those starting with u') and generates a regular string to be output or written to a file. decode() takes a string object and generate a unicode object with the corresponding code points. This is done with the unicode() call when generated from a string object, you could also call a.decode('latin-1') instead. >>> a = '\222\222\223\225' >>> u = unicode(a,'latin-1') >>> u u'\x92\x92\x93\x95' >>> print u.encode('utf-8')  >>> print u.encode('utf-16') ÿþ >>> print u.encode('latin-1') >>> for c in u: ... print chr(ord(c) - 3 - 0 -30) ... q q r t >>> for c in u: ... print chr(ord(c) - 3 -200 -30) ... Traceback (most recent call last): File "<stdin>", line 2, in <module> ValueError: chr() arg not in range(256) A: As Vinko notes, Latin-1 or ISO 8859-1 doesn't have printable characters for the octal string you quote. According to my notes for 8859-1, "C1 Controls (0x80 - 0x9F) are from ISO/IEC 6429:1992. It does not define names for 80, 81, or 99". The code point names are as Vinko lists them: \222 = 0x92 => PRIVATE USE TWO \223 = 0x93 => SET TRANSMIT STATE \225 = 0x95 => MESSAGE WAITING The correct UTF-8 encoding of those is (Unicode, binary, hex): U+0092 = %11000010 %10010010 = 0xC2 0x92 U+0093 = %11000010 %10010011 = 0xC2 0x93 U+0095 = %11000010 %10010101 = 0xC2 0x95 The LATIN SMALL LETTER A WITH CIRCUMFLEX is ISO 8859-1 code 0xE2 and hence Unicode U+00E2; in UTF-8, that is %11000011 %10100010 or 0xC3 0xA2. The CENT SIGN is ISO 8859-1 code 0xA2 and hence Unicode U+00A2; in UTF-8, that is %11000011 %10000010 or 0xC3 0x82. So, whatever else you are seeing, you do not seem to be seeing a UTF-8 encoding of ISO 8859-1. All else apart, you are seeing but 5 bytes where you would have to see 8. Added: The previous part of the answer addresses the 'UTF-8 encoding' claim, but ignores the rest of the question, which says: Now I need to pass the string into a function that does this operation: strdecryptedPassword + chr(ord(c) - 3 - intCounter - 30) I get this error: chr() arg not in range(256). If I try to encode the string as Latin-1 first I get this error: 'latin-1' codec can't encode characters in position 0-3: ordinal not in range(256). You don't actually show us how intCounter is defined, but if it increments gently per character, sooner or later 'ord(c) - 3 - intCounter - 30' is going to be negative (and, by the way, why not combine the constants and use 'ord(c) - intCounter - 33'?), at which point, chr() is likely to complain. You would need to add 256 if the value is negative, or use a modulus operation to ensure you have a positive value between 0 and 255 to pass to chr(). Since we can't see how intCounter is incremented, we can't tell if it cycles from 0 to 255 or whether it increases monotonically. If the latter, then you need an expression such as: chr(mod(ord(c) - mod(intCounter, 255) + 479, 255)) where 256 - 33 = 223, of course, and 479 = 256 + 223. This guarantees that the value passed to chr() is positive and in the range 0..255 for any input character c and any value of intCounter (and, because the mod() function never gets a negative argument, it also works regardless of how mod() behaves when its arguments are negative). A: Well its because its been encrypted with some terrible scheme that just changes the ord() of the character by some request, so the string coming out of the database has been encrypted and this decrypts it. What you supplied above does not seem to work. In the database it is latin-1, django converts it to unicode, but I cannot pass it to the function as unicode, but when i try and encode it to latin-1 i see that error.
UTF-8 latin-1 conversion issues, python django
ok so my issue is i have the string '\222\222\223\225' which is stored as latin-1 in the db. What I get from django (by printing it) is the following string, 'ââââ¢' which I assume is the UTF conversion of it. Now I need to pass the string into a function that does this operation: strdecryptedPassword + chr(ord(c) - 3 - intCounter - 30) I get this error: chr() arg not in range(256) If I try to encode the string as latin-1 first I get this error: 'latin-1' codec can't encode characters in position 0-3: ordinal not in range(256) I have read a bunch on how character encoding works, and there is something I am missing because I just don't get it!
[ "Your first error 'chr() arg not in range(256)' probably means you have underflowed the value, because chr cannot take negative numbers. I don't know what the encryption algorithm is supposed to do when the inputcounter + 33 is more than the actual character representation, you'll have to check what to do in that case.\nAbout the second error. you must decode() and not encode() a regular string object to get a proper representation of your data. encode() takes a unicode object (those starting with u') and generates a regular string to be output or written to a file. decode() takes a string object and generate a unicode object with the corresponding code points. This is done with the unicode() call when generated from a string object, you could also call a.decode('latin-1') instead.\n>>> a = '\\222\\222\\223\\225'\n>>> u = unicode(a,'latin-1')\n>>> u\nu'\\x92\\x92\\x93\\x95'\n>>> print u.encode('utf-8')\nÂÂÂÂ\n>>> print u.encode('utf-16')\nÿþ\n>>> print u.encode('latin-1')\n\n>>> for c in u:\n... print chr(ord(c) - 3 - 0 -30)\n...\nq\nq\nr\nt\n>>> for c in u:\n... print chr(ord(c) - 3 -200 -30)\n...\nTraceback (most recent call last):\n File \"<stdin>\", line 2, in <module>\nValueError: chr() arg not in range(256)\n\n", "As Vinko notes, Latin-1 or ISO 8859-1 doesn't have printable characters for the octal string you quote. According to my notes for 8859-1, \"C1 Controls (0x80 - 0x9F) are from ISO/IEC 6429:1992. It does not define names for 80, 81, or 99\". The code point names are as Vinko lists them:\n\\222 = 0x92 => PRIVATE USE TWO\n\\223 = 0x93 => SET TRANSMIT STATE\n\\225 = 0x95 => MESSAGE WAITING\n\nThe correct UTF-8 encoding of those is (Unicode, binary, hex):\nU+0092 = %11000010 %10010010 = 0xC2 0x92\nU+0093 = %11000010 %10010011 = 0xC2 0x93\nU+0095 = %11000010 %10010101 = 0xC2 0x95\n\nThe LATIN SMALL LETTER A WITH CIRCUMFLEX is ISO 8859-1 code 0xE2 and hence Unicode U+00E2; in UTF-8, that is %11000011 %10100010 or 0xC3 0xA2.\nThe CENT SIGN is ISO 8859-1 code 0xA2 and hence Unicode U+00A2; in UTF-8, that is %11000011 %10000010 or 0xC3 0x82.\nSo, whatever else you are seeing, you do not seem to be seeing a UTF-8 encoding of ISO 8859-1. All else apart, you are seeing but 5 bytes where you would have to see 8.\nAdded:\nThe previous part of the answer addresses the 'UTF-8 encoding' claim, but ignores the rest of the question, which says:\nNow I need to pass the string into a function that does this operation:\n\n strdecryptedPassword + chr(ord(c) - 3 - intCounter - 30)\n\nI get this error: chr() arg not in range(256). If I try to encode the\nstring as Latin-1 first I get this error: 'latin-1' codec can't encode\ncharacters in position 0-3: ordinal not in range(256).\n\nYou don't actually show us how intCounter is defined, but if it increments gently per character, sooner or later 'ord(c) - 3 - intCounter - 30' is going to be negative (and, by the way, why not combine the constants and use 'ord(c) - intCounter - 33'?), at which point, chr() is likely to complain. You would need to add 256 if the value is negative, or use a modulus operation to ensure you have a positive value between 0 and 255 to pass to chr(). Since we can't see how intCounter is incremented, we can't tell if it cycles from 0 to 255 or whether it increases monotonically. If the latter, then you need an expression such as:\nchr(mod(ord(c) - mod(intCounter, 255) + 479, 255))\n\nwhere 256 - 33 = 223, of course, and 479 = 256 + 223. This guarantees that the value passed to chr() is positive and in the range 0..255 for any input character c and any value of intCounter (and, because the mod() function never gets a negative argument, it also works regardless of how mod() behaves when its arguments are negative).\n", "Well its because its been encrypted with some terrible scheme that just changes the ord() of the character by some request, so the string coming out of the database has been encrypted and this decrypts it. What you supplied above does not seem to work. In the database it is latin-1, django converts it to unicode, but I cannot pass it to the function as unicode, but when i try and encode it to latin-1 i see that error.\n" ]
[ 4, 2, 0 ]
[]
[]
[ "character_encoding", "django", "python", "utf_8" ]
stackoverflow_0000274361_character_encoding_django_python_utf_8.txt
Q: What is the regular expression for /urlchecker/http://www.google.com I'm writing a url rewrite in django that when a person goes to http://mysite.com/urlchecker/http://www.google.com it sends the url: http://ww.google.com to a view as a string variable. I tried doing: (r'^urlchecker/(?P<url>\w+)/$', 'mysite.main.views.urlchecker'), But that didn't work. Anyone know what I'm doing wrong? Also, generally is there a good resource to learn regular expressions specifically for python/django? Thanks guys! A: Try this instead: (r'^urlchecker/(?P<url>.+)$', 'mysite.main.views.urlchecker'), This differs from yours in that: It will take anything after 'urlcheck/', not just "word" characters. It does not force the url to end in a slash. A: I just learned something while grazing the Hidden Features of Python thread. Python's re compiler has a debug mode! (Who knew? Well, apparently someone did :-) Anyway, it's worth a read.
What is the regular expression for /urlchecker/http://www.google.com
I'm writing a url rewrite in django that when a person goes to http://mysite.com/urlchecker/http://www.google.com it sends the url: http://ww.google.com to a view as a string variable. I tried doing: (r'^urlchecker/(?P<url>\w+)/$', 'mysite.main.views.urlchecker'), But that didn't work. Anyone know what I'm doing wrong? Also, generally is there a good resource to learn regular expressions specifically for python/django? Thanks guys!
[ "Try this instead:\n(r'^urlchecker/(?P<url>.+)$', 'mysite.main.views.urlchecker'),\nThis differs from yours in that:\n\nIt will take anything after 'urlcheck/', not just \"word\" characters.\nIt does not force the url to end in a slash.\n\n", "I just learned something while grazing the Hidden Features of Python thread.\nPython's re compiler has a debug mode! (Who knew? Well, apparently someone did :-) Anyway, it's worth a read.\n" ]
[ 2, 0 ]
[]
[]
[ "django", "python", "regex" ]
stackoverflow_0000275109_django_python_regex.txt
Q: How do you get a thumbnail of a movie using IMDbPy? Using IMDbPy it is painfully easy to access movies from the IMDB site: import imdb access = imdb.IMDb() movie = access.get_movie(3242) # random ID print "title: %s year: %s" % (movie['title'], movie['year']) However I see no way to get the picture or thumbnail of the movie cover. Suggestions? A: Note: Not every movie has a cover url. (The random ID in your example doesn't.) Make sure you're using an up-to-date version of IMDbPy. (IMDb changes, and IMDbPy with it.) ... import imdb access = imdb.IMDb() movie = access.get_movie(1132626) print "title: %s year: %s" % (movie['title'], movie['year']) print "Cover url: %s" % movie['cover url'] If for some reason you can't use the above, you can always use something like BeautifulSoup to get the cover url. from BeautifulSoup import BeautifulSoup import imdb access = imdb.IMDb() movie = access.get_movie(1132626) page = urllib2.urlopen(access.get_imdbURL(movie)) soup = BeautifulSoup(page) cover_div = soup.find(attrs={"class" : "photo"}) cover_url = (photo_div.find('img'))['src'] print "Cover url: %s" % cover_url A: Response from the IMDbPy mailing list: If present, the url is accessible through movie['cover url']. Beware that it could be missing, so you must first test it with something like: if 'cover url' in movie: ... After that, you can use the urllib module to fetch the image itself. To provide a complete example, something like that should do the trick: import urllib from imdb import IMDb ia = IMDb(#yourParameters) movie = ia.get_movie(#theMovieID) if 'cover url' in movie: urlObj = urllib.urlopen(movie['cover url']) imageData = urlObj.read() urlObj.close() # now you can save imageData in a file (open it in binary mode). In the same way, a person's headshot is stored in person['headshot']. Things to be aware of: covers and headshots are available only fetching the data from the web server (via the 'http' or 'mobile' data access systems), and not in the plain text data files ('sql' or 'local'). using the images, you must respect the terms of the IMDb's policy; see http://imdbpy.sourceforge.net/docs/DISCLAIMER.txt the images you'll get will vary in size; you can use the python-imaging module to rescale them, if needed.
How do you get a thumbnail of a movie using IMDbPy?
Using IMDbPy it is painfully easy to access movies from the IMDB site: import imdb access = imdb.IMDb() movie = access.get_movie(3242) # random ID print "title: %s year: %s" % (movie['title'], movie['year']) However I see no way to get the picture or thumbnail of the movie cover. Suggestions?
[ "Note:\n\nNot every movie has a cover url. (The random ID in your example doesn't.)\nMake sure you're using an up-to-date version of IMDbPy. (IMDb changes, and IMDbPy with it.)\n\n...\nimport imdb\n\naccess = imdb.IMDb()\nmovie = access.get_movie(1132626)\n\nprint \"title: %s year: %s\" % (movie['title'], movie['year'])\nprint \"Cover url: %s\" % movie['cover url']\n\nIf for some reason you can't use the above, you can always use something like BeautifulSoup to get the cover url.\nfrom BeautifulSoup import BeautifulSoup\nimport imdb\n\naccess = imdb.IMDb()\nmovie = access.get_movie(1132626)\n\npage = urllib2.urlopen(access.get_imdbURL(movie))\nsoup = BeautifulSoup(page)\ncover_div = soup.find(attrs={\"class\" : \"photo\"})\ncover_url = (photo_div.find('img'))['src']\nprint \"Cover url: %s\" % cover_url\n\n", "Response from the IMDbPy mailing list:\n\nIf present, the url is accessible\n through movie['cover url']. Beware\n that it could be missing, so you must\n first test it with something like:\n if 'cover url' in movie:\n ...\nAfter that, you can use the urllib\n module to fetch the image itself.\nTo provide a complete example,\n something like that should do the\n trick:\nimport urllib\nfrom imdb import IMDb\n\nia = IMDb(#yourParameters)\nmovie = ia.get_movie(#theMovieID)\n\nif 'cover url' in movie:\n urlObj = urllib.urlopen(movie['cover url'])\n imageData = urlObj.read()\n urlObj.close()\n # now you can save imageData in a file (open it in binary mode).\n\nIn the same way, a person's headshot\n is stored in person['headshot'].\nThings to be aware of:\n\ncovers and headshots are available only fetching the data from the web server (via the 'http' or 'mobile' data access systems), and not in the plain text data files ('sql' or 'local').\nusing the images, you must respect the terms of the IMDb's policy; see http://imdbpy.sourceforge.net/docs/DISCLAIMER.txt\nthe images you'll get will vary in size; you can use the python-imaging module to rescale them, if needed.\n\n\n" ]
[ 10, 2 ]
[]
[]
[ "imdb", "imdbpy", "python" ]
stackoverflow_0000275683_imdb_imdbpy_python.txt
Q: Database change underneath SQLObject I'm starting a web project that likely should be fine with SQLite. I have SQLObject on top of it, but thinking long term here -- if this project should require a more robust (e.g. able to handle high traffic), I will need to have a transition plan ready. My questions: How easy is it to transition from one DB (SQLite) to another (MySQL or Firebird or PostGre) under SQLObject? Does SQLObject provide any tools to make such a transition easier? Is it simply take the objects I've defined and call createTable? What about having multiple SQLite databases instead? E.g. one per visitor group? Does SQLObject provide a mechanism for handling this scenario and if so, what is the mechanism to use? Thanks, Sean A: 3) Is quite an interesting question. In general, SQLite is pretty useless for web-based stuff. It scales fairly well for size, but scales terribly for concurrency, and so if you are planning to hit it with a few requests at the same time, you will be in trouble. Now your idea in part 3) of the question is to use multiple SQLite databases (eg one per user group, or even one per user). Unfortunately, SQLite will give you no help in this department. But it is possible. The one project I know that has done this before is Divmod's Axiom. So I would certainly check that out. Of course, it would probably be much easier to just use a good concurrent DB like the ones you mention (Firebird, PG, etc). For completeness: 1 and 2) It should be straightforward without you actually writing much code. I find SQLObject a bit restrictive in this department, and would strongly recommend SQLAlchemy instead. This is far more flexible, and if I was starting a new project today, I would certainly use it over SQLObject. It won't be moving "Objects" anywhere. There is no magic involved here, it will be transferring rows in tables in a database. Which as mentioned you could do by hand, but this might save you some time. A: Your success with createTable() will depend on your existing underlying table schema / data types. In other words, how well SQLite maps to the database you choose and how SQLObject decides to use your data types. The safest option may be to create the new database by hand. Then you'll have to deal with data migration, which may be as easy as instantiating two SQLObject database connections over the same table definitions. Why not just start with the more full-featured database? A: I'm not sure I understand the question. The SQLObject documentation lists six kinds of connections available. Further, the database connection (or scheme) is specified in a connection string. Changing database connections from SQLite to MySQL is trivial. Just change the connection string. The documentation lists the different kinds of schemes that are supported.
Database change underneath SQLObject
I'm starting a web project that likely should be fine with SQLite. I have SQLObject on top of it, but thinking long term here -- if this project should require a more robust (e.g. able to handle high traffic), I will need to have a transition plan ready. My questions: How easy is it to transition from one DB (SQLite) to another (MySQL or Firebird or PostGre) under SQLObject? Does SQLObject provide any tools to make such a transition easier? Is it simply take the objects I've defined and call createTable? What about having multiple SQLite databases instead? E.g. one per visitor group? Does SQLObject provide a mechanism for handling this scenario and if so, what is the mechanism to use? Thanks, Sean
[ "3) Is quite an interesting question. In general, SQLite is pretty useless for web-based stuff. It scales fairly well for size, but scales terribly for concurrency, and so if you are planning to hit it with a few requests at the same time, you will be in trouble.\nNow your idea in part 3) of the question is to use multiple SQLite databases (eg one per user group, or even one per user). Unfortunately, SQLite will give you no help in this department. But it is possible. The one project I know that has done this before is Divmod's Axiom. So I would certainly check that out.\nOf course, it would probably be much easier to just use a good concurrent DB like the ones you mention (Firebird, PG, etc).\nFor completeness:\n1 and 2) It should be straightforward without you actually writing much code. I find SQLObject a bit restrictive in this department, and would strongly recommend SQLAlchemy instead. This is far more flexible, and if I was starting a new project today, I would certainly use it over SQLObject. It won't be moving \"Objects\" anywhere. There is no magic involved here, it will be transferring rows in tables in a database. Which as mentioned you could do by hand, but this might save you some time.\n", "Your success with createTable() will depend on your existing underlying table schema / data types. In other words, how well SQLite maps to the database you choose and how SQLObject decides to use your data types.\nThe safest option may be to create the new database by hand. Then you'll have to deal with data migration, which may be as easy as instantiating two SQLObject database connections over the same table definitions.\nWhy not just start with the more full-featured database?\n", "I'm not sure I understand the question.\nThe SQLObject documentation lists six kinds of connections available. Further, the database connection (or scheme) is specified in a connection string. Changing database connections from SQLite to MySQL is trivial. Just change the connection string.\nThe documentation lists the different kinds of schemes that are supported.\n" ]
[ 3, 2, 0 ]
[]
[]
[ "database", "mysql", "python", "sqlite", "sqlobject" ]
stackoverflow_0000275572_database_mysql_python_sqlite_sqlobject.txt
Q: What's the difference between all of the os.popen() methods? I was looking at the Python documentation and saw that there are 4-5 different versions of popen(), e.g. os.popen(), os.popen2(), etc. Apart from the fact that some include stderr while others don't, what are the differences between them and when would you use each one? The documentation didn't really explain it very well. A: Jason has it right. To summarize in a way that's easier to see: os.popen() -> stdout os.popen2() -> (stdin, stdout) os.popen3() -> (stdin, stdout, stderr) os.popen4() -> (stdin, stdout_and_stderr) A: I would recommend to use the subprocess module which has all the features that these functions have and more. A: popen2 doesn't capture standard error, popen3 does capture standard error and gives a unique file handle for it. Finally, popen4 captures standard error but includes it in the same file object as standard output.
What's the difference between all of the os.popen() methods?
I was looking at the Python documentation and saw that there are 4-5 different versions of popen(), e.g. os.popen(), os.popen2(), etc. Apart from the fact that some include stderr while others don't, what are the differences between them and when would you use each one? The documentation didn't really explain it very well.
[ "Jason has it right. To summarize in a way that's easier to see:\n\nos.popen() -> stdout\nos.popen2() -> (stdin, stdout)\nos.popen3() -> (stdin, stdout, stderr)\nos.popen4() -> (stdin, stdout_and_stderr)\n\n", "I would recommend to use the subprocess module which has all the features that these functions have and more.\n", "popen2 doesn't capture standard error, popen3 does capture standard error and gives a unique file handle for it. Finally, popen4 captures standard error but includes it in the same file object as standard output.\n" ]
[ 15, 13, 10 ]
[]
[]
[ "popen", "python", "subprocess" ]
stackoverflow_0000275756_popen_python_subprocess.txt
Q: Remote debugging of multi threaded Python Applications How can I do remote debugging of a multi threaded Python application, running on an Embedded Linux based system, from Windows XP or Vista? So far I have only come across PyScripter based remote debugging. How does it perform? A: I've never used it except a few quick trial runs, but winpdb sounds like it does just what you want: Winpdb is a platform independent GPL Python debugger with support for multiple threads, namespace modification, embedded debugging, encrypted communication and is up to 20 times faster than pdb.
Remote debugging of multi threaded Python Applications
How can I do remote debugging of a multi threaded Python application, running on an Embedded Linux based system, from Windows XP or Vista? So far I have only come across PyScripter based remote debugging. How does it perform?
[ "I've never used it except a few quick trial runs, but winpdb sounds like it does just what you want:\n\nWinpdb is a platform independent GPL\n Python debugger with support for\n multiple threads, namespace\n modification, embedded debugging,\n encrypted communication and is up to\n 20 times faster than pdb.\n\n" ]
[ 1 ]
[]
[]
[ "python", "remote_debugging" ]
stackoverflow_0000275989_python_remote_debugging.txt
Q: Linking languages I asked a question earlier about which language to use for an AI prototype. The consensus seemed to be that if I want it to be fast, I need to use a language like Java or C++, but that Python / Perl / Ruby would be good for the interface bits. So, this leads me on to another question. How easy is it to link these languages together? And which combination works best? So, if I wanted to have a Ruby CGI-type program calling C++ or Java AI functions, is that easy to do? Any pointers for where I look for information on doing that kind of thing? Or would a different combination be better? My main experience with writing web applications started with C++ CGI and then moved on to Java servlets (about 10 years ago) and then after a long gap away from programming I did some PHP. But I've not had experience of writing a web application in a scripting language which then calls out to a compiled language for the speed-critical bits. So any advice will be welcome! A: Boost.Python provides an easy way to turn C++ code into Python modules. It's rather mature and works well in my experience. For example, the inevitable Hello World... char const* greet() { return "hello, world"; } can be exposed to Python by writing a Boost.Python wrapper: #include <boost/python.hpp> BOOST_PYTHON_MODULE(hello_ext) { using namespace boost::python; def("greet", greet); } That's it. We're done. We can now build this as a shared library. The resulting DLL is now visible to Python. Here's a sample Python session: >>> import hello_ext >>> print hello.greet() hello, world (example taken from boost.org) A: First, a meta comment: I would highly recommend coding the entire thing in a high-level language, profiling like mad, and optimizing only where profiling shows it's necessary. First optimize the algorithm, then the code, then think about bringing in the heavy iron. Having an optimum algorithm and clean code will make things much easier when/if you need to reimplement in a lower-level language. Speaking for Python, IronPython/C# is probably the easiest optimization path. CPython with C++ is doable, but I find C a lot easier to handle (but not all that easy, being C). Two tools that ease this are cython/pyrex (for C) and shedskin (for C++). These compile Python into C/C++, and from there you can access C/C++ libraries without too much ado. I've never used jython, but I hear that the jython/Java optimization path isn't all that bad. A: I agree with the Idea of coding first in a high level language such as Python, Profiling and then Implementing any code that needs speeding up in C / C++ and wrapping it for use in the high level language. As an alternative to boost I would like to suggest SWIG for creating Python callable code from C. Its reasonably painless to use, and will compile callable modules for a wide range of languages. (Python, Ruby, Java, Lua. to name a few) from C code. The wrapping process is semi automated, so there is no need to add new functions to the base C code, making a smoother work flow. A: If you choose Perl there are plenty of resources for interfacing other languages. Inline::C Inline::CPP Inline::Java From Inline::C-Cookbook: use Inline C => <<'END_C'; void greet() { printf("Hello, world\n"); } END_C greet; With Perl 6 it gets even easier to import subroutine from native library code using NativeCall. use v6.c; sub c-print ( Str() $s ){ use NativeCall; # restrict the function to inside of this subroutine because printf is # vararg based, and we only handle '%s' based inputs here # it should be possible to handle more but it requires generating # a Signature object based on the format string and then do a # nativecast with that Signature, and a pointer to printf sub printf ( str, str --> int32 ) is native('libc:6') {} printf '%s', $s } c-print 'Hello World'; This is just a simple example, you can create a class that has a representation of a Pointer, and have some of the methods be C code from the library you are using. ( only works if the first argument of the C code is the pointer, otherwise you would have to wrap it ) If you need the Perl 6 subroutine/method name to be different you can use the is symbol trait modifier. There are also Inline modules for Perl 6 as well. A: Perl has several ways to use other languages. Look at the Inline:: family of modules on CPAN. Following the advice from others in this question, I'd write the whole thing in a single dynamic language (Perl, Python, Ruby, etc) and then optimize the bits that need it. With Perl and Inline:: you can optimize in C, C++, or Java. Or you could look at AI::Prolog which allows you to embed Prolog for AI/Logic programming. A: It may be a good approach to start with a script, and call a compilation-based language from that script only for more advanced needs. For instance, calling java from ruby script works quite well. require "java" # The next line exposes Java's String as JString include_class("java.lang.String") { |pkg, name| "J" + name } s = JString.new("f") A: You can build your program in one of the higher level languages for example Python or Ruby and then call modules that are compiled in the lower level language for the parts you need performance. You can choose a platform depending on the lower level language you want. For example if you want to do C++ for the speedy stuff you can just use plain Python or Ruby and call DLLs compiled in C++. If you want to use Java you can use Jython or one of the other dynamic languages on the Java platform to call the Java code this is easier than the C++ route because you've got a common virtual machine so a Java object can be used directly in Jython or JRuby. The same can be done on the .Net platform with the Iron-languages and C# although you seem to have more experience with C++ and Java so those would be better options. A: I have a different perspective, having had lots of luck with integrating C++ and Python for some real time live video image processing. I would say you should match the language to the task for each module. If you're responding to a network, do it in Python, Python can keep up with network traffic just fine. UI: Python, People are slow, and Python is great for UIs using wxPython or PyObjC on Mac, or PyGTK. If you're doing math on lots of data, or signal processing, or image processing... code it in C or C++ with unit tests, then use SWIG to create the binding to any higher level language. I used the image libraries in wxWidgets in my C++, which are already exposed to Python through wxPython, so it was extremely powerful and quick. SCONS is a build tool (like make) which knows what to do with swig's .i files. The topmost level can be in C or Python, you'll have more control and fewer packaging and deployment issues if the top level is in C or C++... but it will take a really long time to duplicate what Py2EXE or Py2App gives you on Windows or Mac (or freeze on Linux.) Enjoy the power of hybrid programming! (I call using multiple languages in a tightly coupled way 'hybrid' but it's just a quirk of mine.) A: If the problem domain is hard (and AI problems can often be hard), then I'd choose a language which is expressive or suited to the domain first, and then worry about speeding it up second. For example, Ruby has meta-programming primitives (ability to easily examine and modify the running program) which can make it very easy/interesting to implement certain types of algorithms. If you implement it in that way and then later need to speed it up, then you can use benchmarking/profiling to locate the bottleneck and either link to a compiled language for that, or optimise the algorithm. In my experience, the biggest performance gain is from tweaking the algorithm, not from using a different implementation language.
Linking languages
I asked a question earlier about which language to use for an AI prototype. The consensus seemed to be that if I want it to be fast, I need to use a language like Java or C++, but that Python / Perl / Ruby would be good for the interface bits. So, this leads me on to another question. How easy is it to link these languages together? And which combination works best? So, if I wanted to have a Ruby CGI-type program calling C++ or Java AI functions, is that easy to do? Any pointers for where I look for information on doing that kind of thing? Or would a different combination be better? My main experience with writing web applications started with C++ CGI and then moved on to Java servlets (about 10 years ago) and then after a long gap away from programming I did some PHP. But I've not had experience of writing a web application in a scripting language which then calls out to a compiled language for the speed-critical bits. So any advice will be welcome!
[ "Boost.Python provides an easy way to turn C++ code into Python modules. It's rather mature and works well in my experience. \nFor example, the inevitable Hello World...\nchar const* greet()\n{\n return \"hello, world\";\n}\n\ncan be exposed to Python by writing a Boost.Python wrapper:\n#include <boost/python.hpp>\n\nBOOST_PYTHON_MODULE(hello_ext)\n{\n using namespace boost::python;\n def(\"greet\", greet);\n}\n\nThat's it. We're done. We can now build this as a shared library. The resulting DLL is now visible to Python. Here's a sample Python session:\n>>> import hello_ext\n>>> print hello.greet()\nhello, world\n\n(example taken from boost.org)\n", "First, a meta comment: I would highly recommend coding the entire thing in a high-level language, profiling like mad, and optimizing only where profiling shows it's necessary. First optimize the algorithm, then the code, then think about bringing in the heavy iron. Having an optimum algorithm and clean code will make things much easier when/if you need to reimplement in a lower-level language.\nSpeaking for Python, IronPython/C# is probably the easiest optimization path. \nCPython with C++ is doable, but I find C a lot easier to handle (but not all that easy, being C). Two tools that ease this are cython/pyrex (for C) and shedskin (for C++). These compile Python into C/C++, and from there you can access C/C++ libraries without too much ado.\nI've never used jython, but I hear that the jython/Java optimization path isn't all that bad.\n", "I agree with the Idea of coding first in a high level language such as Python, Profiling and then Implementing any code that needs speeding up in C / C++ and wrapping it for use in the high level language.\nAs an alternative to boost I would like to suggest SWIG for creating Python callable code from C. Its reasonably painless to use, and will compile callable modules for a wide range of languages. (Python, Ruby, Java, Lua. to name a few) from C code.\nThe wrapping process is semi automated, so there is no need to add new functions to the base C code, making a smoother work flow. \n", "If you choose Perl there are plenty of resources for interfacing other languages.\nInline::C\nInline::CPP\nInline::Java\nFrom Inline::C-Cookbook:\nuse Inline C => <<'END_C';\n\n void greet() {\n printf(\"Hello, world\\n\");\n }\nEND_C\n\ngreet;\n\n\nWith Perl 6 it gets even easier to import subroutine from native library code using NativeCall.\nuse v6.c;\n\nsub c-print ( Str() $s ){\n use NativeCall;\n\n # restrict the function to inside of this subroutine because printf is\n # vararg based, and we only handle '%s' based inputs here\n\n # it should be possible to handle more but it requires generating\n # a Signature object based on the format string and then do a\n # nativecast with that Signature, and a pointer to printf\n\n sub printf ( str, str --> int32 ) is native('libc:6') {}\n\n printf '%s', $s\n}\n\nc-print 'Hello World';\n\nThis is just a simple example, you can create a class that has a representation of a Pointer, and have some of the methods be C code from the library you are using. ( only works if the first argument of the C code is the pointer, otherwise you would have to wrap it )\nIf you need the Perl 6 subroutine/method name to be different you can use the is symbol trait modifier.\nThere are also Inline modules for Perl 6 as well.\n", "Perl has several ways to use other languages. Look at the Inline:: family of modules on CPAN. Following the advice from others in this question, I'd write the whole thing in a single dynamic language (Perl, Python, Ruby, etc) and then optimize the bits that need it. With Perl and Inline:: you can optimize in C, C++, or Java. Or you could look at AI::Prolog which allows you to embed Prolog for AI/Logic programming.\n", "It may be a good approach to start with a script, and call a compilation-based language from that script only for more advanced needs.\nFor instance, calling java from ruby script works quite well.\nrequire \"java\"\n# The next line exposes Java's String as JString\ninclude_class(\"java.lang.String\") { |pkg, name| \"J\" + name }\ns = JString.new(\"f\")\n\n", "You can build your program in one of the higher level languages for example Python or Ruby and then call modules that are compiled in the lower level language for the parts you need performance. You can choose a platform depending on the lower level language you want.\nFor example if you want to do C++ for the speedy stuff you can just use plain Python or Ruby and call DLLs compiled in C++. If you want to use Java you can use Jython or one of the other dynamic languages on the Java platform to call the Java code this is easier than the C++ route because you've got a common virtual machine so a Java object can be used directly in Jython or JRuby. The same can be done on the .Net platform with the Iron-languages and C# although you seem to have more experience with C++ and Java so those would be better options.\n", "I have a different perspective, having had lots of luck with integrating C++ and Python for some real time live video image processing.\nI would say you should match the language to the task for each module. If you're responding to a network, do it in Python, Python can keep up with network traffic just fine. UI: Python, People are slow, and Python is great for UIs using wxPython or PyObjC on Mac, or PyGTK. If you're doing math on lots of data, or signal processing, or image processing... code it in C or C++ with unit tests, then use SWIG to create the binding to any higher level language.\nI used the image libraries in wxWidgets in my C++, which are already exposed to Python through wxPython, so it was extremely powerful and quick. SCONS is a build tool (like make) which knows what to do with swig's .i files.\nThe topmost level can be in C or Python, you'll have more control and fewer packaging and deployment issues if the top level is in C or C++... but it will take a really long time to duplicate what Py2EXE or Py2App gives you on Windows or Mac (or freeze on Linux.) \nEnjoy the power of hybrid programming! (I call using multiple languages in a tightly coupled way 'hybrid' but it's just a quirk of mine.)\n", "If the problem domain is hard (and AI problems can often be hard), then I'd choose a language which is expressive or suited to the domain first, and then worry about speeding it up second. For example, Ruby has meta-programming primitives (ability to easily examine and modify the running program) which can make it very easy/interesting to implement certain types of algorithms.\nIf you implement it in that way and then later need to speed it up, then you can use benchmarking/profiling to locate the bottleneck and either link to a compiled language for that, or optimise the algorithm. In my experience, the biggest performance gain is from tweaking the algorithm, not from using a different implementation language.\n" ]
[ 14, 9, 6, 5, 4, 2, 2, 1, 1 ]
[]
[]
[ "c++", "java", "perl", "python", "ruby" ]
stackoverflow_0000271488_c++_java_perl_python_ruby.txt
Q: How to show the visitor a moved web page AND return a 301 redirect HTTP response status code in Django? When a webpage has moved to a new location, how do I show the moved web page AND return a 301 permanent redirect HTTP response status code in Django? A: from django import http return http.HttpResponsePermanentRedirect('/yournewpage.html') the browser will get the 301, and go to /yournewpage.html as expected. the other answer is technically correct, in that python is not handling the redirection per se, the browser is. this is what's happening under the hood: Browser Python HTTP -------------------> GET /youroldpage.html HTTP/1.1 <------------------- HTTP/1.1 301 Moved Permanently Location: /yournewpage.html -------------------> GET /yournewpage.html HTTP/1.1 A: You can't. 301 is an HTTP return code that is directly acted upon by the browser. Many sites handle these two issues by first sending the user to a redirect-er page that tells the user about the change and then X seconds later sends them to the new page. But the redirect-er page must have a 200 code. One small variant is to detect search engine spiders (by IP and/or user agent) and give them the 301. That way the search results point to your new page.
How to show the visitor a moved web page AND return a 301 redirect HTTP response status code in Django?
When a webpage has moved to a new location, how do I show the moved web page AND return a 301 permanent redirect HTTP response status code in Django?
[ " from django import http\n\n return http.HttpResponsePermanentRedirect('/yournewpage.html')\n\nthe browser will get the 301, and go to /yournewpage.html as expected. the other answer is technically correct, in that python is not handling the redirection per se, the browser is. this is what's happening under the hood:\nBrowser Python HTTP\n -------------------> GET /youroldpage.html HTTP/1.1\n\n <------------------- HTTP/1.1 301 Moved Permanently\n Location: /yournewpage.html\n -------------------> GET /yournewpage.html HTTP/1.1\n\n", "You can't.\n301 is an HTTP return code that is directly acted upon by the browser. Many sites handle these two issues by first sending the user to a redirect-er page that tells the user about the change and then X seconds later sends them to the new page. But the redirect-er page must have a 200 code.\nOne small variant is to detect search engine spiders (by IP and/or user agent) and give them the 301. That way the search results point to your new page.\n" ]
[ 10, 4 ]
[]
[]
[ "django", "http", "http_headers", "python", "redirect" ]
stackoverflow_0000276286_django_http_http_headers_python_redirect.txt
Q: Converting PDF to HTML with Python How can I convert PDF files to HTML with Python? I was thinking something alone the lines of what Google does (or seems to do) to index PDF files. My final goal is to setup Apache to show the HTML for the PDF files, so anything leading me in that direction would also be appreciated. A: The poppler package provides a pdf2html utility that you might be able to use. There is also a Python binding to libpoppler.
Converting PDF to HTML with Python
How can I convert PDF files to HTML with Python? I was thinking something alone the lines of what Google does (or seems to do) to index PDF files. My final goal is to setup Apache to show the HTML for the PDF files, so anything leading me in that direction would also be appreciated.
[ "The poppler package provides a pdf2html utility that you might be able to use. There is also a Python binding to libpoppler.\n" ]
[ 6 ]
[]
[]
[ "apache", "html", "pdf", "python" ]
stackoverflow_0000276434_apache_html_pdf_python.txt
Q: import mechanize module to python script I tried to import mechanize module to my python script like this, from mechanize import Browser But, Google appengine throws HTTP 500 when accessing my script. To make things more clear, Let me give you the snapshot of my package structure, root ....mechanize(where all the mechanize related files there) ....main.py ....app.yaml ....image ....script Can anyone help me out to resolve this issue? Thanks, Ponmalar A: The mechanize main page says: mechanize.Browser is a subclass of mechanize.UserAgentBase, which is, in turn, a subclass of urllib2.OpenerDirector My understanding is that urllib2 is one of the sandboxed modules in GAE, with its functionality being replaced by the Google-provided urlfetch. You'd need to re-implement the mechanize.UserAgentBase class to use urlfetch, if that's at all possible. A: When GAE throws a 500, you can see the actual error in the logs on your admin console. If that doesn't help, paste it here and we'll help further. Also, does it work on the dev_appserver?
import mechanize module to python script
I tried to import mechanize module to my python script like this, from mechanize import Browser But, Google appengine throws HTTP 500 when accessing my script. To make things more clear, Let me give you the snapshot of my package structure, root ....mechanize(where all the mechanize related files there) ....main.py ....app.yaml ....image ....script Can anyone help me out to resolve this issue? Thanks, Ponmalar
[ "The mechanize main page says:\n\nmechanize.Browser is a subclass of mechanize.UserAgentBase, which is, in turn, a subclass of urllib2.OpenerDirector\n\nMy understanding is that urllib2 is one of the sandboxed modules in GAE, with its functionality being replaced by the Google-provided urlfetch. You'd need to re-implement the mechanize.UserAgentBase class to use urlfetch, if that's at all possible.\n", "When GAE throws a 500, you can see the actual error in the logs on your admin console. If that doesn't help, paste it here and we'll help further.\nAlso, does it work on the dev_appserver?\n" ]
[ 2, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0000275980_google_app_engine_python.txt
Q: Django Forms - How to Use Prefix Parameter Say I have a form like: class GeneralForm(forms.Form): field1 = forms.IntegerField(required=False) field2 = forms. IntegerField(required=False) And I want to show it twice on a page within one form tag each time with a different prefix e.g.,: rest of page ... <form ..> GeneralForm(data,prefix="form1").as_table() GeneralForm(data,prefix="form2").as_table() <input type="submit" /> </form> rest of page ... When the user submits this, how do I get the submitted form back into two separate forms to do validation, and redisplay it? This was the only documentation I could find and it's peckish. A: You process each form as you normally would, ensuring that you create instances which have the same prefixes as those used to generate the form initially. Here's a slightly awkward example using the form you've given, as I don't know what the exact use case is: def some_view(request): if request.method == 'POST': form1 = GeneralForm(request.POST, prefix='form1') form2 = GeneralForm(request.POST, prefix='form2') if all([form1.is_valid(), form2.is_valid()]): pass # Do stuff with the forms else: form1 = GeneralForm(prefix='form1') form2 = GeneralForm(prefix='form2') return render_to_response('some_template.html', { 'form1': form1, 'form2': form2, }) Here's some real-world sample code which demonstrates processing forms using the prefix: http://collingrady.wordpress.com/2008/02/18/editing-multiple-objects-in-django-with-newforms/ A: Even better, I think formsets is exactly what you're looking for. class GeneralForm(forms.Form): field1 = forms.IntegerField(required=False) field2 = forms. IntegerField(required=False) from django.forms.formsets import formset_factory # GeneralSet is a formset with 2 occurrences of GeneralForm # ( as a formset allows the user to add new items, this enforces # 2 fixed items, no less, no more ) GeneralSet = formset_factory(GeneralForm, extra=2, max_num=2) # example view def someview(request): general_set = GeneralSet(request.POST) if general_set.is_valid(): for form in general_set.forms: # do something with data return render_to_response("template.html", {'form': general_set}, RequestContext(request)) You can even have a formset automatically generated from a model with modelformset_factory , which are used by the automated django admin. FormSet handle even more stuff than simple forms, like adding, removing and sorting items.
Django Forms - How to Use Prefix Parameter
Say I have a form like: class GeneralForm(forms.Form): field1 = forms.IntegerField(required=False) field2 = forms. IntegerField(required=False) And I want to show it twice on a page within one form tag each time with a different prefix e.g.,: rest of page ... <form ..> GeneralForm(data,prefix="form1").as_table() GeneralForm(data,prefix="form2").as_table() <input type="submit" /> </form> rest of page ... When the user submits this, how do I get the submitted form back into two separate forms to do validation, and redisplay it? This was the only documentation I could find and it's peckish.
[ "You process each form as you normally would, ensuring that you create instances which have the same prefixes as those used to generate the form initially.\nHere's a slightly awkward example using the form you've given, as I don't know what the exact use case is:\ndef some_view(request):\n if request.method == 'POST':\n form1 = GeneralForm(request.POST, prefix='form1')\n form2 = GeneralForm(request.POST, prefix='form2')\n if all([form1.is_valid(), form2.is_valid()]):\n pass # Do stuff with the forms\n else:\n form1 = GeneralForm(prefix='form1')\n form2 = GeneralForm(prefix='form2')\n return render_to_response('some_template.html', {\n 'form1': form1,\n 'form2': form2,\n })\n\nHere's some real-world sample code which demonstrates processing forms using the prefix:\nhttp://collingrady.wordpress.com/2008/02/18/editing-multiple-objects-in-django-with-newforms/\n", "Even better, I think formsets is exactly what you're looking for. \nclass GeneralForm(forms.Form):\n field1 = forms.IntegerField(required=False)\n field2 = forms. IntegerField(required=False)\n\nfrom django.forms.formsets import formset_factory\n\n# GeneralSet is a formset with 2 occurrences of GeneralForm \n# ( as a formset allows the user to add new items, this enforces\n# 2 fixed items, no less, no more )\nGeneralSet = formset_factory(GeneralForm, extra=2, max_num=2)\n\n# example view\n\ndef someview(request):\n general_set = GeneralSet(request.POST)\n if general_set.is_valid():\n for form in general_set.forms:\n # do something with data\n return render_to_response(\"template.html\", {'form': general_set}, RequestContext(request))\n\nYou can even have a formset automatically generated from a model with modelformset_factory , which are used by the automated django admin. FormSet handle even more stuff than simple forms, like adding, removing and sorting items.\n" ]
[ 39, 6 ]
[]
[]
[ "django", "forms", "html", "python" ]
stackoverflow_0000226510_django_forms_html_python.txt
Q: Syntax error whenever I put Python code inside a Django template I'm trying to do the following in my Django template: {% for embed in embeds %} {% embed2 = embed.replace("&lt;", "<") %} {{embed2}}<br /> {% endfor %} However, I always get an invalid block or some syntax error when I do anything like that (by that I mean {% %} code inside a loop). Python doesn't have {} to signify "scope" so I think this might be my problem? Am I formatting my code wrong? Edit: the exact error is: Invalid block tag: 'embed2' Edit2: Since someone said what I'm doing is not supported by Django templates, I rewrote the code, putting the logic in the view. I now have: embed_list = [] for embed in embeds: embed_list[len(embed_list):] = [embed.replace("&lt;", "<")] #this is line 35 return render_to_response("scanvideos.html", { "embed_list" :embed_list }) However, I now get an error: 'NoneType' object is not callable" on line 35. A: I am quite sure that Django templates does not support that. For your replace operation I would look into different filters. You really should try to keep as much logic as you can in your views and not in the templates. A: Django's template language is deliberately hobbled. When used by non-programming designers, this is definitely a Good Thing, but there are times when you need to do a little programming. (No, I don't want to argue about that. This has come up several times on django-users and django-dev.) Two ways to accomplish what you were trying: Use a different template engine. See Jinja2 for a good example that is fully explained for integrating with Django. Use a template tag that permits you to do Python expressions. See limodou's Expr tag. I have used the expr tag in several places and it has made life much easier. My next major Django site will use jinja2. A: I don't see why you'd get "NoneType object is not callable". That should mean that somewhere on the line is an expression like "foo(...)", and it means foo is None. BTW: You are trying to extend the embed_list, and it's easier to do it like this: embed_list = [] for embed in embeds: embed_list.append(embed.replace("&lt;", "<")) #this is line 35 return render_to_response("scanvideos.html", {"embed_list":embed_list}) and even easier to use a list comprehension: embed_list = [embed.replace("&lt;", "<") for embed in embeds] A: Django templates use their own syntax, not like Kid or Genshi. You have to roll your own Custom Template Tag. I guess the main reason is enforcing good practice. In my case, I've already a hard time explaining those special templates tags to the designer on our team. If it was plain Python I'm pretty sure we wouldn't have chosen Django at all. I think there's also a performance issue, Django templates benchmarks are fast, while last time I checked genshi was much slower. I don't know if it's due to freely embedded Python, though. You either need to review your approach and write your own custom templates (more or less synonyms to "helpers" in Ruby on Rails), or try another template engine. For your edit, there's a better syntax in Python: embed_list.append(embed.replace("&lt;", "<")) I don't know if it'll fix your error, but at least it's less JavaScriptesque ;-) Edit 2: Django automatically escapes all variables. You can enforce raw HTML with |safe filter : {{embed|safe}}. You'd better take some time reading the documentation, which is really great and useful. A: Instead of using a slice assignment to grow a list embed_list[len(embed_list):] = [foo] you should probably just do embed_list.append(foo) But really you should try unescaping html with a library function rather than doing it yourself. That NoneType error sounds like embed.replace is None at some point, which only makes sense if your list is not a list of strings - you might want to double-check that with some asserts or something similar.
Syntax error whenever I put Python code inside a Django template
I'm trying to do the following in my Django template: {% for embed in embeds %} {% embed2 = embed.replace("&lt;", "<") %} {{embed2}}<br /> {% endfor %} However, I always get an invalid block or some syntax error when I do anything like that (by that I mean {% %} code inside a loop). Python doesn't have {} to signify "scope" so I think this might be my problem? Am I formatting my code wrong? Edit: the exact error is: Invalid block tag: 'embed2' Edit2: Since someone said what I'm doing is not supported by Django templates, I rewrote the code, putting the logic in the view. I now have: embed_list = [] for embed in embeds: embed_list[len(embed_list):] = [embed.replace("&lt;", "<")] #this is line 35 return render_to_response("scanvideos.html", { "embed_list" :embed_list }) However, I now get an error: 'NoneType' object is not callable" on line 35.
[ "I am quite sure that Django templates does not support that.\nFor your replace operation I would look into different filters.\nYou really should try to keep as much logic as you can in your views and not in the templates.\n", "Django's template language is deliberately hobbled. When used by non-programming designers, this is definitely a Good Thing, but there are times when you need to do a little programming. (No, I don't want to argue about that. This has come up several times on django-users and django-dev.)\nTwo ways to accomplish what you were trying:\n\nUse a different template engine. See Jinja2 for a good example that is fully explained for integrating with Django.\nUse a template tag that permits you to do Python expressions. See limodou's Expr tag.\n\nI have used the expr tag in several places and it has made life much easier. My next major Django site will use jinja2.\n", "I don't see why you'd get \"NoneType object is not callable\". That should mean that somewhere on the line is an expression like \"foo(...)\", and it means foo is None.\nBTW: You are trying to extend the embed_list, and it's easier to do it like this:\nembed_list = []\nfor embed in embeds:\n embed_list.append(embed.replace(\"&lt;\", \"<\")) #this is line 35\nreturn render_to_response(\"scanvideos.html\", {\"embed_list\":embed_list})\n\nand even easier to use a list comprehension:\nembed_list = [embed.replace(\"&lt;\", \"<\") for embed in embeds]\n\n", "Django templates use their own syntax, not like Kid or Genshi.\nYou have to roll your own Custom Template Tag.\nI guess the main reason is enforcing good practice. In my case, I've already a hard time explaining those special templates tags to the designer on our team. If it was plain Python I'm pretty sure we wouldn't have chosen Django at all. I think there's also a performance issue, Django templates benchmarks are fast, while last time I checked genshi was much slower. I don't know if it's due to freely embedded Python, though.\nYou either need to review your approach and write your own custom templates (more or less synonyms to \"helpers\" in Ruby on Rails), or try another template engine.\nFor your edit, there's a better syntax in Python:\nembed_list.append(embed.replace(\"&lt;\", \"<\"))\n\nI don't know if it'll fix your error, but at least it's less JavaScriptesque ;-)\nEdit 2: Django automatically escapes all variables. You can enforce raw HTML with |safe filter : {{embed|safe}}.\nYou'd better take some time reading the documentation, which is really great and useful.\n", "Instead of using a slice assignment to grow a list\nembed_list[len(embed_list):] = [foo]\nyou should probably just do\nembed_list.append(foo)\nBut really you should try unescaping html with a library function rather than doing it yourself.\nThat NoneType error sounds like embed.replace is None at some point, which only makes sense if your list is not a list of strings - you might want to double-check that with some asserts or something similar.\n" ]
[ 8, 7, 4, 3, 3 ]
[]
[]
[ "django", "django_templates", "python", "templates" ]
stackoverflow_0000276345_django_django_templates_python_templates.txt
Q: How to import a python file in python script more than once Is it possible to import a python file more than once in a python script because i run a loop back to my driver file in a function by using the import command but it only works once? thanks edit: Resolved myself thanks A: You most probably should not use import for what you are trying to do. Without further information I can only guess, but you should move the code in the module you import from the top level into a function, do the import once and than simply call the function from you loop. A: The easiest answer is to put the code you are trying to run inside a function like this (inside your module that you are importing now): def main(): # All the code that currently does work goes in here # rather than just in the module (The module that does the importing) import your_module #used to do the work your_module.main() # now does the work (and you can call it multiple times) # some other code your_module.main() # do the work again A: The import statement -- by definition -- only imports once. You can, if you want, try to use execfile() (or eval()) to execute a separate file more than once. A: While Tom Ley's answer is the correct approach, it is possible to import a module more than once, using the reload built-in. module.py: print "imported!" >>> import module imported! >>> reload(module) imported! <module 'module' from 'module.pyc'> Note that reload returns the module, allowing you to rebind it if necessary.
How to import a python file in python script more than once
Is it possible to import a python file more than once in a python script because i run a loop back to my driver file in a function by using the import command but it only works once? thanks edit: Resolved myself thanks
[ "You most probably should not use import for what you are trying to do.\nWithout further information I can only guess, but you should move the code in the module you import from the top level into a function, do the import once and than simply call the function from you loop.\n", "The easiest answer is to put the code you are trying to run inside a function like this\n(inside your module that you are importing now):\ndef main():\n # All the code that currently does work goes in here \n # rather than just in the module\n\n(The module that does the importing)\nimport your_module #used to do the work\n\nyour_module.main() # now does the work (and you can call it multiple times)\n# some other code\nyour_module.main() # do the work again\n\n", "The import statement -- by definition -- only imports once. \nYou can, if you want, try to use execfile() (or eval()) to execute a separate file more than once. \n", "While Tom Ley's answer is the correct approach, it is possible to import a module more than once, using the reload built-in.\nmodule.py:\nprint \"imported!\"\n\n>>> import module\nimported!\n>>> reload(module)\nimported!\n<module 'module' from 'module.pyc'>\n\nNote that reload returns the module, allowing you to rebind it if necessary.\n" ]
[ 7, 4, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000276679_python.txt
Q: Dictionary or If statements, Jython I am writing a script at the moment that will grab certain information from HTML using dom4j. Since Python/Jython does not have a native switch statement I decided to use a whole bunch of if statements that call the appropriate method, like below: if type == 'extractTitle': extractTitle(dom) if type == 'extractMetaTags': extractMetaTags(dom) I will be adding more depending on what information I want to extract from the HTML and thought about taking the dictionary approach which I found elsewhere on this site, example below: { 'extractTitle': extractTitle, 'extractMetaTags': extractMetaTags }[type](dom) I know that each time I run the script the dictionary will be built, but at the same time if I were to use the if statements the script would have to check through all of them until it hits the correct one. What I am really wondering, which one performs better or is generally better practice to use? Update: @Brian - Thanks for the great reply. I have a question, if any of the extract methods require more than one object, e.g. handle_extractTag(self, dom, anotherObject) # Do something How would you make the appropriate changes to the handle method to implemented this? Hope you know what I mean :) Cheers A: To avoid specifying the tag and handler in the dict, you could just use a handler class with methods named to match the type. Eg class MyHandler(object): def handle_extractTitle(self, dom): # do something def handle_extractMetaTags(self, dom): # do something def handle(self, type, dom): func = getattr(self, 'handle_%s' % type, None) if func is None: raise Exception("No handler for type %r" % type) return func(dom) Usage: handler = MyHandler() handler.handle('extractTitle', dom) Update: When you have multiple arguments, just change the handle function to take those arguments and pass them through to the function. If you want to make it more generic (so you don't have to change both the handler functions and the handle method when you change the argument signature), you can use the *args and **kwargs syntax to pass through all received arguments. The handle method then becomes: def handle(self, type, *args, **kwargs): func = getattr(self, 'handle_%s' % type, None) if func is None: raise Exception("No handler for type %r" % type) return func(*args, **kwargs) A: With your code you're running your functions all get called. handlers = { 'extractTitle': extractTitle, 'extractMetaTags': extractMetaTags } handlers[type](dom) Would work like your original if code. A: It depends on how many if statements we're talking about; if it's a very small number, then it will be more efficient than using a dictionary. However, as always, I strongly advice you to do whatever makes your code look cleaner until experience and profiling tell you that a specific block of code needs to be optimized. A: Your use of the dictionary is not quite correct. In your implementation, all methods will be called and all the useless one discarded. What is usually done is more something like: switch_dict = {'extractTitle': extractTitle, 'extractMetaTags': extractMetaTags} switch_dict[type](dom) And that way is facter and more extensible if you have a large (or variable) number of items. A: The efficiency question is barely relevant. The dictionary lookup is done with a simple hashing technique, the if-statements have to be evaluated one at a time. Dictionaries tend to be quicker. I suggest that you actually have polymorphic objects that do extractions from the DOM. It's not clear how type gets set, but it sure looks like it might be a family of related objects, not a simple string. class ExtractTitle( object ): def process( dom ): return something class ExtractMetaTags( object ): def process( dom ): return something Instead of setting type="extractTitle", you'd do this. type= ExtractTitle() # or ExtractMetaTags() or ExtractWhatever() type.process( dom ) Then, you wouldn't be building this particular dictionary or if-statement.
Dictionary or If statements, Jython
I am writing a script at the moment that will grab certain information from HTML using dom4j. Since Python/Jython does not have a native switch statement I decided to use a whole bunch of if statements that call the appropriate method, like below: if type == 'extractTitle': extractTitle(dom) if type == 'extractMetaTags': extractMetaTags(dom) I will be adding more depending on what information I want to extract from the HTML and thought about taking the dictionary approach which I found elsewhere on this site, example below: { 'extractTitle': extractTitle, 'extractMetaTags': extractMetaTags }[type](dom) I know that each time I run the script the dictionary will be built, but at the same time if I were to use the if statements the script would have to check through all of them until it hits the correct one. What I am really wondering, which one performs better or is generally better practice to use? Update: @Brian - Thanks for the great reply. I have a question, if any of the extract methods require more than one object, e.g. handle_extractTag(self, dom, anotherObject) # Do something How would you make the appropriate changes to the handle method to implemented this? Hope you know what I mean :) Cheers
[ "To avoid specifying the tag and handler in the dict, you could just use a handler class with methods named to match the type. Eg\nclass MyHandler(object):\n def handle_extractTitle(self, dom):\n # do something\n\n def handle_extractMetaTags(self, dom):\n # do something\n\n def handle(self, type, dom):\n func = getattr(self, 'handle_%s' % type, None)\n if func is None:\n raise Exception(\"No handler for type %r\" % type)\n return func(dom)\n\nUsage:\n handler = MyHandler()\n handler.handle('extractTitle', dom)\n\nUpdate: \nWhen you have multiple arguments, just change the handle function to take those arguments and pass them through to the function. If you want to make it more generic (so you don't have to change both the handler functions and the handle method when you change the argument signature), you can use the *args and **kwargs syntax to pass through all received arguments. The handle method then becomes:\ndef handle(self, type, *args, **kwargs):\n func = getattr(self, 'handle_%s' % type, None)\n if func is None:\n raise Exception(\"No handler for type %r\" % type)\n return func(*args, **kwargs)\n\n", "With your code you're running your functions all get called.\n\nhandlers = {\n'extractTitle': extractTitle, \n'extractMetaTags': extractMetaTags\n}\n\nhandlers[type](dom)\n\nWould work like your original if code.\n", "It depends on how many if statements we're talking about; if it's a very small number, then it will be more efficient than using a dictionary.\nHowever, as always, I strongly advice you to do whatever makes your code look cleaner until experience and profiling tell you that a specific block of code needs to be optimized.\n", "Your use of the dictionary is not quite correct. In your implementation, all methods will be called and all the useless one discarded. What is usually done is more something like:\nswitch_dict = {'extractTitle': extractTitle, \n 'extractMetaTags': extractMetaTags}\nswitch_dict[type](dom)\n\nAnd that way is facter and more extensible if you have a large (or variable) number of items.\n", "The efficiency question is barely relevant. The dictionary lookup is done with a simple hashing technique, the if-statements have to be evaluated one at a time. Dictionaries tend to be quicker.\nI suggest that you actually have polymorphic objects that do extractions from the DOM.\nIt's not clear how type gets set, but it sure looks like it might be a family of related objects, not a simple string.\nclass ExtractTitle( object ):\n def process( dom ):\n return something\n\nclass ExtractMetaTags( object ):\n def process( dom ):\n return something\n\nInstead of setting type=\"extractTitle\", you'd do this.\ntype= ExtractTitle() # or ExtractMetaTags() or ExtractWhatever()\ntype.process( dom )\n\nThen, you wouldn't be building this particular dictionary or if-statement.\n" ]
[ 14, 2, 1, 1, 1 ]
[]
[]
[ "jython", "python", "switch_statement" ]
stackoverflow_0000277965_jython_python_switch_statement.txt
Q: Can anyone recommend a decent FOSS PDF generator for Python? I need a basic pdf generator that'll let me toss some images and text into a pdf file. The ability to have some basic drawing commands (lines and so forth) would also be a plus. I did read through this question, but I really don't need a report generator and most of the responses there seemed like real overkill for what I'm trying to do. (I don't need templates or LaTeX-grade layout control.) A: For one of my projects, I have tested and/or implemented probably six or seven different methods of going from an image to a PDF in the last six months. Ultimately I ended up coming back to ReportLab (which I had initially avoided for reasons similar to those you described) because all of the others had glaring limitations or outright omissions (such as the inability to set document metadata). ReportLab isn't as difficult to handle as it appears at first glance and it may save you a lot of headache-laden refactoring later on. I would strongly suggest you go ahead and use it and therefore know that if you ever want to be able to do more you will have the ability too rather than do what I did and bounce back and forth between a number of different utilities, libraries, and formats. EDIT: It is also worth mentioning that you can bypass the Platypus layout system that comes with ReportLab if all you want to do is put bit a of text and imagery on a page. A: I think going through Latex is the easiest way, and not overkill at all. Generating a working PDF file is quite a difficult activity, whereas generating a Tex source is much easier. Any other typesetting change would probably work as well, such as going through reStructuredText or troff. A: Is the reportlab code not ok? The reason why using LaTeX might not be overkill is because pdf is a really low-level format. In pdf you do not get line-breaks automatically, you have to calculate line-widths yourself.
Can anyone recommend a decent FOSS PDF generator for Python?
I need a basic pdf generator that'll let me toss some images and text into a pdf file. The ability to have some basic drawing commands (lines and so forth) would also be a plus. I did read through this question, but I really don't need a report generator and most of the responses there seemed like real overkill for what I'm trying to do. (I don't need templates or LaTeX-grade layout control.)
[ "For one of my projects, I have tested and/or implemented probably six or seven different methods of going from an image to a PDF in the last six months. Ultimately I ended up coming back to ReportLab (which I had initially avoided for reasons similar to those you described) because all of the others had glaring limitations or outright omissions (such as the inability to set document metadata).\nReportLab isn't as difficult to handle as it appears at first glance and it may save you a lot of headache-laden refactoring later on. I would strongly suggest you go ahead and use it and therefore know that if you ever want to be able to do more you will have the ability too rather than do what I did and bounce back and forth between a number of different utilities, libraries, and formats.\nEDIT:\nIt is also worth mentioning that you can bypass the Platypus layout system that comes with ReportLab if all you want to do is put bit a of text and imagery on a page.\n", "I think going through Latex is the easiest way, and not overkill at all. Generating a working PDF file is quite a difficult activity, whereas generating a Tex source is much easier. Any other typesetting change would probably work as well, such as going through reStructuredText or troff.\n", "Is the reportlab code not ok? The reason why using LaTeX might not be overkill is because pdf is a really low-level format. In pdf you do not get line-breaks automatically, you have to calculate line-widths yourself.\n" ]
[ 5, 1, 0 ]
[]
[]
[ "pdf_generation", "python" ]
stackoverflow_0000279129_pdf_generation_python.txt
Q: Python: How do I generate a keypress? I am opening a process (with os.popen() ) that, for some commands, detects certain keypresses (e.g. ESC - not the character, the key). Is there a way to send keypress events to the process? A: You probably want something like Pexpect. It's been around a while, and there may be a better alternative, now, but it will let you do what you want. As far as I know, there is no easy way to do that kind of thing with os.popen or the commands in the subprocess module. A: The obvious way would be to start the process in it's own shell. something like os.popen("sh command") A: What platform is this on? You may have to actually feed events into the event loop, if it's running on Win32.
Python: How do I generate a keypress?
I am opening a process (with os.popen() ) that, for some commands, detects certain keypresses (e.g. ESC - not the character, the key). Is there a way to send keypress events to the process?
[ "You probably want something like Pexpect. It's been around a while, and there may be a better alternative, now, but it will let you do what you want. \nAs far as I know, there is no easy way to do that kind of thing with os.popen or the commands in the subprocess module.\n", "The obvious way would be to start the process in it's own shell.\nsomething like os.popen(\"sh command\") \n", "What platform is this on? \nYou may have to actually feed events into the event loop, if it's running on Win32.\n" ]
[ 1, 0, 0 ]
[]
[]
[ "keypress", "popen", "python" ]
stackoverflow_0000279434_keypress_popen_python.txt
Q: making a python GUI How do I make a GUI for my python program because now it only runs in Idle and a command line and what software packages can I use and where can I get them? Thanks. A: The GuiProgramming page in the Python wiki has a good overview of the different options you have. A: The two most interesting toolkits for use with python are probably PyQt4 or wxPython. They are both open source, cross platform and well documented, and they both have gui builders available (Qt Designer and wxGlade. Keep in mind that developing closed source software with QT requires a license, both for QT and the python bindings. A: We started down the path of wxPython a few years ago and found it to be quite easy to do for simple, quick and dirty app. However, you are not going to get something you can put on the modern desktop. So we switched to WinForms and Python.Net and haven't looked back since. It's fairly easy to get going and you get all the power and support of rich windows UI with .NET. A: One thing not mentioned yet is that Tkinter is included in the standard library. In most cases all other gui toolkits will require additional installs. Tkinter isn't pretty, but it gives you the basics. And if you don't want to worry about additional setup, this is your best choice. My personal preference is wxpython. It has many of the standard widgets you expect from a gui toolkit and a native look.
making a python GUI
How do I make a GUI for my python program because now it only runs in Idle and a command line and what software packages can I use and where can I get them? Thanks.
[ "The GuiProgramming page in the Python wiki has a good overview of the different options you have.\n", "The two most interesting toolkits for use with python are probably PyQt4 or wxPython.\nThey are both open source, cross platform and well documented, and they both have gui builders available (Qt Designer and wxGlade. Keep in mind that developing closed source software with QT requires a license, both for QT and the python bindings.\n", "We started down the path of wxPython a few years ago and found it to be quite easy to do for simple, quick and dirty app. However, you are not going to get something you can put on the modern desktop. So we switched to WinForms and Python.Net and haven't looked back since. It's fairly easy to get going and you get all the power and support of rich windows UI with .NET.\n", "One thing not mentioned yet is that Tkinter is included in the standard library.\nIn most cases all other gui toolkits will require additional installs.\nTkinter isn't pretty, but it gives you the basics. And if you don't want to worry about additional setup, this is your best choice.\nMy personal preference is wxpython. It has many of the standard widgets you expect from a gui toolkit and a native look.\n" ]
[ 5, 5, 0, 0 ]
[]
[]
[ "python", "user_interface" ]
stackoverflow_0000279707_python_user_interface.txt
Q: How can one get the set of all classes with reverse relationships for a model in Django? Given: from django.db import models class Food(models.Model): """Food, by name.""" name = models.CharField(max_length=25) class Cat(models.Model): """A cat eats one type of food""" food = models.ForeignKey(Food) class Cow(models.Model): """A cow eats one type of food""" food = models.ForeignKey(Food) class Human(models.Model): """A human may eat lots of types of food""" food = models.ManyToManyField(Food) How can one, given only the class Food, get a set of all classes that it has "reverse relationships" to. I.e. given the class Food, how can one get the classes Cat, Cow and Human. I would think it's possible because Food has the three "reverse relations": Food.cat_set, Food.cow_set, and Food.human_set. Help's appreciated & thank you! A: Some digging in the source code revealed: django/db/models/options.py: def get_all_related_objects(self, local_only=False): def get_all_related_many_to_many_objects(self, local_only=False) And, using these functions on the models from above, you hypothetically get: >>> Food._meta.get_all_related_objects() [<RelatedObject: app_label:cow related to food>, <RelatedObject: app_label:cat related to food>,] >>> Food._meta.get_all_related_many_to_many_objects() [<RelatedObject: app_label:human related to food>,] # and, per django/db/models/related.py # you can retrieve the model with >>> Food._meta.get_all_related_objects()[0].model <class 'app_label.models.Cow'> Note: I hear Model._meta is 'unstable', and perhaps ought not to be relied upon in the post Django-1.0 world. Thanks for reading. :) A: Either A) Use multiple table inheritance and create a "Eater" base class, that Cat, Cow and Human inherit from. B) Use a Generic Relation, where Food could be linked to any other Model. Those are well-documented and officially supported features, you'd better stick to them to keep your own code clean, avoid workarounds and be sure it'll be still supported in the future. -- EDIT ( A.k.a. "how to be a reputation whore" ) So, here is a recipe for that particular case. Let's assume you absolutely want separate models for Cat, Cow and Human. In a real-world application, you want to ask to yourself why a "category" field wouldn't do the job. It's easier to get to the "real" class through generic relations, so here is the implementation for B. We can't have that 'food' field in Person, Cat or Cow, or we'll run into the same problems. So we'll create an intermediary "FoodConsumer" model. We'll have to write additional validation tests if we don't want more than one food for an instance. from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic class Food(models.Model): """Food, by name.""" name = models.CharField(max_length=25) # ConsumedFood has a foreign key to Food, and a "eaten_by" generic relation class ConsumedFood(models.Model): food = models.ForeignKey(Food, related_name="eaters") content_type = models.ForeignKey(ContentType, null=True) object_id = models.PositiveIntegerField(null=True) eaten_by = generic.GenericForeignKey('content_type', 'object_id') class Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) birth_date = models.DateField() address = models.CharField(max_length=100) city = models.CharField(max_length=50) foods = generic.GenericRelation(ConsumedFood) class Cat(models.Model): name = models.CharField(max_length=50) foods = generic.GenericRelation(ConsumedFood) class Cow(models.Model): farmer = models.ForeignKey(Person) foods = generic.GenericRelation(ConsumedFood) Now, to demonstrate it let's just write this working doctest: """ >>> from models import * Create some food records >>> weed = Food(name="weed") >>> weed.save() >>> burger = Food(name="burger") >>> burger.save() >>> pet_food = Food(name="Pet food") >>> pet_food.save() John the farmer likes burgers >>> john = Person(first_name="John", last_name="Farmer", birth_date="1960-10-12") >>> john.save() >>> john.foods.create(food=burger) <ConsumedFood: ConsumedFood object> Wilma the cow eats weed >>> wilma = Cow(farmer=john) >>> wilma.save() >>> wilma.foods.create(food=weed) <ConsumedFood: ConsumedFood object> Felix the cat likes pet food >>> felix = Cat(name="felix") >>> felix.save() >>> pet_food.eaters.create(eaten_by=felix) <ConsumedFood: ConsumedFood object> What food john likes again ? >>> john.foods.all()[0].food.name u'burger' Who's getting pet food ? >>> living_thing = pet_food.eaters.all()[0].eaten_by >>> isinstance(living_thing,Cow) False >>> isinstance(living_thing,Cat) True John's farm is in fire ! He looses his cow. >>> wilma.delete() John is a lot poorer right now >>> john.foods.clear() >>> john.foods.create(food=pet_food) <ConsumedFood: ConsumedFood object> Who's eating pet food now ? >>> for consumed_food in pet_food.eaters.all(): ... consumed_food.eaten_by <Cat: Cat object> <Person: Person object> Get the second pet food eater >>> living_thing = pet_food.eaters.all()[1].eaten_by Try to find if it's a person and reveal his name >>> if isinstance(living_thing,Person): living_thing.first_name u'John' """
How can one get the set of all classes with reverse relationships for a model in Django?
Given: from django.db import models class Food(models.Model): """Food, by name.""" name = models.CharField(max_length=25) class Cat(models.Model): """A cat eats one type of food""" food = models.ForeignKey(Food) class Cow(models.Model): """A cow eats one type of food""" food = models.ForeignKey(Food) class Human(models.Model): """A human may eat lots of types of food""" food = models.ManyToManyField(Food) How can one, given only the class Food, get a set of all classes that it has "reverse relationships" to. I.e. given the class Food, how can one get the classes Cat, Cow and Human. I would think it's possible because Food has the three "reverse relations": Food.cat_set, Food.cow_set, and Food.human_set. Help's appreciated & thank you!
[ "Some digging in the source code revealed:\ndjango/db/models/options.py:\ndef get_all_related_objects(self, local_only=False):\n\ndef get_all_related_many_to_many_objects(self, local_only=False)\n\nAnd, using these functions on the models from above, you hypothetically get:\n>>> Food._meta.get_all_related_objects()\n[<RelatedObject: app_label:cow related to food>,\n <RelatedObject: app_label:cat related to food>,]\n\n>>> Food._meta.get_all_related_many_to_many_objects()\n[<RelatedObject: app_label:human related to food>,]\n\n# and, per django/db/models/related.py\n# you can retrieve the model with\n>>> Food._meta.get_all_related_objects()[0].model\n<class 'app_label.models.Cow'>\n\nNote: I hear Model._meta is 'unstable', and perhaps ought not to be relied upon in the post Django-1.0 world.\nThanks for reading. :)\n", "Either \nA) Use multiple table inheritance and create a \"Eater\" base class, that Cat, Cow and Human inherit from.\nB) Use a Generic Relation, where Food could be linked to any other Model.\nThose are well-documented and officially supported features, you'd better stick to them to keep your own code clean, avoid workarounds and be sure it'll be still supported in the future.\n-- EDIT ( A.k.a. \"how to be a reputation whore\" )\nSo, here is a recipe for that particular case.\nLet's assume you absolutely want separate models for Cat, Cow and Human. In a real-world application, you want to ask to yourself why a \"category\" field wouldn't do the job.\nIt's easier to get to the \"real\" class through generic relations, so here is the implementation for B. We can't have that 'food' field in Person, Cat or Cow, or we'll run into the same problems. So we'll create an intermediary \"FoodConsumer\" model. We'll have to write additional validation tests if we don't want more than one food for an instance.\nfrom django.db import models\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.contrib.contenttypes import generic\n\nclass Food(models.Model):\n \"\"\"Food, by name.\"\"\"\n name = models.CharField(max_length=25)\n\n# ConsumedFood has a foreign key to Food, and a \"eaten_by\" generic relation\nclass ConsumedFood(models.Model):\n food = models.ForeignKey(Food, related_name=\"eaters\")\n content_type = models.ForeignKey(ContentType, null=True)\n object_id = models.PositiveIntegerField(null=True)\n eaten_by = generic.GenericForeignKey('content_type', 'object_id')\n\nclass Person(models.Model):\n first_name = models.CharField(max_length=50)\n last_name = models.CharField(max_length=50)\n birth_date = models.DateField()\n address = models.CharField(max_length=100)\n city = models.CharField(max_length=50)\n foods = generic.GenericRelation(ConsumedFood)\n\nclass Cat(models.Model):\n name = models.CharField(max_length=50)\n foods = generic.GenericRelation(ConsumedFood) \n\nclass Cow(models.Model):\n farmer = models.ForeignKey(Person)\n foods = generic.GenericRelation(ConsumedFood) \n\nNow, to demonstrate it let's just write this working doctest:\n\"\"\"\n>>> from models import *\n\nCreate some food records\n\n>>> weed = Food(name=\"weed\")\n>>> weed.save()\n\n>>> burger = Food(name=\"burger\")\n>>> burger.save()\n\n>>> pet_food = Food(name=\"Pet food\")\n>>> pet_food.save()\n\nJohn the farmer likes burgers\n\n>>> john = Person(first_name=\"John\", last_name=\"Farmer\", birth_date=\"1960-10-12\")\n>>> john.save()\n>>> john.foods.create(food=burger)\n<ConsumedFood: ConsumedFood object>\n\nWilma the cow eats weed\n\n>>> wilma = Cow(farmer=john)\n>>> wilma.save()\n>>> wilma.foods.create(food=weed)\n<ConsumedFood: ConsumedFood object>\n\nFelix the cat likes pet food\n\n>>> felix = Cat(name=\"felix\")\n>>> felix.save()\n>>> pet_food.eaters.create(eaten_by=felix)\n<ConsumedFood: ConsumedFood object>\n\nWhat food john likes again ?\n>>> john.foods.all()[0].food.name\nu'burger'\n\nWho's getting pet food ?\n>>> living_thing = pet_food.eaters.all()[0].eaten_by\n>>> isinstance(living_thing,Cow)\nFalse\n>>> isinstance(living_thing,Cat)\nTrue\n\nJohn's farm is in fire ! He looses his cow.\n>>> wilma.delete()\n\nJohn is a lot poorer right now\n>>> john.foods.clear()\n>>> john.foods.create(food=pet_food)\n<ConsumedFood: ConsumedFood object>\n\nWho's eating pet food now ?\n>>> for consumed_food in pet_food.eaters.all():\n... consumed_food.eaten_by\n<Cat: Cat object>\n<Person: Person object>\n\nGet the second pet food eater\n>>> living_thing = pet_food.eaters.all()[1].eaten_by\n\nTry to find if it's a person and reveal his name\n>>> if isinstance(living_thing,Person): living_thing.first_name\nu'John'\n\n\"\"\"\n\n" ]
[ 14, 7 ]
[]
[]
[ "django", "django_models", "django_orm", "python" ]
stackoverflow_0000279782_django_django_models_django_orm_python.txt
Q: Python 2.5 dictionary 2 key sort I have a dictionary of 200,000 items (the keys are strings and the values are integers). What is the best/most pythonic way to print the items sorted by descending value then ascending key (i.e. a 2 key sort)? a={ 'keyC':1, 'keyB':2, 'keyA':1 } b = a.items() b.sort( key=lambda a:a[0]) b.sort( key=lambda a:a[1], reverse=True ) print b >>>[('keyB', 2), ('keyA', 1), ('keyC', 1)] A: You can't sort dictionaries. You have to sort the list of items. Previous versions were wrong. When you have a numeric value, it's easy to sort in reverse order. These will do that. But this isn't general. This only works because the value is numeric. a = { 'key':1, 'another':2, 'key2':1 } b= a.items() b.sort( key=lambda a:(-a[1],a[0]) ) print b Here's an alternative, using an explicit function instead of a lambda and the cmp instead of the key option. def valueKeyCmp( a, b ): return cmp( (-a[1], a[0]), (-b[1], b[0] ) ) b.sort( cmp= valueKeyCmp ) print b The more general solution is actually two separate sorts b.sort( key=lambda a:a[1], reverse=True ) b.sort( key=lambda a:a[0] ) print b A: data = { 'keyC':1, 'keyB':2, 'keyA':1 } for key, value in sorted(data.items(), key=lambda x: (-1*x[1], x[0])): print key, value A: The most pythonic way to do it would be to know a little more about the actual data -- specifically, the maximum value you can have -- and then do it like this: def sortkey((k, v)): return (maxval - v, k) items = thedict.items() items.sort(key=sortkey) but unless you already know the maximum value, searching for the maximum value means looping through the dict an extra time (with max(thedict.itervalues())), which may be expensive. Alternatively, a keyfunc version of S.Lott's solution: def sortkey((k, v)): return (-v, k) items = thedict.items() items.sort(key=sortkey) An alternative that doesn't care about the types would be a comparison function: def sortcmp((ak, av), (bk, bv)): # compare values 'in reverse' r = cmp(bv, av) if not r: # and then keys normally r = cmp(ak, bk) return r items = thedict.items() items.sort(cmp=sortcmp) and this solution actually works for any type of key and value that you want to mix ascending and descending sorting with in the same key. If you value brevity you can write sortcmp as: def sortcmp((ak, av), (bk, bv)): return cmp((bk, av), (ak, bv)) A: You can use something like this: dic = {'aaa':1, 'aab':3, 'aaf':3, 'aac':2, 'aad':2, 'aae':4} def sort_compare(a, b): c = cmp(dic[b], dic[a]) if c != 0: return c return cmp(a, b) for k in sorted(dic.keys(), cmp=sort_compare): print k, dic[k] Don't know how pythonic it is however :) A: Building on Thomas Wouters and Ricardo Reyes solutions: def combine(*cmps): """Sequence comparisons.""" def comparator(a, b): for cmp in cmps: result = cmp(a, b): if result: return result return 0 return comparator def reverse(cmp): """Invert a comparison.""" def comparator(a, b): return cmp(b, a) return comparator def compare_nth(cmp, n): """Compare the n'th item from two sequences.""" def comparator(a, b): return cmp(a[n], b[n]) return comparator rev_val_key_cmp = combine( # compare values, decreasing reverse(compare_nth(1, cmp)), # compare keys, increasing compare_nth(0, cmp) ) data = { 'keyC':1, 'keyB':2, 'keyA':1 } for key, value in sorted(data.items(), cmp=rev_val_key_cmp): print key, value A: >>> keys = sorted(a, key=lambda k: (-a[k], k)) or >>> keys = sorted(a) >>> keys.sort(key=a.get, reverse=True) then print [(key, a[key]) for key in keys] [('keyB', 2), ('keyA', 1), ('keyC', 1)]
Python 2.5 dictionary 2 key sort
I have a dictionary of 200,000 items (the keys are strings and the values are integers). What is the best/most pythonic way to print the items sorted by descending value then ascending key (i.e. a 2 key sort)? a={ 'keyC':1, 'keyB':2, 'keyA':1 } b = a.items() b.sort( key=lambda a:a[0]) b.sort( key=lambda a:a[1], reverse=True ) print b >>>[('keyB', 2), ('keyA', 1), ('keyC', 1)]
[ "You can't sort dictionaries. You have to sort the list of items.\nPrevious versions were wrong. When you have a numeric value, it's easy to sort in reverse order. These will do that. But this isn't general. This only works because the value is numeric.\na = { 'key':1, 'another':2, 'key2':1 }\n\nb= a.items()\nb.sort( key=lambda a:(-a[1],a[0]) )\nprint b\n\nHere's an alternative, using an explicit function instead of a lambda and the cmp instead of the key option.\ndef valueKeyCmp( a, b ):\n return cmp( (-a[1], a[0]), (-b[1], b[0] ) )\n\nb.sort( cmp= valueKeyCmp )\nprint b\n\nThe more general solution is actually two separate sorts\nb.sort( key=lambda a:a[1], reverse=True )\nb.sort( key=lambda a:a[0] )\nprint b\n\n", "data = { 'keyC':1, 'keyB':2, 'keyA':1 }\n\nfor key, value in sorted(data.items(), key=lambda x: (-1*x[1], x[0])):\n print key, value\n\n", "The most pythonic way to do it would be to know a little more about the actual data -- specifically, the maximum value you can have -- and then do it like this:\ndef sortkey((k, v)): \n return (maxval - v, k)\n\nitems = thedict.items()\nitems.sort(key=sortkey)\n\nbut unless you already know the maximum value, searching for the maximum value means looping through the dict an extra time (with max(thedict.itervalues())), which may be expensive. Alternatively, a keyfunc version of S.Lott's solution:\ndef sortkey((k, v)): \n return (-v, k)\n\nitems = thedict.items()\nitems.sort(key=sortkey)\n\nAn alternative that doesn't care about the types would be a comparison function:\ndef sortcmp((ak, av), (bk, bv)):\n # compare values 'in reverse' \n r = cmp(bv, av)\n if not r:\n # and then keys normally\n r = cmp(ak, bk)\n return r\n\nitems = thedict.items()\nitems.sort(cmp=sortcmp) \n\nand this solution actually works for any type of key and value that you want to mix ascending and descending sorting with in the same key. If you value brevity you can write sortcmp as:\ndef sortcmp((ak, av), (bk, bv)):\n return cmp((bk, av), (ak, bv))\n\n", "You can use something like this:\ndic = {'aaa':1, 'aab':3, 'aaf':3, 'aac':2, 'aad':2, 'aae':4}\n\ndef sort_compare(a, b):\n c = cmp(dic[b], dic[a])\n if c != 0:\n return c\n return cmp(a, b)\n\nfor k in sorted(dic.keys(), cmp=sort_compare):\n print k, dic[k]\n\nDon't know how pythonic it is however :)\n", "Building on Thomas Wouters and Ricardo Reyes solutions:\ndef combine(*cmps):\n \"\"\"Sequence comparisons.\"\"\"\n def comparator(a, b):\n for cmp in cmps:\n result = cmp(a, b):\n if result:\n return result\n return 0\n return comparator\n\ndef reverse(cmp):\n \"\"\"Invert a comparison.\"\"\"\n def comparator(a, b):\n return cmp(b, a)\n return comparator\n\ndef compare_nth(cmp, n):\n \"\"\"Compare the n'th item from two sequences.\"\"\"\n def comparator(a, b):\n return cmp(a[n], b[n])\n return comparator\n\nrev_val_key_cmp = combine(\n # compare values, decreasing\n reverse(compare_nth(1, cmp)),\n\n # compare keys, increasing\n compare_nth(0, cmp)\n )\n\ndata = { 'keyC':1, 'keyB':2, 'keyA':1 }\n\nfor key, value in sorted(data.items(), cmp=rev_val_key_cmp):\n print key, value\n\n", ">>> keys = sorted(a, key=lambda k: (-a[k], k))\n\nor\n>>> keys = sorted(a)\n>>> keys.sort(key=a.get, reverse=True)\n\nthen\nprint [(key, a[key]) for key in keys]\n[('keyB', 2), ('keyA', 1), ('keyC', 1)]\n\n" ]
[ 18, 6, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000157424_python.txt
Q: When is "self" required? I have been using classes for only a short while and when I write a method, I make all variables reference self, e.g. self.foo. However, I'm looking through the wxPython in Action book and notice that "self" isn't used all the time. For example: import wx class TextFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, -1, 'Text Entry Example', size=(300, 100)) panel = wx.Panel(self, -1) basicLabel = wx.StaticText(panel, -1, "Basic Control:") basicText = wx.TextCtrl(panel, -1, "I've entered some text!", size=(175, -1)) basicText.SetInsertionPoint(0) pwdLabel = wx.StaticText(panel, -1, "Password:") pwdText = wx.TextCtrl(panel, -1, "password", size=(175, -1), style=wx.TE_PASSWORD) sizer = wx.FlexGridSizer(cols=2, hgap=6, vgap=6) sizer.AddMany([basicLabel, basicText, pwdLabel, pwdText]) panel.SetSizer(sizer) The one below does use "self". import wx class ButtonFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, -1, 'Button Example', size=(300, 100)) panel = wx.Panel(self, -1) self.button = wx.Button(panel, -1, "Hello", pos=(50, 20)) self.Bind(wx.EVT_BUTTON, self.OnClick, self.button) self.button.SetDefault() def OnClick(self, event): self.button.SetLabel("Clicked") If I remember correctly, "self" is reference to a particular instance of the class, so when is it not necessary? Is there a general rule of thumb? A: You use self.attribute to reference an attribute of your current instance. You use wx.Frame.__init__() to reference a method of the parent class. You don't use self if you only reference a local name (variable) of the method (function) you are in. These are not "rules of thumb," because there are no exceptions. What is probably confusing you in this particular example is that panel seems to be only a local name in the constructor, so it looks like the panel would disappear, once your constructor returns. If you look at the documentation to wx.Panel, though, you will see that its constructor attaches the panel to the parent window, so it will continue to exist, even after the constructor returns. Magic :) A: In those instances, if you do not use self then you will create only a local variable of that name. In the first example, panel is created as a local variable and then referenced later in the function, but it won't be available outside that function. The act of passing self to the wx.Panel constructor associated it with the current object in some fashion, so it doesn't just disappear when the function returns. A: self is always required when referring to the instance itself, except when calling the base class constructor (wx.Frame.__init__). All the other variables that you see in the examples (panel, basicLabel, basicText, ...) are just local variables - not related to the current object at all. These names will be gone when the method returns - everything put into self.foo will survive the end of the method, and be available in the next method (e.g. self.button).
When is "self" required?
I have been using classes for only a short while and when I write a method, I make all variables reference self, e.g. self.foo. However, I'm looking through the wxPython in Action book and notice that "self" isn't used all the time. For example: import wx class TextFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, -1, 'Text Entry Example', size=(300, 100)) panel = wx.Panel(self, -1) basicLabel = wx.StaticText(panel, -1, "Basic Control:") basicText = wx.TextCtrl(panel, -1, "I've entered some text!", size=(175, -1)) basicText.SetInsertionPoint(0) pwdLabel = wx.StaticText(panel, -1, "Password:") pwdText = wx.TextCtrl(panel, -1, "password", size=(175, -1), style=wx.TE_PASSWORD) sizer = wx.FlexGridSizer(cols=2, hgap=6, vgap=6) sizer.AddMany([basicLabel, basicText, pwdLabel, pwdText]) panel.SetSizer(sizer) The one below does use "self". import wx class ButtonFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, -1, 'Button Example', size=(300, 100)) panel = wx.Panel(self, -1) self.button = wx.Button(panel, -1, "Hello", pos=(50, 20)) self.Bind(wx.EVT_BUTTON, self.OnClick, self.button) self.button.SetDefault() def OnClick(self, event): self.button.SetLabel("Clicked") If I remember correctly, "self" is reference to a particular instance of the class, so when is it not necessary? Is there a general rule of thumb?
[ "You use self.attribute to reference an attribute of your current instance.\nYou use wx.Frame.__init__() to reference a method of the parent class.\nYou don't use self if you only reference a local name (variable) of the method (function) you are in.\nThese are not \"rules of thumb,\" because there are no exceptions.\n\nWhat is probably confusing you in this particular example is that panel seems to be only a local name in the constructor, so it looks like the panel would disappear, once your constructor returns.\nIf you look at the documentation to wx.Panel, though, you will see that its constructor attaches the panel to the parent window, so it will continue to exist, even after the constructor returns.\nMagic :)\n", "In those instances, if you do not use self then you will create only a local variable of that name. In the first example, panel is created as a local variable and then referenced later in the function, but it won't be available outside that function. The act of passing self to the wx.Panel constructor associated it with the current object in some fashion, so it doesn't just disappear when the function returns.\n", "self is always required when referring to the instance itself, except when calling the base class constructor (wx.Frame.__init__). All the other variables that you see in the examples (panel, basicLabel, basicText, ...) are just local variables - not related to the current object at all. These names will be gone when the method returns - everything put into self.foo will survive the end of the method, and be available in the next method (e.g. self.button).\n" ]
[ 9, 4, 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0000280324_python_wxpython.txt
Q: email body from a parsed email object in jython I have an object. fp = open(self.currentEmailPath, "rb") p = email.Parser.Parser() self._currentEmailParsedInstance= p.parse(fp) fp.close() self.currentEmailParsedInstance, from this object I want to get the body of an email, text only no HTML.... How do I do it? something like this? newmsg=self._currentEmailParsedInstance.get_payload() body=newmsg[0].get_content....? then strip the html from body. just what is that .... method to return the actual text... maybe I mis-understand you msg=self._currentEmailParsedInstance.get_payload() print type(msg) output = type 'list' the email Return-Path: Received: from xx.xx.net (example) by mxx3.xx.net (xxx) id 485EF65F08EDX5E12 for xxx@xx.com; Thu, 23 Oct 2008 06:07:51 +0200 Received: from xxxxx2 (ccc) by example.net (ccc) (authenticated as xxxx.xxx@example.com) id 48798D4001146189 for example.example@example-example.com; Thu, 23 Oct 2008 06:07:51 +0200 From: "example" To: Subject: FW: example Date: Thu, 23 Oct 2008 12:07:45 +0800 Organization: example Message-ID: <001601c934c4$xxxx30$a9ff460a@xxx> MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="----=_NextPart_000_0017_01C93507.F6F64E30" X-Mailer: Microsoft Office Outlook 11 X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2900.3138 Thread-Index: Ack0wLaumqgZo1oXSBuIpUCEg/wfOAABAFEA This is a multi-part message in MIME format. ------=_NextPart_000_0017_01C93507.F6F64E30 Content-Type: multipart/alternative; boundary="----=_NextPart_001_0018_01C93507.F6F64E30" ------=_NextPart_001_0018_01C93507.F6F64E30 Content-Type: text/plain; charset="us-ascii" Content-Transfer-Encoding: 7bit From: example.example[mailto:example@example.com] Sent: Thursday, October 23, 2008 11:37 AM To: xxxx@example.com Subject: S/I for example(B/L No.:4357-0120-810.044) Please find attached the example.doc), Thanks. B.rgds, xxx xxx ------=_NextPart_001_0018_01C93507.F6F64E30 Content-Type: text/html; charset="us-ascii" Content-Transfer-Encoding: quoted-printable xmlns:o=3D"urn:schemas-microsoft-com:office:office" = xmlns:w=3D"urn:schemas-microsoft-com:office:word" = xmlns:st1=3D"urn:schemas-microsoft-com:office:smarttags" = xmlns=3D"http://www.w3.org/TR/REC-html40"> HTML STUFF till ------=_NextPart_001_0018_01C93507.F6F64E30-- ------=_NextPart_000_0017_01C93507.F6F64E30 Content-Type: application/msword; name="xxxx.doc" Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename="xxxx.doc" 0M8R4KGxGuEAAAAAAAAAAAAAAAAAAAAAPgADAP7/CQAGAAAAAAAAAAAAAAABAAAAYAAAAAAAAAAA EAAAYgAAAAEAAAD+////AAAAAF8AAAD///////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////s pcEAI2AJBAAA+FK/AAAAAAAAEAAAAAAABgAAnEIAAA4AYmpiaqEVoRUAAAAAAAAAAAAAAAAAAAAA AAAECBYAMlAAAMN/AADDfwAAQQ4AAAAAAAAPAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//w8AAAAA AAAAAAD//w8AAAAAAAAAAAD//w8AAAAAAAAAAAAAAAAAAAAAAKQAAAAAAEYEAAAAAAAARgQAAEYE AAAAAAAARgQAAAAAAABGBAAAAAAAAEYEAAAAAAAARgQAABQAAAAAAAAAAAAAAFoEAAAAAAAA4hsA AAAAAADiGwAAAAAAAOIbAAA4AAAAGhwAAHwAAACWHAAARAAAAFoEAAAAAAAABzcAAEgBAADmHAAA FgAAAPwcAAAAAAAA/BwAAAAAAAD8HAAAAAAAAPwcAAAAAAAA/BwAAAAAAAD8HAAAAAAAAPwcAAAA AAAAMjYAAAIAAAA0NgAAAAAAADQ2AAAAAAAANDYAAAAAAAA0NgAAAAAAADQ2AAAAAAAANDYAACQA AABPOAAAaAIAALc6AACOAAAAWDYAAGkAAAAAAAAAAAAAAAAAAAAAAAAARgQAAAAAAABHLAAAAAAA AAAAAAAAAAAAAAAAAAAAAAD8HAAAAAAAAPwcAAAAAAAARywAAAAAAABHLAAAAAAAAFg2AAAAAAAA ------=_NextPart_000_0017_01C93507.F6F64E30-- I just want to get : From: xxxx.xxxx [mailto:xxxx@example.com] Sent: Thursday, October 23, 2008 11:37 AM To: xxxx@example.com Subject: S/I for xxxxx (B/L No.:4357-0120-810.044) Pls find attached the xxxx.doc), Thanks. B.rgds, xxx xxx not sure if the mail is malformed! seems if you get an html page you have to do this: parts=self._currentEmailParsedInstance.get_payload() print parts[0].get_content_type() ..._multipart/alternative_ textParts=parts[0].get_payload() print textParts[0].get_content_type() ..._text/plain_ body=textParts[0].get_payload() print body ...get the text without a problem!! thank you so much Vinko. So its kinda like dealing with xml, recursive in nature. A: This will get you the contents of the message self.currentEmailParsedInstance.get_payload() As for the text only part you will have to strip HTML on your own, for example using BeautifulSoup. Check this link for more information about the Message class the Parser returns. If you mean getting the text part of messages containing both HTML and plain text version of themselves, you can specify an index to get_payload() to get the part you want. I tried with a different MIME email because what you pasted seems malformed, hopefully it got malformed when you edited it. >>> parser = email.parser.Parser() >>> message = parser.parse(open('/home/vinko/jlm.txt','r')) >>> message.is_multipart() True >>> parts = message.get_payload() >>> len(parts) 2 >>> parts[0].get_content_type() 'text/plain' >>> parts[1].get_content_type() 'message/rfc822' >>> parts[0].get_payload() 'Message Text' parts will contain all parts of the multipart message, you can check their content types as shown and get only the text/plain ones, for instance. Good luck. A: ended up with this parser = email.parser.Parser() self._email = parser.parse(open('/home/vinko/jlm.txt','r')) parts=self._email.get_payload() check=parts[0].get_content_type() if check == "text/plain": return parts[0].get_payload() elif check == "multipart/alternative": part=parts[0].get_payload() if part[0].get_content_type() == "text/plain": return part[0].get_payload() else: return "cannot obtain the body of the email" else: return "cannot obtain the body of the email"
email body from a parsed email object in jython
I have an object. fp = open(self.currentEmailPath, "rb") p = email.Parser.Parser() self._currentEmailParsedInstance= p.parse(fp) fp.close() self.currentEmailParsedInstance, from this object I want to get the body of an email, text only no HTML.... How do I do it? something like this? newmsg=self._currentEmailParsedInstance.get_payload() body=newmsg[0].get_content....? then strip the html from body. just what is that .... method to return the actual text... maybe I mis-understand you msg=self._currentEmailParsedInstance.get_payload() print type(msg) output = type 'list' the email Return-Path: Received: from xx.xx.net (example) by mxx3.xx.net (xxx) id 485EF65F08EDX5E12 for xxx@xx.com; Thu, 23 Oct 2008 06:07:51 +0200 Received: from xxxxx2 (ccc) by example.net (ccc) (authenticated as xxxx.xxx@example.com) id 48798D4001146189 for example.example@example-example.com; Thu, 23 Oct 2008 06:07:51 +0200 From: "example" To: Subject: FW: example Date: Thu, 23 Oct 2008 12:07:45 +0800 Organization: example Message-ID: <001601c934c4$xxxx30$a9ff460a@xxx> MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="----=_NextPart_000_0017_01C93507.F6F64E30" X-Mailer: Microsoft Office Outlook 11 X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2900.3138 Thread-Index: Ack0wLaumqgZo1oXSBuIpUCEg/wfOAABAFEA This is a multi-part message in MIME format. ------=_NextPart_000_0017_01C93507.F6F64E30 Content-Type: multipart/alternative; boundary="----=_NextPart_001_0018_01C93507.F6F64E30" ------=_NextPart_001_0018_01C93507.F6F64E30 Content-Type: text/plain; charset="us-ascii" Content-Transfer-Encoding: 7bit From: example.example[mailto:example@example.com] Sent: Thursday, October 23, 2008 11:37 AM To: xxxx@example.com Subject: S/I for example(B/L No.:4357-0120-810.044) Please find attached the example.doc), Thanks. B.rgds, xxx xxx ------=_NextPart_001_0018_01C93507.F6F64E30 Content-Type: text/html; charset="us-ascii" Content-Transfer-Encoding: quoted-printable xmlns:o=3D"urn:schemas-microsoft-com:office:office" = xmlns:w=3D"urn:schemas-microsoft-com:office:word" = xmlns:st1=3D"urn:schemas-microsoft-com:office:smarttags" = xmlns=3D"http://www.w3.org/TR/REC-html40"> HTML STUFF till ------=_NextPart_001_0018_01C93507.F6F64E30-- ------=_NextPart_000_0017_01C93507.F6F64E30 Content-Type: application/msword; name="xxxx.doc" Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename="xxxx.doc" 0M8R4KGxGuEAAAAAAAAAAAAAAAAAAAAAPgADAP7/CQAGAAAAAAAAAAAAAAABAAAAYAAAAAAAAAAA EAAAYgAAAAEAAAD+////AAAAAF8AAAD///////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////s pcEAI2AJBAAA+FK/AAAAAAAAEAAAAAAABgAAnEIAAA4AYmpiaqEVoRUAAAAAAAAAAAAAAAAAAAAA AAAECBYAMlAAAMN/AADDfwAAQQ4AAAAAAAAPAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//w8AAAAA AAAAAAD//w8AAAAAAAAAAAD//w8AAAAAAAAAAAAAAAAAAAAAAKQAAAAAAEYEAAAAAAAARgQAAEYE AAAAAAAARgQAAAAAAABGBAAAAAAAAEYEAAAAAAAARgQAABQAAAAAAAAAAAAAAFoEAAAAAAAA4hsA AAAAAADiGwAAAAAAAOIbAAA4AAAAGhwAAHwAAACWHAAARAAAAFoEAAAAAAAABzcAAEgBAADmHAAA FgAAAPwcAAAAAAAA/BwAAAAAAAD8HAAAAAAAAPwcAAAAAAAA/BwAAAAAAAD8HAAAAAAAAPwcAAAA AAAAMjYAAAIAAAA0NgAAAAAAADQ2AAAAAAAANDYAAAAAAAA0NgAAAAAAADQ2AAAAAAAANDYAACQA AABPOAAAaAIAALc6AACOAAAAWDYAAGkAAAAAAAAAAAAAAAAAAAAAAAAARgQAAAAAAABHLAAAAAAA AAAAAAAAAAAAAAAAAAAAAAD8HAAAAAAAAPwcAAAAAAAARywAAAAAAABHLAAAAAAAAFg2AAAAAAAA ------=_NextPart_000_0017_01C93507.F6F64E30-- I just want to get : From: xxxx.xxxx [mailto:xxxx@example.com] Sent: Thursday, October 23, 2008 11:37 AM To: xxxx@example.com Subject: S/I for xxxxx (B/L No.:4357-0120-810.044) Pls find attached the xxxx.doc), Thanks. B.rgds, xxx xxx not sure if the mail is malformed! seems if you get an html page you have to do this: parts=self._currentEmailParsedInstance.get_payload() print parts[0].get_content_type() ..._multipart/alternative_ textParts=parts[0].get_payload() print textParts[0].get_content_type() ..._text/plain_ body=textParts[0].get_payload() print body ...get the text without a problem!! thank you so much Vinko. So its kinda like dealing with xml, recursive in nature.
[ "This will get you the contents of the message\nself.currentEmailParsedInstance.get_payload()\n\nAs for the text only part you will have to strip HTML on your own, for example using BeautifulSoup.\nCheck this link for more information about the Message class the Parser returns. If you mean getting the text part of messages containing both HTML and plain text version of themselves, you can specify an index to get_payload() to get the part you want.\nI tried with a different MIME email because what you pasted seems malformed, hopefully it got malformed when you edited it.\n>>> parser = email.parser.Parser()\n>>> message = parser.parse(open('/home/vinko/jlm.txt','r'))\n>>> message.is_multipart()\nTrue\n>>> parts = message.get_payload()\n>>> len(parts)\n2\n>>> parts[0].get_content_type()\n'text/plain'\n>>> parts[1].get_content_type()\n'message/rfc822'\n>>> parts[0].get_payload()\n'Message Text'\n\nparts will contain all parts of the multipart message, you can check their content types as shown and get only the text/plain ones, for instance.\nGood luck.\n", "ended up with this\n parser = email.parser.Parser()\n self._email = parser.parse(open('/home/vinko/jlm.txt','r'))\n parts=self._email.get_payload()\n check=parts[0].get_content_type()\n if check == \"text/plain\":\n return parts[0].get_payload()\n elif check == \"multipart/alternative\":\n part=parts[0].get_payload()\n if part[0].get_content_type() == \"text/plain\":\n return part[0].get_payload()\n else:\n return \"cannot obtain the body of the email\"\n else:\n return \"cannot obtain the body of the email\"\n\n" ]
[ 4, 0 ]
[]
[]
[ "email", "jython", "parsing", "python" ]
stackoverflow_0000280207_email_jython_parsing_python.txt
Q: Calculate poisson probability percentage When you use the POISSON function in Excel (or in OpenOffice Calc), it takes two arguments: an integer an 'average' number and returns a float. In Python (I tried RandomArray and NumPy) it returns an array of random poisson numbers. What I really want is the percentage that this event will occur (it is a constant number and the array has every time different numbers - so is it an average?). for example: print poisson(2.6,6) returns [1 3 3 0 1 3] (and every time I run it, it's different). The number I get from calc/excel is 3.19 (POISSON(6,2.16,0)*100). Am I using the python's poisson wrong (no pun!) or am I missing something? A: scipy has what you want >>> scipy.stats.distributions <module 'scipy.stats.distributions' from '/home/coventry/lib/python2.5/site-packages/scipy/stats/distributions.pyc'> >>> scipy.stats.distributions.poisson.pmf(6, 2.6) array(0.031867055625524499) It's worth noting that it's pretty easy to calculate by hand, too. A: It is easy to do by hand, but you can overflow doing it that way. You can do the exponent and factorial in a loop to avoid the overflow: def poisson_probability(actual, mean): # naive: math.exp(-mean) * mean**actual / factorial(actual) # iterative, to keep the components from getting too large or small: p = math.exp(-mean) for i in xrange(actual): p *= mean p /= i+1 return p A: This page explains why you get an array, and the meaning of the numbers in it, at least.
Calculate poisson probability percentage
When you use the POISSON function in Excel (or in OpenOffice Calc), it takes two arguments: an integer an 'average' number and returns a float. In Python (I tried RandomArray and NumPy) it returns an array of random poisson numbers. What I really want is the percentage that this event will occur (it is a constant number and the array has every time different numbers - so is it an average?). for example: print poisson(2.6,6) returns [1 3 3 0 1 3] (and every time I run it, it's different). The number I get from calc/excel is 3.19 (POISSON(6,2.16,0)*100). Am I using the python's poisson wrong (no pun!) or am I missing something?
[ "scipy has what you want\n>>> scipy.stats.distributions\n<module 'scipy.stats.distributions' from '/home/coventry/lib/python2.5/site-packages/scipy/stats/distributions.pyc'>\n>>> scipy.stats.distributions.poisson.pmf(6, 2.6)\narray(0.031867055625524499)\n\nIt's worth noting that it's pretty easy to calculate by hand, too.\n", "It is easy to do by hand, but you can overflow doing it that way. You can do the exponent and factorial in a loop to avoid the overflow:\ndef poisson_probability(actual, mean):\n # naive: math.exp(-mean) * mean**actual / factorial(actual)\n\n # iterative, to keep the components from getting too large or small:\n p = math.exp(-mean)\n for i in xrange(actual):\n p *= mean\n p /= i+1\n return p\n\n", "This page explains why you get an array, and the meaning of the numbers in it, at least.\n" ]
[ 26, 14, 1 ]
[]
[]
[ "poisson", "python", "statistics" ]
stackoverflow_0000280797_poisson_python_statistics.txt
Q: Python - sort a list of nested lists I have input consisting of a list of nested lists like this: l = [[[[[39]]]], [1, 2, 3], [4, [5, 3], 1], [[[[8, 9], 10], 11], 12]] I want to sort this list based on the sum of all the numbers in the nested lists... so, the values I want to sort by of l would look like this: [39, 6, 13, 50] Then I want to sort based on these. So the output should be: [[1, 2, 3], [4, [5, 3], 1], [[[[39]]]], [[[[8, 9], 10], 11], 12]] What's a nice pythonic way of doing this? A: A slight simplification and generalization to the answers provided so far, using a recent addition to python's syntax: >>> l = [[[[[39]]]], [1, 2, 3], [4, [5, 3], 1], [[[[8, 9], 10], 11], 12]] >>> def asum(t): return sum(map(asum, t)) if hasattr(t, '__iter__') else t ... >>> sorted(l, key=asum) [[1, 2, 3], [4, [5, 3], 1], [[[[39]]]], [[[[8, 9], 10], 11], 12]] A: A little recursive function would do it: def asum(a): if isinstance(a, list): return sum(asum(x) for x in a) else: return a l = [[[[[39]]]], [1, 2, 3], [4, [5, 3], 1], [[[[8, 9], 10], 11], 12]] l.sort(key=asum) print l A: l.sort(key=sum_nested) Where sum_nested() is: def sum_nested(astruct): try: return sum(map(sum_nested, astruct)) except TypeError: return astruct assert sum_nested([[([8, 9], 10), 11], 12]) == 50
Python - sort a list of nested lists
I have input consisting of a list of nested lists like this: l = [[[[[39]]]], [1, 2, 3], [4, [5, 3], 1], [[[[8, 9], 10], 11], 12]] I want to sort this list based on the sum of all the numbers in the nested lists... so, the values I want to sort by of l would look like this: [39, 6, 13, 50] Then I want to sort based on these. So the output should be: [[1, 2, 3], [4, [5, 3], 1], [[[[39]]]], [[[[8, 9], 10], 11], 12]] What's a nice pythonic way of doing this?
[ "A slight simplification and generalization to the answers provided so far, using a recent addition to python's syntax:\n>>> l = [[[[[39]]]], [1, 2, 3], [4, [5, 3], 1], [[[[8, 9], 10], 11], 12]]\n>>> def asum(t): return sum(map(asum, t)) if hasattr(t, '__iter__') else t\n...\n>>> sorted(l, key=asum)\n[[1, 2, 3], [4, [5, 3], 1], [[[[39]]]], [[[[8, 9], 10], 11], 12]]\n\n", "A little recursive function would do it:\ndef asum(a):\n if isinstance(a, list):\n return sum(asum(x) for x in a)\n else:\n return a\n\nl = [[[[[39]]]], [1, 2, 3], [4, [5, 3], 1], [[[[8, 9], 10], 11], 12]]\nl.sort(key=asum)\nprint l\n\n", "l.sort(key=sum_nested)\n\nWhere sum_nested() is:\ndef sum_nested(astruct):\n try: return sum(map(sum_nested, astruct))\n except TypeError:\n return astruct\n\n\nassert sum_nested([[([8, 9], 10), 11], 12]) == 50\n\n" ]
[ 16, 12, 5 ]
[]
[]
[ "list", "nested_lists", "python", "sorting" ]
stackoverflow_0000280222_list_nested_lists_python_sorting.txt
Q: Is there a more Pythonic way to merge two HTML header rows with colspans? I am using BeautifulSoup in Python to parse some HTML. One of the problems I am dealing with is that I have situations where the colspans are different across header rows. (Header rows are the rows that need to be combined to get the column headings in my jargon) That is one column may span a number of columns above or below it and the words need to be appended or prepended based on the spanning. Below is a routine to do this. I use BeautifulSoup to pull the colspans and to pull the contents of each cell in each row. longHeader is the contents of the header row with the most items, spanLong is a list with the colspans of each item in the row. This works but it is not looking very Pythonic. Alos-it is not going to work if the diff is <0, I can fix that with the same approach I used to get this to work. But before I do I wonder if anyone can quickly look at this and suggest a more Pythonic approach. I am a long time SAS programmer and so I struggle to break the mold-well I will write code as if I am writing a SAS macro. longHeader=['','','bananas','','','','','','','','','','trains','','planes','','','',''] shortHeader=['','','bunches','','cars','','trucks','','freight','','cargo','','all other','',''] spanShort=[1,1,3,1,3,1,3,1,3,1,3,1,3,1,3] spanLong=[1,1,3,1,1,1,1,1,1,1,1,1,3,1,3,1,3,1,3] combinedHeader=[] sumSpanLong=0 sumSpanShort=0 spanDiff=0 longHeaderCount=0 for each in range(len(shortHeader)): sumSpanLong=sumSpanLong+spanLong[longHeaderCount] sumSpanShort=sumSpanShort+spanShort[each] spanDiff=sumSpanShort-sumSpanLong if spanDiff==0: combinedHeader.append([longHeader[longHeaderCount]+' '+shortHeader[each]]) longHeaderCount=longHeaderCount+1 continue for i in range(0,spanDiff): combinedHeader.append([longHeader[longHeaderCount]+' '+shortHeader[each]]) longHeaderCount=longHeaderCount+1 sumSpanLong=sumSpanLong+spanLong[longHeaderCount] spanDiff=sumSpanShort-sumSpanLong if spanDiff==0: combinedHeader.append([longHeader[longHeaderCount]+' '+shortHeader[each]]) longHeaderCount=longHeaderCount+1 break print combinedHeader A: Here is a modified version of your algorithm. zip is used to iterate over short lengths and headers and a class object is used to count and iterate the long items, as well as combine the headers. while is more appropriate for the inner loop. (forgive the too short names). class collector(object): def __init__(self, header): self.longHeader = header self.combinedHeader = [] self.longHeaderCount = 0 def combine(self, shortValue): self.combinedHeader.append( [self.longHeader[self.longHeaderCount]+' '+shortValue] ) self.longHeaderCount += 1 return self.longHeaderCount def main(): longHeader = [ '','','bananas','','','','','','','','','','trains','','planes','','','',''] shortHeader = [ '','','bunches','','cars','','trucks','','freight','','cargo','','all other','',''] spanShort=[1,1,3,1,3,1,3,1,3,1,3,1,3,1,3] spanLong=[1,1,3,1,1,1,1,1,1,1,1,1,3,1,3,1,3,1,3] sumSpanLong=0 sumSpanShort=0 combiner = collector(longHeader) for sLen,sHead in zip(spanShort,shortHeader): sumSpanLong += spanLong[combiner.longHeaderCount] sumSpanShort += sLen while sumSpanShort - sumSpanLong > 0: combiner.combine(sHead) sumSpanLong += spanLong[combiner.longHeaderCount] combiner.combine(sHead) return combiner.combinedHeader A: You've actually got a lot going on in this example. You've "over-processed" the Beautiful Soup Tag objects to make lists. Leave them as Tags. All of these kinds of merge algorithms are hard. It helps to treat the two things being merged symmetrically. Here's a version that should work directly with the Beautiful Soup Tag objects. Also, this version doesn't assume anything about the lengths of the two rows. def merge3( row1, row2 ): i1= 0 i2= 0 result= [] while i1 != len(row1) or i2 != len(row2): if i1 == len(row1): result.append( ' '.join(row1[i1].contents) ) i2 += 1 elif i2 == len(row2): result.append( ' '.join(row2[i2].contents) ) i1 += 1 else: if row1[i1]['colspan'] < row2[i2]['colspan']: # Fill extra cols from row1 c1= row1[i1]['colspan'] while c1 != row2[i2]['colspan']: result.append( ' '.join(row2[i2].contents) ) c1 += 1 elif row1[i1]['colspan'] > row2[i2]['colspan']: # Fill extra cols from row2 c2= row2[i2]['colspan'] while row1[i1]['colspan'] != c2: result.append( ' '.join(row1[i1].contents) ) c2 += 1 else: assert row1[i1]['colspan'] == row2[i2]['colspan'] pass txt1= ' '.join(row1[i1].contents) txt2= ' '.join(row2[i2].contents) result.append( txt1 + " " + txt2 ) i1 += 1 i2 += 1 return result A: Maybe look at the zip function for parts of the problem: >>> execfile('so_ques.py') [[' '], [' '], ['bananas bunches'], [' '], [' cars'], [' cars'], [' cars'], [' '], [' trucks'], [' trucks'], [' trucks'], [' '], ['trains freight'], [' '], ['planes cargo'], [' '], [' all other'], [' '], [' ']] >>> zip(long_header, short_header) [('', ''), ('', ''), ('bananas', 'bunches'), ('', ''), ('', 'cars'), ('', ''), ('', 'trucks'), ('', ''), ('', 'freight'), ('', ''), ('', 'cargo'), ('', ''), ('trains', 'all other'), ('', ''), ('planes', '')] >>> enumerate can help avoid some of the complex indexing with counters: >>> diff_list = [] >>> for place, header in enumerate(short_header): diff_list.append(abs(span_short[place] - span_long[place])) >>> for place, num in enumerate(diff_list): if num: new_shortlist.extend(short_header[place] for item in range(num+1)) else: new_shortlist.append(short_header[place]) >>> new_shortlist ['', '', 'bunches', '', 'cars', 'cars', 'cars', '', 'trucks', 'trucks', 'trucks', '',... >>> z = zip(new_shortlist, long_header) >>> z [('', ''), ('', ''), ('bunches', 'bananas'), ('', ''), ('cars', ''), ('cars', ''), ('cars', '')... Also more pythonic naming may add clarity: for each in range(len(short_header)): sum_span_long += span_long[long_header_count] sum_span_short += span_short[each] span_diff = sum_span_short - sum_span_long if not span_diff: combined_header.append... A: I guess I am going to answer my own question but I did receive a lot of help. Thanks for all of the help. I made S.LOTT's answer work after a few small corrections. (They may be so small as to not be visible (inside joke)). So now the question is why is this more Pythonic? I think I see that it is less denser / works with the raw inputs instead of derivations / I cannot judge if it is easier to read ---> though it is easy to read S.LOTT's Answer Corrected row1=headerCells[0] row2=headerCells[1] i1= 0 i2= 0 result= [] while i1 != len(row1) or i2 != len(row2): if i1 == len(row1): result.append( ' '.join(row1[i1]) ) i2 += 1 elif i2 == len(row2): result.append( ' '.join(row2[i2]) ) i1 += 1 else: if int(row1[i1].get("colspan","1")) < int(row2[i2].get("colspan","1")): c1= int(row1[i1].get("colspan","1")) while c1 != int(row2[i2].get("colspan","1")): txt1= ' '.join(row1[i1]) # needed to add when working adjust opposing case txt2= ' '.join(row2[i2]) # needed to add when working adjust opposing case result.append( txt1 + " " + txt2 ) # needed to add when working adjust opposing case print 'stayed in middle', 'i1=',i1,'i2=',i2, ' c1=',c1 c1 += 1 i1 += 1 # Is this the problem it elif int(row1[i1].get("colspan","1"))> int(row2[i2].get("colspan","1")): # Fill extra cols from row2 Make same adjustment as above c2= int(row2[i2].get("colspan","1")) while int(row1[i1].get("colspan","1")) != c2: result.append( ' '.join(row1[i1]) ) c2 += 1 i2 += 1 else: assert int(row1[i1].get("colspan","1")) == int(row2[i2].get("colspan","1")) pass txt1= ' '.join(row1[i1]) txt2= ' '.join(row2[i2]) result.append( txt1 + " " + txt2 ) print 'went to bottom', 'i1=',i1,'i2=',i2 i1 += 1 i2 += 1 print result A: Well I have an answer now. I was thinking through this and decided that I needed to use parts of every answer. I still need to figure out if I want a class or a function. But I have the algorithm that I think is probably more Pythonic than any of the others. But, it borrows heavily from the answers that some very generous people provided. I appreciate those a lot because I have learned quite a bit. To save the time of having to make test cases I am going to paste the the complete code I have been banging away with in IDLE and follow that with an HTML sample file. Other than making a decision about class/function (and I need to think about how I am using this code in my program) I would be happy to see any improvements that make the code more Pythonic. from BeautifulSoup import BeautifulSoup original=file(r"C:\testheaders.htm").read() soupOriginal=BeautifulSoup(original) all_Rows=soupOriginal.findAll('tr') header_Rows=[] for each in range(len(all_Rows)): header_Rows.append(all_Rows[each]) header_Cells=[] for each in header_Rows: header_Cells.append(each.findAll('td')) temp_Header_Row=[] header=[] for row in range(len(header_Cells)): for column in range(len(header_Cells[row])): x=int(header_Cells[row][column].get("colspan","1")) if x==1: temp_Header_Row.append( ' '.join(header_Cells[row][column]) ) else: for item in range(x): temp_Header_Row.append( ''.join(header_Cells[row][column]) ) header.append(temp_Header_Row) temp_Header_Row=[] combined_Header=zip(*header) for each in combined_Header: print each Okay test file contents are below Sorry I tried to attach these but couldn't make it happen: <TABLE style="font-size: 10pt" cellspacing="0" border="0" cellpadding="0" width="100%"> <TR valign="bottom"> <TD width="40%">&nbsp;</TD> <TD width="5%">&nbsp;</TD> <TD width="3%">&nbsp;</TD> <TD width="3%">&nbsp;</TD> <TD width="1%">&nbsp;</TD> <TD width="5%">&nbsp;</TD> <TD width="3%">&nbsp;</TD> <TD width="3%">&nbsp;</TD> <TD width="1%">&nbsp;</TD> <TD width="5%">&nbsp;</TD> <TD width="3%">&nbsp;</TD> <TD width="1%">&nbsp;</TD> <TD width="1%">&nbsp;</TD> <TD width="5%">&nbsp;</TD> <TD width="3%">&nbsp;</TD> <TD width="1%">&nbsp;</TD> <TD width="1%">&nbsp;</TD> <TD width="5%">&nbsp;</TD> <TD width="3%">&nbsp;</TD> <TD width="3%">&nbsp;</TD> <TD width="1%">&nbsp;</TD> </TR> <TR style="font-size: 10pt" valign="bottom"> <TD>&nbsp;</TD> <TD>&nbsp;</TD> <TD>&nbsp;</TD> <TD>&nbsp;</TD> <TD>&nbsp;</TD> <TD>&nbsp;</TD> <TD>&nbsp;</TD> <TD>&nbsp;</TD> <TD>&nbsp;</TD> <TD>&nbsp;</TD> <TD nowrap align="right" colspan="2">FOODS WE LIKE</TD> <TD>&nbsp;</TD> <TD>&nbsp;</TD> <TD nowrap align="right" colspan="2">&nbsp;</TD> <TD>&nbsp;</TD> <TD>&nbsp;</TD> <TD nowrap align="right" colspan="2">&nbsp;</TD> <TD>&nbsp;</TD> </TR> <TR style="font-size: 10pt" valign="bottom"> <TD>&nbsp;</TD> <TD>&nbsp;</TD> <TD nowrap align="CENTER" colspan="6">SILLY STUFF</TD> <TD>&nbsp;</TD> <TD>&nbsp;</TD> <TD nowrap align="right" colspan="2">OTHER THAN</TD> <TD>&nbsp;</TD> <TD>&nbsp;</TD> <TD nowrap align="CENTER" colspan="6">FAVORITE PEOPLE</TD> <TD>&nbsp;</TD> </TR> <TR style="font-size: 10pt" valign="bottom"> <TD>&nbsp;</TD> <TD>&nbsp;</TD> <TD nowrap align="right" colspan="2">MONTY PYTHON</TD> <TD>&nbsp;</TD> <TD>&nbsp;</TD> <TD nowrap align="right" colspan="2">CHERRYPY</TD> <TD>&nbsp;</TD> <TD>&nbsp;</TD> <TD nowrap align="right" colspan="2">APPLE PIE</TD> <TD>&nbsp;</TD> <TD>&nbsp;</TD> <TD nowrap align="right" colspan="2">MOTHERS</TD> <TD>&nbsp;</TD> <TD>&nbsp;</TD> <TD nowrap align="right" colspan="2">FATHERS</TD> <TD>&nbsp;</TD> </TR> <TR style="font-size: 10pt" valign="bottom"> <TD nowrap align="left">Name</TD> <TD>&nbsp;</TD> <TD nowrap align="right" colspan="2">SHOWS</TD> <TD>&nbsp;</TD> <TD>&nbsp;</TD> <TD nowrap align="right" colspan="2">PROGRAMS</TD> <TD>&nbsp;</TD> <TD>&nbsp;</TD> <TD nowrap align="right" colspan="2">BANANAS</TD> <TD>&nbsp;</TD> <TD>&nbsp;</TD> <TD nowrap align="right" colspan="2">PERFUME</TD> <TD>&nbsp;</TD> <TD>&nbsp;</TD> <TD nowrap align="right" colspan="2">TOOLS</TD> <TD>&nbsp;</TD> </TR> </TABLE>
Is there a more Pythonic way to merge two HTML header rows with colspans?
I am using BeautifulSoup in Python to parse some HTML. One of the problems I am dealing with is that I have situations where the colspans are different across header rows. (Header rows are the rows that need to be combined to get the column headings in my jargon) That is one column may span a number of columns above or below it and the words need to be appended or prepended based on the spanning. Below is a routine to do this. I use BeautifulSoup to pull the colspans and to pull the contents of each cell in each row. longHeader is the contents of the header row with the most items, spanLong is a list with the colspans of each item in the row. This works but it is not looking very Pythonic. Alos-it is not going to work if the diff is <0, I can fix that with the same approach I used to get this to work. But before I do I wonder if anyone can quickly look at this and suggest a more Pythonic approach. I am a long time SAS programmer and so I struggle to break the mold-well I will write code as if I am writing a SAS macro. longHeader=['','','bananas','','','','','','','','','','trains','','planes','','','',''] shortHeader=['','','bunches','','cars','','trucks','','freight','','cargo','','all other','',''] spanShort=[1,1,3,1,3,1,3,1,3,1,3,1,3,1,3] spanLong=[1,1,3,1,1,1,1,1,1,1,1,1,3,1,3,1,3,1,3] combinedHeader=[] sumSpanLong=0 sumSpanShort=0 spanDiff=0 longHeaderCount=0 for each in range(len(shortHeader)): sumSpanLong=sumSpanLong+spanLong[longHeaderCount] sumSpanShort=sumSpanShort+spanShort[each] spanDiff=sumSpanShort-sumSpanLong if spanDiff==0: combinedHeader.append([longHeader[longHeaderCount]+' '+shortHeader[each]]) longHeaderCount=longHeaderCount+1 continue for i in range(0,spanDiff): combinedHeader.append([longHeader[longHeaderCount]+' '+shortHeader[each]]) longHeaderCount=longHeaderCount+1 sumSpanLong=sumSpanLong+spanLong[longHeaderCount] spanDiff=sumSpanShort-sumSpanLong if spanDiff==0: combinedHeader.append([longHeader[longHeaderCount]+' '+shortHeader[each]]) longHeaderCount=longHeaderCount+1 break print combinedHeader
[ "Here is a modified version of your algorithm. zip is used to iterate over short lengths and headers and a class object is used to count and iterate the long items, as well as combine the headers. while is more appropriate for the inner loop.\n(forgive the too short names).\nclass collector(object):\n def __init__(self, header):\n self.longHeader = header\n self.combinedHeader = []\n self.longHeaderCount = 0\n def combine(self, shortValue):\n self.combinedHeader.append(\n [self.longHeader[self.longHeaderCount]+' '+shortValue] )\n self.longHeaderCount += 1\n return self.longHeaderCount\n\ndef main():\n longHeader = [ \n '','','bananas','','','','','','','','','','trains','','planes','','','','']\n shortHeader = [\n '','','bunches','','cars','','trucks','','freight','','cargo','','all other','','']\n spanShort=[1,1,3,1,3,1,3,1,3,1,3,1,3,1,3]\n spanLong=[1,1,3,1,1,1,1,1,1,1,1,1,3,1,3,1,3,1,3]\n sumSpanLong=0\n sumSpanShort=0\n\n combiner = collector(longHeader)\n for sLen,sHead in zip(spanShort,shortHeader):\n sumSpanLong += spanLong[combiner.longHeaderCount]\n sumSpanShort += sLen\n while sumSpanShort - sumSpanLong > 0:\n combiner.combine(sHead)\n sumSpanLong += spanLong[combiner.longHeaderCount]\n combiner.combine(sHead)\n\n return combiner.combinedHeader\n\n", "You've actually got a lot going on in this example.\n\nYou've \"over-processed\" the Beautiful Soup Tag objects to make lists. Leave them as Tags.\nAll of these kinds of merge algorithms are hard. It helps to treat the two things being merged symmetrically.\n\nHere's a version that should work directly with the Beautiful Soup Tag objects. Also, this version doesn't assume anything about the lengths of the two rows.\ndef merge3( row1, row2 ):\n i1= 0\n i2= 0\n result= []\n while i1 != len(row1) or i2 != len(row2):\n if i1 == len(row1):\n result.append( ' '.join(row1[i1].contents) )\n i2 += 1\n elif i2 == len(row2):\n result.append( ' '.join(row2[i2].contents) )\n i1 += 1\n else:\n if row1[i1]['colspan'] < row2[i2]['colspan']:\n # Fill extra cols from row1\n c1= row1[i1]['colspan']\n while c1 != row2[i2]['colspan']:\n result.append( ' '.join(row2[i2].contents) )\n c1 += 1\n elif row1[i1]['colspan'] > row2[i2]['colspan']:\n # Fill extra cols from row2\n c2= row2[i2]['colspan']\n while row1[i1]['colspan'] != c2:\n result.append( ' '.join(row1[i1].contents) )\n c2 += 1\n else:\n assert row1[i1]['colspan'] == row2[i2]['colspan']\n pass\n txt1= ' '.join(row1[i1].contents)\n txt2= ' '.join(row2[i2].contents)\n result.append( txt1 + \" \" + txt2 )\n i1 += 1\n i2 += 1\n return result\n\n", "Maybe look at the zip function for parts of the problem:\n>>> execfile('so_ques.py')\n[[' '], [' '], ['bananas bunches'], [' '], [' cars'], [' cars'], [' cars'], [' '], [' trucks'], [' trucks'], [' trucks'], [' '], ['trains freight'], [' '], ['planes cargo'], [' '], [' all other'], [' '], [' ']]\n\n>>> zip(long_header, short_header)\n[('', ''), ('', ''), ('bananas', 'bunches'), ('', ''), ('', 'cars'), ('', ''), ('', 'trucks'), ('', ''), ('', 'freight'), ('', ''), ('', 'cargo'), ('', ''), ('trains', 'all other'), ('', ''), ('planes', '')]\n>>> \n\nenumerate can help avoid some of the complex indexing with counters:\n>>> diff_list = []\n>>> for place, header in enumerate(short_header):\n diff_list.append(abs(span_short[place] - span_long[place]))\n\n>>> for place, num in enumerate(diff_list):\n if num:\n new_shortlist.extend(short_header[place] for item in range(num+1))\n else:\n new_shortlist.append(short_header[place])\n\n\n>>> new_shortlist\n['', '', 'bunches', '', 'cars', 'cars', 'cars', '', 'trucks', 'trucks', 'trucks', '',... \n>>> z = zip(new_shortlist, long_header)\n>>> z\n[('', ''), ('', ''), ('bunches', 'bananas'), ('', ''), ('cars', ''), ('cars', ''), ('cars', '')...\n\nAlso more pythonic naming may add clarity:\n for each in range(len(short_header)):\n sum_span_long += span_long[long_header_count]\n sum_span_short += span_short[each]\n span_diff = sum_span_short - sum_span_long\n if not span_diff:\n combined_header.append...\n\n", "I guess I am going to answer my own question but I did receive a lot of help. Thanks for all of the help. I made S.LOTT's answer work after a few small corrections. (They may be so small as to not be visible (inside joke)). So now the question is why is this more Pythonic? I think I see that it is less denser / works with the raw inputs instead of derivations / I cannot judge if it is easier to read ---> though it is easy to read\nS.LOTT's Answer Corrected\nrow1=headerCells[0]\nrow2=headerCells[1]\n\ni1= 0\ni2= 0\nresult= []\nwhile i1 != len(row1) or i2 != len(row2):\n if i1 == len(row1):\n result.append( ' '.join(row1[i1]) )\n i2 += 1\n elif i2 == len(row2):\n result.append( ' '.join(row2[i2]) )\n i1 += 1\n else:\n if int(row1[i1].get(\"colspan\",\"1\")) < int(row2[i2].get(\"colspan\",\"1\")):\n c1= int(row1[i1].get(\"colspan\",\"1\"))\n while c1 != int(row2[i2].get(\"colspan\",\"1\")): \n txt1= ' '.join(row1[i1]) # needed to add when working adjust opposing case\n txt2= ' '.join(row2[i2]) # needed to add when working adjust opposing case\n result.append( txt1 + \" \" + txt2 ) # needed to add when working adjust opposing case\n print 'stayed in middle', 'i1=',i1,'i2=',i2, ' c1=',c1\n c1 += 1\n i1 += 1 # Is this the problem it\n \n elif int(row1[i1].get(\"colspan\",\"1\"))> int(row2[i2].get(\"colspan\",\"1\")):\n # Fill extra cols from row2 Make same adjustment as above\n c2= int(row2[i2].get(\"colspan\",\"1\"))\n while int(row1[i1].get(\"colspan\",\"1\")) != c2:\n result.append( ' '.join(row1[i1]) )\n c2 += 1\n i2 += 1\n else:\n assert int(row1[i1].get(\"colspan\",\"1\")) == int(row2[i2].get(\"colspan\",\"1\"))\n pass\n \n \n txt1= ' '.join(row1[i1])\n txt2= ' '.join(row2[i2])\n result.append( txt1 + \" \" + txt2 )\n print 'went to bottom', 'i1=',i1,'i2=',i2\n i1 += 1\n i2 += 1\nprint result\n\n", "Well I have an answer now. I was thinking through this and decided that I needed to use parts of every answer. I still need to figure out if I want a class or a function. But I have the algorithm that I think is probably more Pythonic than any of the others. But, it borrows heavily from the answers that some very generous people provided. I appreciate those a lot because I have learned quite a bit.\nTo save the time of having to make test cases I am going to paste the the complete code I have been banging away with in IDLE and follow that with an HTML sample file. Other than making a decision about class/function (and I need to think about how I am using this code in my program) I would be happy to see any improvements that make the code more Pythonic.\nfrom BeautifulSoup import BeautifulSoup\n\noriginal=file(r\"C:\\testheaders.htm\").read()\n\nsoupOriginal=BeautifulSoup(original)\nall_Rows=soupOriginal.findAll('tr')\n\n\nheader_Rows=[]\nfor each in range(len(all_Rows)):\n header_Rows.append(all_Rows[each])\n\n\nheader_Cells=[]\nfor each in header_Rows:\n header_Cells.append(each.findAll('td'))\n\ntemp_Header_Row=[]\nheader=[]\nfor row in range(len(header_Cells)):\n for column in range(len(header_Cells[row])):\n x=int(header_Cells[row][column].get(\"colspan\",\"1\"))\n if x==1:\n temp_Header_Row.append( ' '.join(header_Cells[row][column]) )\n\n else:\n for item in range(x):\n\n temp_Header_Row.append( ''.join(header_Cells[row][column]) )\n\n header.append(temp_Header_Row)\ntemp_Header_Row=[]\ncombined_Header=zip(*header)\n\nfor each in combined_Header:\n print each\n\nOkay test file contents are below Sorry I tried to attach these but couldn't make it happen:\n <TABLE style=\"font-size: 10pt\" cellspacing=\"0\" border=\"0\" cellpadding=\"0\" width=\"100%\">\n <TR valign=\"bottom\">\n <TD width=\"40%\">&nbsp;</TD>\n <TD width=\"5%\">&nbsp;</TD>\n <TD width=\"3%\">&nbsp;</TD>\n <TD width=\"3%\">&nbsp;</TD>\n <TD width=\"1%\">&nbsp;</TD>\n\n <TD width=\"5%\">&nbsp;</TD>\n <TD width=\"3%\">&nbsp;</TD>\n <TD width=\"3%\">&nbsp;</TD>\n <TD width=\"1%\">&nbsp;</TD>\n\n <TD width=\"5%\">&nbsp;</TD>\n <TD width=\"3%\">&nbsp;</TD>\n <TD width=\"1%\">&nbsp;</TD>\n <TD width=\"1%\">&nbsp;</TD>\n\n <TD width=\"5%\">&nbsp;</TD>\n <TD width=\"3%\">&nbsp;</TD>\n <TD width=\"1%\">&nbsp;</TD>\n <TD width=\"1%\">&nbsp;</TD>\n\n <TD width=\"5%\">&nbsp;</TD>\n <TD width=\"3%\">&nbsp;</TD>\n <TD width=\"3%\">&nbsp;</TD>\n <TD width=\"1%\">&nbsp;</TD>\n </TR>\n <TR style=\"font-size: 10pt\" valign=\"bottom\">\n <TD>&nbsp;</TD>\n <TD>&nbsp;</TD>\n <TD>&nbsp;</TD>\n <TD>&nbsp;</TD>\n <TD>&nbsp;</TD>\n <TD>&nbsp;</TD>\n <TD>&nbsp;</TD>\n <TD>&nbsp;</TD>\n <TD>&nbsp;</TD>\n <TD>&nbsp;</TD>\n <TD nowrap align=\"right\" colspan=\"2\">FOODS WE LIKE</TD>\n <TD>&nbsp;</TD>\n <TD>&nbsp;</TD>\n <TD nowrap align=\"right\" colspan=\"2\">&nbsp;</TD>\n <TD>&nbsp;</TD>\n <TD>&nbsp;</TD>\n <TD nowrap align=\"right\" colspan=\"2\">&nbsp;</TD>\n <TD>&nbsp;</TD>\n </TR>\n <TR style=\"font-size: 10pt\" valign=\"bottom\">\n <TD>&nbsp;</TD>\n <TD>&nbsp;</TD>\n <TD nowrap align=\"CENTER\" colspan=\"6\">SILLY STUFF</TD>\n\n <TD>&nbsp;</TD>\n <TD>&nbsp;</TD>\n <TD nowrap align=\"right\" colspan=\"2\">OTHER THAN</TD>\n <TD>&nbsp;</TD>\n <TD>&nbsp;</TD>\n <TD nowrap align=\"CENTER\" colspan=\"6\">FAVORITE PEOPLE</TD>\n <TD>&nbsp;</TD>\n </TR>\n <TR style=\"font-size: 10pt\" valign=\"bottom\">\n <TD>&nbsp;</TD>\n <TD>&nbsp;</TD>\n <TD nowrap align=\"right\" colspan=\"2\">MONTY PYTHON</TD>\n <TD>&nbsp;</TD>\n <TD>&nbsp;</TD>\n <TD nowrap align=\"right\" colspan=\"2\">CHERRYPY</TD>\n <TD>&nbsp;</TD>\n <TD>&nbsp;</TD>\n <TD nowrap align=\"right\" colspan=\"2\">APPLE PIE</TD>\n <TD>&nbsp;</TD>\n <TD>&nbsp;</TD>\n <TD nowrap align=\"right\" colspan=\"2\">MOTHERS</TD>\n <TD>&nbsp;</TD>\n <TD>&nbsp;</TD>\n <TD nowrap align=\"right\" colspan=\"2\">FATHERS</TD>\n <TD>&nbsp;</TD>\n </TR>\n <TR style=\"font-size: 10pt\" valign=\"bottom\">\n <TD nowrap align=\"left\">Name</TD>\n <TD>&nbsp;</TD>\n <TD nowrap align=\"right\" colspan=\"2\">SHOWS</TD>\n <TD>&nbsp;</TD>\n <TD>&nbsp;</TD>\n <TD nowrap align=\"right\" colspan=\"2\">PROGRAMS</TD>\n <TD>&nbsp;</TD>\n <TD>&nbsp;</TD>\n <TD nowrap align=\"right\" colspan=\"2\">BANANAS</TD>\n <TD>&nbsp;</TD>\n <TD>&nbsp;</TD>\n <TD nowrap align=\"right\" colspan=\"2\">PERFUME</TD>\n <TD>&nbsp;</TD>\n <TD>&nbsp;</TD>\n <TD nowrap align=\"right\" colspan=\"2\">TOOLS</TD>\n <TD>&nbsp;</TD>\n </TR>\n </TABLE>\n\n" ]
[ 3, 2, 1, 0, 0 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0000277187_beautifulsoup_python.txt
Q: How to use Popen in Windows to invoke an external .py script and wait for its completion Have you ever tried this feedback calling an external zip.py script to work? My CGITB does not show any error messages. It simply did not invoke external .py script to work. It simply skipped over to gush. I should be grateful if you can assist me in making this zip.py callable in feedback.py. Regards. David #********************************************************************** # Description: # Zips the contents of a folder. # Parameters: # 0 - Input folder. # 1 - Output zip file. It is assumed that the user added the .zip # extension. #********************************************************************** # Import modules and create the geoprocessor # import sys, zipfile, arcgisscripting, os, traceback gp = arcgisscripting.create() # Function for zipping files. If keep is true, the folder, along with # all its contents, will be written to the zip file. If false, only # the contents of the input folder will be written to the zip file - # the input folder name will not appear in the zip file. # def zipws(path, zip, keep): path = os.path.normpath(path) # os.walk visits every subdirectory, returning a 3-tuple # of directory name, subdirectories in it, and filenames # in it. # for (dirpath, dirnames, filenames) in os.walk(path): # Iterate over every filename # for file in filenames: # Ignore .lock files # if not file.endswith('.lock'): gp.AddMessage("Adding %s..." % os.path.join(path, dirpath, file)) try: if keep: zip.write(os.path.join(dirpath, file), os.path.join(os.path.basename(path), os.path.join(dirpath, file)[len(path)+len(os.sep):])) else: zip.write(os.path.join(dirpath, file), os.path.join(dirpath[len(path):], file)) except Exception, e: gp.AddWarning(" Error adding %s: %s" % (file, e)) return None if __name__ == '__main__': try: # Get the tool parameter values # infolder = gp.GetParameterAsText(0) outfile = gp.GetParameterAsText(1) # Create the zip file for writing compressed data. In some rare # instances, the ZIP_DEFLATED constant may be unavailable and # the ZIP_STORED constant is used instead. When ZIP_STORED is # used, the zip file does not contain compressed data, resulting # in large zip files. # try: zip = zipfile.ZipFile(outfile, 'w', zipfile.ZIP_DEFLATED) zipws(infolder, zip, True) zip.close() except RuntimeError: # Delete zip file if exists # if os.path.exists(outfile): os.unlink(outfile) zip = zipfile.ZipFile(outfile, 'w', zipfile.ZIP_STORED) zipws(infolder, zip, True) zip.close() gp.AddWarning(" Unable to compress zip file contents.") gp.AddMessage("Zip file created successfully") except: # Return any python specific errors as well as any errors from the geoprocessor # tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] pymsg = "PYTHON ERRORS:\nTraceback Info:\n" + tbinfo + "\nError Info:\n " + str(sys.exc_type) + ": " + str(sys.exc_value) + "\n" gp.AddError(pymsg) msgs = "GP ERRORS:\n" + gp.GetMessages(2) + "\n" gp.AddError(msgs) A: zip() is a built-in function in Python. Therefore it is a bad practice to use zip as a variable name. zip_ can be used instead of. execfile() function reads and executes a Python script. It is probably that you actually need just import zip_ in feedback.py instead of execfile(). A: Yay ArcGIS. Just to clarify how are you trying to call this script using popen, can you post some code? If your invoking this script via another script in the ArcGIS environment, then the thing is, when you use Popen the script wont be invoked within the ArcGIS environment, instead it will be invoked within windows. So you will loose all real control over it. Also just another ArcGIS comment you never initalize a license for the geoprocessor. My suggestion refactor your code, into a module function that simply attempts to zip the files, if it fails print the message out to ArcGIS. If you want post how you are calling it, and how this is being run.
How to use Popen in Windows to invoke an external .py script and wait for its completion
Have you ever tried this feedback calling an external zip.py script to work? My CGITB does not show any error messages. It simply did not invoke external .py script to work. It simply skipped over to gush. I should be grateful if you can assist me in making this zip.py callable in feedback.py. Regards. David #********************************************************************** # Description: # Zips the contents of a folder. # Parameters: # 0 - Input folder. # 1 - Output zip file. It is assumed that the user added the .zip # extension. #********************************************************************** # Import modules and create the geoprocessor # import sys, zipfile, arcgisscripting, os, traceback gp = arcgisscripting.create() # Function for zipping files. If keep is true, the folder, along with # all its contents, will be written to the zip file. If false, only # the contents of the input folder will be written to the zip file - # the input folder name will not appear in the zip file. # def zipws(path, zip, keep): path = os.path.normpath(path) # os.walk visits every subdirectory, returning a 3-tuple # of directory name, subdirectories in it, and filenames # in it. # for (dirpath, dirnames, filenames) in os.walk(path): # Iterate over every filename # for file in filenames: # Ignore .lock files # if not file.endswith('.lock'): gp.AddMessage("Adding %s..." % os.path.join(path, dirpath, file)) try: if keep: zip.write(os.path.join(dirpath, file), os.path.join(os.path.basename(path), os.path.join(dirpath, file)[len(path)+len(os.sep):])) else: zip.write(os.path.join(dirpath, file), os.path.join(dirpath[len(path):], file)) except Exception, e: gp.AddWarning(" Error adding %s: %s" % (file, e)) return None if __name__ == '__main__': try: # Get the tool parameter values # infolder = gp.GetParameterAsText(0) outfile = gp.GetParameterAsText(1) # Create the zip file for writing compressed data. In some rare # instances, the ZIP_DEFLATED constant may be unavailable and # the ZIP_STORED constant is used instead. When ZIP_STORED is # used, the zip file does not contain compressed data, resulting # in large zip files. # try: zip = zipfile.ZipFile(outfile, 'w', zipfile.ZIP_DEFLATED) zipws(infolder, zip, True) zip.close() except RuntimeError: # Delete zip file if exists # if os.path.exists(outfile): os.unlink(outfile) zip = zipfile.ZipFile(outfile, 'w', zipfile.ZIP_STORED) zipws(infolder, zip, True) zip.close() gp.AddWarning(" Unable to compress zip file contents.") gp.AddMessage("Zip file created successfully") except: # Return any python specific errors as well as any errors from the geoprocessor # tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] pymsg = "PYTHON ERRORS:\nTraceback Info:\n" + tbinfo + "\nError Info:\n " + str(sys.exc_type) + ": " + str(sys.exc_value) + "\n" gp.AddError(pymsg) msgs = "GP ERRORS:\n" + gp.GetMessages(2) + "\n" gp.AddError(msgs)
[ "\nzip() is a built-in function in Python. Therefore it is a bad practice to use zip as a variable name. zip_ can be used instead of.\nexecfile() function reads and executes a Python script.\nIt is probably that you actually need just import zip_ in feedback.py instead of execfile().\n\n", "Yay ArcGIS.\nJust to clarify how are you trying to call this script using popen, can you post some code?\nIf your invoking this script via another script in the ArcGIS environment, then the thing is, when you use Popen the script wont be invoked within the ArcGIS environment, instead it will be invoked within windows. So you will loose all real control over it.\nAlso just another ArcGIS comment you never initalize a license for the geoprocessor.\nMy suggestion refactor your code, into a module function that simply attempts to zip the files, if it fails print the message out to ArcGIS.\nIf you want post how you are calling it, and how this is being run.\n" ]
[ 1, 0 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0000283894_python_windows.txt
Q: Testing Web Services Consumer Here are some tools that I have found to test web services consumers: http://www.soapui.org/ https://wsunit.dev.java.net/ Are there any others? I would prefer testing frameworks that are written in Java or Python. A: I have used soapui by a maven plugin. It can create junit-linke reports to be run and analysed like unit tests. This can be easily integrated in continious build, also with the free distribution of soapui. A: I've used Web Service Studio. Web Service Studio is a tool to invoke web methods interactively. The user can provide a WSDL endpoint. On clicking button Get the tool fetches the WSDL, generates .NET proxy from the WSDL and displays the list of methods available. The user can choose any method and provide the required input parameters. On clicking Invoke the SOAP request is sent to the server and the response is parsed to display the return value. This tool is meant for web service implementers to test their web services without having to write the client code. This could also be used to access other web services whose WSDL endpoint is known. Also the Web Services Explorer in Eclipse which comes as part of the Web Tools Platform. Through UDDI and WSIL, other applications can discover WSDL documents and bind with them to execute transactions or perform other business processes. The Web Services Explorer allows you to explore, import, and test WSDL documents. A: The Grinder is right up your ally with both Java and Python, that handles most web services, (SOAP/REST/CORBA/RMI/JMS/EJB) etc. http://grinder.sourceforge.net/ A: You really need to be more specific: What is it that you want to test in your WS-consumer? That it calls the right WS? This looks a bit pointless - WS are a perfect place for mocking whatever may be called - without anything being called. In order to test the consumer you'd otherwise be writing a Webservice that mocks the original, right? I'd suppose that the communication protocol that goes through the wire is not the clients domain - e.g. it's generated. So the only thing a WS-consumer's client sees is the interface. And there's nothing to test in an interface. It might be that I completely misunderstood your question - please clarify if I did. I'll revise the answer then.
Testing Web Services Consumer
Here are some tools that I have found to test web services consumers: http://www.soapui.org/ https://wsunit.dev.java.net/ Are there any others? I would prefer testing frameworks that are written in Java or Python.
[ "I have used soapui by a maven plugin. It can create junit-linke reports to be run and analysed like unit tests. This can be easily integrated in continious build, also with the free distribution of soapui.\n", "I've used Web Service Studio.\n\nWeb Service Studio is a tool to invoke web methods interactively. The\n user can provide a WSDL endpoint. On clicking button Get the tool\n fetches the WSDL, generates .NET proxy from the WSDL and displays the\n list of methods available. The user can choose any method and provide\n the required input parameters. On clicking Invoke the SOAP request is\n sent to the server and the response is parsed to display the return\n value.\nThis tool is meant for web service implementers to test their web\n services without having to write the client code. This could also be\n used to access other web services whose WSDL endpoint is known.\n\nAlso the Web Services Explorer in Eclipse which comes as part of the Web Tools Platform.\n\nThrough UDDI and WSIL, other applications can discover WSDL documents\n and bind with them to execute transactions or perform other business\n processes. The Web Services Explorer allows you to explore, import,\n and test WSDL documents.\n\n", "The Grinder is right up your ally with both Java and Python, that handles most web services, (SOAP/REST/CORBA/RMI/JMS/EJB) etc.\nhttp://grinder.sourceforge.net/\n", "You really need to be more specific: What is it that you want to test in your WS-consumer? That it calls the right WS? This looks a bit pointless - WS are a perfect place for mocking whatever may be called - without anything being called.\nIn order to test the consumer you'd otherwise be writing a Webservice that mocks the original, right? I'd suppose that the communication protocol that goes through the wire is not the clients domain - e.g. it's generated. So the only thing a WS-consumer's client sees is the interface. And there's nothing to test in an interface.\nIt might be that I completely misunderstood your question - please clarify if I did. I'll revise the answer then.\n" ]
[ 1, 1, 0, 0 ]
[]
[]
[ "integration_testing", "java", "python", "testing", "web_services" ]
stackoverflow_0000273060_integration_testing_java_python_testing_web_services.txt
Q: Is it possible to use wxPython inside IronPython? When my IronPython program gets to the line import wx I get this message: A first chance exception of type 'IronPython.Runtime.Exceptions.PythonImportErrorException' occurred in IronPython.dll Additional information: No module named _core_ although I do have the file wx\_core_.pyd. Also, before attempting the import, I have the lines: sys.path.append('c:\\Python24\\Lib\\site-packages') sys.path.append('c:\\Python24\\Lib\\site-packages\\wx-2.6-msw-unicode') sys.path.append('c:\\Python24\\Lib\\site-packages\\wx-2.6-msw-unicode\\wx') sys.path.append('c:\\Python24\\Lib\\site-packages\\wx-2.6-msw-unicode\\wx\\lib') sys.path.append('c:\\Python24\\Lib\\site-packages\\wx-2.6-msw-unicode\\wxpython\\lib') sys.path.append('c:\\Python24\\Lib\\site-packages\\wxaddons') which I hoped would let IronPython find everything it needed. A: No, this won't work. Wx bindings (like most other "python bindings") are actually compiled against CPython. In this regards they are not just packages on sys.path to be found, as you have tried. They actually depend on CPython itself. This rather dry document explains the process. Note: There was a mission by some of the crew at Resolver Systems to allow you to use CPython bindings with IronPython (called IronClad) but this is in its early stages, and I think they will concentrate on getting things like Numpy working first, GUI toolkits will always be the last, and hardest. A: While wxPython is unavailable for the reasons listed by @Ali, you may want to take a look at wx.NET. You could use IronPython to call these assemblies instead, and it should be cross-platform (I'm assuming that's what you're after, or you would just use WinForms). If all you're looking for is API compatibility, I think you're out of luck :(
Is it possible to use wxPython inside IronPython?
When my IronPython program gets to the line import wx I get this message: A first chance exception of type 'IronPython.Runtime.Exceptions.PythonImportErrorException' occurred in IronPython.dll Additional information: No module named _core_ although I do have the file wx\_core_.pyd. Also, before attempting the import, I have the lines: sys.path.append('c:\\Python24\\Lib\\site-packages') sys.path.append('c:\\Python24\\Lib\\site-packages\\wx-2.6-msw-unicode') sys.path.append('c:\\Python24\\Lib\\site-packages\\wx-2.6-msw-unicode\\wx') sys.path.append('c:\\Python24\\Lib\\site-packages\\wx-2.6-msw-unicode\\wx\\lib') sys.path.append('c:\\Python24\\Lib\\site-packages\\wx-2.6-msw-unicode\\wxpython\\lib') sys.path.append('c:\\Python24\\Lib\\site-packages\\wxaddons') which I hoped would let IronPython find everything it needed.
[ "No, this won't work. Wx bindings (like most other \"python bindings\") are actually compiled against CPython.\nIn this regards they are not just packages on sys.path to be found, as you have tried. They actually depend on CPython itself. This rather dry document explains the process.\nNote: There was a mission by some of the crew at Resolver Systems to allow you to use CPython bindings with IronPython (called IronClad) but this is in its early stages, and I think they will concentrate on getting things like Numpy working first, GUI toolkits will always be the last, and hardest.\n", "While wxPython is unavailable for the reasons listed by @Ali, you may want to take a look at wx.NET. You could use IronPython to call these assemblies instead, and it should be cross-platform (I'm assuming that's what you're after, or you would just use WinForms). If all you're looking for is API compatibility, I think you're out of luck :(\n" ]
[ 8, 5 ]
[]
[]
[ "ironpython", "python", "wxpython" ]
stackoverflow_0000283447_ironpython_python_wxpython.txt
Q: How can I download python .egg files, when behind a firewall I'm going to try out turbogears however I'm on windows vista. however due to firewall proxy problems, it seems i can't download .egg files which is required for setup turbogears to get installed in my windows environment. I do have a bootable, or I can make a bootable Linux USB, I can try cygwin but I am not sure where to start with cygwin, so I was wondering what would solve my firewall / proxy problem of installing something like turbogears. if it's possible, is there some non-online version of turbogears that i could just download from visiting a site and then somehow importing that non-online version into my python environment? thanks so much!:) A: Perhaps the problem is not with the firewall per se, but with the fact that you need to use an HTTP proxy. If you do need to use a proxy, try setting the http_proxy environment variable. It might be that your firewall uses NTLM proxy authentication (which Python doesn't support); in this case, try setting up an APS proxy server on your local machine, and point http_proxy to localhost. A: You can run TG locally from windows. The tgsetup.py method of installation uses setuptools which depends on being able to bring in .egg files from the internet. The best approach would be to open the firewall to eggs, as others suggested. TG has a list of egg files that you can try to bring manually (maybe from an open internet connection). Installing an egg manually is possible, but not recommended. If changing the firewall rules is not possible, you can use a Linux (bootable or virtual) installation that has a pre-configured TG package. For example, Fedora has one. This way, the TG package crosses (hopefully) the firewall as an .rpm file. A: You could use the old firewall hack... try throwing "?file.jpg" or "#file.jpg" on the end (sans quotes). The firewall may see this as you're trying to download an image file which it'll allow, the responding server probably won't care that you've attached a query string, and (I think) python will just see an egg. A: Add python to the firewall exceptions list. Just make sure you don't run any questionable code made in python, of course. A: This might not be what you are looking for, but you can bypass the proxy tunneling SSH. Another possibility is using Tor.
How can I download python .egg files, when behind a firewall
I'm going to try out turbogears however I'm on windows vista. however due to firewall proxy problems, it seems i can't download .egg files which is required for setup turbogears to get installed in my windows environment. I do have a bootable, or I can make a bootable Linux USB, I can try cygwin but I am not sure where to start with cygwin, so I was wondering what would solve my firewall / proxy problem of installing something like turbogears. if it's possible, is there some non-online version of turbogears that i could just download from visiting a site and then somehow importing that non-online version into my python environment? thanks so much!:)
[ "Perhaps the problem is not with the firewall per se, but with the fact that you need to use an HTTP proxy. If you do need to use a proxy, try setting the http_proxy environment variable. It might be that your firewall uses NTLM proxy authentication (which Python doesn't support); in this case, try setting up an APS proxy server on your local machine, and point http_proxy to localhost.\n", "You can run TG locally from windows. The tgsetup.py method of installation uses setuptools which depends on being able to bring in .egg files from the internet. The best approach would be to open the firewall to eggs, as others suggested. TG has a list of egg files that you can try to bring manually (maybe from an open internet connection).\nInstalling an egg manually is possible, but not recommended.\nIf changing the firewall rules is not possible, you can use a Linux (bootable or virtual) installation that has a pre-configured TG package. For example, Fedora has one. This way, the TG package crosses (hopefully) the firewall as an .rpm file.\n", "You could use the old firewall hack... try throwing \"?file.jpg\" or \"#file.jpg\" on the end (sans quotes). The firewall may see this as you're trying to download an image file which it'll allow, the responding server probably won't care that you've attached a query string, and (I think) python will just see an egg.\n", "Add python to the firewall exceptions list. Just make sure you don't run any questionable code made in python, of course.\n", "This might not be what you are looking for, but you can bypass the proxy tunneling SSH. Another possibility is using Tor.\n" ]
[ 4, 3, 2, 1, 0 ]
[]
[]
[ "cygwin", "linux", "python", "turbogears", "windows" ]
stackoverflow_0000282907_cygwin_linux_python_turbogears_windows.txt
Q: XPath search with ElementTree New to xml. Looking for XPath to search a xml file with python ElementTree format <root> <child>One</child> <child>Two</child> <child>Three</child> </root> to do search for child with "Two" and return true/false if it was started off like from elementtree import ElementTree root = ElementTree.parse(open(PathFile)).getroot() how can this be achieved A: I've been playing with ElementTree lately, lets see.. >>> from xml.etree import ElementTree >>> help(ElementTree.ElementPath) >>> root = ElementTree.fromstring(""" <root><child>One</child><child>Two</child><child>Three</child></root> """) >>> ElementTree.ElementPath.findall(root, "child") [<Element child at 2ac98c0>, <Element child at 2ac9638>, <Element child at 2ac9518>] >>> elements = ElementTree.ElementPath.findall(root, "child") >>> two = [x for x in elements if x.text == "Two"] >>> two[0].text 'Two' This is what you look for right? It says ElementPath has just limited xpath support though, but it does not say not support at all. A: When the following XPath expression is evaluated:     boolean(/*/*[.='Two']) the result is true, if such an element (a child of the top element such that its string value is equal to "Two") exists, and false otherwise. Hope this helped. Cheers, Dimitre Novatchev
XPath search with ElementTree
New to xml. Looking for XPath to search a xml file with python ElementTree format <root> <child>One</child> <child>Two</child> <child>Three</child> </root> to do search for child with "Two" and return true/false if it was started off like from elementtree import ElementTree root = ElementTree.parse(open(PathFile)).getroot() how can this be achieved
[ "I've been playing with ElementTree lately, lets see..\n>>> from xml.etree import ElementTree\n>>> help(ElementTree.ElementPath)\n>>> root = ElementTree.fromstring(\"\"\"\n<root><child>One</child><child>Two</child><child>Three</child></root>\n\"\"\")\n>>> ElementTree.ElementPath.findall(root, \"child\")\n[<Element child at 2ac98c0>, <Element child at 2ac9638>, <Element child at 2ac9518>]\n>>> elements = ElementTree.ElementPath.findall(root, \"child\")\n>>> two = [x for x in elements if x.text == \"Two\"]\n>>> two[0].text\n'Two'\n\nThis is what you look for right? It says ElementPath has just limited xpath support though, but it does not say not support at all.\n", "When the following XPath expression is evaluated:\n    boolean(/*/*[.='Two'])\nthe result is true, if such an element (a child of the top element such that its string value is equal to \"Two\") exists,\nand false otherwise.\nHope this helped.\nCheers,\nDimitre Novatchev\n" ]
[ 1, 1 ]
[]
[]
[ "python", "xml", "xpath" ]
stackoverflow_0000238697_python_xml_xpath.txt
Q: Python module to extract probable dates from strings? I'm looking for a Python module that would take an arbitrary block of text, search it for something that looks like a date string, and build a DateTime object out of it. Something like Date::Extract in Perl Thank you in advance. A: The nearest equivalent is probably the dateutil module. Usage is: >>> from dateutil.parser import parse >>> parse("Wed, Nov 12") datetime.datetime(2008, 11, 12, 0, 0) Using the fuzzy parameter should ignore extraneous text. ie >>> parse("the date was the 1st of December 2006 2:30pm", fuzzy=True) datetime.datetime(2006, 12, 1, 14, 30) A: Why no give parsedatetime a try?
Python module to extract probable dates from strings?
I'm looking for a Python module that would take an arbitrary block of text, search it for something that looks like a date string, and build a DateTime object out of it. Something like Date::Extract in Perl Thank you in advance.
[ "The nearest equivalent is probably the dateutil module. Usage is:\n>>> from dateutil.parser import parse\n>>> parse(\"Wed, Nov 12\")\ndatetime.datetime(2008, 11, 12, 0, 0)\n\nUsing the fuzzy parameter should ignore extraneous text. ie\n>>> parse(\"the date was the 1st of December 2006 2:30pm\", fuzzy=True)\ndatetime.datetime(2006, 12, 1, 14, 30)\n\n", "Why no give parsedatetime a try?\n" ]
[ 12, 5 ]
[]
[]
[ "python" ]
stackoverflow_0000285408_python.txt
Q: With what kind of IDE (if any) you build python GUI projects? Is there any IDE (like VS) with drag and drop support for building python GUI, connecting to dbs etc? Eventhough I am an emacs guy, I find it much easier to create GUI with VS. A: The short answer is "no". There is not a swiss-army-knife like IDE that is both a full-featured Python code-editor and a full-featured WYSIWYG GUI editor. However, there are several stand-alone tools that make creating a GUI easier and there are a myriad of code editors, so if you can handle having two windows open, then you can accomplish what you are trying to. As for stand-alone GUI editors, which you choose is going to depend on what library you choose to develop your GUI with. I would recommend using GTK+, which binds to Python via PyGtk and has the Glade GUI designer. I believe that there are other GUI libraries for Python that have WYSIWYG designers (Qt, Tkinter, wxWindows, etc.), but GTK+ is the one I have the most experience with so I will leave the others for other commentators. Note, however, that the designer in this case is not at all language dependent. It just spits out a .glade file that could be loaded into any language that has GTK+ bindings. If you are looking for a designer that produces raw Python code (like the Code-Behind model that VS.Net uses), then I am not aware of any. As for general code-editing IDE's (that do not include a GUI designer), there are many, of which PyDev/Eclipse is probably the most Visual Studio-like. (Revised for clarity.) A: For GUI only, I find VisualWx (http://visualwx.altervista.org/) to be very good for designing wxPython apps under Windows. For GUI + database, dabo (http://dabodev.com/) is probably a good answer. A: Also for PyGTK, there is Gazpacho, it's pure python which makes adding your own custom widgets easier, and already has gtkbuilder support. I took over maintenance of the project a few months ago, and we plan to release it under the umbrella of the PIDA IDE, in a more Visual Studio-like setup. Patches accepted! A: I'm not really a Pythonista, but I am a Mac user and I appreciate a good, native interface in the apps I write and use. So, if I were to use Python for a GUI app on the Mac, I'd use PyObjC with Interface Builder and Xcode, rather than a cross-platform solution. A: If your into QT EricIDE is a good choice A: Eclipse has python support. There's also IDLE or Wingware, though I'm not sure of their GUI support. I'm sure a good google search would turn up more. But in the end, I doubt it. Python is dependent on third-party widget sets like Qt, Tk, Gtk, wxWidgets, etc for GUI support. Each of those will have their own system for laying things out. A: You can try Boa Constructor or Dabo A: I'm a GNOME guy, so I prefer PyGTK. The standard GUI builder for that is the Glade Interface Designer (until it transitions to GtkBuilder). A: For wxPython I use xrced to make GUI definitions contained in xml files, I find this way to be elegant and scalable. wxformbuilder is also good. As for the IDE, I'm a WingIDE fan.
With what kind of IDE (if any) you build python GUI projects?
Is there any IDE (like VS) with drag and drop support for building python GUI, connecting to dbs etc? Eventhough I am an emacs guy, I find it much easier to create GUI with VS.
[ "The short answer is \"no\". There is not a swiss-army-knife like IDE that is both a full-featured Python code-editor and a full-featured WYSIWYG GUI editor. However, there are several stand-alone tools that make creating a GUI easier and there are a myriad of code editors, so if you can handle having two windows open, then you can accomplish what you are trying to.\nAs for stand-alone GUI editors, which you choose is going to depend on what library you choose to develop your GUI with. I would recommend using GTK+, which binds to Python via PyGtk and has the Glade GUI designer. I believe that there are other GUI libraries for Python that have WYSIWYG designers (Qt, Tkinter, wxWindows, etc.), but GTK+ is the one I have the most experience with so I will leave the others for other commentators.\nNote, however, that the designer in this case is not at all language dependent. It just spits out a .glade file that could be loaded into any language that has GTK+ bindings. If you are looking for a designer that produces raw Python code (like the Code-Behind model that VS.Net uses), then I am not aware of any.\nAs for general code-editing IDE's (that do not include a GUI designer), there are many, of which PyDev/Eclipse is probably the most Visual Studio-like.\n(Revised for clarity.)\n", "For GUI only, I find VisualWx (http://visualwx.altervista.org/) to be very good for designing wxPython apps under Windows.\nFor GUI + database, dabo (http://dabodev.com/) is probably a good answer.\n", "Also for PyGTK, there is Gazpacho, it's pure python which makes adding your own custom widgets easier, and already has gtkbuilder support.\nI took over maintenance of the project a few months ago, and we plan to release it under the umbrella of the PIDA IDE, in a more Visual Studio-like setup. Patches accepted!\n", "I'm not really a Pythonista, but I am a Mac user and I appreciate a good, native interface in the apps I write and use. So, if I were to use Python for a GUI app on the Mac, I'd use PyObjC with Interface Builder and Xcode, rather than a cross-platform solution.\n", "If your into QT EricIDE is a good choice\n", "Eclipse has python support.\nThere's also IDLE or Wingware, though I'm not sure of their GUI support.\nI'm sure a good google search would turn up more.\nBut in the end, I doubt it. Python is dependent on third-party widget sets like Qt, Tk, Gtk, wxWidgets, etc for GUI support. Each of those will have their own system for laying things out.\n", "You can try Boa Constructor or Dabo\n", "I'm a GNOME guy, so I prefer PyGTK. The standard GUI builder for that is the Glade Interface Designer (until it transitions to GtkBuilder).\n", "For wxPython I use xrced to make GUI definitions contained in xml files, I find this way to be elegant and scalable.\nwxformbuilder is also good.\nAs for the IDE, I'm a WingIDE fan.\n" ]
[ 4, 4, 4, 2, 2, 1, 1, 1, 0 ]
[]
[]
[ "ide", "python", "user_interface" ]
stackoverflow_0000285132_ide_python_user_interface.txt
Q: Using Regex Plus Function in Python to Encode and Substitute I'm trying to substitute something in a string in python and am having some trouble. Here's what I'd like to do. For a given comment in my posting: "here are some great sites that i will do cool things with! https://stackoverflow.com/it's a pig & http://google.com" I'd like to use python to make the strings like this: "here are some great sites that i will do cool things with! <a href="http://stackoverflow.com">http%3A//stackoverflow.com</a> &amp; <a href="http://google.com">http%3A//google.com</a> Here's what I have so far... import re import urllib def getExpandedURL(url) encoded_url = urllib.quote(url) return "<a href=\"<a href="+url+"\">"+encoded_url+"</a>" text = '<text from above>' url_pattern = re.compile('(http.+?[^ ]+', re.I | re.S | re.M) url_iterator = url_pattern.finditer(text) for matched_url in url_iterator: getExpandedURL(matched_url.groups(1)[0]) But this is where i'm stuck. I've previously seen things on here like this: Regular Expressions but for Writing in the Match but surely there's got to be a better way than iterating through each match and doing a position replace on them. The difficulty here is that it's not a straight replace, but I need to do something specific with each match before replacing it. A: I think you want url_pattern.sub(getExpandedURL, text). re.sub(pattern, repl, string, count=0) Return the string obtained by replacing the leftmost non-overlapping occurrences of the pattern in string by the replacement repl. repl can be either a string or a callable; if a callable, it's passed the match object and must return a replacement string to be used.
Using Regex Plus Function in Python to Encode and Substitute
I'm trying to substitute something in a string in python and am having some trouble. Here's what I'd like to do. For a given comment in my posting: "here are some great sites that i will do cool things with! https://stackoverflow.com/it's a pig & http://google.com" I'd like to use python to make the strings like this: "here are some great sites that i will do cool things with! <a href="http://stackoverflow.com">http%3A//stackoverflow.com</a> &amp; <a href="http://google.com">http%3A//google.com</a> Here's what I have so far... import re import urllib def getExpandedURL(url) encoded_url = urllib.quote(url) return "<a href=\"<a href="+url+"\">"+encoded_url+"</a>" text = '<text from above>' url_pattern = re.compile('(http.+?[^ ]+', re.I | re.S | re.M) url_iterator = url_pattern.finditer(text) for matched_url in url_iterator: getExpandedURL(matched_url.groups(1)[0]) But this is where i'm stuck. I've previously seen things on here like this: Regular Expressions but for Writing in the Match but surely there's got to be a better way than iterating through each match and doing a position replace on them. The difficulty here is that it's not a straight replace, but I need to do something specific with each match before replacing it.
[ "I think you want url_pattern.sub(getExpandedURL, text).\n\nre.sub(pattern, repl, string, count=0)\nReturn the string obtained by replacing the leftmost non-overlapping occurrences of the pattern in string by the replacement repl. repl can be either a string or a callable; if a callable, it's passed the match object and must return a replacement string to be used.\n\n" ]
[ 3 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0000285931_python_regex.txt
Q: Decomposing HTML to link text and target Given an HTML link like <a href="urltxt" class="someclass" close="true">texttxt</a> how can I isolate the url and the text? Updates I'm using Beautiful Soup, and am unable to figure out how to do that. I did soup = BeautifulSoup.BeautifulSoup(urllib.urlopen(url)) links = soup.findAll('a') for link in links: print "link content:", link.content," and attr:",link.attrs i get *link content: None and attr: [(u'href', u'_redirectGeneric.asp?genericURL=/root /support.asp')]* ... ... Why am i missing the content? edit: elaborated on 'stuck' as advised :) A: Use Beautiful Soup. Doing it yourself is harder than it looks, you'll be better off using a tried and tested module. EDIT: I think you want: soup = BeautifulSoup.BeautifulSoup(urllib.urlopen(url).read()) By the way, it's a bad idea to try opening the URL there, as if it goes wrong it could get ugly. EDIT 2: This should show you all the links in a page: import urlparse, urllib from BeautifulSoup import BeautifulSoup url = "http://www.example.com/index.html" source = urllib.urlopen(url).read() soup = BeautifulSoup(source) for item in soup.fetchall('a'): try: link = urlparse.urlparse(item['href'].lower()) except: # Not a valid link pass else: print link A: Here's a code example, showing getting the attributes and contents of the links: soup = BeautifulSoup.BeautifulSoup(urllib.urlopen(url)) for link in soup.findAll('a'): print link.attrs, link.contents A: Looks like you have two issues there: link.contents, not link.content attrs is a dictionary, not a string. It holds key value pairs for each attribute in an HTML element. link.attrs['href'] will get you what you appear to be looking for, but you'd want to wrap that in a check in case you come across an a tag without an href attribute. A: Though I suppose the others might be correct in pointing you to using Beautiful Soup, they might not, and using an external library might be massively over-the-top for your purposes. Here's a regex which will do what you ask. /<a\s+[^>]*?href="([^"]*)".*?>(.*?)<\/a>/ Here's what it matches: '<a href="url" close="true">text</a>' // Parts: "url", "text" '<a href="url" close="true">text<span>something</span></a>' // Parts: "url", "text<span>something</span>" If you wanted to get just the text (eg: "textsomething" in the second example above), I'd just run another regex over it to strip anything between pointed brackets.
Decomposing HTML to link text and target
Given an HTML link like <a href="urltxt" class="someclass" close="true">texttxt</a> how can I isolate the url and the text? Updates I'm using Beautiful Soup, and am unable to figure out how to do that. I did soup = BeautifulSoup.BeautifulSoup(urllib.urlopen(url)) links = soup.findAll('a') for link in links: print "link content:", link.content," and attr:",link.attrs i get *link content: None and attr: [(u'href', u'_redirectGeneric.asp?genericURL=/root /support.asp')]* ... ... Why am i missing the content? edit: elaborated on 'stuck' as advised :)
[ "Use Beautiful Soup. Doing it yourself is harder than it looks, you'll be better off using a tried and tested module.\nEDIT:\nI think you want:\nsoup = BeautifulSoup.BeautifulSoup(urllib.urlopen(url).read())\n\nBy the way, it's a bad idea to try opening the URL there, as if it goes wrong it could get ugly.\nEDIT 2:\nThis should show you all the links in a page:\nimport urlparse, urllib\nfrom BeautifulSoup import BeautifulSoup\n\nurl = \"http://www.example.com/index.html\"\nsource = urllib.urlopen(url).read()\n\nsoup = BeautifulSoup(source)\n\nfor item in soup.fetchall('a'):\n try:\n link = urlparse.urlparse(item['href'].lower())\n except:\n # Not a valid link\n pass\n else:\n print link\n\n", "Here's a code example, showing getting the attributes and contents of the links:\nsoup = BeautifulSoup.BeautifulSoup(urllib.urlopen(url))\nfor link in soup.findAll('a'):\n print link.attrs, link.contents\n\n", "Looks like you have two issues there:\n\nlink.contents, not link.content\nattrs is a dictionary, not a string. It holds key value pairs for each attribute in an HTML element. link.attrs['href'] will get you what you appear to be looking for, but you'd want to wrap that in a check in case you come across an a tag without an href attribute.\n\n", "Though I suppose the others might be correct in pointing you to using Beautiful Soup, they might not, and using an external library might be massively over-the-top for your purposes. Here's a regex which will do what you ask.\n/<a\\s+[^>]*?href=\"([^\"]*)\".*?>(.*?)<\\/a>/\n\nHere's what it matches:\n'<a href=\"url\" close=\"true\">text</a>'\n// Parts: \"url\", \"text\"\n\n'<a href=\"url\" close=\"true\">text<span>something</span></a>'\n// Parts: \"url\", \"text<span>something</span>\"\n\nIf you wanted to get just the text (eg: \"textsomething\" in the second example above), I'd just run another regex over it to strip anything between pointed brackets.\n" ]
[ 8, 6, 4, 3 ]
[]
[]
[ "beautifulsoup", "html", "python", "regex" ]
stackoverflow_0000285938_beautifulsoup_html_python_regex.txt
Q: How to split a web address So I'm using python to do some parsing of web pages and I want to split the full web address into two parts. Say I have the address http://www.stackoverflow.com/questions/ask. I would need the protocol and domain (e.g. http://www.stackoverflow.com) and the path (e.g. /questions/ask). I figured this might be solved by some regex, however I'm not so handy with that. Any suggestions? A: Dan is right: urlparse is your friend: >>> from urlparse import urlparse >>> >>> parts = urlparse("http://www.stackoverflow.com/questions/ask") >>> parts.scheme + "://" + parts.netloc 'http://www.stackoverflow.com' >>> parts.path '/questions/ask' Note: In Python 3 it's from urllib.parse import urlparse A: Use the Python urlparse module: https://docs.python.org/library/urlparse.html For a well-defined and well-traveled problem like this, don't bother with writing your own code, let alone your own regular expressions. They cause too much trouble ;-).
How to split a web address
So I'm using python to do some parsing of web pages and I want to split the full web address into two parts. Say I have the address http://www.stackoverflow.com/questions/ask. I would need the protocol and domain (e.g. http://www.stackoverflow.com) and the path (e.g. /questions/ask). I figured this might be solved by some regex, however I'm not so handy with that. Any suggestions?
[ "Dan is right: urlparse is your friend:\n>>> from urlparse import urlparse\n>>>\n>>> parts = urlparse(\"http://www.stackoverflow.com/questions/ask\")\n>>> parts.scheme + \"://\" + parts.netloc\n'http://www.stackoverflow.com'\n>>> parts.path\n'/questions/ask'\n\nNote: In Python 3 it's from urllib.parse import urlparse\n", "Use the Python urlparse module:\nhttps://docs.python.org/library/urlparse.html\nFor a well-defined and well-traveled problem like this, don't bother with writing your own code, let alone your own regular expressions. They cause too much trouble ;-).\n" ]
[ 13, 7 ]
[ "import re\nurl = \"http://stackoverflow.com/questions/ask\"\nprotocol, domain = re.match(r\"(http://[^/]*)(.*)\", url).groups()\n\n" ]
[ -1 ]
[ "python", "split", "string", "url" ]
stackoverflow_0000286150_python_split_string_url.txt
Q: Python + Leopard + Fink + Mac Ports + Python.org + Idiot = broken Python - fresh start? I have been enjoying learning the basics of python, but before I started reading things I tried to install various python versions and modules clumsily. Now that I have some ideas of what I want to do and how to do it I'm finding that various aspects are broken. For instance, 2.6 IDLE won't launch, and when I try to import modules they usually don't work. My question is, how would you recommend I clean this up and start fresh? I have read information about modifying the 2.6 install, but I still can't get it to work. IDLE 2.4 works, and when I launch python from the terminal I am running python 2.4.4. A: I had this problem so much when I first got my Mac. The best solution I found was to delete everything I'd installed and just go with the pythonmac.org version of Python (2.6). I then installed setuptools from the same site, and then used easy_install to install every other package. Oh, and I got the GNU C Compiler from the Xcode developer tools CD (which you can download from Apple's website), so that I can compile C extensions. A: Macports should be easy to get rid of; just delete /opt/local/. I think that Fink does something similar. You can do which python to see what python is the default one. The system python should be in /System/Library/Frameworks/Python.framework/Versions/2.5/bin/python The MacPython you may have downloaded would either be in /Library/Frameworks/Python.framework. You can delete this as well. Also, both MacPython and MacPorts edit your ~/.profile and change the PYTHONPATH, make sure to edit it and remove the extra paths there. A: The easiest way to start afresh with Mac Ports or Fink is to simply remove the folder /sw/ (for fink) or /opt/ for MacPorts. To completely remove them, you will have to remove a line in your ~/.profile file: For fink: test -r /sw/bin/init.sh && . /sw/bin/init.sh ..and for MacPorts, I don't have it installed currently, but there will be something along the lines of: export PATH=$PATH:/opt/local/bin export PATH=$PATH:/opt/local/sbin As for installing Python, currently the cleanest way is to build it from source.. I wrote up how I installed Python 2.6 on Leopard here. It was for one of the 2.6 beta releases, so change the curl -O line to the newest release! In short, download and extract the latest python 2.6 source tarball, then (in a terminal) cd to where you extracted the tarball, and run the following commands.. ./configure --prefix=/usr/local/python2.6 make sudo make install That will install python2.6 into /usr/local/python2.6/ (the last line requires sudo, so will ask you for your password) Finally add /usr/local/python2.6 to $PATH, by adding the following line you the file ~/.profile export PATH=$PATH:/usr/local/python2.6 Then you will be able to run the python2.6 command. Ideally you would just install MacPython, but it doesn't seem to have a decent Python 2.6 installer yet.
Python + Leopard + Fink + Mac Ports + Python.org + Idiot = broken Python - fresh start?
I have been enjoying learning the basics of python, but before I started reading things I tried to install various python versions and modules clumsily. Now that I have some ideas of what I want to do and how to do it I'm finding that various aspects are broken. For instance, 2.6 IDLE won't launch, and when I try to import modules they usually don't work. My question is, how would you recommend I clean this up and start fresh? I have read information about modifying the 2.6 install, but I still can't get it to work. IDLE 2.4 works, and when I launch python from the terminal I am running python 2.4.4.
[ "I had this problem so much when I first got my Mac. The best solution I found was to delete everything I'd installed and just go with the pythonmac.org version of Python (2.6). I then installed setuptools from the same site, and then used easy_install to install every other package.\nOh, and I got the GNU C Compiler from the Xcode developer tools CD (which you can download from Apple's website), so that I can compile C extensions.\n", "Macports should be easy to get rid of; just delete /opt/local/. I think that Fink does something similar.\nYou can do which python to see what python is the default one. The system python should be in /System/Library/Frameworks/Python.framework/Versions/2.5/bin/python\nThe MacPython you may have downloaded would either be in /Library/Frameworks/Python.framework. You can delete this as well.\nAlso, both MacPython and MacPorts edit your ~/.profile and change the PYTHONPATH, make sure to edit it and remove the extra paths there.\n", "The easiest way to start afresh with Mac Ports or Fink is to simply remove the folder /sw/ (for fink) or /opt/ for MacPorts.\nTo completely remove them, you will have to remove a line in your ~/.profile file:\nFor fink:\ntest -r /sw/bin/init.sh && . /sw/bin/init.sh\n\n..and for MacPorts, I don't have it installed currently, but there will be something along the lines of:\nexport PATH=$PATH:/opt/local/bin\nexport PATH=$PATH:/opt/local/sbin\n\n\nAs for installing Python, currently the cleanest way is to build it from source..\nI wrote up how I installed Python 2.6 on Leopard here. It was for one of the 2.6 beta releases, so change the curl -O line to the newest release!\nIn short, download and extract the latest python 2.6 source tarball, then (in a terminal) cd to where you extracted the tarball, and run the following commands..\n./configure --prefix=/usr/local/python2.6\nmake\nsudo make install\n\nThat will install python2.6 into /usr/local/python2.6/ (the last line requires sudo, so will ask you for your password)\nFinally add /usr/local/python2.6 to $PATH, by adding the following line you the file ~/.profile\nexport PATH=$PATH:/usr/local/python2.6\n\nThen you will be able to run the python2.6 command.\nIdeally you would just install MacPython, but it doesn't seem to have a decent Python 2.6 installer yet.\n" ]
[ 4, 1, 1 ]
[]
[]
[ "python", "python_2.6", "python_install" ]
stackoverflow_0000242065_python_python_2.6_python_install.txt
Q: Why would an "command not recognized" error occur only when a window is populated? My record sheet app has a menu option for creating a new, blank record sheet. When I open a sheet window, I can open new windows without a problem, using subprocess.Popen() to do it. However, under Windows (I haven't tested it on other OSes yet), if I open a new window then use the "open file" dialog to populate the fields with data from a file, I'm no longer able to create new windows. Once it's populated, Windows gives me the 'foo.py' is not recognized as an internal or external command, operable program or batch file. I don't understand what would cause Windows to suddenly not recognize the Popen() call. I don't have any code that would affect it in any way that I'm aware of. A: From the error message, it looks like you need to pass the full path of "foo.py" to your Popen call. Normally just having "foo.py" will search in your current working directory, but this can be a bit unpredictable on Windows, I have found. Yours seems to be jumping around with the open file dialog. Secondly, just for good measure, it would seem like you would need to pass foo.py as an argument to python.exe executable, rather than executing foo.py itself. Again, I would specify this by path. So to be safe, something like: subprocess.Popen([r'C:\Python2.5\python.exe', r'C:\path\to\foo.py']) A: The suggested answer seems to have fixed the problem. I also realized that I needed to use os.name to determine which OS is being used, then I can use the correct path format for loading the external Python file.
Why would an "command not recognized" error occur only when a window is populated?
My record sheet app has a menu option for creating a new, blank record sheet. When I open a sheet window, I can open new windows without a problem, using subprocess.Popen() to do it. However, under Windows (I haven't tested it on other OSes yet), if I open a new window then use the "open file" dialog to populate the fields with data from a file, I'm no longer able to create new windows. Once it's populated, Windows gives me the 'foo.py' is not recognized as an internal or external command, operable program or batch file. I don't understand what would cause Windows to suddenly not recognize the Popen() call. I don't have any code that would affect it in any way that I'm aware of.
[ "From the error message, it looks like you need to pass the full path of \"foo.py\" to your Popen call. Normally just having \"foo.py\" will search in your current working directory, but this can be a bit unpredictable on Windows, I have found. Yours seems to be jumping around with the open file dialog.\nSecondly, just for good measure, it would seem like you would need to pass foo.py as an argument to python.exe executable, rather than executing foo.py itself. Again, I would specify this by path.\nSo to be safe, something like:\nsubprocess.Popen([r'C:\\Python2.5\\python.exe', r'C:\\path\\to\\foo.py'])\n\n", "The suggested answer seems to have fixed the problem. I also realized that I needed to use os.name to determine which OS is being used, then I can use the correct path format for loading the external Python file.\n" ]
[ 4, 0 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0000283431_python_windows.txt
Q: Best video manipulation library for Python? I'd like to include some simple video editing functionality for the Python application I'm writing and googling comes up with: pymedia pyglet (using the media module) gst-python Requirements: Small footprint. I'm already using wxPython (just because), which bloats up the final EXE file pretty easily so preferably whatever I use to implement this video editing functionality shouldn't add to the bloat significantly. The library should still be actively maintained. It shouldn't require proprietary licensing, so FMOD is out of the question. Minimal dependencies Not a full-blown video editor. No need for fancy pants stuff. Just the ability to skip to different parts of a video and either grab a frame or put (multiple) markers for start and end of video sections to lop off bits. Cross platform - should be able to run on Windows, Linux and OS X at the end of the day. If you've used any of the above video editing libraries listed above or others I have yet to come across in your Python application, I'd like to know the pitfalls for each and how they stack up against each other. If you also know of a Python binding for avbin, I would like to know where to find it. gst-python (Gstreamer with Python bindings) doesn't seem to be very well documented. It also appears to be tightly coupled with pyGTK, which is also a pretty big toolkit. A: I would recommend that you look again at gst-python! It is not coupled with pyGTK. You can use it completely separately, with no dependencies on either the Python bindings or the C libraries of GTK. I've written several command-line utilities that use gst-python and not GTK. It's true that the gst-python docs are not so great. However, the documentation for the C API and modules is really very extensive, and the mapping from the C API to the Python API is very straightforward. And there is a very active Gstreamer community and I had good luck finding help on the mailing lists and IRC! A: I'm working on a project using pyglet right now and I absolutely love it. Their website is going slow right now, but normally the programming guide on their documentation page is an excellent introduction to the library. Their standard API documentation is also very thorough. I can't really go into the specifics right now of what our project is, but when you say you need Not a full blown video editor. No need for fancy pants stuff. Just the ability to skip to different parts of a video and either grab a frame or put (multiple) markers for start and end of video sections to lop off bits. I can verify that pyglet will make coding this a breeze. Going through the rest of your list, I can't speak for/against the file size right now, but pyglet is being actively maintained (in fact the devs were quite helpful to me on the bug tracker just two weeks ago), is BSD licensed, depends on nothing (with optional AVBIN support for additional file formats), It works for us on Windows and Linux. So far the only cross-platform gotcha we have come to is that as far as sound is concerned on Linux, you've got the option of OpenAL which will mix down stereo files to mono and ALSA which will not give you any volume control while a sound is playing. They claim that both of these problems are with upstream and are being worked on. A: gst-python isn't coupled with pygtk at all - it just happens to share a common object model (pygobject) and a way to help generate bindings. But you can easily use gst-python without pygtk - take Flumotion as an example. A: I am currently in the same predicament. I have been fortunate to get in touch with the developers of the Ardome Media Library project. This library is a filter graph based system. It is freely based on the http://www.khronos.org/openml/ I think. It currently runs on Linux and OS X with pending Windows integration.
Best video manipulation library for Python?
I'd like to include some simple video editing functionality for the Python application I'm writing and googling comes up with: pymedia pyglet (using the media module) gst-python Requirements: Small footprint. I'm already using wxPython (just because), which bloats up the final EXE file pretty easily so preferably whatever I use to implement this video editing functionality shouldn't add to the bloat significantly. The library should still be actively maintained. It shouldn't require proprietary licensing, so FMOD is out of the question. Minimal dependencies Not a full-blown video editor. No need for fancy pants stuff. Just the ability to skip to different parts of a video and either grab a frame or put (multiple) markers for start and end of video sections to lop off bits. Cross platform - should be able to run on Windows, Linux and OS X at the end of the day. If you've used any of the above video editing libraries listed above or others I have yet to come across in your Python application, I'd like to know the pitfalls for each and how they stack up against each other. If you also know of a Python binding for avbin, I would like to know where to find it. gst-python (Gstreamer with Python bindings) doesn't seem to be very well documented. It also appears to be tightly coupled with pyGTK, which is also a pretty big toolkit.
[ "I would recommend that you look again at gst-python! It is not coupled with pyGTK. You can use it completely separately, with no dependencies on either the Python bindings or the C libraries of GTK. I've written several command-line utilities that use gst-python and not GTK.\nIt's true that the gst-python docs are not so great. However, the documentation for the C API and modules is really very extensive, and the mapping from the C API to the Python API is very straightforward. And there is a very active Gstreamer community and I had good luck finding help on the mailing lists and IRC!\n", "I'm working on a project using pyglet right now and I absolutely love it. Their website is going slow right now, but normally the programming guide on their documentation page is an excellent introduction to the library. Their standard API documentation is also very thorough.\nI can't really go into the specifics right now of what our project is, but when you say you need\n\nNot a full blown video editor. No need\nfor fancy pants stuff. Just the\nability to skip to different parts of\na video and either grab a frame or put\n(multiple) markers for start and end\nof video sections to lop off bits.\n\nI can verify that pyglet will make coding this a breeze.\nGoing through the rest of your list, I can't speak for/against the file size right now, but pyglet is being actively maintained (in fact the devs were quite helpful to me on the bug tracker just two weeks ago), is BSD licensed, depends on nothing (with optional AVBIN support for additional file formats), It works for us on Windows and Linux.\nSo far the only cross-platform gotcha we have come to is that as far as sound is concerned on Linux, you've got the option of OpenAL which will mix down stereo files to mono and ALSA which will not give you any volume control while a sound is playing. They claim that both of these problems are with upstream and are being worked on.\n", "gst-python isn't coupled with pygtk at all - it just happens to share a common object model (pygobject) and a way to help generate bindings. But you can easily use gst-python without pygtk - take Flumotion as an example.\n", "I am currently in the same predicament. I have been fortunate to get in touch with the developers of the Ardome Media Library project.\nThis library is a filter graph based system. It is freely based on the \nhttp://www.khronos.org/openml/ I think.\nIt currently runs on Linux and OS X with pending Windows integration.\n" ]
[ 13, 9, 6, 3 ]
[]
[]
[ "editor", "python", "video" ]
stackoverflow_0000220866_editor_python_video.txt
Q: Accounting for a changing path In relation to another question, how do you account for paths that may change? For example, if a program is calling a file in the same directory as the program, you can simply use the path ".\foo.py" in *nix. However, apparently Windows likes to have the path hard-coded, e.g. "C:\Python_project\foo.py". What happens if the path changes? For example, the file may not be on the C: drive but on a thumb drive or external drive that can change the drive letter. The file may still be in the same directory as the program but it won't match the drive letter in the code. I want the program to be cross-platform, but I expect I may have to use os.name or something to determine which path code block to use. A: Simple answer: You work out the absolute path based on the environment. What you really need is a few pointers. There are various bits of runtime and environment information that you can glean from various places in the standard library (and they certainly help me when I want to deploy an application on windows). So, first some general things: os.path - standard library module with lots of cross-platform path manipulation. Your best friend. "Follow the os.path" I once read in a book. __file__ - The location of the current module. sys.executable - The location of the running Python. Now you can fairly much glean anything you want from these three sources. The functions from os.path will help you get around the tree: os.path.join('path1', 'path2') - join path segments in a cross-platform way os.path.expanduser('a_path') - find the path a_path in the user's home directory os.path.abspath('a_path') - convert a relative path to an absolute path os.path.dirname('a_path') - get the directory that a path is in many many more... So combining this, for example: # script1.py # Get the path to the script2.py in the same directory import os this_script_path = os.path.abspath(__file__) this_dir_path = os.path.dirname(this_script_path) script2_path = os.path.join(this_dir_path, 'script2.py') print script2_path And running it: ali@work:~/tmp$ python script1.py /home/ali/tmp/script2.py Now for your specific case, it seems you are slightly confused between the concept of a "working directory" and the "directory that a script is in". These can be the same, but they can also be different. For example the "working directory" can be changed, and so functions that use it might be able to find what they are looking for sometimes but not others. subprocess.Popen is an example of this. If you always pass paths absolutely, you will never get into working directory issues. A: If your file is always in the same directory as your program then: def _isInProductionMode(): """ returns True when running the exe, False when running from a script, ie development mode. """ return (hasattr(sys, "frozen") or # new py2exe hasattr(sys, "importers") # old py2exe or imp.is_frozen("__main__")) #tools/freeze def _getAppDir(): """ returns the directory name of the script or the directory name of the exe """ if _isInProductionMode(): return os.path.dirname(sys.executable) return os.path.dirname(__file__) should work. Also, I've used py2exe for my own application, and haven't tested it with other exe conversion apps. A: What -- specifically -- do you mean by "calling a file...foo.py"? Import? If so, the path is totally outside of your program. Set the PYTHONPATH environment variable with . or c:\ or whatever at the shell level. You can, for example, write 2-line shell scripts to set an environment variable and run Python. Windows SET PYTHONPATH=C:\path\to\library python myapp.py Linux export PYTHONPATH=./relative/path python myapp.py Execfile? Consider using import. Read and Eval? Consider using import. If the PYTHONPATH is too complicated, then put your module in the Python lib/site-packages directory, where it's put onto the PYTHONPATH by default for you.
Accounting for a changing path
In relation to another question, how do you account for paths that may change? For example, if a program is calling a file in the same directory as the program, you can simply use the path ".\foo.py" in *nix. However, apparently Windows likes to have the path hard-coded, e.g. "C:\Python_project\foo.py". What happens if the path changes? For example, the file may not be on the C: drive but on a thumb drive or external drive that can change the drive letter. The file may still be in the same directory as the program but it won't match the drive letter in the code. I want the program to be cross-platform, but I expect I may have to use os.name or something to determine which path code block to use.
[ "Simple answer: You work out the absolute path based on the environment.\nWhat you really need is a few pointers. There are various bits of runtime and environment information that you can glean from various places in the standard library (and they certainly help me when I want to deploy an application on windows).\nSo, first some general things:\n\nos.path - standard library module with lots of cross-platform path manipulation. Your best friend. \"Follow the os.path\" I once read in a book.\n__file__ - The location of the current module.\nsys.executable - The location of the running Python.\n\nNow you can fairly much glean anything you want from these three sources. The functions from os.path will help you get around the tree:\n\nos.path.join('path1', 'path2') - join path segments in a cross-platform way\nos.path.expanduser('a_path') - find the path a_path in the user's home directory\nos.path.abspath('a_path') - convert a relative path to an absolute path\nos.path.dirname('a_path') - get the directory that a path is in\nmany many more...\n\nSo combining this, for example:\n# script1.py\n# Get the path to the script2.py in the same directory\nimport os\nthis_script_path = os.path.abspath(__file__)\nthis_dir_path = os.path.dirname(this_script_path)\nscript2_path = os.path.join(this_dir_path, 'script2.py')\nprint script2_path\n\nAnd running it:\nali@work:~/tmp$ python script1.py \n/home/ali/tmp/script2.py\n\nNow for your specific case, it seems you are slightly confused between the concept of a \"working directory\" and the \"directory that a script is in\". These can be the same, but they can also be different. For example the \"working directory\" can be changed, and so functions that use it might be able to find what they are looking for sometimes but not others. subprocess.Popen is an example of this.\nIf you always pass paths absolutely, you will never get into working directory issues.\n", "If your file is always in the same directory as your program then:\ndef _isInProductionMode():\n \"\"\" returns True when running the exe, \n False when running from a script, ie development mode.\n \"\"\"\n return (hasattr(sys, \"frozen\") or # new py2exe\n hasattr(sys, \"importers\") # old py2exe\n or imp.is_frozen(\"__main__\")) #tools/freeze\n\ndef _getAppDir():\n \"\"\" returns the directory name of the script or the directory \n name of the exe\n \"\"\"\n if _isInProductionMode():\n return os.path.dirname(sys.executable)\n return os.path.dirname(__file__)\n\nshould work. Also, I've used py2exe for my own application, and haven't tested it with other exe conversion apps. \n", "What -- specifically -- do you mean by \"calling a file...foo.py\"?\n\nImport? If so, the path is totally outside of your program. Set the PYTHONPATH environment variable with . or c:\\ or whatever at the shell level. You can, for example, write 2-line shell scripts to set an environment variable and run Python.\nWindows\nSET PYTHONPATH=C:\\path\\to\\library\npython myapp.py\n\nLinux\nexport PYTHONPATH=./relative/path\npython myapp.py\n\nExecfile? Consider using import.\nRead and Eval? Consider using import.\n\nIf the PYTHONPATH is too complicated, then put your module in the Python lib/site-packages directory, where it's put onto the PYTHONPATH by default for you.\n" ]
[ 5, 0, 0 ]
[ "I figured out by using os.getcwd(). I also learned about using os.path.join to automatically determine the correct path format based on the OS. Here's the code:\ndef openNewRecord(self, event): # wxGlade: CharSheet.<event_handler>\n \"\"\"Create a new, blank record sheet.\"\"\"\n path = os.getcwd()\n subprocess.Popen(os.path.join(path, \"TW2K_char_rec_sheet.py\"), shell=True).stdout\n\nIt appears to be working. Thanks for the ideas.\n" ]
[ -1 ]
[ "file", "path", "python" ]
stackoverflow_0000286486_file_path_python.txt
Q: Parsing C++ preprocessor #if statements I have a C/C++ source file with conditional compilation. Before I ship it to customers I want to remove most of the #if statements, so that my customers do not need to worry about passing the right -D options to the compiler. I have this implemented and working in Python, but it only handles #ifdef and #ifndef statements properly. I need to add support for #if statements, but the syntax of #if is much more complex. (E.g. you can use &&, ||, !, brackets, relational operators, arithmetic, etc). Is there any existing open-source code to parse and evaluate #if statements? (Preferably in Python). The only implementation I know of is GCC, and that's much too complex for this task. A: As KeithB said, you could just let the preprocessor do this for you. But if you're not trying to hide things (ie., there may be stuff in the conditionally compiled code that you don't want or aren't permitted to give to some one else) a much simpler option would be to just put the proper #define directives in a header that's globally included. your clients don't need to worry about -D options you don't have to have some custom step in your build process the code you give your clients isn't potentially semi-obfuscated you don't introduce bugs because the tool does things subtly different from the C preprocessor you don't have to maintain some custom tool A: How about just passing through the C preprocessor, and letting that do the job. It will get rid of all of them, so you might need to have a pre-preprocessor step and a post pre-processor step to protect things you don't want to be expanded. Change all #include to @include Pass file through preprocessor Change @include back to #include A: Instead of reinventing the wheel, download "unifdef". If you're on some flavour of Linux, you can probably find a package for it, otherwise it's on FreshMeat A: Have you looked at Boost.Wave? A: The GCC preprocessor is typicallly a stand-alone program, typically called cpp. That will probably also strip off your comments, of course.
Parsing C++ preprocessor #if statements
I have a C/C++ source file with conditional compilation. Before I ship it to customers I want to remove most of the #if statements, so that my customers do not need to worry about passing the right -D options to the compiler. I have this implemented and working in Python, but it only handles #ifdef and #ifndef statements properly. I need to add support for #if statements, but the syntax of #if is much more complex. (E.g. you can use &&, ||, !, brackets, relational operators, arithmetic, etc). Is there any existing open-source code to parse and evaluate #if statements? (Preferably in Python). The only implementation I know of is GCC, and that's much too complex for this task.
[ "As KeithB said, you could just let the preprocessor do this for you. \nBut if you're not trying to hide things (ie., there may be stuff in the conditionally compiled code that you don't want or aren't permitted to give to some one else) a much simpler option would be to just put the proper #define directives in a header that's globally included.\n\nyour clients don't need to worry about -D options\nyou don't have to have some custom step in your build process\nthe code you give your clients isn't potentially semi-obfuscated\nyou don't introduce bugs because the tool does things subtly different from the C preprocessor\nyou don't have to maintain some custom tool\n\n", "How about just passing through the C preprocessor, and letting that do the job. It will get rid of all of them, so you might need to have a pre-preprocessor step and a post pre-processor step to protect things you don't want to be expanded.\n\nChange all #include to @include\nPass file through preprocessor\nChange @include back to #include\n\n", "Instead of reinventing the wheel, download \"unifdef\". If you're on some flavour of Linux, you can probably find a package for it, otherwise it's on FreshMeat\n", "Have you looked at Boost.Wave?\n", "The GCC preprocessor is typicallly a stand-alone program, typically called cpp. That will probably also strip off your comments, of course.\n" ]
[ 14, 12, 8, 4, 0 ]
[]
[]
[ "c", "c++", "c_preprocessor", "parsing", "python" ]
stackoverflow_0000287379_c_c++_c_preprocessor_parsing_python.txt
Q: Python program start Should I start a Python program with: if__name__ == '__main__': some code... And if so, why? I saw it many times but don't have a clue about it. A: If your program is usable as a library but you also have a main program (e.g. to test the library), that construct lets others import the file as a library and not run your main program. If your program is named foo.py and you do "import foo" from another python file, __name__ evaluates to 'foo', but if you run "python foo.py" from the command line, __name__ evaluates to '__main__'. Note that you do need to insert a space between if and _, and indent the main program: if __name__ == '__main__': main program here A: A better pattern is this: def main(): ... if __name__ == '__main__': main() This allows your code to be invoked by someone who imported it, while also making programs such as pychecker and pylint work. A: Guido Van Rossum suggests: def main(argv=None): if argv is None: argv = sys.argv ... if __name__ == "__main__": sys.exit(main()) This way you can run main() from somewhere else (supplying the arguments), and if you want to exit with an error code just return 1 from main(), and it won't make an interactive interpreter exit by mistake. A: This is good practice. First, it clearly marks your module entry point (assuming you don't have any other executable code at toplevel - yuck). Second, it makes your module importable by other modules without executing, which some tools like code checkers, packagers etc. need to do.
Python program start
Should I start a Python program with: if__name__ == '__main__': some code... And if so, why? I saw it many times but don't have a clue about it.
[ "If your program is usable as a library but you also have a main program (e.g. to test the library), that construct lets others import the file as a library and not run your main program. If your program is named foo.py and you do \"import foo\" from another python file, __name__ evaluates to 'foo', but if you run \"python foo.py\" from the command line, __name__ evaluates to '__main__'.\nNote that you do need to insert a space between if and _, and indent the main program:\nif __name__ == '__main__':\n main program here\n\n", "A better pattern is this:\ndef main():\n ...\n\nif __name__ == '__main__':\n main()\n\nThis allows your code to be invoked by someone who imported it, while also making programs such as pychecker and pylint work.\n", "Guido Van Rossum suggests:\ndef main(argv=None):\n if argv is None:\n argv = sys.argv\n ...\n\nif __name__ == \"__main__\":\n sys.exit(main())\n\nThis way you can run main() from somewhere else (supplying the arguments), and if you want to exit with an error code just return 1 from main(), and it won't make an interactive interpreter exit by mistake.\n", "This is good practice. First, it clearly marks your module entry point (assuming you don't have any other executable code at toplevel - yuck). Second, it makes your module importable by other modules without executing, which some tools like code checkers, packagers etc. need to do.\n" ]
[ 30, 25, 22, 3 ]
[]
[]
[ "python" ]
stackoverflow_0000287204_python.txt
Q: What's the best way to transfer data from python to another application in windows? I'm developing an application with a team in .Net (C++) and provide a COM interface to interact with python and other languages. What we've found is that pushing data through COM turns out to be pretty slow. I've considered several alternatives: dumping data to a file and sending the file path through com Shared Memory via mmap? Stream data through a socket directly? From your experience what's the best way to pass around data? A: Staying within the Windows interprocess communication mechanisms, we had positive experience using windows named pipes. Using Windows overlapped IO and the win32pipe module from pywin32. You can learn much about win32 and python in the Python Programming On Win32 book. The sending part simply writes to r'\\.\pipe\mypipe'. A listener (ovpipe) object holds an event handle, and waiting for a message with possible other events involves calling win32event.WaitForMultipleObjects. rc = win32event.WaitForMultipleObjects( eventlist, # Objects to wait for. 0, # Wait for one object timeout) # timeout in milli-seconds. Here is part of the python overlapped listener class: import win32event import pywintypes import win32file import win32pipe class ovpipe: "Overlapped I/O named pipe class" def __init__(self): self.over=pywintypes.OVERLAPPED() evt=win32event.CreateEvent(None,1,0,None) self.over.hEvent=evt self.pname='mypipe' self.hpipe = win32pipe.CreateNamedPipe( r'\\.\pipe\mypipe', # pipe name win32pipe.PIPE_ACCESS_DUPLEX| # read/write access win32file.FILE_FLAG_OVERLAPPED, win32pipe.PIPE_TYPE_MESSAGE| # message-type pipe win32pipe.PIPE_WAIT, # blocking mode 1, # number of instances 512, # output buffer size 512, # input buffer size 2000, # client time-out None) # no security attributes self.buffer = win32file.AllocateReadBuffer(512) self.state='noconnected' self.chstate() def execmsg(self): "Translate the received message" pass def chstate(self): "Change the state of the pipe depending on current state" if self.state=='noconnected': win32pipe.ConnectNamedPipe(self.hpipe,self.over) self.state='connectwait' return -6 elif self.state=='connectwait': j,self.strbuf=win32file.ReadFile(self.hpipe,self.buffer,self.over) self.state='readwait' return -6 elif self.state=='readwait': size=win32file.GetOverlappedResult(self.hpipe,self.over,1) self.msg=self.strbuf[:size] ret=self.execmsg() self.state = 'noconnected' win32pipe.DisconnectNamedPipe(self.hpipe) return ret A: XML/JSON and a either a Web Service or directly through a socket. It is also language and platform independent so if you decide you want to host the python portion on UNIX you can, or if you want to suddenly use Java or PHP or pretty much any other language you can. As a general rule proprietary protocols/architectures like COM offer more restrictions than they do benefits. This is why the open specifications appeared in the first place. HTH A: +1 on the named pipes but I would also like to add that from your comments it seems that your application is very chatty. Every time you make a remote call no matter how fast the underlying transport is you have a fixed cost of marshaling the data and making a connection. You can save a huge amount of overhead if you change the addpoint(lat, long) method to a addpoints(point_array) method. The idea is similar to why we have database connection pools and http-keep-alive connections. The less actual calls you make the better. Your existing COM solution may even be good enough if you can just limit the number of calls you make over it. A: It shouldn't be too complicated to set up a test for each of your alternatives and do a benchmark. Noting beats context sensitive empirical data... :) Oh, and if you do this I'm sure a lot of people would be interested in the results.
What's the best way to transfer data from python to another application in windows?
I'm developing an application with a team in .Net (C++) and provide a COM interface to interact with python and other languages. What we've found is that pushing data through COM turns out to be pretty slow. I've considered several alternatives: dumping data to a file and sending the file path through com Shared Memory via mmap? Stream data through a socket directly? From your experience what's the best way to pass around data?
[ "Staying within the Windows interprocess communication mechanisms, we had positive experience using windows named pipes. \nUsing Windows overlapped IO and the win32pipe module from pywin32.\nYou can learn much about win32 and python in the Python Programming On Win32 book.\nThe sending part simply writes to r'\\\\.\\pipe\\mypipe'.\nA listener (ovpipe) object holds an event handle, and waiting for a message with possible other events involves calling win32event.WaitForMultipleObjects.\nrc = win32event.WaitForMultipleObjects(\n eventlist, # Objects to wait for.\n 0, # Wait for one object\n timeout) # timeout in milli-seconds.\n\nHere is part of the python overlapped listener class:\nimport win32event\nimport pywintypes\nimport win32file\nimport win32pipe\n\nclass ovpipe:\n\"Overlapped I/O named pipe class\"\ndef __init__(self):\n self.over=pywintypes.OVERLAPPED()\n evt=win32event.CreateEvent(None,1,0,None)\n self.over.hEvent=evt\n self.pname='mypipe'\n self.hpipe = win32pipe.CreateNamedPipe(\n r'\\\\.\\pipe\\mypipe', # pipe name \n win32pipe.PIPE_ACCESS_DUPLEX| # read/write access\n win32file.FILE_FLAG_OVERLAPPED,\n win32pipe.PIPE_TYPE_MESSAGE| # message-type pipe \n win32pipe.PIPE_WAIT, # blocking mode \n 1, # number of instances \n 512, # output buffer size \n 512, # input buffer size \n 2000, # client time-out\n None) # no security attributes\n self.buffer = win32file.AllocateReadBuffer(512)\n self.state='noconnected'\n self.chstate()\n\ndef execmsg(self):\n \"Translate the received message\"\n pass\n\ndef chstate(self):\n \"Change the state of the pipe depending on current state\"\n if self.state=='noconnected':\n win32pipe.ConnectNamedPipe(self.hpipe,self.over)\n self.state='connectwait'\n return -6\n\n elif self.state=='connectwait':\n j,self.strbuf=win32file.ReadFile(self.hpipe,self.buffer,self.over)\n self.state='readwait'\n return -6\n\n elif self.state=='readwait':\n size=win32file.GetOverlappedResult(self.hpipe,self.over,1)\n self.msg=self.strbuf[:size]\n ret=self.execmsg()\n self.state = 'noconnected'\n win32pipe.DisconnectNamedPipe(self.hpipe)\n return ret\n\n", "XML/JSON and a either a Web Service or directly through a socket. It is also language and platform independent so if you decide you want to host the python portion on UNIX you can, or if you want to suddenly use Java or PHP or pretty much any other language you can.\nAs a general rule proprietary protocols/architectures like COM offer more restrictions than they do benefits. This is why the open specifications appeared in the first place.\nHTH\n", "+1 on the named pipes but I would also like to add that from your comments it seems that your application is very chatty. Every time you make a remote call no matter how fast the underlying transport is you have a fixed cost of marshaling the data and making a connection. You can save a huge amount of overhead if you change the addpoint(lat, long) method to a addpoints(point_array) method. The idea is similar to why we have database connection pools and http-keep-alive connections. The less actual calls you make the better. Your existing COM solution may even be good enough if you can just limit the number of calls you make over it.\n", "It shouldn't be too complicated to set up a test for each of your alternatives and do a benchmark. Noting beats context sensitive empirical data... :)\nOh, and if you do this I'm sure a lot of people would be interested in the results.\n" ]
[ 9, 2, 2, 0 ]
[]
[]
[ "com", "data_transfer", "python", "winapi" ]
stackoverflow_0000286614_com_data_transfer_python_winapi.txt
Q: Dictonaries and Lambda inside a class? How can i do something like this: class Foo(): do_stuff = { "A" : lambda x: self.do_A(x), "B" : lambda x: self.do_B(x) } def __init__(self): print "hi" def run(self): muh = ['A', 'B', 'A'] for each in muh: self.do_stuff[each](each) def do_A(self, moo): print "A" def do_B(self, boo): print "B" if(__name__ == '__main__'): aFoo = Foo() aFoo.run() This results in it giving an error that self isn't defined at the lambda function, but if i remove it. It says do_A or do_B isn't defined. EDIT I managed to figure it out. I need to change the lambda expression into something like this: lambda x, y: x.do_A(y) and i would call it like: self.do_stuff[each](self, each) Is this a terrible idea? A: do_stuff is not an instance variable in your example. It's more like a static variable. You need to define do_stuff within a method (e.g., the init method) where you have a reference to self in order to make it an instance variable. I hope this example clarifies things for you: class Foo: def __init__(self): self.do_stuff = { "A": self.do_A, "B": self.do_B } def run(self): for x in ["A", "B"]: self.do_stuff[x]("hi") def do_A(self, x): pass def do_B(self, x): pass Note that the lambda functions aren't necessary. You can just store references to the functions themselves in your dictionary. The notation "self.do_A" will automatically pass self as the first argument. EDIT: Does anyone know how to make underscores show properly in non-code-sample text? EDIT: WTH? The preview is showing underscores differently than the post.
Dictonaries and Lambda inside a class?
How can i do something like this: class Foo(): do_stuff = { "A" : lambda x: self.do_A(x), "B" : lambda x: self.do_B(x) } def __init__(self): print "hi" def run(self): muh = ['A', 'B', 'A'] for each in muh: self.do_stuff[each](each) def do_A(self, moo): print "A" def do_B(self, boo): print "B" if(__name__ == '__main__'): aFoo = Foo() aFoo.run() This results in it giving an error that self isn't defined at the lambda function, but if i remove it. It says do_A or do_B isn't defined. EDIT I managed to figure it out. I need to change the lambda expression into something like this: lambda x, y: x.do_A(y) and i would call it like: self.do_stuff[each](self, each) Is this a terrible idea?
[ "do_stuff is not an instance variable in your example. It's more like a static variable. You need to define do_stuff within a method (e.g., the init method) where you have a reference to self in order to make it an instance variable. I hope this example clarifies things for you:\nclass Foo:\n\n def __init__(self):\n self.do_stuff = { \"A\": self.do_A, \"B\": self.do_B }\n\n def run(self):\n for x in [\"A\", \"B\"]:\n self.do_stuff[x](\"hi\")\n\n def do_A(self, x):\n pass\n\n def do_B(self, x):\n pass\n\nNote that the lambda functions aren't necessary. You can just store references to the functions themselves in your dictionary. The notation \"self.do_A\" will automatically pass self as the first argument. \nEDIT: Does anyone know how to make underscores show properly in non-code-sample text?\n\nEDIT: WTH? The preview is showing underscores differently than the post.\n" ]
[ 7 ]
[]
[]
[ "lambda", "python" ]
stackoverflow_0000287823_lambda_python.txt
Q: What Python tools can I use to interface with a website's API? Let's say I wanted to make a python script interface with a site like Twitter. What would I use to do that? I'm used to using curl/wget from bash, but Python seems to be much nicer to use. What's the equivalent? (This isn't Python run from a webserver, but run locally via the command line) A: For something like Twitter, you'll save yourself a ton of time by not reinventing the wheel. Try a library like python-twitter. This way, you can write your script, or even a full fledged application, that interfaces with Twitter, and you don't have to care about the implementation details. If you want to roll your own interface library, you're going to have to get familiar with urllib and depending on what format they provide results, either lxml (or some other xml parser) or simplejson. A: Python has urllib2, which is extensible library for opening URLs Full-featured easy to use library. https://docs.python.org/library/urllib2.html A: I wholeheartedly recommend mechanize for python. It's exactly a programmable web browser that you can use from python, which handles forms and cookies as well! It makes any kind of site crawling a breeze. Take a look at the examples on that link to see what it can do. A: Python has a very nice httplib module as well as a url module which together will probably accomplish most of what you need (at least with regards to wget functionality). A: If you're used to dealing with cURL, consider PycURL.
What Python tools can I use to interface with a website's API?
Let's say I wanted to make a python script interface with a site like Twitter. What would I use to do that? I'm used to using curl/wget from bash, but Python seems to be much nicer to use. What's the equivalent? (This isn't Python run from a webserver, but run locally via the command line)
[ "For something like Twitter, you'll save yourself a ton of time by not reinventing the wheel. Try a library like python-twitter. This way, you can write your script, or even a full fledged application, that interfaces with Twitter, and you don't have to care about the implementation details.\nIf you want to roll your own interface library, you're going to have to get familiar with urllib and depending on what format they provide results, either lxml (or some other xml parser) or simplejson.\n", "Python has urllib2, which is extensible library for opening URLs\nFull-featured easy to use library.\nhttps://docs.python.org/library/urllib2.html\n", "I wholeheartedly recommend mechanize for python. It's exactly a programmable web browser that you can use from python, which handles forms and cookies as well! It makes any kind of site crawling a breeze.\nTake a look at the examples on that link to see what it can do.\n", "Python has a very nice httplib module as well as a url module which together will probably accomplish most of what you need (at least with regards to wget functionality).\n", "If you're used to dealing with cURL, consider PycURL.\n" ]
[ 8, 5, 4, 2, 0 ]
[]
[]
[ "python", "twitter", "web_services" ]
stackoverflow_0000285226_python_twitter_web_services.txt
Q: In Python, how can I efficiently manage references between script files? I have a fair number of Python scripts that contain reusable code that are used and referenced by other Python scripts. However, these scripts tend to be scattered across different directories and I find it to be somewhat tedious to have to include (most often multiple) calls to sys.path.append on my top-level scripts. I just want to provide the 'import' statements without the additional file references in the same script. Currently, I have this: import sys sys.path.append('..//shared1//reusable_foo') import Foo sys.path.append('..//shared2//reusable_bar') import Bar My preference would be the following: import Foo import Bar My background is primarily in the .NET platform so I am accustomed to having meta files such as *.csproj, *.vbproj, *.sln, etc. to manage and contain the actual file path references outside of the source files. This allows me to just provide 'using' directives (equivalent to Python's import) without exposing all of the references and allowing for reuse of the path references themselves across multiple scripts. Does Python have equivalent support for this and, if not, what are some techniques and approaches? A: The simple answer is to put your reusable code in your site-packages directory, which is in your sys.path. You can also extend the search path by adding .pth files somewhere in your path. See https://docs.python.org/2/install/#modifying-python-s-search-path for more details Oh, and python 2.6/3.0 adds support for PEP370, Per-user site-packages Directory A: If your reusable files are packaged (that is, they include an __init__.py file) and the path to that package is part of your PYTHONPATH or sys.path then you should be able to do just import Foo This question provides a few more details. (Note: As Jim said, you could also drop your reusable code into your site-packages directory.) A: You can put the reusable stuff in site-packages. That's completely transparent, since it's in sys.path by default. You can put someName.pth files in site-packages. These files have the directory in which your actual reusable stuff lives. This is also completely transparent. And doesn't involve the extra step of installing a change in site-packages. You can put the directory of the reusable stuff on PYTHONPATH. That's a little less transparent, because you have to make sure it's set. Not rocket science, but not completely transparent. A: In one project, I wanted to make sure that the user could put python scripts (that could basically be used as plugins) anywhere. My solution was to put the following in the config file for that project: [server] PYPATH_APPEND: /home/jason:/usr/share/some_directory That way, this would add /home/jason and /usr/share/some_directory to the python path at program launch. Then, it's just a simple matter of splitting the string by the colons and adding those directories to the end of the sys.path. You may want to consider putting a module in the site-packages directory that contains a function to read in that config file and add those directories to the sys.path (unfortunately, I don't have time at the moment to write an example). As others have mentioned, it's a good idea to put as much in site-packages as possible and also using .pth files. But this can be a good idea if you have a script that needs to import a bunch of stuff that's not in site-packages that you wouldn't want to import from other scripts. (there may also be a way to do this using .pth files, but I like being able to manipulate the python path in the same place as I put the rest of my configuration info) A: The simplest way is to set (or add to) PYTHONPATH, and put (or symlink) your modules and packages into a path contained in PYTHONPATH. A: My solution was to package up one utility that would import the module: my_util is in site packages import my_util foo = myutil.import_script('..//shared1//reusable_foo') if foo == None: sys.exit(1) def import_script(script_path, log_status = True): """ imports a module and returns the handle """ lpath = os.path.split(script_path) if lpath[1] == '': log('Error in script "%s" in import_script' % (script_path)) return None #check if path is already in sys.path so we don't repeat npath = None if lpath[0] == '': npath = '.' else: if lpath[0] not in sys.path: npath = lpath[0] if npath != None: try: sys.path.append(npath) except: if log_status == True: log('Error adding path "%s" in import_script' % npath) return None try: mod = __import__(lpath[1]) except: error_trace,error_reason = FormatExceptionInfo() if log_status == True: log('Error importing "%s" module in import_script: %s' % (script_path, error_trace + error_reason)) sys.path.remove(npath) return None return mod
In Python, how can I efficiently manage references between script files?
I have a fair number of Python scripts that contain reusable code that are used and referenced by other Python scripts. However, these scripts tend to be scattered across different directories and I find it to be somewhat tedious to have to include (most often multiple) calls to sys.path.append on my top-level scripts. I just want to provide the 'import' statements without the additional file references in the same script. Currently, I have this: import sys sys.path.append('..//shared1//reusable_foo') import Foo sys.path.append('..//shared2//reusable_bar') import Bar My preference would be the following: import Foo import Bar My background is primarily in the .NET platform so I am accustomed to having meta files such as *.csproj, *.vbproj, *.sln, etc. to manage and contain the actual file path references outside of the source files. This allows me to just provide 'using' directives (equivalent to Python's import) without exposing all of the references and allowing for reuse of the path references themselves across multiple scripts. Does Python have equivalent support for this and, if not, what are some techniques and approaches?
[ "The simple answer is to put your reusable code in your site-packages directory, which is in your sys.path.\nYou can also extend the search path by adding .pth files somewhere in your path.\nSee https://docs.python.org/2/install/#modifying-python-s-search-path for more details\nOh, and python 2.6/3.0 adds support for PEP370, Per-user site-packages Directory\n", "If your reusable files are packaged (that is, they include an __init__.py file) and the path to that package is part of your PYTHONPATH or sys.path then you should be able to do just\nimport Foo\n\nThis question provides a few more details.\n(Note: As Jim said, you could also drop your reusable code into your site-packages directory.)\n", "You can put the reusable stuff in site-packages. That's completely transparent, since it's in sys.path by default.\nYou can put someName.pth files in site-packages. These files have the directory in which your actual reusable stuff lives. This is also completely transparent. And doesn't involve the extra step of installing a change in site-packages.\nYou can put the directory of the reusable stuff on PYTHONPATH. That's a little less transparent, because you have to make sure it's set. Not rocket science, but not completely transparent.\n", "In one project, I wanted to make sure that the user could put python scripts (that could basically be used as plugins) anywhere. My solution was to put the following in the config file for that project:\n[server]\nPYPATH_APPEND: /home/jason:/usr/share/some_directory\n\nThat way, this would add /home/jason and /usr/share/some_directory to the python path at program launch.\nThen, it's just a simple matter of splitting the string by the colons and adding those directories to the end of the sys.path. You may want to consider putting a module in the site-packages directory that contains a function to read in that config file and add those directories to the sys.path (unfortunately, I don't have time at the moment to write an example).\nAs others have mentioned, it's a good idea to put as much in site-packages as possible and also using .pth files. But this can be a good idea if you have a script that needs to import a bunch of stuff that's not in site-packages that you wouldn't want to import from other scripts.\n(there may also be a way to do this using .pth files, but I like being able to manipulate the python path in the same place as I put the rest of my configuration info)\n", "The simplest way is to set (or add to) PYTHONPATH, and put (or symlink) your modules and packages into a path contained in PYTHONPATH.\n", "My solution was to package up one utility that would import the module:\nmy_util is in site packages\nimport my_util\n\nfoo = myutil.import_script('..//shared1//reusable_foo')\nif foo == None:\n sys.exit(1)\n\n\ndef import_script(script_path, log_status = True):\n \"\"\"\n imports a module and returns the handle\n \"\"\"\n lpath = os.path.split(script_path)\n\n if lpath[1] == '':\n log('Error in script \"%s\" in import_script' % (script_path))\n return None\n\n\n #check if path is already in sys.path so we don't repeat\n npath = None\n if lpath[0] == '':\n npath = '.'\n else:\n if lpath[0] not in sys.path:\n npath = lpath[0]\n\n if npath != None:\n try:\n sys.path.append(npath)\n except:\n if log_status == True:\n log('Error adding path \"%s\" in import_script' % npath)\n return None\n\n try: \n mod = __import__(lpath[1])\n except:\n error_trace,error_reason = FormatExceptionInfo()\n if log_status == True:\n log('Error importing \"%s\" module in import_script: %s' % (script_path, error_trace + error_reason))\n sys.path.remove(npath)\n return None\n\n return mod\n\n" ]
[ 4, 3, 1, 1, 1, 0 ]
[]
[]
[ "metadata", "python", "scripting" ]
stackoverflow_0000287845_metadata_python_scripting.txt
Q: receiving data over a python socket I'm making a program that retrieves decently large amounts of data through a python socket and then immediately disconnects when the information is finished sending. But I'm not sure how to do this All the examples on the web are of tcp clients where they have while 1: data = sock.recv(1024) But this creates a look to infinite loop to receive data via the socket, does it not? I need to figure out the size of the message coming in and loop through it in buffer-sized increments to get the full message. And after the message has finished sending, I would like to disconnect, although i think the connection will be closed from the other end. Any help would be nice Thanks A: You've probably missed a very important part of those examples - the lines that follow the "recv()" call: while 1: data = conn.recv(1024) if not data: break conn.send(data) conn.close()
receiving data over a python socket
I'm making a program that retrieves decently large amounts of data through a python socket and then immediately disconnects when the information is finished sending. But I'm not sure how to do this All the examples on the web are of tcp clients where they have while 1: data = sock.recv(1024) But this creates a look to infinite loop to receive data via the socket, does it not? I need to figure out the size of the message coming in and loop through it in buffer-sized increments to get the full message. And after the message has finished sending, I would like to disconnect, although i think the connection will be closed from the other end. Any help would be nice Thanks
[ "You've probably missed a very important part of those examples - the lines that follow the \"recv()\" call:\nwhile 1:\n data = conn.recv(1024)\n if not data: break\n conn.send(data)\nconn.close()\n\n" ]
[ 21 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0000289035_python_sockets.txt
Q: Why does Excel macro work in Excel but not when called from Python? I have an Excel macro that deletes a sheet, copies another sheet and renames it to the same name of the deleted sheet. This works fine when run from Excel, but when I run it by calling the macro from Python I get the following error message: Run-time error '1004' - Cannot rename a sheet to the same name as another sheet, a referenced object library or a workbook referenced by VisualBasic. The macro has code like the following: Sheets("CC").Delete ActiveWindow.View = xlPageBreakPreview Sheets("FY").Copy After:=Sheets(Sheets.Count) Sheets(Sheets.Count).Name = "CC" and the debugger highlights the error on the last line where the sheet is renamed. I've also tried putting these calls directly in python but get the same error message. Any suggestions are much appreciated! Thanks. A: I ran the code inside Excel VBA. I am guessing that the following line is failing. Sheets("CC").Delete And that is the reason, you can't give the new sheet same name as existing (non-deleted) sheet. Put Application.DisplayAlerts = False before Sheets("CC").Delete and Application.DisplayAlerts = True once you are finished with the code. I haven't used python but it seems the library is swallowing that error for you and letting you go ahead to the next statement. Hope that helps. A: Behind the scenes, VB and VBA are maintaining references to COM objects for the application, worksheets etc. This is why you have the globals 'Application', 'Worksheets' etc. It is possible that VBA is still holding a reference to the worksheet, so Excel hasn't tidied it up properly. Try not using these implicit globals and referencing the items in the object model explicitly. Alternatively you could do it directly in Python. Here's a python script that will do something like what you want: import win32com.client xl = win32com.client.Dispatch ('Excel.Application') xl.Visible = True wb = xl.Workbooks.Add() wb.Worksheets[0].Delete() wb.Worksheets.Add() wb.Worksheets[0].Name = 'Sheet1'
Why does Excel macro work in Excel but not when called from Python?
I have an Excel macro that deletes a sheet, copies another sheet and renames it to the same name of the deleted sheet. This works fine when run from Excel, but when I run it by calling the macro from Python I get the following error message: Run-time error '1004' - Cannot rename a sheet to the same name as another sheet, a referenced object library or a workbook referenced by VisualBasic. The macro has code like the following: Sheets("CC").Delete ActiveWindow.View = xlPageBreakPreview Sheets("FY").Copy After:=Sheets(Sheets.Count) Sheets(Sheets.Count).Name = "CC" and the debugger highlights the error on the last line where the sheet is renamed. I've also tried putting these calls directly in python but get the same error message. Any suggestions are much appreciated! Thanks.
[ "I ran the code inside Excel VBA.\nI am guessing that the following line is failing.\n\nSheets(\"CC\").Delete\n\nAnd that is the reason, you can't give the new sheet same name as existing (non-deleted) sheet. \nPut Application.DisplayAlerts = False before Sheets(\"CC\").Delete and Application.DisplayAlerts = True once you are finished with the code.\nI haven't used python but it seems the library is swallowing that error for you and letting you go ahead to the next statement.\nHope that helps.\n", "Behind the scenes, VB and VBA are maintaining references to COM objects for the application, worksheets etc. This is why you have the globals 'Application', 'Worksheets' etc. It is possible that VBA is still holding a reference to the worksheet, so Excel hasn't tidied it up properly.\nTry not using these implicit globals and referencing the items in the object model explicitly. Alternatively you could do it directly in Python.\nHere's a python script that will do something like what you want:\nimport win32com.client\nxl = win32com.client.Dispatch ('Excel.Application')\nxl.Visible = True\nwb = xl.Workbooks.Add()\nwb.Worksheets[0].Delete()\nwb.Worksheets.Add()\nwb.Worksheets[0].Name = 'Sheet1'\n\n" ]
[ 2, 1 ]
[]
[]
[ "excel", "python", "pywin32", "vba" ]
stackoverflow_0000289187_excel_python_pywin32_vba.txt
Q: How do I use my icons when compiling my python program with py2exe? I don't know what commands to enter into the setup.py file when compiling a python program to use my icons. Can anyone help me? Thanks in advance. A: from distutils.core import setup import py2exe setup( windows=[{"script": 'app.py', "icon_resources": [(1, "icon.ico")]}], options={"py2exe":{"unbuffered": True, "optimize": 2, "bundle_files" : 1, "dist_dir": "bin"}}, zipfile = "lib.zip", ) A: I haven't tried this, but here's a link I found: http://www.py2exe.org/index.cgi/CustomIcons
How do I use my icons when compiling my python program with py2exe?
I don't know what commands to enter into the setup.py file when compiling a python program to use my icons. Can anyone help me? Thanks in advance.
[ "from distutils.core import setup\nimport py2exe\nsetup(\n windows=[{\"script\": 'app.py', \"icon_resources\": [(1, \"icon.ico\")]}],\n options={\"py2exe\":{\"unbuffered\": True,\n \"optimize\": 2,\n \"bundle_files\" : 1,\n \"dist_dir\": \"bin\"}},\n zipfile = \"lib.zip\", \n)\n\n", "I haven't tried this, but here's a link I found:\nhttp://www.py2exe.org/index.cgi/CustomIcons\n" ]
[ 6, 4 ]
[]
[]
[ "py2exe", "python" ]
stackoverflow_0000289668_py2exe_python.txt
Q: Using python to build web applications This is a follow-up to two questions I asked a week or so back. The upshot of those was that I was building a prototype of an AI-based application for the web, and I wondered what language(s) to use. The conclusion seemed to be that I should go for something like python and then convert any critical bits into something faster like Java or C/C++. That sounds fine to me, but I'm wondering now whether python is really the right language to use for building a web application. Most web applications I've worked on in the past were C/C++ CGI and then php. The php I found much easier to work with as it made linking the user interface to the back-end so much easier, and also it made more logical sense to me. I've not used python before, but what I'm basically wondering is how easy is CGI programming in python? Will I have to go back to the tedious way of doing it in C/C++ where you have to store HTML code in templates and have the CGI read them in and replace special codes with appropriate values or is it possible to have the templates be the code as with php? I'm probably asking a deeply ignorant question here, for which I apologise, but hopefully someone will know what I'm getting at! My overall question is: is writing web applications in python a good idea, and is it as easy as it is with php? A: Python is a good choice. I would avoid the CGI model though - you'll pay a large penalty for the interpreter launch on each request. Most Python web frameworks support the WSGI standard and can be hooked up to servers in a myriad of ways, but most live in some sort of long-running process that the web server communicates with (via proxying, FastCGI, SCGI, etc). Speaking of frameworks, the Python landscape is ripe with them. This is both good and bad. There are many fine options but it can be daunting to a newcomer. If you are looking for something that comes prepackaged with web/DB/templating integration I'd suggest looking at Django, TurboGears or Pylons. If you want to have more control over the individual components, look at CherryPy, Colubrid or web.py. As for whether or not it is as "easy as PHP", that is subjective. Usually it is encouraged to keep your templates and application logic separate in the Python web programming world, which can make your life easier. On the other hand, being able to write all of the code for a page in a PHP file is another definition of "easy". Good luck. A: "how easy is CGI programming in python?" Easier than C, that's for sure. Python is easier because -- simply -- it's an easier language to work with than C. First and foremost: no memory allocation-deallocation. Beyond that, the OO programming model is excellent. Beyond the essential language simplicity, the Python WSGI standard is much easier to cope with than the CGI standard. However, raw CGI is a huge pain when compared with the greatly simplified world of an all-Python framework (TurboGears, CherryPy, Django, whatever.) The frameworks impose a lot of (necessary) structure. The out-of-the-box experience for a CGI programmer is that it's too much to learn. True. All new things are too much to learn. However, the value far exceeds the investment. With Django, you're up and running within minutes. Seriously. django-admin.py startproject and you have something you can run almost immediately. You do have to design your URL's, write view functions and design page templates. All of which is work. But it's less work than CGI in C. Django has a better architecture than PHP because the presentation templates are completely separated from the processing. This leads to some confusion (see Syntax error whenever I put python code inside a django template) when you want to use the free-and-unconstrained PHP style on the Django framework. linking the user interface to the back-end Python front-end (Django, for example) uses Python view functions. Those view functions can contain any Python code at all. That includes, if necessary, modules written in C and callable from Python. That means you can compile a CLIPS module with a Python-friendly interface. It becomes something available to your Python code with the import statement. Sometimes, however, that's ineffective because your Django pages are waiting for the CLIPS engine to finish. An alternative is to use something like a named pipe. You have your CLIPS-based app, written entirely in C, reading from a named pipe. Your Django application, written entirely in Python, writes to that named pipe. Since you've got two independent processes, you'll max out all of your cores pretty quickly like this. A: I would suggest Django, but given that you ask for something "as easy as it is with php" then you must take a look at PSP (Python Server Pages). While Django is a complete framework for doing websites, PSP can be used in the same way than PHP, without any framework. A: It is easier to write web-apps in python than it's in php. Particularly because python is not a broken language. Pick up some web framework that supports mod_wsgi or roll out your own. WSGI apps are really easy to deploy after you get a hold from doing it. If you want templates then genshi is about the best templating engine I've found for python and you can use it however you like.
Using python to build web applications
This is a follow-up to two questions I asked a week or so back. The upshot of those was that I was building a prototype of an AI-based application for the web, and I wondered what language(s) to use. The conclusion seemed to be that I should go for something like python and then convert any critical bits into something faster like Java or C/C++. That sounds fine to me, but I'm wondering now whether python is really the right language to use for building a web application. Most web applications I've worked on in the past were C/C++ CGI and then php. The php I found much easier to work with as it made linking the user interface to the back-end so much easier, and also it made more logical sense to me. I've not used python before, but what I'm basically wondering is how easy is CGI programming in python? Will I have to go back to the tedious way of doing it in C/C++ where you have to store HTML code in templates and have the CGI read them in and replace special codes with appropriate values or is it possible to have the templates be the code as with php? I'm probably asking a deeply ignorant question here, for which I apologise, but hopefully someone will know what I'm getting at! My overall question is: is writing web applications in python a good idea, and is it as easy as it is with php?
[ "Python is a good choice. \nI would avoid the CGI model though - you'll pay a large penalty for the interpreter launch on each request. Most Python web frameworks support the WSGI standard and can be hooked up to servers in a myriad of ways, but most live in some sort of long-running process that the web server communicates with (via proxying, FastCGI, SCGI, etc).\nSpeaking of frameworks, the Python landscape is ripe with them. This is both good and bad. There are many fine options but it can be daunting to a newcomer.\nIf you are looking for something that comes prepackaged with web/DB/templating integration I'd suggest looking at Django, TurboGears or Pylons. If you want to have more control over the individual components, look at CherryPy, Colubrid or web.py.\nAs for whether or not it is as \"easy as PHP\", that is subjective. Usually it is encouraged to keep your templates and application logic separate in the Python web programming world, which can make your life easier. On the other hand, being able to write all of the code for a page in a PHP file is another definition of \"easy\".\nGood luck.\n", "\"how easy is CGI programming in python?\" Easier than C, that's for sure. Python is easier because -- simply -- it's an easier language to work with than C. First and foremost: no memory allocation-deallocation. Beyond that, the OO programming model is excellent.\nBeyond the essential language simplicity, the Python WSGI standard is much easier to cope with than the CGI standard.\nHowever, raw CGI is a huge pain when compared with the greatly simplified world of an all-Python framework (TurboGears, CherryPy, Django, whatever.)\nThe frameworks impose a lot of (necessary) structure. The out-of-the-box experience for a CGI programmer is that it's too much to learn. True. All new things are too much to learn. However, the value far exceeds the investment.\nWith Django, you're up and running within minutes. Seriously. django-admin.py startproject and you have something you can run almost immediately. You do have to design your URL's, write view functions and design page templates. All of which is work. But it's less work than CGI in C. \nDjango has a better architecture than PHP because the presentation templates are completely separated from the processing. This leads to some confusion (see Syntax error whenever I put python code inside a django template) when you want to use the free-and-unconstrained PHP style on the Django framework.\nlinking the user interface to the back-end\nPython front-end (Django, for example) uses Python view functions. Those view functions can contain any Python code at all. That includes, if necessary, modules written in C and callable from Python.\nThat means you can compile a CLIPS module with a Python-friendly interface. It becomes something available to your Python code with the import statement.\nSometimes, however, that's ineffective because your Django pages are waiting for the CLIPS engine to finish. An alternative is to use something like a named pipe.\nYou have your CLIPS-based app, written entirely in C, reading from a named pipe. Your Django application, written entirely in Python, writes to that named pipe. Since you've got two independent processes, you'll max out all of your cores pretty quickly like this.\n", "I would suggest Django, but given that you ask for something \"as easy as it is with php\" then you must take a look at PSP (Python Server Pages).\nWhile Django is a complete framework for doing websites, PSP can be used in the same way than PHP, without any framework.\n", "It is easier to write web-apps in python than it's in php. Particularly because python is not a broken language.\nPick up some web framework that supports mod_wsgi or roll out your own. WSGI apps are really easy to deploy after you get a hold from doing it.\nIf you want templates then genshi is about the best templating engine I've found for python and you can use it however you like.\n" ]
[ 17, 8, 5, 3 ]
[]
[]
[ "cgi", "python" ]
stackoverflow_0000290456_cgi_python.txt
Q: Search directory in SVN for files with specific file extension and copy to another folder? I would like my python script to search through a directory in SVN, locate the files ending with a particular extension (eg. *.exe), and copy these files to a directory that has been created in my C drive. How can I do this? I'm new to Python so a detailed response and/or point in the right direction would be very much appreciated. Follow-up: When using os.walk what parameter would I pass in to ensure that I'm copying files with a specific extension (eg. *.exe)? A: I think it is easiest to check out (or, better, export) the source tree using the svn command line utility: you can use os.system to invoke it. There are also direct Python-to-svn API bindings, but I would advise against using them if you are new to Python. You can then traverse the checkout folder, e.g. using os.walk; the copying itself can be done with shutil.copy.
Search directory in SVN for files with specific file extension and copy to another folder?
I would like my python script to search through a directory in SVN, locate the files ending with a particular extension (eg. *.exe), and copy these files to a directory that has been created in my C drive. How can I do this? I'm new to Python so a detailed response and/or point in the right direction would be very much appreciated. Follow-up: When using os.walk what parameter would I pass in to ensure that I'm copying files with a specific extension (eg. *.exe)?
[ "I think it is easiest to check out (or, better, export) the source tree using the svn command line utility: you can use os.system to invoke it. There are also direct Python-to-svn API bindings, but I would advise against using them if you are new to Python.\nYou can then traverse the checkout folder, e.g. using os.walk; the copying itself can be done with shutil.copy.\n" ]
[ 2 ]
[]
[]
[ "file", "python", "svn" ]
stackoverflow_0000291467_file_python_svn.txt
Q: Best Practices for Building a SSO System I am looking to build a Single-signon system for a couple web apps that used form based authentication. They way that I envision it is that my sso system would handle authentication against active directory pass the verification through to the desired web app when ever the used clicked a link through my sso portal. What might be the best way to build something like this? A: When a user accesses an application URL without a session cookie, he is redirected to the SSO system. He then logs into the SSO form, which then redirects him back to your app with a ticket ID that you can look up in the SSO system to get cridentials. Also, take a look at Crowd and CAS. A: Check out JA-SIG CAS. Even if you build your own, you should look at their architecture for ideas on how to implement.
Best Practices for Building a SSO System
I am looking to build a Single-signon system for a couple web apps that used form based authentication. They way that I envision it is that my sso system would handle authentication against active directory pass the verification through to the desired web app when ever the used clicked a link through my sso portal. What might be the best way to build something like this?
[ "When a user accesses an application URL without a session cookie, he is redirected to the SSO system. He then logs into the SSO form, which then redirects him back to your app with a ticket ID that you can look up in the SSO system to get cridentials.\nAlso, take a look at Crowd and CAS.\n", "Check out JA-SIG CAS. Even if you build your own, you should look at their architecture for ideas on how to implement.\n" ]
[ 1, 0 ]
[]
[]
[ "active_directory", "python", "web_applications", "web_services" ]
stackoverflow_0000291874_active_directory_python_web_applications_web_services.txt
Q: Python exception backtrace tells me where line ends, where does it begin? When A Python exception is thrown by code that spans multiple lines, e.g.: myfoos = [foo("bar", "baz", "quux", i) for i in range(10)] Python will report the line number of the last line, and will show the code fragment from that line: Traceback (most recent call last): File "test.py", line 4, in <module> i) for i in range(10)] NameError: name 'foo' is not defined Is there any way to determine what the first line is? Is there any way to catch the exception and manipulate the traceback object to be able to report something like this instead: Traceback (most recent call last): File "test.py", lines 1-4 in <module> myfoos = [foo("bar", "baz", "quux", i) for i in range(10)] NameError: name 'foo' is not defined A: Finding the beginning of the line will be really hard. You'll have to either parse the Python or maybe dig into the compiled byte code. There are modules in the standard library for parsing Python, but I can tell you from experience that interpreting their output is a black art. And I'm not sure the compiled byte code has the answer either... A: In a try/except block you can except NameError and try setting NameError.lineno, though I'm not exactly sure if or how this works, but it's the best I've found thusfar. try: somecode except NameError NameError.lineno = [1,4] You'll have to figure out where the statement begins and ends yourself somehow as well as which statement is raising the error. Hope this helps
Python exception backtrace tells me where line ends, where does it begin?
When A Python exception is thrown by code that spans multiple lines, e.g.: myfoos = [foo("bar", "baz", "quux", i) for i in range(10)] Python will report the line number of the last line, and will show the code fragment from that line: Traceback (most recent call last): File "test.py", line 4, in <module> i) for i in range(10)] NameError: name 'foo' is not defined Is there any way to determine what the first line is? Is there any way to catch the exception and manipulate the traceback object to be able to report something like this instead: Traceback (most recent call last): File "test.py", lines 1-4 in <module> myfoos = [foo("bar", "baz", "quux", i) for i in range(10)] NameError: name 'foo' is not defined
[ "Finding the beginning of the line will be really hard. You'll have to either parse the Python or maybe dig into the compiled byte code. There are modules in the standard library for parsing Python, but I can tell you from experience that interpreting their output is a black art. And I'm not sure the compiled byte code has the answer either...\n", "In a try/except block you can except NameError and try setting NameError.lineno, though I'm not exactly sure if or how this works, but it's the best I've found thusfar.\ntry:\n somecode\nexcept NameError\n NameError.lineno = [1,4]\n\nYou'll have to figure out where the statement begins and ends yourself somehow as well as which statement is raising the error.\nHope this helps\n" ]
[ 3, 0 ]
[]
[]
[ "exception", "python" ]
stackoverflow_0000291508_exception_python.txt
Q: Best Python supported server/client protocol? I'm looking for a good server/client protocol supported in Python for making data requests/file transfers between one server and many clients. Security is also an issue - so secure login would be a plus. I've been looking into XML-RPC, but it looks to be a pretty old (and possibly unused these days?) protocol. A: If you are looking to do file transfers, XMLRPC is likely a bad choice. It will require that you encode all of your data as XML (and load it into memory). "Data requests" and "file transfers" sounds a lot like plain old HTTP to me, but your statement of the problem doesn't make your requirements clear. What kind of information needs to be encoded in the request? Would a URL like "http://yourserver.example.com/service/request?color=yellow&flavor=banana" be good enough? There are lots of HTTP clients and servers in Python, none of which are especially great, but all of which I'm sure will get the job done for basic file transfers. You can do security the "normal" web way, which is to use HTTPS and passwords, which will probably be sufficient. If you want two-way communication then HTTP falls down, and a protocol like Twisted's perspective broker (PB) or asynchronous messaging protocol (AMP) might suit you better. These protocols are certainly well-supported by Twisted. A: ProtocolBuffers was released by Google as a way of serializing data in a very compact efficient way. They have support for C++, Java and Python. I haven't used it yet, but looking at the source, there seem to be RPC clients and servers for each language. I personally have used XML-RPC on several projects, and it always did exactly what I was hoping for. I was usually going between C++, Java and Python. I use libxmlrpc in Python often because it's easy to memorize and type interactively, but it is actually much slower than the alternative pyxmlrpc. PyAMF is mostly for RPC with Flash clients, but it's a compact RPC format worth looking at too. When you have Python on both ends, I don't believe anything beats Pyro (Python Remote Objects.) Pyro even has a "name server" that lets services announce their availability to a network. Clients use the name server to find the services it needs no matter where they're active at a particular moment. This gives you free redundancy, and the ability to move services from one machine to another without any downtime. For security, I'd tunnel over SSH, or use TLS or SSL at the connection level. Of course, all these options are essentially the same, they just have various difficulties of setup. A: Pyro (Python Remote Objects) is fairly clever if all your server/clients are going to be in Python. I use XMPP alot though since I'm communicating with hosts that are not always Python. XMPP lends itself to being extended fairly easily too. There is an excellent XMPP library for python called PyXMPP which is reasonably up to date and has no dependancy on Twisted. A: I suggest you look at 1. XMLRPC 2. JSONRPC 3. SOAP 4. REST/ATOM XMLRPC is a valid choice. Don't worry it is too old. That is not a problem. It is so simple that little needed changing since original specification. The pro is that in every programming langauge I know there is a library for a client to be written in. Certainly for python. I made it work with mod_python and had no problem at all. The big problem with it is its verbosity. For simple values there is a lot of XML overhead. You can gzip it of cause, but then you loose some debugging ability with the tools like Fiddler. My personal preference is JSONRPC. It has all of the XMLRPC advantages and it is very compact. Further, Javascript clients can "eval" it so no parsing is necessary. Most of them are built for version 1.0 of the standard. I have seen diverse attempts to improve on it, called 1.1 1.2 and 2.0 but they are not built one on top of another and, to my knowledge, are not widely supported yet. 2.0 looks the best, but I would still stick with 1.0 for now (October 2008) Third candidate would be REST/ATOM. REST is a principle, and ATOM is how you convey bulk of data when it needs to for POST, PUT requests and GET responses. For a very nice implementation of it, look at GData, Google's API. Real real nice. SOAP is old, and lots lots of libraries / langauges support it. IT is heeavy and complicated, but if your primary clients are .NET or Java, it might be worth the bother. Visual Studio would import your WSDL file and create a wrapper and to C# programmer it would look like local assembly indeed. The nice thing about all this, is that if you architect your solution right, existing libraries for Python would allow you support more then one with almost no overhead. XMLRPC and JSONRPC are especially good match. Regarding authentication. XMLRPC and JSONRPC don't bother defining one. It is independent thing from the serialization. So you can implement Basic Authentication, Digest Authentication or your own with any of those. I have seen couple of examples of client side Digest Authentication for python, but am yet to see the server based one. If you use Apache, you might not need one, using mod_auth_digest Apache module instead. This depens on the nature of your application Transport security. It is obvously SSL (HTTPS). I can't currently remember how XMLRPC deals with, but with JSONRPC implementation that I have it is trivial - you merely change http to https in your URLs to JSONRPC and it shall be going over SSL enabled transport. A: HTTP seems to suit your requirements and is very well supported in Python. Twisted is good for serious asynchronous network programming in Python, but it has a steep learning curve, so it might be worth using something simpler unless you know your system will need to handle a lot of concurrency. To start, I would suggest using urllib for the client and a WSGI service behind Apache for the server. Apache can be set up to deal with HTTPS fairly simply. A: SSH can be a good choice for file transfer and remote control, especially if you are concerned with secure login. Most Linux and Solaris servers will already run an SSH service for administration, so if your Python program use ssh then you don't need to open up any additional ports or services on remote machines. OpenSSH is the standard and portable SSH client and server, and can be used via subprocesses from Python. If you want more flexibility Twisted includes Twisted Conch which is a SSH client and server implementation which provides flexible programmable control of an SSH stack, on both Linux and Windows. I use both in production. A: I'd use http and start with understanding what the Python library offers. Then I'd move onto the more industrial strength Twisted library. A: There is no need to use HTTP (indeed, HTTP is not good for RPC in general in some respects), and no need to use a standards-based protocol if you're talking about a python client talking to a python server. Use a Python-specific RPC library such as Pyro, or what Twisted provides (Twisted.spread). A: XMLRPC is very simple to get started with, and at my previous job, we used it extensively for intra-node communication in a distributed system. As long as you keep track of the fact that the None value can't be easily transferred, it's dead easy to work with, and included in Python's standard library. Run it over https and add a username/password parameter to all calls, and you'll have simple security in place. Not sure about how easy it is to verify server certificate in Python, though. However, if you are transferring large amounts of data, the coding into XML might become a bottleneck, so using a REST-inspired architecture over https may be as good as xmlrpclib. A: Facebook's thrift project may be a good answer. It uses a light-weight protocol to pass object around and allows you to use any language you wish. It may fall-down on security though as I believe there is none.
Best Python supported server/client protocol?
I'm looking for a good server/client protocol supported in Python for making data requests/file transfers between one server and many clients. Security is also an issue - so secure login would be a plus. I've been looking into XML-RPC, but it looks to be a pretty old (and possibly unused these days?) protocol.
[ "If you are looking to do file transfers, XMLRPC is likely a bad choice. It will require that you encode all of your data as XML (and load it into memory).\n\"Data requests\" and \"file transfers\" sounds a lot like plain old HTTP to me, but your statement of the problem doesn't make your requirements clear. What kind of information needs to be encoded in the request? Would a URL like \"http://yourserver.example.com/service/request?color=yellow&flavor=banana\" be good enough?\nThere are lots of HTTP clients and servers in Python, none of which are especially great, but all of which I'm sure will get the job done for basic file transfers. You can do security the \"normal\" web way, which is to use HTTPS and passwords, which will probably be sufficient.\nIf you want two-way communication then HTTP falls down, and a protocol like Twisted's perspective broker (PB) or asynchronous messaging protocol (AMP) might suit you better. These protocols are certainly well-supported by Twisted.\n", "ProtocolBuffers was released by Google as a way of serializing data in a very compact efficient way. They have support for C++, Java and Python. I haven't used it yet, but looking at the source, there seem to be RPC clients and servers for each language. \nI personally have used XML-RPC on several projects, and it always did exactly what I was hoping for. I was usually going between C++, Java and Python. I use libxmlrpc in Python often because it's easy to memorize and type interactively, but it is actually much slower than the alternative pyxmlrpc.\nPyAMF is mostly for RPC with Flash clients, but it's a compact RPC format worth looking at too.\nWhen you have Python on both ends, I don't believe anything beats Pyro (Python Remote Objects.) Pyro even has a \"name server\" that lets services announce their availability to a network. Clients use the name server to find the services it needs no matter where they're active at a particular moment. This gives you free redundancy, and the ability to move services from one machine to another without any downtime.\nFor security, I'd tunnel over SSH, or use TLS or SSL at the connection level. Of course, all these options are essentially the same, they just have various difficulties of setup.\n", "Pyro (Python Remote Objects) is fairly clever if all your server/clients are going to be in Python. I use XMPP alot though since I'm communicating with hosts that are not always Python. XMPP lends itself to being extended fairly easily too.\nThere is an excellent XMPP library for python called PyXMPP which is reasonably up to date and has no dependancy on Twisted.\n", "I suggest you look at 1. XMLRPC 2. JSONRPC 3. SOAP 4. REST/ATOM\nXMLRPC is a valid choice. Don't worry it is too old. That is not a problem. It is so simple that little needed changing since original specification. The pro is that in every programming langauge I know there is a library for a client to be written in. Certainly for python. I made it work with mod_python and had no problem at all.\nThe big problem with it is its verbosity. For simple values there is a lot of XML overhead. You can gzip it of cause, but then you loose some debugging ability with the tools like Fiddler.\nMy personal preference is JSONRPC. It has all of the XMLRPC advantages and it is very compact. Further, Javascript clients can \"eval\" it so no parsing is necessary. Most of them are built for version 1.0 of the standard. I have seen diverse attempts to improve on it, called 1.1 1.2 and 2.0 but they are not built one on top of another and, to my knowledge, are not widely supported yet. 2.0 looks the best, but I would still stick with 1.0 for now (October 2008)\nThird candidate would be REST/ATOM. REST is a principle, and ATOM is how you convey bulk of data when it needs to for POST, PUT requests and GET responses.\nFor a very nice implementation of it, look at GData, Google's API. Real real nice.\nSOAP is old, and lots lots of libraries / langauges support it. IT is heeavy and complicated, but if your primary clients are .NET or Java, it might be worth the bother.\nVisual Studio would import your WSDL file and create a wrapper and to C# programmer it would look like local assembly indeed.\nThe nice thing about all this, is that if you architect your solution right, existing libraries for Python would allow you support more then one with almost no overhead. XMLRPC and JSONRPC are especially good match.\nRegarding authentication. XMLRPC and JSONRPC don't bother defining one. It is independent thing from the serialization. So you can implement Basic Authentication, Digest Authentication or your own with any of those. I have seen couple of examples of client side Digest Authentication for python, but am yet to see the server based one. If you use Apache, you might not need one, using mod_auth_digest Apache module instead. This depens on the nature of your application\nTransport security. It is obvously SSL (HTTPS). I can't currently remember how XMLRPC deals with, but with JSONRPC implementation that I have it is trivial - you merely change http to https in your URLs to JSONRPC and it shall be going over SSL enabled transport.\n", "HTTP seems to suit your requirements and is very well supported in Python. \nTwisted is good for serious asynchronous network programming in Python, but it has a steep learning curve, so it might be worth using something simpler unless you know your system will need to handle a lot of concurrency.\nTo start, I would suggest using urllib for the client and a WSGI service behind Apache for the server. Apache can be set up to deal with HTTPS fairly simply.\n", "SSH can be a good choice for file transfer and remote control, especially if you are concerned with secure login. Most Linux and Solaris servers will already run an SSH service for administration, so if your Python program use ssh then you don't need to open up any additional ports or services on remote machines. \nOpenSSH is the standard and portable SSH client and server, and can be used via subprocesses from Python. If you want more flexibility Twisted includes Twisted Conch which is a SSH client and server implementation which provides flexible programmable control of an SSH stack, on both Linux and Windows. I use both in production.\n", "I'd use http and start with understanding what the Python library offers. \nThen I'd move onto the more industrial strength Twisted library.\n", "There is no need to use HTTP (indeed, HTTP is not good for RPC in general in some respects), and no need to use a standards-based protocol if you're talking about a python client talking to a python server.\nUse a Python-specific RPC library such as Pyro, or what Twisted provides (Twisted.spread).\n", "XMLRPC is very simple to get started with, and at my previous job, we used it extensively for intra-node communication in a distributed system. As long as you keep track of the fact that the None value can't be easily transferred, it's dead easy to work with, and included in Python's standard library. \nRun it over https and add a username/password parameter to all calls, and you'll have simple security in place. Not sure about how easy it is to verify server certificate in Python, though.\nHowever, if you are transferring large amounts of data, the coding into XML might become a bottleneck, so using a REST-inspired architecture over https may be as good as xmlrpclib.\n", "Facebook's thrift project may be a good answer. It uses a light-weight protocol to pass object around and allows you to use any language you wish. It may fall-down on security though as I believe there is none.\n" ]
[ 9, 7, 5, 4, 3, 2, 1, 1, 0, 0 ]
[ "In the RPC field, Json-RPC will bring a big performance improvement over xml-rpc: \nhttp://json-rpc.org/wiki/python-json-rpc\n" ]
[ -1 ]
[ "client", "python" ]
stackoverflow_0000064426_client_python.txt
Q: Google AppEngine App Version Is it possible to fetch the current application version programmatically for use in urls with far future expires header? For example: <link rel="stylesheet" href="app.js?v=1.23" /> Should be automatically updated to: <link rel="stylesheet" href="app.js?v=1.24" /> In order to do so I need to get the version. A: From [http://code.google.com/appengine/docs/python/theenvironment.html][1] from google.appengine.ext import webapp import os class PrintEnvironmentHandler(webapp.RequestHandler): def get(self): for name in os.environ.keys(): self.response.out.write("%s = %s<br />\n" % (name, os.environ[name])) [1]: http://code.google.com/appengine/docs/python/theenvironment.html
Google AppEngine App Version
Is it possible to fetch the current application version programmatically for use in urls with far future expires header? For example: <link rel="stylesheet" href="app.js?v=1.23" /> Should be automatically updated to: <link rel="stylesheet" href="app.js?v=1.24" /> In order to do so I need to get the version.
[ "From [http://code.google.com/appengine/docs/python/theenvironment.html][1]\nfrom google.appengine.ext import webapp\nimport os\n\nclass PrintEnvironmentHandler(webapp.RequestHandler):\n def get(self):\n for name in os.environ.keys():\n self.response.out.write(\"%s = %s<br />\\n\" % (name, os.environ[name]))\n\n\n [1]: http://code.google.com/appengine/docs/python/theenvironment.html\n\n" ]
[ 6 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0000289174_google_app_engine_python.txt
Q: Python help - Parsing Packet Logs I'm writing a simple program that's going to parse a logfile of a packet dump from wireshark into a more readable form. I'm doing this with python. Currently I'm stuck on this part: for i in range(len(linelist)): if '### SERVER' in linelist[i]: #do server parsing stuff packet = linelist[i:find("\n\n", i, len(linelist))] linelist is a list created using the readlines() method, so every line in the file is an element in the list. I'm iterating through it for all occurances of "### SERVER", then grabbing all lines after it until the next empty line(which signifies the end of the packet). I must be doing something wrong, because not only is find() not working, but I have a feeling there's a better way to grab everything between ### SERVER and the next occurance of a blank line. Any ideas? A: Looking at thefile.readlines() doc: file.readlines([sizehint]) Read until EOF using readline() and return a list containing the lines thus read. If the optional sizehint argument is present, instead of reading up to EOF, whole lines totalling approximately sizehint bytes (possibly after rounding up to an internal buffer size) are read. Objects implementing a file-like interface may choose to ignore sizehint if it cannot be implemented, or cannot be implemented efficiently. and the file.readline() doc: file.readline([size]) Read one entire line from the file. A trailing newline character is kept in the string (but may be absent when a file ends with an incomplete line). [6] If the size argument is present and non-negative, it is a maximum byte count (including the trailing newline) and an incomplete line may be returned. An empty string is returned only when EOF is encountered immediately. A trailing newline character is kept in the string - means that each line in linelist will contain at most one newline. That is why you cannot find a "\n\n" substring in any of the lines - look for a whole blank line (or an empty one at EOF): if myline in ("\n", ""): handle_empty_line() Note: I tried to explain find behavior, but a pythonic solution looks very different from your code snippet. A: General idea is: inpacket = False packets = [] for line in open("logfile"): if inpacket: content += line if line in ("\n", ""): # empty line inpacket = False packets.append(content) elif '### SERVER' in line: inpacket = True content = line # put here packets.append on eof if needed A: This works well with an explicit iterator, also. That way, nested loops can update the iterator's state by consuming lines. fileIter= iter(theFile) for x in fileIter: if "### SERVER" in x: block = [x] for y in fileIter: if len(y.strip()) == 0: # empty line break block.append(y) print block # Or whatever # elif some other pattern: This has the pleasant property of finding blocks that are at the tail end of the file, and don't have a blank line terminating them. Also, this is quite easy to generalize, since there's no explicit state-change variables, you just go into another loop to soak up lines in other kinds of blocks. A: best way - use generators read presentation Generator Tricks for Systems Programmers This best that I saw about parsing log ;)
Python help - Parsing Packet Logs
I'm writing a simple program that's going to parse a logfile of a packet dump from wireshark into a more readable form. I'm doing this with python. Currently I'm stuck on this part: for i in range(len(linelist)): if '### SERVER' in linelist[i]: #do server parsing stuff packet = linelist[i:find("\n\n", i, len(linelist))] linelist is a list created using the readlines() method, so every line in the file is an element in the list. I'm iterating through it for all occurances of "### SERVER", then grabbing all lines after it until the next empty line(which signifies the end of the packet). I must be doing something wrong, because not only is find() not working, but I have a feeling there's a better way to grab everything between ### SERVER and the next occurance of a blank line. Any ideas?
[ "Looking at thefile.readlines() doc:\n\nfile.readlines([sizehint])\nRead until EOF using readline() and return a list containing the lines thus read. If the optional sizehint argument is present, instead of reading up to EOF, whole lines totalling approximately sizehint bytes (possibly after rounding up to an internal buffer size) are read. Objects implementing a file-like interface may choose to ignore sizehint if it cannot be implemented, or cannot be implemented efficiently.\n\nand the file.readline() doc:\n\nfile.readline([size])\nRead one entire line from the file. A trailing newline character is kept in the string (but may be absent when a file ends with an incomplete line). [6] If the size argument is present and non-negative, it is a maximum byte count (including the trailing newline) and an incomplete line may be returned. An empty string is returned only when EOF is encountered immediately.\n\n A trailing newline character is kept in the string - means that each line in linelist will contain at most one newline. That is why you cannot find a \"\\n\\n\" substring in any of the lines - look for a whole blank line (or an empty one at EOF):\nif myline in (\"\\n\", \"\"):\n handle_empty_line()\n\nNote: I tried to explain find behavior, but a pythonic solution looks very different from your code snippet.\n", "General idea is:\ninpacket = False\npackets = []\nfor line in open(\"logfile\"):\n if inpacket:\n content += line\n if line in (\"\\n\", \"\"): # empty line\n inpacket = False\n packets.append(content)\n elif '### SERVER' in line:\n inpacket = True\n content = line\n# put here packets.append on eof if needed\n\n", "This works well with an explicit iterator, also. That way, nested loops can update the iterator's state by consuming lines.\nfileIter= iter(theFile)\nfor x in fileIter:\n if \"### SERVER\" in x:\n block = [x]\n for y in fileIter:\n if len(y.strip()) == 0: # empty line\n break\n block.append(y)\n print block # Or whatever\n # elif some other pattern:\n\nThis has the pleasant property of finding blocks that are at the tail end of the file, and don't have a blank line terminating them.\nAlso, this is quite easy to generalize, since there's no explicit state-change variables, you just go into another loop to soak up lines in other kinds of blocks.\n", "best way - use generators\nread presentation Generator Tricks for Systems Programmers \nThis best that I saw about parsing log ;)\n" ]
[ 2, 0, 0, 0 ]
[]
[]
[ "parsing", "python" ]
stackoverflow_0000293444_parsing_python.txt
Q: wxPython, Set value of StaticText() I am making a little GUI frontend for a app at the moment using wxPython. I am using wx.StaticText() to create a place to hold some text, code below: content = wx.StaticText(panel, -1, "Text Here", style=wx.ALIGN_CENTRE) I have a button when clicked retrieves data from MySQL, I am wanting to change the value of the StaticText() to the MySQL data or what else could I use the hold the data. I have tried using the below method: contents = wx.TextCtrl(bkg, style=wx.TE_MULTILINE | wx.HSCROLL) content.SetValue("New Text") This displays the data fine but after the data is loaded you can edit the data and I do not want this. Hope you guys understand what I am trying to do, I am new to Python :) Cheers A: If you are using a wx.StaticText() you can just: def __init__(self, parent, *args, **kwargs): #frame constructor, etc. self.some_text = wx.StaticText(panel, wx.ID_ANY, label="Awaiting MySQL Data", style=wx.ALIGN_CENTER) def someFunction(self): mysql_data = databasemodel.returnData() #query your database to return a string self.some_text.SetLabel(mysql_data) As litb mentioned, the wxWidgets docs are often much easier to use than the wxPython docs. In order to see that the SetLabel() function can be applied to a wx.StaticText instance, you have to travel up the namespace hierarchy in the wxPython docs to the wxWindow superclass, from which wx.StaticText is subclassed. There are a few things different in wxPython from wxWidgets, and it can be challenging to find out what they are. Fortunately, a lot of the time, the differences are convenience functions that have been added to wxPython and are not found in wxWidgets. A: wx.TextCtrl has a style called wx.TE_READONLY . Use that to make it read-only. As a sidenode, you can use the C++ wxWidgets Manual for wxPython aswell. Where special handling for wxPython or other ports is required, the manual often points out the difference.
wxPython, Set value of StaticText()
I am making a little GUI frontend for a app at the moment using wxPython. I am using wx.StaticText() to create a place to hold some text, code below: content = wx.StaticText(panel, -1, "Text Here", style=wx.ALIGN_CENTRE) I have a button when clicked retrieves data from MySQL, I am wanting to change the value of the StaticText() to the MySQL data or what else could I use the hold the data. I have tried using the below method: contents = wx.TextCtrl(bkg, style=wx.TE_MULTILINE | wx.HSCROLL) content.SetValue("New Text") This displays the data fine but after the data is loaded you can edit the data and I do not want this. Hope you guys understand what I am trying to do, I am new to Python :) Cheers
[ "If you are using a wx.StaticText() you can just:\ndef __init__(self, parent, *args, **kwargs): #frame constructor, etc.\n self.some_text = wx.StaticText(panel, wx.ID_ANY, label=\"Awaiting MySQL Data\", style=wx.ALIGN_CENTER)\n\ndef someFunction(self):\n mysql_data = databasemodel.returnData() #query your database to return a string\n self.some_text.SetLabel(mysql_data)\n\nAs litb mentioned, the wxWidgets docs are often much easier to use than the wxPython docs. In order to see that the SetLabel() function can be applied to a wx.StaticText instance, you have to travel up the namespace hierarchy in the wxPython docs to the wxWindow superclass, from which wx.StaticText is subclassed. There are a few things different in wxPython from wxWidgets, and it can be challenging to find out what they are. Fortunately, a lot of the time, the differences are convenience functions that have been added to wxPython and are not found in wxWidgets.\n", "wx.TextCtrl has a style called wx.TE_READONLY . Use that to make it read-only.\nAs a sidenode, you can use the C++ wxWidgets Manual for wxPython aswell. Where special handling for wxPython or other ports is required, the manual often points out the difference.\n" ]
[ 64, 24 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0000293344_python_wxpython.txt