title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
Cannot import file in Python/Django
1,419,224
<p>I'm not sure what's going on, but on my own laptop, everything works okay. When I upload to my host with Python 2.3.5, my views.py can't find anything in my models.py. I have:</p> <pre><code>from dtms.models import User from dtms.item_list import * </code></pre> <p>where my models, item_list, and views files are in /mysite/dtms/</p> <p>It ends up telling me it can't find User. Any ideas?</p> <p>Also, when I use the django shell, I can do "from dtms.models import *" and it works just fine.</p> <p>Okay, after doing the suggestion below, I get a log file of:</p> <pre><code>syspath = ['/home/victor/django/django_projects', '/home/victor/django/django_projects/mysite'] DEBUG:root:something &lt;module 'dtms' from '/home/victor/django/django_projects/mysite/dtms/__init__.pyc'&gt; DEBUG:root:/home/victor/django/django_projects/mysite/dtms/__init__.pyc DEBUG:root:['/home/victor/django/django_projects/mysite/dtms'] </code></pre> <p>I'm not entirely sure what this means - my file is in mysite/dtms/item_list.py. Does this mean it's being loaded? I see the dtms module is being loaded, but it still can't find dtms.models</p>
0
2009-09-14T00:34:57Z
1,419,747
<p>To check your sys.path you can do what Alex said, but instead of using print you can use the logging module:</p> <pre><code> import logging LOG_FILENAME = '/tmp/logging_example.out' logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG,) logging.debug('This message should go to the log file') </code></pre>
2
2009-09-14T05:02:11Z
[ "python", "django" ]
appengine select based on timestamp
1,419,354
<p>I can't seem to select something based on timestamp. The behavior is a bit weird and the &lt; and = symbols don't seem to mean what I expect them to.</p> <pre> """ A site message """ class Message( db.Model ) : # from/to/ a few other fields subject = db.StringProperty() body = db.Text() # this is the field i'm trying to use sent = db.DateTimeProperty( auto_now_add=True ) </pre> <p>When I write GQL queries like</p> <pre> select * from Message where sent = '2009-09-14 01:00:02.648000' </pre> <p>(there is a message with PRECISELY that time stamp in the datastore)</p> <p>it gives me <em>nothing</em> back.</p> <p>If I try</p> <pre> select * from Message where sent &lt; '2009-09-14 01:00:02.648000' </pre> <p>It simply gives me all of them. When I try the &gt; sign, it simply gives me none again.</p> <p>What's going on here and how do I select based on timestamp?</p>
2
2009-09-14T01:41:59Z
1,419,366
<p>Do <strong>NOT</strong> use strings to "stand in" for datetimes! It just won't work...</p> <p>See <a href="http://code.google.com/appengine/docs/python/datastore/typesandpropertyclasses.html">the docs</a>: <code>DateTimeProperty</code> corresponds to a <a href="http://code.google.com/appengine/docs/python/datastore/typesandpropertyclasses.html#datetime">datetime.datetime</a> value. <code>import datetime</code>, convert your beloved strings to <code>datetime.datetime</code> instances (e.g. by calling the <code>strptime</code> method thereof), use THOSE instances for comparisons -- and, of course, live happily ever after!-)</p>
5
2009-09-14T01:47:20Z
[ "python", "google-app-engine" ]
How to install distutils packages using distutils api or setuptools api
1,419,379
<p>I'm working on a buildout script that needs to install a distutils package on remote server.</p> <p>On PyPi there are 2 recipes for doing this <a href="http://pypi.python.org/pypi?%3Aaction=search&amp;term=recipe.distutils&amp;submit=search" rel="nofollow">collective.recipe.distutils 0.1 and zerokspot.recipe.distutils 0.1.1</a>.</p> <p>The later module a derivative of the former, and is a little more convenient then the first, but the both suffer from the same problem, which I will describe now.</p> <p>When bootstrap.py is executed, it downloads zc.buildout package and puts it into buildout's eggs directory. This gives ./bin/buildout access to zc.buildout code, but /usr/local/python does not know anything about zc.buildout at this point.</p> <p>Buildout attepts to install the package by running 'python setup.py install' inside of a subprocess. This produces an ImportError because zc.buildout is not installed for /usr/local/python.</p> <p>So, I have several solutions.</p> <ol> <li><p>Install zc.buildout using easy_install on the remote server. I don't like this option at all, it makes a special case for a module that is very insignificant.</p></li> <li><p>Modify zerokspot.recipe.distutils to put try block around 'import zc.buildout' this way, it will install even if zc.buildout is not installed. It's an ok solution, but somewhat hackish.</p></li> <li><p>Replace subprocess with code that will install the package using distutils api or setuptools api. This would be the best solution in my opinion.</p></li> </ol> <p>The question is how would i do #3?</p> <p>Thank you, Taras</p> <p>PS: I solved the problem by creating another package that does not have dependancy on zc.buildout. My package is called <a href="http://pypi.python.org/pypi/taras.recipe.distutils" rel="nofollow">taras.recipe.distutils</a> and it's available on pypi.</p>
2
2009-09-14T01:53:28Z
1,419,477
<p>Are you sure you don't want to just generate a <a href="http://docs.python.org/distutils/builtdist.html" rel="nofollow">bdist</a>?</p>
0
2009-09-14T02:45:42Z
[ "python", "distutils", "buildout" ]
How to install distutils packages using distutils api or setuptools api
1,419,379
<p>I'm working on a buildout script that needs to install a distutils package on remote server.</p> <p>On PyPi there are 2 recipes for doing this <a href="http://pypi.python.org/pypi?%3Aaction=search&amp;term=recipe.distutils&amp;submit=search" rel="nofollow">collective.recipe.distutils 0.1 and zerokspot.recipe.distutils 0.1.1</a>.</p> <p>The later module a derivative of the former, and is a little more convenient then the first, but the both suffer from the same problem, which I will describe now.</p> <p>When bootstrap.py is executed, it downloads zc.buildout package and puts it into buildout's eggs directory. This gives ./bin/buildout access to zc.buildout code, but /usr/local/python does not know anything about zc.buildout at this point.</p> <p>Buildout attepts to install the package by running 'python setup.py install' inside of a subprocess. This produces an ImportError because zc.buildout is not installed for /usr/local/python.</p> <p>So, I have several solutions.</p> <ol> <li><p>Install zc.buildout using easy_install on the remote server. I don't like this option at all, it makes a special case for a module that is very insignificant.</p></li> <li><p>Modify zerokspot.recipe.distutils to put try block around 'import zc.buildout' this way, it will install even if zc.buildout is not installed. It's an ok solution, but somewhat hackish.</p></li> <li><p>Replace subprocess with code that will install the package using distutils api or setuptools api. This would be the best solution in my opinion.</p></li> </ol> <p>The question is how would i do #3?</p> <p>Thank you, Taras</p> <p>PS: I solved the problem by creating another package that does not have dependancy on zc.buildout. My package is called <a href="http://pypi.python.org/pypi/taras.recipe.distutils" rel="nofollow">taras.recipe.distutils</a> and it's available on pypi.</p>
2
2009-09-14T01:53:28Z
1,419,644
<p>You can call a command line program within your Python program using the <a href="http://docs.python.org/library/subprocess.html#module-subprocess" rel="nofollow">subprocess</a> module:</p> <pre><code>import subprocess subprocess.call('python setup.py install') </code></pre> <p>However, how much control do you have over the environment that this install will be run? If it is a package that you are distributing, you will likely have issues no matter what solution people propose. How will you handle cases of needing root access (e.g. sudo python setup.py install)?</p> <p>You may consider looking into <a href="http://www.blueskyonmars.com/projects/paver/" rel="nofollow">Paver</a> since it provides an API that is in some ways an extension of setuptools.</p>
1
2009-09-14T04:12:12Z
[ "python", "distutils", "buildout" ]
How to install distutils packages using distutils api or setuptools api
1,419,379
<p>I'm working on a buildout script that needs to install a distutils package on remote server.</p> <p>On PyPi there are 2 recipes for doing this <a href="http://pypi.python.org/pypi?%3Aaction=search&amp;term=recipe.distutils&amp;submit=search" rel="nofollow">collective.recipe.distutils 0.1 and zerokspot.recipe.distutils 0.1.1</a>.</p> <p>The later module a derivative of the former, and is a little more convenient then the first, but the both suffer from the same problem, which I will describe now.</p> <p>When bootstrap.py is executed, it downloads zc.buildout package and puts it into buildout's eggs directory. This gives ./bin/buildout access to zc.buildout code, but /usr/local/python does not know anything about zc.buildout at this point.</p> <p>Buildout attepts to install the package by running 'python setup.py install' inside of a subprocess. This produces an ImportError because zc.buildout is not installed for /usr/local/python.</p> <p>So, I have several solutions.</p> <ol> <li><p>Install zc.buildout using easy_install on the remote server. I don't like this option at all, it makes a special case for a module that is very insignificant.</p></li> <li><p>Modify zerokspot.recipe.distutils to put try block around 'import zc.buildout' this way, it will install even if zc.buildout is not installed. It's an ok solution, but somewhat hackish.</p></li> <li><p>Replace subprocess with code that will install the package using distutils api or setuptools api. This would be the best solution in my opinion.</p></li> </ol> <p>The question is how would i do #3?</p> <p>Thank you, Taras</p> <p>PS: I solved the problem by creating another package that does not have dependancy on zc.buildout. My package is called <a href="http://pypi.python.org/pypi/taras.recipe.distutils" rel="nofollow">taras.recipe.distutils</a> and it's available on pypi.</p>
2
2009-09-14T01:53:28Z
1,420,372
<p>zerokspot.recipe.distutils is fundamentally broken in that it adds a dependency on zc.buildout in it's setup.py, as follows:</p> <ol> <li><code>setup.py</code> imports <code>get_version</code> from <code>zerokspot.recipe.distutils</code></li> <li>All of <code>zerokspot.recipe.distutils</code> is defined in it's <code>__init__.py</code>, including <code>get_version</code></li> <li><code>__init__.py</code> in <code>zerokspot.recipe.distutils</code> imports <code>zc.buildout</code></li> </ol> <p>Why the author defines <code>get_version</code> is a mystery to me; best practice keeps a simple version string in <code>setup.py</code> itself and lets setuptools deal with dev versions (through <code>setup.cfg</code>), and distutils for version metadata extraction.</p> <p>Generally it is not a good idea to import the whole package in <code>setup.py</code> as that would require all the package dependencies to be present at install time. Obviously the author of the package has zc.buildout installed as a site-wide package and didn't notice his oversight.</p> <p>Your best bet is to fork the package on github, remove the get_version dependency, and propose the change to the original author while you use your fork instead.</p>
1
2009-09-14T08:40:23Z
[ "python", "distutils", "buildout" ]
How to Model a Foreign Key in a Reusable Django App?
1,419,442
<p>In my django site I have two apps, blog and links. blog has a model blogpost, and links has a model link. There should be a one to many relationship between these two things. There are many links per blogpost, but each link has one and only one blog post. The simple answer is to put a ForeignKey to blogpost in the link model. </p> <p>That's all well and good, however there is a problem. I want to make the links app reusable. I don't want it to depend upon the blog app. I want to be able to use it again in other sites and perhaps associate links with other non-blogpost apps and models. </p> <p>A generic foreign key seems like it might be the answer, but not really. I don't want links to be able to associate with any model in my site. Just the one that I explicitly specify. And I know from prior experience that there can be issues using generic foreign keys in terms of database usage because you can't do a select_related over a generic foreign key the way you can with a regular foreign key.</p> <p>What is the "correct" way to model this relationship?</p>
11
2009-09-14T02:24:10Z
1,419,548
<p>Probably you need to use the content types app to link to a model. You might then arrange for your app to check the settings to do some additional checking to limit which content types it will accept or suggest.</p>
0
2009-09-14T03:19:40Z
[ "python", "django", "django-models" ]
How to Model a Foreign Key in a Reusable Django App?
1,419,442
<p>In my django site I have two apps, blog and links. blog has a model blogpost, and links has a model link. There should be a one to many relationship between these two things. There are many links per blogpost, but each link has one and only one blog post. The simple answer is to put a ForeignKey to blogpost in the link model. </p> <p>That's all well and good, however there is a problem. I want to make the links app reusable. I don't want it to depend upon the blog app. I want to be able to use it again in other sites and perhaps associate links with other non-blogpost apps and models. </p> <p>A generic foreign key seems like it might be the answer, but not really. I don't want links to be able to associate with any model in my site. Just the one that I explicitly specify. And I know from prior experience that there can be issues using generic foreign keys in terms of database usage because you can't do a select_related over a generic foreign key the way you can with a regular foreign key.</p> <p>What is the "correct" way to model this relationship?</p>
11
2009-09-14T02:24:10Z
1,419,617
<p>I think TokenMacGuy is on the right track. I would look at how <a href="http://code.google.com/p/django-tagging/" rel="nofollow">django-tagging</a> handles a similar generic relationship using the content type, generic object_id, <a href="http://code.google.com/p/django-tagging/source/browse/trunk/tagging/generic.py" rel="nofollow">and generic.py</a>. From <a href="http://code.google.com/p/django-tagging/source/browse/trunk/tagging/models.py" rel="nofollow">models.py</a></p> <pre><code>class TaggedItem(models.Model): """ Holds the relationship between a tag and the item being tagged. """ tag = models.ForeignKey(Tag, verbose_name=_('tag'), related_name='items') content_type = models.ForeignKey(ContentType, verbose_name=_('content type')) object_id = models.PositiveIntegerField(_('object id'), db_index=True) object = generic.GenericForeignKey('content_type', 'object_id') objects = TaggedItemManager() class Meta: # Enforce unique tag association per object unique_together = (('tag', 'content_type', 'object_id'),) verbose_name = _('tagged item') verbose_name_plural = _('tagged items') </code></pre>
1
2009-09-14T04:00:17Z
[ "python", "django", "django-models" ]
How to Model a Foreign Key in a Reusable Django App?
1,419,442
<p>In my django site I have two apps, blog and links. blog has a model blogpost, and links has a model link. There should be a one to many relationship between these two things. There are many links per blogpost, but each link has one and only one blog post. The simple answer is to put a ForeignKey to blogpost in the link model. </p> <p>That's all well and good, however there is a problem. I want to make the links app reusable. I don't want it to depend upon the blog app. I want to be able to use it again in other sites and perhaps associate links with other non-blogpost apps and models. </p> <p>A generic foreign key seems like it might be the answer, but not really. I don't want links to be able to associate with any model in my site. Just the one that I explicitly specify. And I know from prior experience that there can be issues using generic foreign keys in terms of database usage because you can't do a select_related over a generic foreign key the way you can with a regular foreign key.</p> <p>What is the "correct" way to model this relationship?</p>
11
2009-09-14T02:24:10Z
1,419,704
<p>If you think the link app will always point to a single app then one approach would be to pass the name of the foreign model as a string containing the application label instead of a class reference (<a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#foreignkey">Django docs explanation</a>).</p> <p>In other words, instead of:</p> <pre><code>class Link(models.Model): blog_post = models.ForeignKey(BlogPost) </code></pre> <p>do:</p> <pre><code>from django.conf import setings class Link(models.Model): link_model = models.ForeignKey(settings.LINK_MODEL) </code></pre> <p>and in your settings.py:</p> <pre><code>LINK_MODEL = 'someproject.somemodel' </code></pre>
21
2009-09-14T04:39:11Z
[ "python", "django", "django-models" ]
How to Model a Foreign Key in a Reusable Django App?
1,419,442
<p>In my django site I have two apps, blog and links. blog has a model blogpost, and links has a model link. There should be a one to many relationship between these two things. There are many links per blogpost, but each link has one and only one blog post. The simple answer is to put a ForeignKey to blogpost in the link model. </p> <p>That's all well and good, however there is a problem. I want to make the links app reusable. I don't want it to depend upon the blog app. I want to be able to use it again in other sites and perhaps associate links with other non-blogpost apps and models. </p> <p>A generic foreign key seems like it might be the answer, but not really. I don't want links to be able to associate with any model in my site. Just the one that I explicitly specify. And I know from prior experience that there can be issues using generic foreign keys in terms of database usage because you can't do a select_related over a generic foreign key the way you can with a regular foreign key.</p> <p>What is the "correct" way to model this relationship?</p>
11
2009-09-14T02:24:10Z
1,423,477
<p>I'd go with generic relations. You can do something like select_related, it just require some extra work. But I think it's worth it. </p> <p>One possible solution for generic select_related-like functionality: </p> <p><a href="http://bitbucket.org/kmike/django-generic-images/src/tip/generic%5Futils/managers.py" rel="nofollow">http://bitbucket.org/kmike/django-generic-images/src/tip/generic_utils/managers.py</a></p> <p>(look at GenericInjector manager and it's inject_to method)</p>
0
2009-09-14T19:36:25Z
[ "python", "django", "django-models" ]
How to Model a Foreign Key in a Reusable Django App?
1,419,442
<p>In my django site I have two apps, blog and links. blog has a model blogpost, and links has a model link. There should be a one to many relationship between these two things. There are many links per blogpost, but each link has one and only one blog post. The simple answer is to put a ForeignKey to blogpost in the link model. </p> <p>That's all well and good, however there is a problem. I want to make the links app reusable. I don't want it to depend upon the blog app. I want to be able to use it again in other sites and perhaps associate links with other non-blogpost apps and models. </p> <p>A generic foreign key seems like it might be the answer, but not really. I don't want links to be able to associate with any model in my site. Just the one that I explicitly specify. And I know from prior experience that there can be issues using generic foreign keys in terms of database usage because you can't do a select_related over a generic foreign key the way you can with a regular foreign key.</p> <p>What is the "correct" way to model this relationship?</p>
11
2009-09-14T02:24:10Z
1,424,850
<p>This question and Van Gale's <a href="http://stackoverflow.com/questions/1419442/how-to-model-a-foreign-key-in-a-reusable-django-app/1419704#1419704">answer</a> lead me to the question, how it could be possible, to limit contenttypes for GFK without the need of defining it via Q objects in the model, so it could be completly reuseable</p> <p>the solution is based on</p> <ul> <li>django.db.models.get_model</li> <li>and the eval built-in, that evaluates a Q-Object from <code>settings.TAGGING_ALLOWED</code>. This is necessary for usage in the admin-interface</li> </ul> <p>My code is quite rough and not fully tested</p> <p>settings.py</p> <pre><code>TAGGING_ALLOWED=('myapp.modela', 'myapp.modelb') </code></pre> <p>models.py:</p> <pre><code>from django.db import models from django.db.models import Q from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic from django.db.models import get_model from django.conf import settings as s from django.db import IntegrityError TAGABLE = [get_model(i.split('.')[0],i.split('.')[1]) for i in s.TAGGING_ALLOWED if type(i) is type('')] print TAGABLE TAGABLE_Q = eval( '|'.join( ["Q(name='%s', app_label='%s')"%( i.split('.')[1],i.split('.')[0]) for i in s.TAGGING_ALLOWED ] )) class TaggedItem(models.Model): content_type = models.ForeignKey(ContentType, limit_choices_to = TAGABLE_Q) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') def save(self, force_insert=False, force_update=False): if self.content_object and not type( self.content_object) in TAGABLE: raise IntegrityError( 'ContentType %s not allowed'%( type(kwargs['instance'].content_object))) super(TaggedItem,self).save(force_insert, force_update) from django.db.models.signals import post_init def post_init_action(sender, **kwargs): if kwargs['instance'].content_object and not type( kwargs['instance'].content_object) in TAGABLE: raise IntegrityError( 'ContentType %s not allowed'%( type(kwargs['instance'].content_object))) post_init.connect(post_init_action, sender= TaggedItem) </code></pre> <p>Of course the limitations of the contenttype-framework affect this solution</p> <pre><code># This will fail &gt;&gt;&gt; TaggedItem.objects.filter(content_object=a) # This will also fail &gt;&gt;&gt; TaggedItem.objects.get(content_object=a) </code></pre>
0
2009-09-15T02:33:14Z
[ "python", "django", "django-models" ]
How to Model a Foreign Key in a Reusable Django App?
1,419,442
<p>In my django site I have two apps, blog and links. blog has a model blogpost, and links has a model link. There should be a one to many relationship between these two things. There are many links per blogpost, but each link has one and only one blog post. The simple answer is to put a ForeignKey to blogpost in the link model. </p> <p>That's all well and good, however there is a problem. I want to make the links app reusable. I don't want it to depend upon the blog app. I want to be able to use it again in other sites and perhaps associate links with other non-blogpost apps and models. </p> <p>A generic foreign key seems like it might be the answer, but not really. I don't want links to be able to associate with any model in my site. Just the one that I explicitly specify. And I know from prior experience that there can be issues using generic foreign keys in terms of database usage because you can't do a select_related over a generic foreign key the way you can with a regular foreign key.</p> <p>What is the "correct" way to model this relationship?</p>
11
2009-09-14T02:24:10Z
7,248,794
<p>Anoher way to solve this is how <a href="http://django-mptt.github.com/django-mptt/models.html" rel="nofollow">django-mptt</a> does this: define only an abstract model in a reusable app(MPTTModel), and require to inherit it with defining some fields (parent=ForeignKey to self, or whatever your app usecase will require)</p>
1
2011-08-30T19:36:52Z
[ "python", "django", "django-models" ]
Python __init__ setattr on arguments?
1,419,470
<p>It seems that often <code>__init__</code> methods are similar to this:</p> <pre><code>def __init__(self, ivar1, ivar2, ivar3): self.ivar1 = ivar1 self.ivar2 = ivar2 self.ivar3 = ivar3 </code></pre> <p>Is there someway to turn the arguments into a list (without resorting to <code>*args</code> or <code>**kwargs</code>) and then using <code>setattr</code> to set the instance variables, with the name of the parameter and the argument passed? And maybe slice the list, e.g. you'd need to at least slice it to <code>[1:]</code> because you don't want <code>self.self</code>.</p> <p>(actually I guess it would need to be a dictionary to hold the name and value)</p> <p>like this:</p> <pre><code>def __init__(self, ivar1, ivar2, ivar3, optional=False): for k, v in makedict(self.__class__.__init__.__args__): # made up __args__ setattr(self, k, v) </code></pre> <p>Thanks!</p> <p>Responding to Unknown's answer, I found this to work:</p> <pre><code>Class A(object): def __init__(self, length, width, x): self.__dict__.update(dict([(k, v) for k, v in locals().iteritems() if k != 'self'])) </code></pre> <p>or</p> <pre><code>Class A(object): def __init__(self, length, width, x): self.__dict__.update(locals()) del self.__dict__['self'] </code></pre> <p>Not too bad..</p>
5
2009-09-14T02:41:58Z
1,419,490
<p>There is no good way to get the arguments as a list if they are specified individually in the function signature. You can probably do something with inspect or frame hacks, but that will be uglier than simply spelling it out as you have done.</p>
4
2009-09-14T02:51:23Z
[ "python", "list", "parameters", "initialization", "setattr" ]
Python __init__ setattr on arguments?
1,419,470
<p>It seems that often <code>__init__</code> methods are similar to this:</p> <pre><code>def __init__(self, ivar1, ivar2, ivar3): self.ivar1 = ivar1 self.ivar2 = ivar2 self.ivar3 = ivar3 </code></pre> <p>Is there someway to turn the arguments into a list (without resorting to <code>*args</code> or <code>**kwargs</code>) and then using <code>setattr</code> to set the instance variables, with the name of the parameter and the argument passed? And maybe slice the list, e.g. you'd need to at least slice it to <code>[1:]</code> because you don't want <code>self.self</code>.</p> <p>(actually I guess it would need to be a dictionary to hold the name and value)</p> <p>like this:</p> <pre><code>def __init__(self, ivar1, ivar2, ivar3, optional=False): for k, v in makedict(self.__class__.__init__.__args__): # made up __args__ setattr(self, k, v) </code></pre> <p>Thanks!</p> <p>Responding to Unknown's answer, I found this to work:</p> <pre><code>Class A(object): def __init__(self, length, width, x): self.__dict__.update(dict([(k, v) for k, v in locals().iteritems() if k != 'self'])) </code></pre> <p>or</p> <pre><code>Class A(object): def __init__(self, length, width, x): self.__dict__.update(locals()) del self.__dict__['self'] </code></pre> <p>Not too bad..</p>
5
2009-09-14T02:41:58Z
1,419,494
<p>See if the new namedtuple (new in Python 2.6) from the collections module might work for you.</p>
2
2009-09-14T02:52:25Z
[ "python", "list", "parameters", "initialization", "setattr" ]
Python __init__ setattr on arguments?
1,419,470
<p>It seems that often <code>__init__</code> methods are similar to this:</p> <pre><code>def __init__(self, ivar1, ivar2, ivar3): self.ivar1 = ivar1 self.ivar2 = ivar2 self.ivar3 = ivar3 </code></pre> <p>Is there someway to turn the arguments into a list (without resorting to <code>*args</code> or <code>**kwargs</code>) and then using <code>setattr</code> to set the instance variables, with the name of the parameter and the argument passed? And maybe slice the list, e.g. you'd need to at least slice it to <code>[1:]</code> because you don't want <code>self.self</code>.</p> <p>(actually I guess it would need to be a dictionary to hold the name and value)</p> <p>like this:</p> <pre><code>def __init__(self, ivar1, ivar2, ivar3, optional=False): for k, v in makedict(self.__class__.__init__.__args__): # made up __args__ setattr(self, k, v) </code></pre> <p>Thanks!</p> <p>Responding to Unknown's answer, I found this to work:</p> <pre><code>Class A(object): def __init__(self, length, width, x): self.__dict__.update(dict([(k, v) for k, v in locals().iteritems() if k != 'self'])) </code></pre> <p>or</p> <pre><code>Class A(object): def __init__(self, length, width, x): self.__dict__.update(locals()) del self.__dict__['self'] </code></pre> <p>Not too bad..</p>
5
2009-09-14T02:41:58Z
1,419,497
<p>Here you go. Yes this is an ugly evil hack. Yes the object needs a __dict__ variable. But hey, its a neat little one liner!</p> <pre><code>def __init__(self): self.__dict__.update(locals()) </code></pre> <p>The constructor can take any type of arguments.</p> <pre><code>class test(object): def __init__(self, a, b, foo, bar=5)... a = test(1,2,3) dir(a) ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a', 'b', 'foo', 'bar', 'self'] </code></pre> <p>It will also include self, but you can easily delete that or make your own update function that ignores self.</p>
7
2009-09-14T02:55:37Z
[ "python", "list", "parameters", "initialization", "setattr" ]
Python __init__ setattr on arguments?
1,419,470
<p>It seems that often <code>__init__</code> methods are similar to this:</p> <pre><code>def __init__(self, ivar1, ivar2, ivar3): self.ivar1 = ivar1 self.ivar2 = ivar2 self.ivar3 = ivar3 </code></pre> <p>Is there someway to turn the arguments into a list (without resorting to <code>*args</code> or <code>**kwargs</code>) and then using <code>setattr</code> to set the instance variables, with the name of the parameter and the argument passed? And maybe slice the list, e.g. you'd need to at least slice it to <code>[1:]</code> because you don't want <code>self.self</code>.</p> <p>(actually I guess it would need to be a dictionary to hold the name and value)</p> <p>like this:</p> <pre><code>def __init__(self, ivar1, ivar2, ivar3, optional=False): for k, v in makedict(self.__class__.__init__.__args__): # made up __args__ setattr(self, k, v) </code></pre> <p>Thanks!</p> <p>Responding to Unknown's answer, I found this to work:</p> <pre><code>Class A(object): def __init__(self, length, width, x): self.__dict__.update(dict([(k, v) for k, v in locals().iteritems() if k != 'self'])) </code></pre> <p>or</p> <pre><code>Class A(object): def __init__(self, length, width, x): self.__dict__.update(locals()) del self.__dict__['self'] </code></pre> <p>Not too bad..</p>
5
2009-09-14T02:41:58Z
1,419,520
<p>Try <a href="http://docs.python.org/library/inspect.html#inspect.getargspec" rel="nofollow">inspect.getargspec</a>:</p> <pre><code>In [31]: inspect.getargspec(C.__init__) Out[31]: ArgSpec(args=['self', 'ivar1', 'ivar2', 'ivar3', 'optional'], varargs=None, keywords=None, defaults=(False,)) </code></pre>
3
2009-09-14T03:09:28Z
[ "python", "list", "parameters", "initialization", "setattr" ]
Python __init__ setattr on arguments?
1,419,470
<p>It seems that often <code>__init__</code> methods are similar to this:</p> <pre><code>def __init__(self, ivar1, ivar2, ivar3): self.ivar1 = ivar1 self.ivar2 = ivar2 self.ivar3 = ivar3 </code></pre> <p>Is there someway to turn the arguments into a list (without resorting to <code>*args</code> or <code>**kwargs</code>) and then using <code>setattr</code> to set the instance variables, with the name of the parameter and the argument passed? And maybe slice the list, e.g. you'd need to at least slice it to <code>[1:]</code> because you don't want <code>self.self</code>.</p> <p>(actually I guess it would need to be a dictionary to hold the name and value)</p> <p>like this:</p> <pre><code>def __init__(self, ivar1, ivar2, ivar3, optional=False): for k, v in makedict(self.__class__.__init__.__args__): # made up __args__ setattr(self, k, v) </code></pre> <p>Thanks!</p> <p>Responding to Unknown's answer, I found this to work:</p> <pre><code>Class A(object): def __init__(self, length, width, x): self.__dict__.update(dict([(k, v) for k, v in locals().iteritems() if k != 'self'])) </code></pre> <p>or</p> <pre><code>Class A(object): def __init__(self, length, width, x): self.__dict__.update(locals()) del self.__dict__['self'] </code></pre> <p>Not too bad..</p>
5
2009-09-14T02:41:58Z
1,419,950
<p>You could use inspect.getargspec and encapsulate it as a decorator. The lookup of optional and keyword arguments is a bit tricky, but this should do it:</p> <pre><code>def inits_args(func): """Initializes object attributes by the initializer signature""" argspec = inspect.getargspec(func) argnames = argspec.args[1:] defaults = dict(zip(argnames[-len(argspec.defaults):], argspec.defaults)) @functools.wraps(func) def __init__(self, *args, **kwargs): args_it = iter(args) for key in argnames: if key in kwargs: value = kwargs[key] else: try: value = args_it.next() except StopIteration: value = defaults[key] setattr(self, key, value) func(self, *args, **kwargs) return __init__ </code></pre> <p>You can then use it like this:</p> <pre><code>class Foo(object): @inits_args def __init__(self, spam, eggs=4, ham=5): print "Foo(%r, %r, %r)" % (self.spam, self.eggs, self.ham) </code></pre>
6
2009-09-14T06:24:38Z
[ "python", "list", "parameters", "initialization", "setattr" ]
Python __init__ setattr on arguments?
1,419,470
<p>It seems that often <code>__init__</code> methods are similar to this:</p> <pre><code>def __init__(self, ivar1, ivar2, ivar3): self.ivar1 = ivar1 self.ivar2 = ivar2 self.ivar3 = ivar3 </code></pre> <p>Is there someway to turn the arguments into a list (without resorting to <code>*args</code> or <code>**kwargs</code>) and then using <code>setattr</code> to set the instance variables, with the name of the parameter and the argument passed? And maybe slice the list, e.g. you'd need to at least slice it to <code>[1:]</code> because you don't want <code>self.self</code>.</p> <p>(actually I guess it would need to be a dictionary to hold the name and value)</p> <p>like this:</p> <pre><code>def __init__(self, ivar1, ivar2, ivar3, optional=False): for k, v in makedict(self.__class__.__init__.__args__): # made up __args__ setattr(self, k, v) </code></pre> <p>Thanks!</p> <p>Responding to Unknown's answer, I found this to work:</p> <pre><code>Class A(object): def __init__(self, length, width, x): self.__dict__.update(dict([(k, v) for k, v in locals().iteritems() if k != 'self'])) </code></pre> <p>or</p> <pre><code>Class A(object): def __init__(self, length, width, x): self.__dict__.update(locals()) del self.__dict__['self'] </code></pre> <p>Not too bad..</p>
5
2009-09-14T02:41:58Z
1,419,995
<p>You can do it using introspection of the arguments, but the code is going to be longer than the code you try to replace. Especially if you are handling kw, which you may have to do.</p> <p>This short code works in most cases (improved from Unknowns example):</p> <pre><code>&gt;&gt;&gt; class Foo: ... def __init__(self, labamba, **kw): ... params = locals().copy() ... del params['self'] ... if 'kw' in params: ... params.update(params['kw']) ... del params['kw'] ... self.__dict__.update(params) </code></pre> <p>But it's an ugly hack, making code less readable for no particular reason except laziness, so don't do it. And also, how often do you <em>really</em> have classes that have more than 5-6 init parameters?</p>
2
2009-09-14T06:38:39Z
[ "python", "list", "parameters", "initialization", "setattr" ]
Python __init__ setattr on arguments?
1,419,470
<p>It seems that often <code>__init__</code> methods are similar to this:</p> <pre><code>def __init__(self, ivar1, ivar2, ivar3): self.ivar1 = ivar1 self.ivar2 = ivar2 self.ivar3 = ivar3 </code></pre> <p>Is there someway to turn the arguments into a list (without resorting to <code>*args</code> or <code>**kwargs</code>) and then using <code>setattr</code> to set the instance variables, with the name of the parameter and the argument passed? And maybe slice the list, e.g. you'd need to at least slice it to <code>[1:]</code> because you don't want <code>self.self</code>.</p> <p>(actually I guess it would need to be a dictionary to hold the name and value)</p> <p>like this:</p> <pre><code>def __init__(self, ivar1, ivar2, ivar3, optional=False): for k, v in makedict(self.__class__.__init__.__args__): # made up __args__ setattr(self, k, v) </code></pre> <p>Thanks!</p> <p>Responding to Unknown's answer, I found this to work:</p> <pre><code>Class A(object): def __init__(self, length, width, x): self.__dict__.update(dict([(k, v) for k, v in locals().iteritems() if k != 'self'])) </code></pre> <p>or</p> <pre><code>Class A(object): def __init__(self, length, width, x): self.__dict__.update(locals()) del self.__dict__['self'] </code></pre> <p>Not too bad..</p>
5
2009-09-14T02:41:58Z
1,420,325
<p>How about deriving from a special class? I think it's <strong>more explicit and more flexible</strong> this way:</p> <pre><code>class InitMe: def __init__(self, data): if 'self' in data: data = data.copy() del data['self'] self.__dict__.update(data) class MyClassA(InitMe): def __init__(self, ivar1, ivar2, ivar3 = 'default value'): super().__init__(locals()) class MyClassB(InitMe): def __init__(self, foo): super().__init__({'xxx': foo, 'yyy': foo, 'zzz': None}) # or super().__init__(dict(xxx=foo, yyy=foo, zzz=None)) class MyClassC(InitMe): def __init__(self, foo, **keywords): super().__init__(keywords) </code></pre>
0
2009-09-14T08:28:50Z
[ "python", "list", "parameters", "initialization", "setattr" ]
Python __init__ setattr on arguments?
1,419,470
<p>It seems that often <code>__init__</code> methods are similar to this:</p> <pre><code>def __init__(self, ivar1, ivar2, ivar3): self.ivar1 = ivar1 self.ivar2 = ivar2 self.ivar3 = ivar3 </code></pre> <p>Is there someway to turn the arguments into a list (without resorting to <code>*args</code> or <code>**kwargs</code>) and then using <code>setattr</code> to set the instance variables, with the name of the parameter and the argument passed? And maybe slice the list, e.g. you'd need to at least slice it to <code>[1:]</code> because you don't want <code>self.self</code>.</p> <p>(actually I guess it would need to be a dictionary to hold the name and value)</p> <p>like this:</p> <pre><code>def __init__(self, ivar1, ivar2, ivar3, optional=False): for k, v in makedict(self.__class__.__init__.__args__): # made up __args__ setattr(self, k, v) </code></pre> <p>Thanks!</p> <p>Responding to Unknown's answer, I found this to work:</p> <pre><code>Class A(object): def __init__(self, length, width, x): self.__dict__.update(dict([(k, v) for k, v in locals().iteritems() if k != 'self'])) </code></pre> <p>or</p> <pre><code>Class A(object): def __init__(self, length, width, x): self.__dict__.update(locals()) del self.__dict__['self'] </code></pre> <p>Not too bad..</p>
5
2009-09-14T02:41:58Z
1,727,051
<p>I like that form the most, not too long and both copy-pasteable and sub-classable:</p> <pre><code>class DynamicInitClass(object): __init_defargs=('x',) def __init__(self,*args,**attrs): for idx,val in enumerate(args): attrs[self.__init_defargs[idx]]=val for key,val in attrs.iteritems(): setattr(self,key,val) </code></pre>
1
2009-11-13T03:58:20Z
[ "python", "list", "parameters", "initialization", "setattr" ]
Selecting based on __key__ (a unique identifier) in google appengine
1,419,522
<p>Again i have</p> <pre> """ A site message """ class Message( db.Model ) : # from/to/ a few other fields subject = db.StringProperty() body = db.Text() sent = db.DateTimeProperty( auto_now_add=True ) </pre> <p>Now I'm trying to pick out a Message by its KEY. I saved off the key earlier and planted it in an HTML form. The result is a clickable link that looks something like</p> <pre> &lt;a href="/readmessage?key=aght52oobW1hZHIOCxIHTWVzc2FnZRiyAQw"&gt;click to open&lt;/a&gt; </pre> <p>So then I run this GQL query:</p> <pre> gql = """select * from Message where __key__='aght52oobW1hZHIOCxIHTWVzc2FnZRiyAQw'""" </pre> <p>But its not working because</p> <blockquote> BadFilterError: BadFilterError: invalid filter: __key__ filter value must be a Key; received aght52oobW1hZHIOCxIHTWVzc2FnZRiyAQw (a str). </blockquote> <p>I'm totally missing something here, and that is <b>how do you put an <em>object</em> into a GQL query string.. and not have Gql parser complain of that it is a string?</b></p>
1
2009-09-14T03:10:29Z
1,419,579
<p>Don't bother with GQL for key-based retrieval -- make a key object from the string:</p> <pre><code>k = db.Key('aght52oobW1hZHIOCxIHTWVzc2FnZRiyAQw') </code></pre> <p>and just <code>db.get(k)</code>. If you insist on GQL, btw, that <code>k</code> -- a suitably constructed instance of <code>db.Key</code>, <strong>NOT</strong> a string object!-) -- is also what you need to substitute into the GQL query (by <code>:1</code> or whatrever).</p>
6
2009-09-14T03:37:32Z
[ "python", "google-app-engine" ]
Selecting based on __key__ (a unique identifier) in google appengine
1,419,522
<p>Again i have</p> <pre> """ A site message """ class Message( db.Model ) : # from/to/ a few other fields subject = db.StringProperty() body = db.Text() sent = db.DateTimeProperty( auto_now_add=True ) </pre> <p>Now I'm trying to pick out a Message by its KEY. I saved off the key earlier and planted it in an HTML form. The result is a clickable link that looks something like</p> <pre> &lt;a href="/readmessage?key=aght52oobW1hZHIOCxIHTWVzc2FnZRiyAQw"&gt;click to open&lt;/a&gt; </pre> <p>So then I run this GQL query:</p> <pre> gql = """select * from Message where __key__='aght52oobW1hZHIOCxIHTWVzc2FnZRiyAQw'""" </pre> <p>But its not working because</p> <blockquote> BadFilterError: BadFilterError: invalid filter: __key__ filter value must be a Key; received aght52oobW1hZHIOCxIHTWVzc2FnZRiyAQw (a str). </blockquote> <p>I'm totally missing something here, and that is <b>how do you put an <em>object</em> into a GQL query string.. and not have Gql parser complain of that it is a string?</b></p>
1
2009-09-14T03:10:29Z
8,303,679
<p>You can also construct a query by hand by constructing "<a href="http://code.google.com/appengine/docs/python/datastore/gqlreference.html" rel="nofollow">an entity key literal, with...a complete path of kinds and key names/IDs</a>".</p> <pre><code>SELECT * FROM Message WHERE __key__ = KEY('Message', 'message_key') </code></pre> <p>This is even more helpful if you are using the Datastore Viewer/Explorer and can't use Python syntax.</p>
1
2011-11-28T23:07:09Z
[ "python", "google-app-engine" ]
Django LEFT JOIN?
1,419,537
<p>I have models, more or less like this:</p> <pre><code>class ModelA(models.Model): field = models.CharField(..) class ModelB(models.Model): name = models.CharField(.., unique=True) modela = models.ForeignKey(ModelA, blank=True, related_name='modelbs') class Meta: unique_together = ('name','modela') </code></pre> <p>I want to do a query that says something like: "Get all the ModelA's where field name equals to X that have a ModelB model with a name of X OR with no model name at all"</p> <p>So far I have this:</p> <pre><code>ModelA.objects.exclude(field=condition).filter(modelsbs__name=condition) </code></pre> <p>This will get me all the ModelAs that have at least one modelB (and in reality it will ALWAYS be just one) - but if a ModelA has no related ModelBs, it will not be in the result set. I need it to be in the resultset with something like obj.modelb = None</p> <p>How can I accomplish this?</p>
9
2009-09-14T03:15:57Z
1,419,596
<p>Use Q to combine the two conditions:</p> <pre><code>from django.db.models import Q qs = ModelA.objects.exclude(field=condition) qs = qs.filter(Q(modelbs__name=condition) | Q(modelbs__isnull=True)) </code></pre> <p>To examine the resulting SQL query:</p> <pre><code>print qs.query.as_sql() </code></pre> <p>On a similar query, this generates a LEFT OUTER JOIN ... WHERE (a.val = b OR a.id IS NULL).</p>
11
2009-09-14T03:51:31Z
[ "python", "django" ]
Django LEFT JOIN?
1,419,537
<p>I have models, more or less like this:</p> <pre><code>class ModelA(models.Model): field = models.CharField(..) class ModelB(models.Model): name = models.CharField(.., unique=True) modela = models.ForeignKey(ModelA, blank=True, related_name='modelbs') class Meta: unique_together = ('name','modela') </code></pre> <p>I want to do a query that says something like: "Get all the ModelA's where field name equals to X that have a ModelB model with a name of X OR with no model name at all"</p> <p>So far I have this:</p> <pre><code>ModelA.objects.exclude(field=condition).filter(modelsbs__name=condition) </code></pre> <p>This will get me all the ModelAs that have at least one modelB (and in reality it will ALWAYS be just one) - but if a ModelA has no related ModelBs, it will not be in the result set. I need it to be in the resultset with something like obj.modelb = None</p> <p>How can I accomplish this?</p>
9
2009-09-14T03:15:57Z
1,421,015
<p>LEFT JOIN is a union of two queries. Sometimes it's optimized to one query. Sometimes, it is not actually optimized by the underlying SQL engine and is done as two separate queries.</p> <p>Do this.</p> <pre><code>for a in ModelA.objects.all(): related = a.model_b.set().all() if related.count() == 0: # These are the A with no B's else: # These are the A with some B's </code></pre> <p>Don't fetishize about SQL outer joins appearing to be a "single" query.</p>
-3
2009-09-14T11:33:31Z
[ "python", "django" ]
Django LEFT JOIN?
1,419,537
<p>I have models, more or less like this:</p> <pre><code>class ModelA(models.Model): field = models.CharField(..) class ModelB(models.Model): name = models.CharField(.., unique=True) modela = models.ForeignKey(ModelA, blank=True, related_name='modelbs') class Meta: unique_together = ('name','modela') </code></pre> <p>I want to do a query that says something like: "Get all the ModelA's where field name equals to X that have a ModelB model with a name of X OR with no model name at all"</p> <p>So far I have this:</p> <pre><code>ModelA.objects.exclude(field=condition).filter(modelsbs__name=condition) </code></pre> <p>This will get me all the ModelAs that have at least one modelB (and in reality it will ALWAYS be just one) - but if a ModelA has no related ModelBs, it will not be in the result set. I need it to be in the resultset with something like obj.modelb = None</p> <p>How can I accomplish this?</p>
9
2009-09-14T03:15:57Z
1,433,401
<p>It looks like you are coming up against the 80% barrier. Why not just use <a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#extra-select-none-where-none-params-none-tables-none-order-by-none-select-params-none" rel="nofollow"><code>.extra(select={'has_x_or_none':'(EXISTS (SELECT ...))'})</code></a> to perform a subquery? You can write the subquery any way you like and should be able to filter against the new field. The SQL should wind up looking something like this:</p> <pre><code>SELECT *, ((EXISTS (SELECT * FROM other WHERE other.id=primary.id AND other.name='X')) OR (NOT EXISTS (SELECT * FROM other WHERE other.id=primary.id))) AS has_x_or_none FROM primary WHERE has_x_or_none=1; </code></pre>
1
2009-09-16T14:39:11Z
[ "python", "django" ]
Django LEFT JOIN?
1,419,537
<p>I have models, more or less like this:</p> <pre><code>class ModelA(models.Model): field = models.CharField(..) class ModelB(models.Model): name = models.CharField(.., unique=True) modela = models.ForeignKey(ModelA, blank=True, related_name='modelbs') class Meta: unique_together = ('name','modela') </code></pre> <p>I want to do a query that says something like: "Get all the ModelA's where field name equals to X that have a ModelB model with a name of X OR with no model name at all"</p> <p>So far I have this:</p> <pre><code>ModelA.objects.exclude(field=condition).filter(modelsbs__name=condition) </code></pre> <p>This will get me all the ModelAs that have at least one modelB (and in reality it will ALWAYS be just one) - but if a ModelA has no related ModelBs, it will not be in the result set. I need it to be in the resultset with something like obj.modelb = None</p> <p>How can I accomplish this?</p>
9
2009-09-14T03:15:57Z
9,735,655
<p>Try this patch for custom joins: <a href="https://code.djangoproject.com/ticket/7231" rel="nofollow">https://code.djangoproject.com/ticket/7231</a></p>
1
2012-03-16T10:32:43Z
[ "python", "django" ]
How to forward port to router using python
1,419,590
<p>I am building python p2p application like p2p instant messenger. I am communicating with other peers using TCP/IP connection. I do not want client to do port forwarding. When application starts it should check whether port is forwarded to router if not it should forward it to router. Is it possible to programaticaly forward the port to router. Or how can I use port 80 for p2p communication as its used by browsers. </p>
3
2009-09-14T03:46:07Z
1,419,639
<p>You may find the post and files listed here helpful. This person implemented a Nat PMP library in Python.</p> <p><a href="http://blog.yimingliu.com/2008/01/07/nat-pmp-client-library-for-python/" rel="nofollow">http://blog.yimingliu.com/2008/01/07/nat-pmp-client-library-for-python/</a></p> <p>If you want to use port 80 for p2p communication, you will simply just need to write your own protocol in HTTP and connect over port 80.</p>
1
2009-09-14T04:09:54Z
[ "python", "p2p", "portforwarding" ]
How to extract and then refer to variables defined in a python module?
1,419,620
<p>I'm trying to build a simple environment check script for my firm's test environment. My goal is to be able to ping each of the hosts defined for a given test environment instance. The hosts are defined in a file like this:</p> <pre><code>#!/usr/bin/env python host_ip = '192.168.100.10' router_ip = '192.168.100.254' fs_ip = '192.168.200.10' </code></pre> <p>How can I obtain all of these values in a way that is iterable (i.e. I need to loop through and ping each ip address)?</p> <p>I've looked at local() and vars(), but trying do something like this:</p> <pre><code>for key, value in vars(): print key, value </code></pre> <p>generates this error:</p> <pre><code>ValueError: too many values to unpack </code></pre> <p>I have been able to extract the names of all variables by checking <code>dir(local_variables)</code> for values that don't contain a '__' string, but then I have a list of strings, and I can't figure out how to get from the string to the value of the same-named variable.</p>
2
2009-09-14T04:00:43Z
1,419,622
<p>You need to do vars().iteritems(). (or .items())</p> <p>Looping over a dictionary like vars() will only extract the keys in the dictionary.</p> <p>Example.</p> <pre><code>&gt;&gt;&gt; for key in vars(): print key ... __builtins__ __name__ __doc__ key __package__ &gt;&gt;&gt; for key, value in vars().items(): print key, value ... __builtins__ &lt;module '__builtin__' (built-in)&gt; value None __package__ None key __doc__ __name__ __main__ __doc__ None </code></pre>
2
2009-09-14T04:02:45Z
[ "python", "variables", "import" ]
How to extract and then refer to variables defined in a python module?
1,419,620
<p>I'm trying to build a simple environment check script for my firm's test environment. My goal is to be able to ping each of the hosts defined for a given test environment instance. The hosts are defined in a file like this:</p> <pre><code>#!/usr/bin/env python host_ip = '192.168.100.10' router_ip = '192.168.100.254' fs_ip = '192.168.200.10' </code></pre> <p>How can I obtain all of these values in a way that is iterable (i.e. I need to loop through and ping each ip address)?</p> <p>I've looked at local() and vars(), but trying do something like this:</p> <pre><code>for key, value in vars(): print key, value </code></pre> <p>generates this error:</p> <pre><code>ValueError: too many values to unpack </code></pre> <p>I have been able to extract the names of all variables by checking <code>dir(local_variables)</code> for values that don't contain a '__' string, but then I have a list of strings, and I can't figure out how to get from the string to the value of the same-named variable.</p>
2
2009-09-14T04:00:43Z
1,419,642
<p>First off, I strongly recommend not doing it that way. Instead, do:</p> <pre><code>hosts = { "host_ip": '192.168.100.10', "router_ip": '192.168.100.254', "fs_ip": '192.168.200.10', } </code></pre> <p>Then you can simply import the module and reference it normally--this gives an ordinary, standard way to access this data from any Python code:</p> <pre><code>import config for host, ip in config.hosts.iteritems(): ... </code></pre> <p>If you do access variables directly, you're going to get a bunch of stuff you don't want: the builtins (<code>__builtins__</code>, <code>__package__</code>, etc); anything that was imported while setting up the other variables, etc.</p> <p>You'll also want to make sure that the context you're running in is different from the one whose variables you're iterating over, or you'll be creating new variables in locals() (or vars(), or globals()) while you're iterating over it, and you'll get <code>"RuntimeError: dictionary changed size during iteration"</code>.</p>
8
2009-09-14T04:11:15Z
[ "python", "variables", "import" ]
How to extract and then refer to variables defined in a python module?
1,419,620
<p>I'm trying to build a simple environment check script for my firm's test environment. My goal is to be able to ping each of the hosts defined for a given test environment instance. The hosts are defined in a file like this:</p> <pre><code>#!/usr/bin/env python host_ip = '192.168.100.10' router_ip = '192.168.100.254' fs_ip = '192.168.200.10' </code></pre> <p>How can I obtain all of these values in a way that is iterable (i.e. I need to loop through and ping each ip address)?</p> <p>I've looked at local() and vars(), but trying do something like this:</p> <pre><code>for key, value in vars(): print key, value </code></pre> <p>generates this error:</p> <pre><code>ValueError: too many values to unpack </code></pre> <p>I have been able to extract the names of all variables by checking <code>dir(local_variables)</code> for values that don't contain a '__' string, but then I have a list of strings, and I can't figure out how to get from the string to the value of the same-named variable.</p>
2
2009-09-14T04:00:43Z
1,419,649
<p>Here's a hack I use all the time. You got really close when you returned the list of string names, but you have to use the eval() function to return the actual object that bears the name represented by the string:</p> <pre><code>hosts = [eval('modulename.' + x) for x in dir(local_variables) if '_ip' in x] </code></pre> <p>If I'm not mistaken, this method also doesn't pose the same drawbacks as locals() and vars() explained by Glen Maynard.</p>
-1
2009-09-14T04:14:11Z
[ "python", "variables", "import" ]
How to extract and then refer to variables defined in a python module?
1,419,620
<p>I'm trying to build a simple environment check script for my firm's test environment. My goal is to be able to ping each of the hosts defined for a given test environment instance. The hosts are defined in a file like this:</p> <pre><code>#!/usr/bin/env python host_ip = '192.168.100.10' router_ip = '192.168.100.254' fs_ip = '192.168.200.10' </code></pre> <p>How can I obtain all of these values in a way that is iterable (i.e. I need to loop through and ping each ip address)?</p> <p>I've looked at local() and vars(), but trying do something like this:</p> <pre><code>for key, value in vars(): print key, value </code></pre> <p>generates this error:</p> <pre><code>ValueError: too many values to unpack </code></pre> <p>I have been able to extract the names of all variables by checking <code>dir(local_variables)</code> for values that don't contain a '__' string, but then I have a list of strings, and I can't figure out how to get from the string to the value of the same-named variable.</p>
2
2009-09-14T04:00:43Z
1,419,661
<p>If this really is all that your imported file contains, you could also read it as just a text file, and then parse the input lines using basic string methods.</p> <pre><code>iplistfile = open("iplist.py") host_addr_map = {} for line in iplistfile: if not line or line[0] == '#': continue host, ipaddr = map(str.strip, line.split('=')) host_addr_map[host] = ipaddr iplistfile.close() </code></pre> <p>Now you have a dict of your ip addresses, addressable by host name. To get them all, just use basic dict-style methods:</p> <pre><code>for hostname in host_addr_map: print hostname, host_addr_map[hostname] print host_addr_map.keys() </code></pre> <p>This also has the advantage that it removes any temptation any misguided person might have to add more elaborate Python logic to what you thought was just a configuration file.</p>
0
2009-09-14T04:18:53Z
[ "python", "variables", "import" ]
How to extract and then refer to variables defined in a python module?
1,419,620
<p>I'm trying to build a simple environment check script for my firm's test environment. My goal is to be able to ping each of the hosts defined for a given test environment instance. The hosts are defined in a file like this:</p> <pre><code>#!/usr/bin/env python host_ip = '192.168.100.10' router_ip = '192.168.100.254' fs_ip = '192.168.200.10' </code></pre> <p>How can I obtain all of these values in a way that is iterable (i.e. I need to loop through and ping each ip address)?</p> <p>I've looked at local() and vars(), but trying do something like this:</p> <pre><code>for key, value in vars(): print key, value </code></pre> <p>generates this error:</p> <pre><code>ValueError: too many values to unpack </code></pre> <p>I have been able to extract the names of all variables by checking <code>dir(local_variables)</code> for values that don't contain a '__' string, but then I have a list of strings, and I can't figure out how to get from the string to the value of the same-named variable.</p>
2
2009-09-14T04:00:43Z
1,419,724
<p>Glenn Maynard makes a good point, using a dictionary is simpler and more standard. That being said, here are a couple of tricks I've used sometimes:</p> <p>In the file <code>hosts.py</code>:</p> <pre><code>#!/usr/bin/env python host_ip = '192.168.100.10' router_ip = '192.168.100.254' fs_ip = '192.168.200.10' </code></pre> <p>and in another file:</p> <pre><code>hosts_dict = {} execfile('hosts.py', hosts_dict) </code></pre> <p>or</p> <pre><code>import hosts hosts_dict = hosts.__dict__ </code></pre> <p>But again, those are both rather hackish.</p>
0
2009-09-14T04:51:16Z
[ "python", "variables", "import" ]
Atlassian Bamboo with Django & Python - Possible?
1,419,629
<p>At my company, we currently use <a href="http://www.atlassian.com/software/bamboo/">Atlassian Bamboo</a> for our continuous integration tool. We currently use Java for all of our projects, so it works great.</p> <p>However, we are considering using a Django + Python for one of our new applications. I was wondering if it is possible to use Bamboo for this.</p> <p>First off, let me say that I have a low level of familiarity with Bamboo, as I've only ever used it, not configured it (other than simple changes like changing the svn checkout directory for a build).</p> <p>Obviously there isn't a lot of point in just running a build (since Python projects don't really build), but I'd like to be able to use Bamboo for running the test suite, as well as use bamboo to deploy the latest code to our various test environments the way we do with our Java projects.</p> <p>Does Bamboo support this type of thing with a Python project? </p>
27
2009-09-14T04:04:31Z
1,419,723
<p>Bamboo essentially just runs a shell script, so this could just as easily be:</p> <pre><code>./manage.py test </code></pre> <p>as it typically is:</p> <pre><code>mvn clean install </code></pre> <p>or:</p> <pre><code>ant compile </code></pre> <p>You may have to massage to output of the Django test runner into traditional JUnit XML output, so that Bamboo can give you pretty graphs on how many tests passed. Look at <a href="http://redsolo.blogspot.com/2007/11/hudson-embraces-python.html">this post</a> about using xmlrunner.py to get Python working with <a href="http://hudson.dev.java.net/">Hudson</a>. Also take a look at <a href="http://confluence.atlassian.com/display/BAMEXT/NoseXUnit+-+JUnit+like+XML+reporting+for+Python+PyUnit">NoseXUnit</a>.</p>
23
2009-09-14T04:51:13Z
[ "python", "django", "deployment", "continuous-integration", "bamboo" ]
Atlassian Bamboo with Django & Python - Possible?
1,419,629
<p>At my company, we currently use <a href="http://www.atlassian.com/software/bamboo/">Atlassian Bamboo</a> for our continuous integration tool. We currently use Java for all of our projects, so it works great.</p> <p>However, we are considering using a Django + Python for one of our new applications. I was wondering if it is possible to use Bamboo for this.</p> <p>First off, let me say that I have a low level of familiarity with Bamboo, as I've only ever used it, not configured it (other than simple changes like changing the svn checkout directory for a build).</p> <p>Obviously there isn't a lot of point in just running a build (since Python projects don't really build), but I'd like to be able to use Bamboo for running the test suite, as well as use bamboo to deploy the latest code to our various test environments the way we do with our Java projects.</p> <p>Does Bamboo support this type of thing with a Python project? </p>
27
2009-09-14T04:04:31Z
25,667,201
<p>You can even add a bootstrap for pip and virtualenv on a clean environment quite easily, which is cool:</p> <pre><code>wget https://bootstrap.pypa.io/get-pip.py python get-pip.py --root=${bamboo.build.working.directory}/tmp --ignore-installed export PATH=${bamboo.build.working.directory}/tmp/usr/local/bin:$PATH export PYTHONPATH=${bamboo.build.working.directory}/tmp/usr/local/lib/python2.7/dist-packages:$PYTHONPATH pip install --root=${bamboo.build.working.directory}/tmp --ignore-installed virtualenv virtualenv virtual_tmp cd virtual_tmp . bin/activate echo Pip is located `which pip` pip install django pip install djangorestframework </code></pre> <p>Warning, <code>source bin/activate</code> does not work as the inline script tasks are stored into an sh file (so <code>bash</code> run it in <code>sh</code> compatibility mode).</p> <h1>Edit</h1> <p>Even better, we can run unit tests on the top of it, with xml outputs that can be parsed by the JUnit of bamboo:</p> <pre><code>pip install unittest-xml-reporting python manage.py test --noinput --testrunner="xmlrunner.extra.djangotestrunner.XMLTestRunner" </code></pre>
9
2014-09-04T13:49:23Z
[ "python", "django", "deployment", "continuous-integration", "bamboo" ]
Atlassian Bamboo with Django & Python - Possible?
1,419,629
<p>At my company, we currently use <a href="http://www.atlassian.com/software/bamboo/">Atlassian Bamboo</a> for our continuous integration tool. We currently use Java for all of our projects, so it works great.</p> <p>However, we are considering using a Django + Python for one of our new applications. I was wondering if it is possible to use Bamboo for this.</p> <p>First off, let me say that I have a low level of familiarity with Bamboo, as I've only ever used it, not configured it (other than simple changes like changing the svn checkout directory for a build).</p> <p>Obviously there isn't a lot of point in just running a build (since Python projects don't really build), but I'd like to be able to use Bamboo for running the test suite, as well as use bamboo to deploy the latest code to our various test environments the way we do with our Java projects.</p> <p>Does Bamboo support this type of thing with a Python project? </p>
27
2009-09-14T04:04:31Z
31,393,864
<p>If you use pytest you can simply use <code>py.test --junitxml=/path/to/results/xml/file.xml</code></p>
0
2015-07-13T21:31:24Z
[ "python", "django", "deployment", "continuous-integration", "bamboo" ]
Atlassian Bamboo with Django & Python - Possible?
1,419,629
<p>At my company, we currently use <a href="http://www.atlassian.com/software/bamboo/">Atlassian Bamboo</a> for our continuous integration tool. We currently use Java for all of our projects, so it works great.</p> <p>However, we are considering using a Django + Python for one of our new applications. I was wondering if it is possible to use Bamboo for this.</p> <p>First off, let me say that I have a low level of familiarity with Bamboo, as I've only ever used it, not configured it (other than simple changes like changing the svn checkout directory for a build).</p> <p>Obviously there isn't a lot of point in just running a build (since Python projects don't really build), but I'd like to be able to use Bamboo for running the test suite, as well as use bamboo to deploy the latest code to our various test environments the way we do with our Java projects.</p> <p>Does Bamboo support this type of thing with a Python project? </p>
27
2009-09-14T04:04:31Z
39,509,301
<p>It turns out it is possible. There are two major integration tasks: test runner results and code coverage results. I assume normal Python 3 codebase and standard <code>unittest</code> test suite.</p> <h1>Test runner</h1> <p>Bamboo expects test runner results in <a href="https://confluence.atlassian.com/bamboo/junit-parsing-in-bamboo-289277357.html" rel="nofollow">JUnit XML format</a>. There is <a href="https://pypi.python.org/pypi/unittest-xml-reporting/" rel="nofollow">separate test runner</a> on the Cheese Shop able to produce such output, but it would require you to write a little code to run it, which is not nice. Better way which keeps the codebase intact is to use <a href="https://pypi.python.org/pypi/pytest" rel="nofollow">pytest</a>'s features.</p> <h1>Code coverage</h1> <p>Bamboo only supports the XML format of Atlassian Clover. Important note here is that you don't need Atlassian Clover plugin enabled (and license for it which costs some bucks). Bamboo works on its own.</p> <p>Python de facto standard code coverage tool, <a href="https://pypi.python.org/pypi/coverage" rel="nofollow">coverage</a>, produces somewhat Cobertura XML format, but there's a <a href="https://pypi.python.org/pypi/cobertura-clover-transform" rel="nofollow">converter</a>. There's a <a href="https://pypi.python.org/pypi/pytest-cov" rel="nofollow">pytest plugin</a> for integration with the coverage tool. </p> <h1>Solution</h1> <p>Here's the <a href="https://pypi.python.org/pypi/tox" rel="nofollow">Tox</a> environment where I used pytest to make both Bamboo integrations work.</p> <pre><code>[tox] envlist = py34 skipsdist = True [testenv] setenv = LANG=C.UTF-8 basepython = python3.4 deps = -r{toxinidir}/requirements.txt [testenv:bamboo] commands = py.test --junitxml=results.xml \ --cov=project_name --cov-config=tox.ini --cov-report=xml \ --cov-report=html project_name/test coverage2clover -i coverage.xml -o clover.xml deps = {[testenv]deps} pytest pytest-cov coverage2clover # read by pytest [pytest] python_files = *.py # read by coverage [run] omit=project_name/test/*,project_name/__main__.py </code></pre> <p>Note that both pytest and pytest-cov use <code>tox.ini</code> for the configuration that is not supported on command line. It again saves your from having additional clutter in root of your repo. pytest tries to read <code>tox.ini</code> automatically. pytest-cov bypasses to <a href="http://coverage.readthedocs.io/en/coverage-4.0.3/config.html" rel="nofollow"><code>.coveragerc</code></a>, but because it's also an INI file, <code>tox.ini</code> fits.</p> <p>On Bamboo side add a <a href="https://confluence.atlassian.com/bamboo/script-289277046.html" rel="nofollow">script task</a> that runs <code>tox -e bamboo</code>. Then add <a href="https://confluence.atlassian.com/bamboo/junit-parser-289277056.html" rel="nofollow">JUnit parse task</a> to the job. In its dialogue, under <em>Specify custom results directories</em> put <code>results.xml</code>.</p> <p>Coverage configuration is done other way. </p> <ol> <li>Open <em>Miscellaneous</em> tab of your job</li> <li>Check <em>Use Clover to collect Code Coverage for this build</em></li> <li>Select <em>Clover is already integrated into this build and a clover.xml file will be produced</em> </li> <li>Type <code>clover.xml</code> into <em>Clover XML Location</em></li> </ol> <p><a href="http://i.stack.imgur.com/aSymz.png" rel="nofollow"><img src="http://i.stack.imgur.com/aSymz.png" alt="enter image description here"></a></p> <p>At this point in your next build you will see total coverage and two charts: <em>Coverage history</em> and <em>Lines of code history</em>. It's also nice to have interactive HTML produced by coverage tool, so you can drill down to certain line of code. </p> <p>The settings made above (at least in Bamboo 5.7) has created <em>Clover Report (System)</em> in <em>Artifact</em> job's tab. Open it and set <code>htmlcov</code> to <em>Location</em> field, and <code>*.*</code> to <em>Copy pattern</em>. Bamboo will now collect the HTML reports. You can see it at <em>Clover</em> tab of your plan.</p>
0
2016-09-15T10:54:43Z
[ "python", "django", "deployment", "continuous-integration", "bamboo" ]
Just installed QtOpenGL but cannot import it (from Python)
1,419,650
<p>I just installed it with apt-get on debian linux with</p> <pre><code>apt-get install libqt4-opengl </code></pre> <p>the rest of PyQt4 is available, but I cant get to this new module.</p> <pre><code>from PyQt4 import QtOpenGL </code></pre> <p>raises ImportError. any idea what to do? </p>
10
2009-09-14T04:15:01Z
1,419,673
<p>Did you forget to install the Python bindings?</p> <pre><code>apt-get install python-qt4-gl </code></pre>
24
2009-09-14T04:25:35Z
[ "python", "opengl", "pyqt", "apt-get", "pyopengl" ]
Parsing unstructured text in Python
1,419,653
<p>I wanted to parse a text file that contains unstructured text. I need to get the address, date of birth, name, sex, and ID.</p> <pre><code>. 55 MORILLO ZONE VIII, BARANGAY ZONE VIII (POB.), LUISIANA, LAGROS F 01/16/1952 ALOMO, TERESITA CABALLES 3412-00000-A1652TCA2 12 . 22 FABRICANTE ST. ZONE VIII LUISIANA LAGROS, BARANGAY ZONE VIII (POB.), LUISIANA, LAGROS M 10/14/1967 AMURAO, CALIXTO MANALO13 </code></pre> <p>In the example above, the first 3 lines is the address, the line with just an "F" is the sex, the DOB would be the line after "F", name after the DOB, the ID after the name, and the no. 12 under the ID is the index/record no.</p> <p>However, the format is not consistent. In the second group, the address is 4 lines instead of 3 and the index/record no. is appended after the name (if the person doesn't have an ID field).</p> <p>I wanted to rewrite the text into the following format:</p> <pre><code>name, ID, address, sex, DOB </code></pre>
3
2009-09-14T04:15:31Z
1,419,671
<p>you have to exploit whatever regularity and structure the text does have.</p> <p>I suggest you read one line at a time and match it to a regular expression to determine its type, fill in the appropriate field in a person object. writing out that object and starting a new one whenever you get a field that you already have filled in.</p>
3
2009-09-14T04:24:12Z
[ "python", "parsing", "text" ]
Parsing unstructured text in Python
1,419,653
<p>I wanted to parse a text file that contains unstructured text. I need to get the address, date of birth, name, sex, and ID.</p> <pre><code>. 55 MORILLO ZONE VIII, BARANGAY ZONE VIII (POB.), LUISIANA, LAGROS F 01/16/1952 ALOMO, TERESITA CABALLES 3412-00000-A1652TCA2 12 . 22 FABRICANTE ST. ZONE VIII LUISIANA LAGROS, BARANGAY ZONE VIII (POB.), LUISIANA, LAGROS M 10/14/1967 AMURAO, CALIXTO MANALO13 </code></pre> <p>In the example above, the first 3 lines is the address, the line with just an "F" is the sex, the DOB would be the line after "F", name after the DOB, the ID after the name, and the no. 12 under the ID is the index/record no.</p> <p>However, the format is not consistent. In the second group, the address is 4 lines instead of 3 and the index/record no. is appended after the name (if the person doesn't have an ID field).</p> <p>I wanted to rewrite the text into the following format:</p> <pre><code>name, ID, address, sex, DOB </code></pre>
3
2009-09-14T04:15:31Z
1,419,684
<p>You can probably do this with regular expressions without too much difficulty. If you have never used them before, check out the python documentation, then fire up redemo.py (on my computer, it's in c:\python26\Tools\scripts).</p> <p>The first task is to split the flat file into a list of entities (one chunk of text per record). From the snippet of text you gave, you could split the file with a pattern matching the beginning of a line, where the first character is a dot:</p> <pre><code>import re re_entity_splitter = re.compile(r'^\.') entities = re_entity_splitter.split(open(textfile).read()) </code></pre> <p>Note that the dot must be escaped (it's a wildcard character by default). Note also the r before the pattern. The r denotes 'raw string' format, which excuses you from having to escape the escape characters, resulting in so-called 'backslash plague.'</p> <p>Once you have the file split into individual people, picking out the gender and birthdate is a snap. Use these:</p> <pre><code>re_gender = re.compile(r'^[MF]') re_birth_Date = re.compile(r'\d\d/\d\d/\d\d') </code></pre> <p>And away you go. You can paste the flat file into re demo GUI and experiment with creating patterns to match what you need. You'll have it parsed in no time. Once you get good at this, you can use symbolic group names (see docs) to pick out individual elements quickly and cleanly.</p>
2
2009-09-14T04:32:13Z
[ "python", "parsing", "text" ]
Parsing unstructured text in Python
1,419,653
<p>I wanted to parse a text file that contains unstructured text. I need to get the address, date of birth, name, sex, and ID.</p> <pre><code>. 55 MORILLO ZONE VIII, BARANGAY ZONE VIII (POB.), LUISIANA, LAGROS F 01/16/1952 ALOMO, TERESITA CABALLES 3412-00000-A1652TCA2 12 . 22 FABRICANTE ST. ZONE VIII LUISIANA LAGROS, BARANGAY ZONE VIII (POB.), LUISIANA, LAGROS M 10/14/1967 AMURAO, CALIXTO MANALO13 </code></pre> <p>In the example above, the first 3 lines is the address, the line with just an "F" is the sex, the DOB would be the line after "F", name after the DOB, the ID after the name, and the no. 12 under the ID is the index/record no.</p> <p>However, the format is not consistent. In the second group, the address is 4 lines instead of 3 and the index/record no. is appended after the name (if the person doesn't have an ID field).</p> <p>I wanted to rewrite the text into the following format:</p> <pre><code>name, ID, address, sex, DOB </code></pre>
3
2009-09-14T04:15:31Z
1,419,692
<p>Here's a quick hack job.</p> <pre><code>f = open('data.txt') def process(file): address = "" for line in file: if line == '': raise StopIteration line = line.rstrip() # to ignore \n if line in ('M','F'): sex = line break else: address += line DOB = file.readline().rstrip() # to ignore \n name = file.readline().rstrip() if name[-1].isdigit(): name = re.match(r'^([^\d]+)\d+', name).group(1) ID = None else: ID = file.readline().rstrip() file.readline() # ignore the record # print (name, ID, address, sex, DOB) while True: process(f) </code></pre>
1
2009-09-14T04:34:08Z
[ "python", "parsing", "text" ]
Parsing unstructured text in Python
1,419,653
<p>I wanted to parse a text file that contains unstructured text. I need to get the address, date of birth, name, sex, and ID.</p> <pre><code>. 55 MORILLO ZONE VIII, BARANGAY ZONE VIII (POB.), LUISIANA, LAGROS F 01/16/1952 ALOMO, TERESITA CABALLES 3412-00000-A1652TCA2 12 . 22 FABRICANTE ST. ZONE VIII LUISIANA LAGROS, BARANGAY ZONE VIII (POB.), LUISIANA, LAGROS M 10/14/1967 AMURAO, CALIXTO MANALO13 </code></pre> <p>In the example above, the first 3 lines is the address, the line with just an "F" is the sex, the DOB would be the line after "F", name after the DOB, the ID after the name, and the no. 12 under the ID is the index/record no.</p> <p>However, the format is not consistent. In the second group, the address is 4 lines instead of 3 and the index/record no. is appended after the name (if the person doesn't have an ID field).</p> <p>I wanted to rewrite the text into the following format:</p> <pre><code>name, ID, address, sex, DOB </code></pre>
3
2009-09-14T04:15:31Z
1,419,711
<p>It may be overkill, but the leading edge machine learning algorithms for this type of problem are based on <a href="http://en.wikipedia.org/wiki/Conditional%5Frandom%5Ffield" rel="nofollow">conditional random fields</a>. For example, <a href="http://www.aclweb.org/anthology/N/N04/N04-1042.pdf" rel="nofollow">Accurate Information Extraction from Research Papers using Conditional Random Fields</a>. </p> <p>There is software out there that makes training these models relatively easy. See <a href="http://mallet.cs.umass.edu/" rel="nofollow">Mallet</a> or <a href="http://crfpp.sourceforge.net/" rel="nofollow">CRF++</a>.</p>
2
2009-09-14T04:46:00Z
[ "python", "parsing", "text" ]
Parsing unstructured text in Python
1,419,653
<p>I wanted to parse a text file that contains unstructured text. I need to get the address, date of birth, name, sex, and ID.</p> <pre><code>. 55 MORILLO ZONE VIII, BARANGAY ZONE VIII (POB.), LUISIANA, LAGROS F 01/16/1952 ALOMO, TERESITA CABALLES 3412-00000-A1652TCA2 12 . 22 FABRICANTE ST. ZONE VIII LUISIANA LAGROS, BARANGAY ZONE VIII (POB.), LUISIANA, LAGROS M 10/14/1967 AMURAO, CALIXTO MANALO13 </code></pre> <p>In the example above, the first 3 lines is the address, the line with just an "F" is the sex, the DOB would be the line after "F", name after the DOB, the ID after the name, and the no. 12 under the ID is the index/record no.</p> <p>However, the format is not consistent. In the second group, the address is 4 lines instead of 3 and the index/record no. is appended after the name (if the person doesn't have an ID field).</p> <p>I wanted to rewrite the text into the following format:</p> <pre><code>name, ID, address, sex, DOB </code></pre>
3
2009-09-14T04:15:31Z
1,419,730
<p>Here is a first stab at a pyparsing solution (<a href="http://pyparsing.pastebin.com/f45acc301">easy-to-copy code at the pyparsing pastebin</a>). Walk through the separate parts, according to the interleaved comments.</p> <pre><code>data = """\ . 55 MORILLO ZONE VIII, BARANGAY ZONE VIII (POB.), LUISIANA, LAGROS F 01/16/1952 ALOMO, TERESITA CABALLES 3412-00000-A1652TCA2 12 . 22 FABRICANTE ST. ZONE VIII LUISIANA LAGROS, BARANGAY ZONE VIII (POB.), LUISIANA, LAGROS M 10/14/1967 AMURAO, CALIXTO MANALO13 """ from pyparsing import LineEnd, oneOf, Word, nums, Combine, restOfLine, \ alphanums, Suppress, empty, originalTextFor, OneOrMore, alphas, \ Group, ZeroOrMore NL = LineEnd().suppress() gender = oneOf("M F") integer = Word(nums) date = Combine(integer + '/' + integer + '/' + integer) # define the simple line definitions gender_line = gender("sex") + NL dob_line = date("DOB") + NL name_line = restOfLine("name") + NL id_line = Word(alphanums+"-")("ID") + NL recnum_line = integer("recnum") + NL # define forms of address lines first_addr_line = Suppress('.') + empty + restOfLine + NL # a subsequent address line is any line that is not a gender definition subsq_addr_line = ~(gender_line) + restOfLine + NL # a line with a name and a recnum combined, if there is no ID name_recnum_line = originalTextFor(OneOrMore(Word(alphas+',')))("name") + \ integer("recnum") + NL # defining the form of an overall record, either with or without an ID record = Group((first_addr_line + ZeroOrMore(subsq_addr_line))("address") + gender_line + dob_line + ((name_line + id_line + recnum_line) | name_recnum_line)) # parse data records = OneOrMore(record).parseString(data) # output the desired results (note that address is actually a list of lines) for rec in records: if rec.ID: print "%(name)s, %(ID)s, %(address)s, %(sex)s, %(DOB)s" % rec else: print "%(name)s, , %(address)s, %(sex)s, %(DOB)s" % rec print # how to access the individual fields of the parsed record for rec in records: print rec.dump() print rec.name, 'is', rec.sex print </code></pre> <p>Prints:</p> <pre><code>ALOMO, TERESITA CABALLES, 3412-00000-A1652TCA2, ['55 MORILLO ZONE VIII,', 'BARANGAY ZONE VIII', '(POB.), LUISIANA, LAGROS'], F, 01/16/1952 AMURAO, CALIXTO MANALO, , ['22 FABRICANTE ST. ZONE', 'VIII LUISIANA LAGROS,', 'BARANGAY ZONE VIII', '(POB.), LUISIANA, LAGROS'], M, 10/14/1967 ['55 MORILLO ZONE VIII,', 'BARANGAY ZONE VIII', '(POB.), LUISIANA, LAGROS', 'F', '01/16/1952', 'ALOMO, TERESITA CABALLES', '3412-00000-A1652TCA2', '12'] - DOB: 01/16/1952 - ID: 3412-00000-A1652TCA2 - address: ['55 MORILLO ZONE VIII,', 'BARANGAY ZONE VIII', '(POB.), LUISIANA, LAGROS'] - name: ALOMO, TERESITA CABALLES - recnum: 12 - sex: F ALOMO, TERESITA CABALLES is F ['22 FABRICANTE ST. ZONE', 'VIII LUISIANA LAGROS,', 'BARANGAY ZONE VIII', '(POB.), LUISIANA, LAGROS', 'M', '10/14/1967', 'AMURAO, CALIXTO MANALO', '13'] - DOB: 10/14/1967 - address: ['22 FABRICANTE ST. ZONE', 'VIII LUISIANA LAGROS,', 'BARANGAY ZONE VIII', '(POB.), LUISIANA, LAGROS'] - name: AMURAO, CALIXTO MANALO - recnum: 13 - sex: M AMURAO, CALIXTO MANALO is M </code></pre>
11
2009-09-14T04:53:47Z
[ "python", "parsing", "text" ]
convert the key in MIME encoded form in python
1,419,686
<p>this is the code :</p> <pre><code>f = urllib.urlopen('http://pool.sks-keyservers.net:11371/pks/lookup?op=get&amp;search= 0x58e9390daf8c5bf3') #Retrieve the public key from PKS data = f.read() decoded_bytes = base64.b64decode(data) print decoded_bytes </code></pre> <p>i need to convert the key in MIME encoded form which is presently comes in (ascii armored) radix 64 format.for that i have to get this radix64 format in its binary form and also need to remove its header and checksum than coversion in MIME format but i didnt find any method which can do this conversion.</p> <p>i used the base64.b64decode method and its give me error: </p> <pre>Traceback (most recent call last): File "RetEnc.py", line 12, in ? decoded_bytes = base64.b64decode(data) File "/usr/lib/python2.4/base64.py", line 76, in b64decode raise TypeError(msg) TypeError: Incorrect padding</pre> <p>what to do i'didnt getting .can anybody suggest me something related to this......</p> <p>thanks!!!!</p>
0
2009-09-14T04:32:34Z
1,419,721
<p>By adding a <code>print data</code> statement, I see...:</p> <blockquote> <p>'Error handling request\r\n<h1>Error handling request</h1>Error handling request: No keys found\r\n'</p> </blockquote> <p>Kind of hard to make ANYthing out of THAT string, wouldn't you say...?-)</p> <p>What do YOU see when you add a <code>print data</code> statement...?</p>
0
2009-09-14T04:49:30Z
[ "python", "encoding" ]
convert the key in MIME encoded form in python
1,419,686
<p>this is the code :</p> <pre><code>f = urllib.urlopen('http://pool.sks-keyservers.net:11371/pks/lookup?op=get&amp;search= 0x58e9390daf8c5bf3') #Retrieve the public key from PKS data = f.read() decoded_bytes = base64.b64decode(data) print decoded_bytes </code></pre> <p>i need to convert the key in MIME encoded form which is presently comes in (ascii armored) radix 64 format.for that i have to get this radix64 format in its binary form and also need to remove its header and checksum than coversion in MIME format but i didnt find any method which can do this conversion.</p> <p>i used the base64.b64decode method and its give me error: </p> <pre>Traceback (most recent call last): File "RetEnc.py", line 12, in ? decoded_bytes = base64.b64decode(data) File "/usr/lib/python2.4/base64.py", line 76, in b64decode raise TypeError(msg) TypeError: Incorrect padding</pre> <p>what to do i'didnt getting .can anybody suggest me something related to this......</p> <p>thanks!!!!</p>
0
2009-09-14T04:32:34Z
1,419,886
<p>For the encoding in the URL you give, see <a href="http://superuser.com/questions/34826/the-encoding-mechanism">the-encoding-mechanism</a>. It is a public PGP key encoded using Radix64 (OpenPGP's variant of Base64) -- "armored".</p> <p>For a few ideas on dealing with PGP, see <a href="http://stackoverflow.com/questions/1020320/how-to-do-pgp-in-python-generate-keys-encrypt-decrypt">how-to-do-pgp-in-python-generate-keys-encrypt-decrypt</a>.</p> <p>Hopefully, the PGP module in <a href="http://chandlerproject.org/Projects/MeTooCrypto" rel="nofollow">M2Crypto</a> will help.</p>
0
2009-09-14T05:56:18Z
[ "python", "encoding" ]
convert the key in MIME encoded form in python
1,419,686
<p>this is the code :</p> <pre><code>f = urllib.urlopen('http://pool.sks-keyservers.net:11371/pks/lookup?op=get&amp;search= 0x58e9390daf8c5bf3') #Retrieve the public key from PKS data = f.read() decoded_bytes = base64.b64decode(data) print decoded_bytes </code></pre> <p>i need to convert the key in MIME encoded form which is presently comes in (ascii armored) radix 64 format.for that i have to get this radix64 format in its binary form and also need to remove its header and checksum than coversion in MIME format but i didnt find any method which can do this conversion.</p> <p>i used the base64.b64decode method and its give me error: </p> <pre>Traceback (most recent call last): File "RetEnc.py", line 12, in ? decoded_bytes = base64.b64decode(data) File "/usr/lib/python2.4/base64.py", line 76, in b64decode raise TypeError(msg) TypeError: Incorrect padding</pre> <p>what to do i'didnt getting .can anybody suggest me something related to this......</p> <p>thanks!!!!</p>
0
2009-09-14T04:32:34Z
1,419,895
<p>For a start, when you do use a valid <code>search</code> value ("jay" returns an error stating "too many values"), you will receive an HTML page from which you need to extract the actual key. Trying a search value of "jaysh" I get the following response:</p> <pre><code>&gt;&gt;&gt; print urllib.urlopen('http://pool.sks-keyservers.net:11371/pks/lookup?op=get&amp;search=jaysh').read() &lt;html&gt;&lt;head&gt;&lt;title&gt;Public Key Server -- Get ``jaysh ''&lt;/title&gt;&lt;/head&gt; &lt;body&gt;&lt;h1&gt;Public Key Server -- Get ``jaysh ''&lt;/h1&gt; &lt;pre&gt; -----BEGIN PGP PUBLIC KEY BLOCK----- Version: SKS 1.1.1 mQGiBEpz7VIRBADAt9YpYfYHJeGA6d+G261FHW1uA0YXltCWa7TL6JnIsuxvh9vImUoyMJd6 1xEW4TuROTxGcMMiDemQq6HfV9tLi7ptVBLf/8nUEFoGhxS+DPJsy46WmlscKHRIEdIkTYhp uAIMim0q5HWymEqqAfBLwJTOY9sR+nelh0NKepcCqwCgvenJ2R5UgmAh+sOhIBrh3OahZEED /2sRGHi4xRWKePFpttXfb2hry2/jURPae/wYfuI6Xw3k5EO593veGS7Zyjnt+7mVY1N5V/ey rfXaS3R6GsByG/eRVzRJGU2DSQvmF+q2NC6v2s4KSzr5CVKpn586SGUSg/aKvXY3EIrpvAGP rHum1wt6P9m9kr/4X8SdVhj7Jti6A/0TA8C2KYhOn/hSYAMTmhisHan3g2Cm6yNzKeTiq6/0 ooG/ffcY81zC6+Kw236VGy2bLrMLkboXPuecvaRfz14gJA9SGyInIGQcd78BrX8KZDUpF1Ek KxQqL97YRMQevYV89uQADKT1rDBJPNZ+o9f59WT04tClphk/quvMMuSVILQaamF5c2ggPGph eXNocmVlQGdtYWlsLmNvbT6IZgQTEQIAJgUCSnPtUgIbAwUJAAFRgAYLCQgHAwIEFQIIAwQW AgMBAh4BAheAAAoJEFjpOQ2vjFvzS0wAn3vf1A8npIY/DMIFFw0/eGf0FNekAKCBJnub9GVu 9OUY0nISQf7uZZVyI7kBDQRKc+1SEAQAm7Pink6S5+kfHeUoJVldb+VAlHdf7BdvKjVeiKAb dFUa6vR9az+wn8V5asNy/npEAYnHG2nVFpR8DTlN0eO35p78qXkuWkkpNocLIB3bFwkOCbff P3yaCZp27Vq+9182bAR2Ah10T1KShjWTS/wfRpSVECYUGUMSh4bJTnbDA2MAAwUEAIcRhF9N OxAsOezkiZBm+tG4BgT0+uWchY7fItJdEqrdrROuCFqWkJLY2uTbhtZ5RMceFAW3s+IYDHLL PwM1O+ZojhvAkGwLyC4F+6RCE62mscvDJQsdwS4L25CaG2Aw97HhY7+bG00TWqGLb9JibKie X1Lk+W8Sde/4UK3Q8tpbiE8EGBECAA8FAkpz7VICGwwFCQABUYAACgkQWOk5Da+MW/MAAgCg tfUKLOsrFjmyFu7biv7ZwVfejaMAn1QXEJw6hpvte60WZrL0CpS60A6Q =tvYU -----END PGP PUBLIC KEY BLOCK----- &lt;/pre&gt; &lt;/body&gt;&lt;/html&gt; </code></pre> <p>So you need to look only at the key which is wrapped by the <code>&lt;pre&gt;</code> HTML tags.</p> <p>By the way, there are other issues that you will need to contend with such as multiple keys being returned because you are searching by "name", when you should be searching by keyID. For example, keyID <code>0x58E9390DAF8C5BF3</code> will return the public key for <code>jaysh</code> and only <code>jaysh</code> and the corresponsing URL is <a href="http://pool.sks-keyservers.net:11371/pks/lookup?op=get&amp;search=0x58E9390DAF8C5BF3" rel="nofollow">http://pool.sks-keyservers.net:11371/pks/lookup?op=get&amp;search=0x58E9390DAF8C5BF3</a>.</p> <p>This was mostly covered in my earlier answer to <a href="http://stackoverflow.com/questions/1304130/relevent-query-to-how-to-fetch-public-key-from-public-key-server">this question</a> which I presume you also asked.</p>
0
2009-09-14T06:02:19Z
[ "python", "encoding" ]
How can I generate a complete histogram with numpy?
1,420,235
<p>I have a very long list in a <code>numpy.array</code>. I want to generate a histogram for it. However, Numpy's <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html" rel="nofollow" title="numpy.histogram reference">built in histogram</a> requires a pre-defined number of bins. What's the best way to generate a full histogram with one bin for each value?</p>
1
2009-09-14T08:02:22Z
1,420,297
<p>A bin for every value sounds a bit strange but wouldn't</p> <pre><code>bins=a.max()-a.min() </code></pre> <p>give a similar result?</p>
0
2009-09-14T08:21:54Z
[ "python", "numpy", "histogram" ]
How can I generate a complete histogram with numpy?
1,420,235
<p>I have a very long list in a <code>numpy.array</code>. I want to generate a histogram for it. However, Numpy's <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html" rel="nofollow" title="numpy.histogram reference">built in histogram</a> requires a pre-defined number of bins. What's the best way to generate a full histogram with one bin for each value?</p>
1
2009-09-14T08:02:22Z
1,420,316
<p>If you have an array of integers and the max value isn't too large you can use numpy.bincount:</p> <pre><code>hist = dict((key,val) for key, val in enumerate(numpy.bincount(data)) if val) </code></pre> <p>Edit: If you have float data, or data spread over a huge range you can convert it to integers by doing:</p> <pre><code>bins = numpy.unique(data) bincounts = numpy.bincount(numpy.digitize(data, bins) - 1) hist = dict(zip(bins, bincounts)) </code></pre>
7
2009-09-14T08:26:48Z
[ "python", "numpy", "histogram" ]
How can I add a decorator to an existing object method?
1,420,484
<p>If I'm using a module/class I have no control over, how would I decorate one of the methods? </p> <p>I understand I can: <code>my_decorate_method(target_method)()</code> but I'm looking to have this happen wherever <code>target_method</code> is called without having to do a search/replace.</p> <p>Is it even possible?</p>
7
2009-09-14T09:16:12Z
1,420,634
<p>Yes it's possible, but there are several problems. First whet you get method from class in obvious way you get a warper object but not the function itself.</p> <pre><code>class X(object): def m(self,x): print x print X.m #&gt;&gt;&gt; &lt;unbound method X.m&gt; print vars(X)['m'] #&gt;&gt;&gt; &lt;function m at 0x9e17e64&gt; def increase_decorator(function): return lambda self,x: function(self,x+1) </code></pre> <p>Second I don't know if settings new method will always work:</p> <pre><code>x = X() x.m(1) #&gt;&gt;&gt; 1 X.m = increase_decorator( vars(X)['m'] ) x.m(1) #&gt;&gt;&gt; 2 </code></pre>
3
2009-09-14T09:57:09Z
[ "python", "decorator" ]
How can I add a decorator to an existing object method?
1,420,484
<p>If I'm using a module/class I have no control over, how would I decorate one of the methods? </p> <p>I understand I can: <code>my_decorate_method(target_method)()</code> but I'm looking to have this happen wherever <code>target_method</code> is called without having to do a search/replace.</p> <p>Is it even possible?</p>
7
2009-09-14T09:16:12Z
1,420,994
<p>Don't do this.</p> <p>Use inheritance.</p> <pre><code>import some_module class MyVersionOfAClass( some_module.AClass ): def someMethod( self, *args, **kwargs ): # do your "decoration" here. super( MyVersionOfAClass, self ). someMethod( *args, **kwargs ) # you can also do "decoration" here. </code></pre> <p>Now, fix you main program to use <code>MyVersionOfAClass</code> instead of <code>some_module.AClass</code>.</p>
6
2009-09-14T11:26:40Z
[ "python", "decorator" ]
How do I loop through relationships in a list only once?
1,420,705
<p>I have a list of users:</p> <pre><code>users = [1,2,3,4,5] </code></pre> <p>I want to compute a relationship between them:</p> <pre><code>score = compatibility( user[0], user[1] ) </code></pre> <p>How do I loop over users so that a relationship between users are computed only once?</p>
1
2009-09-14T10:19:00Z
1,420,737
<p>use for loops, or list comprehension.</p> <p>here is for loop example:</p> <pre><code>for u in users: for su in users: if su == u: pass else: score = compatibility(u, su) # do score whatever you want </code></pre> <p>list comprehension:</p> <pre><code>score = [compatibility(x, y) for x in users for y in users if x!=y and compatibility(x,y) not in score] </code></pre>
0
2009-09-14T10:25:07Z
[ "python" ]
How do I loop through relationships in a list only once?
1,420,705
<p>I have a list of users:</p> <pre><code>users = [1,2,3,4,5] </code></pre> <p>I want to compute a relationship between them:</p> <pre><code>score = compatibility( user[0], user[1] ) </code></pre> <p>How do I loop over users so that a relationship between users are computed only once?</p>
1
2009-09-14T10:19:00Z
1,420,748
<p>If you care only about ordered relationship, you could do the following:</p> <pre><code>&gt;&gt;&gt; for i, u in enumerate(users[1:]): print(users[i], u) # or do something else 1 2 2 3 3 4 4 5 </code></pre> <p>if you need all combinations you should use <a href="http://docs.python.org/library/itertools.html#itertools.combinations" rel="nofollow"><code>itertools.combinations</code></a>:</p> <pre><code>&gt;&gt;&gt; import itertools &gt;&gt;&gt; for i in itertools.combinations(users, 2): print(*i) 1 2 1 3 1 4 1 5 2 3 2 4 2 5 3 4 3 5 4 5 </code></pre>
11
2009-09-14T10:28:46Z
[ "python" ]
How do I loop through relationships in a list only once?
1,420,705
<p>I have a list of users:</p> <pre><code>users = [1,2,3,4,5] </code></pre> <p>I want to compute a relationship between them:</p> <pre><code>score = compatibility( user[0], user[1] ) </code></pre> <p>How do I loop over users so that a relationship between users are computed only once?</p>
1
2009-09-14T10:19:00Z
1,420,750
<p>Something like the following should work (not tested):</p> <pre><code>users_range = range(len(users)) # Initialize a 2-dimensional array scores = [None for j in users_range for i in users_range] # Assign a compatibility to each pair of users. for i in users_range: for j in users_range: scores[i][j] = compatibility(users[i], users[j]) </code></pre>
0
2009-09-14T10:30:08Z
[ "python" ]
How do I loop through relationships in a list only once?
1,420,705
<p>I have a list of users:</p> <pre><code>users = [1,2,3,4,5] </code></pre> <p>I want to compute a relationship between them:</p> <pre><code>score = compatibility( user[0], user[1] ) </code></pre> <p>How do I loop over users so that a relationship between users are computed only once?</p>
1
2009-09-14T10:19:00Z
1,420,753
<p>I managed to do what I wanted with this:</p> <pre><code>i = 0 for user1 in users: i += 1 for user2 in users[i:]: print compatibility( user1, user2 ) </code></pre>
0
2009-09-14T10:31:39Z
[ "python" ]
How do I loop through relationships in a list only once?
1,420,705
<p>I have a list of users:</p> <pre><code>users = [1,2,3,4,5] </code></pre> <p>I want to compute a relationship between them:</p> <pre><code>score = compatibility( user[0], user[1] ) </code></pre> <p>How do I loop over users so that a relationship between users are computed only once?</p>
1
2009-09-14T10:19:00Z
1,420,790
<p>If you mean that:</p> <pre><code>compatibility(user[0], user[1]) == compatibility(user[1], user[0]) </code></pre> <p>you could use:</p> <pre><code>for i, user1 in enumerate(users): for user2 in users[i:]: score = compatibility(user1, user2) </code></pre> <p>this will also calculate the compatibility between the same users (maybe applicable)</p>
0
2009-09-14T10:39:25Z
[ "python" ]
How do I loop through relationships in a list only once?
1,420,705
<p>I have a list of users:</p> <pre><code>users = [1,2,3,4,5] </code></pre> <p>I want to compute a relationship between them:</p> <pre><code>score = compatibility( user[0], user[1] ) </code></pre> <p>How do I loop over users so that a relationship between users are computed only once?</p>
1
2009-09-14T10:19:00Z
1,420,795
<pre><code>import itertools def compatibility(u1, u2): "just a stub for demonstration purposes" return abs(u1 - u2) def compatibility_map(users): return dict(((u1, u2), compatibility(u1, u2)) for u1, u2 in itertools.combinations(users, 2)) &gt; compat.compatiblity_map([1,2,3,4,5]) {(1, 2): 1, (1, 3): 2, (4, 5): 1, (1, 4): 3, (1, 5): 4, (2, 3): 1, (2, 5): 3, (3, 4): 1, (2, 4): 2, (3, 5): 2} </code></pre> <p>Use itertools.permuations instead of itertools.combinations if compatibility(a,b) doesn't mean the same thing as compatibility(b,a).</p>
0
2009-09-14T10:40:21Z
[ "python" ]
Change keyboard layout with python?
1,420,925
<p>I'm working on a college system (windows XP) and want to set the keyboard to Dvorak when I log on. I currently have a python script that changes the desktop image.</p> <p>Can I use python to change the layout as well? Or are there other ways?</p>
2
2009-09-14T11:11:02Z
1,420,959
<p>answer can be found at <a href="http://stackoverflow.com/questions/167031/programatically-change-keyboard-to-dvorak">http://stackoverflow.com/questions/167031/programatically-change-keyboard-to-dvorak</a></p>
1
2009-09-14T11:19:24Z
[ "python", "keyboard", "registry" ]
Change keyboard layout with python?
1,420,925
<p>I'm working on a college system (windows XP) and want to set the keyboard to Dvorak when I log on. I currently have a python script that changes the desktop image.</p> <p>Can I use python to change the layout as well? Or are there other ways?</p>
2
2009-09-14T11:11:02Z
4,946,652
<p>I would use <a href="http://www.autohotkey.com/" rel="nofollow">AutoHotKey</a> to change the layout. You could write a script remapping the keys and compile it as an executable file.</p> <p>For example</p> <pre><code>q::' +q::" w::, +w::&lt; e::. +e::&gt; r::p </code></pre> <p>etc.</p>
1
2011-02-09T15:06:13Z
[ "python", "keyboard", "registry" ]
Change keyboard layout with python?
1,420,925
<p>I'm working on a college system (windows XP) and want to set the keyboard to Dvorak when I log on. I currently have a python script that changes the desktop image.</p> <p>Can I use python to change the layout as well? Or are there other ways?</p>
2
2009-09-14T11:11:02Z
15,770,148
<p>to Change keyboard layout </p> <pre><code>import win32api win32api.LoadKeyboardLayout('00000409',1) # to switch to english win32api.LoadKeyboardLayout('00000401',1) # to switch to arabic </code></pre> <p>and for Dvorak :</p> <pre><code>win32api.LoadKeyboardLayout("00010409",1) </code></pre> <p>or </p> <pre><code>win32api.LoadKeyboardLayout("00020409",1) </code></pre>
3
2013-04-02T17:12:09Z
[ "python", "keyboard", "registry" ]
Stopping embedded Python
1,420,957
<p>I'm embedding Python interpreter to a C program. However, it might happen that while running some python script via <code>PyRun_SimpleString()</code> will run into infinite loop or execute for too long. Consider <code>PyRun_SimpleString("while 1: pass");</code> In preventing the main program to block I thought I could run the interpreter in a thread.</p> <p>How do I stop executing the python script in embedded interpreter running in a thread without killing the whole process?</p> <p>Is it possible to pass an exception to the interpreter? Should I wrap the script under some other script which would listen to signals?</p> <p>PS: I could run the python in a separate process but this is not what I want - unless it is the last resort...</p> <p><hr /></p> <p><strong>Update:</strong></p> <p>So, it works now. Thank you Denis Otkidach, once again!</p> <p>If I see this right, you have to do two things: tell the interpreter to stop and <code>return -1</code> in the same thread as your PyRun_SimpleString() is running.</p> <p>To stop, one has a few possibilities: <code>PyErr_SetString(PyExc_KeyboardInterrupt, "...")</code> or <code>PyErr_SetInterrupt()</code> - the first one might leave Python running a few more instructions and then it stops, the later one stops the execution immediately.</p> <p>To <code>return -1</code> you use <code>Py_AddPendingCall()</code> to inject a function call into Python execution. The docs are mentioning it since version 2.7 and 3.1 but it runs on earlier Pythons as well (2.6 here). From 2.7 and 3.1 it should also be thread-safe, meaning you can call it without acquiring GIL (?).</p> <p>So one could rewrite the example bellow:</p> <pre><code>int quit() { PyErr_SetInterrupt(); return -1; } </code></pre>
16
2009-09-14T11:19:15Z
1,421,044
<p>Well the python interpreter would have to be running in a separate thread from the embedding program or you will simply never get a chance to interrupt the interpreter.</p> <p>When you have that, perhaps you can use one of the Python API exception calls to trigger an exception in the interpreter? See <a href="http://docs.python.org/c-api/exceptions.html" rel="nofollow">Python C API Exceptions</a></p>
1
2009-09-14T11:40:22Z
[ "python", "process", "multithreading", "embedded-language", "python-c-api" ]
Stopping embedded Python
1,420,957
<p>I'm embedding Python interpreter to a C program. However, it might happen that while running some python script via <code>PyRun_SimpleString()</code> will run into infinite loop or execute for too long. Consider <code>PyRun_SimpleString("while 1: pass");</code> In preventing the main program to block I thought I could run the interpreter in a thread.</p> <p>How do I stop executing the python script in embedded interpreter running in a thread without killing the whole process?</p> <p>Is it possible to pass an exception to the interpreter? Should I wrap the script under some other script which would listen to signals?</p> <p>PS: I could run the python in a separate process but this is not what I want - unless it is the last resort...</p> <p><hr /></p> <p><strong>Update:</strong></p> <p>So, it works now. Thank you Denis Otkidach, once again!</p> <p>If I see this right, you have to do two things: tell the interpreter to stop and <code>return -1</code> in the same thread as your PyRun_SimpleString() is running.</p> <p>To stop, one has a few possibilities: <code>PyErr_SetString(PyExc_KeyboardInterrupt, "...")</code> or <code>PyErr_SetInterrupt()</code> - the first one might leave Python running a few more instructions and then it stops, the later one stops the execution immediately.</p> <p>To <code>return -1</code> you use <code>Py_AddPendingCall()</code> to inject a function call into Python execution. The docs are mentioning it since version 2.7 and 3.1 but it runs on earlier Pythons as well (2.6 here). From 2.7 and 3.1 it should also be thread-safe, meaning you can call it without acquiring GIL (?).</p> <p>So one could rewrite the example bellow:</p> <pre><code>int quit() { PyErr_SetInterrupt(); return -1; } </code></pre>
16
2009-09-14T11:19:15Z
1,427,498
<p>You can use <code>Py_AddPendingCall()</code> to add a function raising exception to be called on next check interval (see docs on <code>sys.setcheckinterval()</code> for more info). Here is an example with <code>Py_Exit()</code> call (which does works for me, but probably is not what you need), replace it with <code>Py_Finalize()</code> or one of <code>PyErr_Set*()</code>:</p> <pre><code>int quit(void *) { Py_Exit(0); } PyGILState_STATE state = PyGILState_Ensure(); Py_AddPendingCall(&amp;quit, NULL); PyGILState_Release(state); </code></pre> <p>This should be enough for any pure-python code. But note, that some C functions can run for a while as a single operation (there was an example with long running regexp search, but I'm not sure it's still relevant).</p>
8
2009-09-15T14:21:33Z
[ "python", "process", "multithreading", "embedded-language", "python-c-api" ]
Yahoo BOSS Python Library, ExpatError
1,421,099
<p>I tried to install the Yahoo BOSS mashup framework, but am having trouble running the examples provided. Examples 1, 2, 5, and 6 work, but 3 &amp; 4 give Expat errors. Here is the output from ex3.py:</p> <pre><code>gpython examples/ex3.py examples/ex3.py:33: Warning: 'as' will become a reserved keyword in Python 2.6 Traceback (most recent call last): File "examples/ex3.py", line 27, in &lt;module&gt; digg = db.select(name="dg", udf=titlef, url="http://digg.com/rss_search?search=google+android&amp;area=dig&amp;type=both&amp;section=news") File "/usr/lib/python2.5/site-packages/yos/yql/db.py", line 214, in select tb = create(name, data=data, url=url, keep_standards_prefix=keep_standards_prefix) File "/usr/lib/python2.5/site-packages/yos/yql/db.py", line 201, in create return WebTable(name, d=rest.load(url), keep_standards_prefix=keep_standards_prefix) File "/usr/lib/python2.5/site-packages/yos/crawl/rest.py", line 38, in load return xml2dict.fromstring(dl) File "/usr/lib/python2.5/site-packages/yos/crawl/xml2dict.py", line 41, in fromstring t = ET.fromstring(s) File "/usr/lib/python2.5/xml/etree/ElementTree.py", line 963, in XML parser.feed(text) File "/usr/lib/python2.5/xml/etree/ElementTree.py", line 1245, in feed self._parser.Parse(data, 0) xml.parsers.expat.ExpatError: syntax error: line 1, column 0 </code></pre> <p>It looks like both examples are failing when trying to query Digg.com. Here is the query that is constructed in ex3.py's code: </p> <pre><code>diggf = lambda r: {"title": r["title"]["value"], "diggs": int(r["diggCount"]["value"])} digg = db.select(name="dg", udf=diggf, url="http://digg.com/rss_search?search=google+android&amp;area=dig&amp;type=both&amp;section=news") </code></pre>
0
2009-09-14T11:54:27Z
1,422,100
<p>I believe that must be an error in the example: it's getting a JSON result (indeed if you copy and paste that URL in your browser, you'll download a file names search.json which starts with </p> <pre><code>{"results":[{"profile_image_url": "http://a3.twimg.com/profile_images/255524395/KEN_OMALLEY_REVISED_normal.jpg", "created_at":"Mon, 14 Sep 2009 14:52:07 +0000","from_user":"twilightlords", </code></pre> <p>i.e. perfectly normal JSON; but then instead of parsing it with modules such as json or simplejson, it tries to parse it as XML -- and obviously this attempt fails.</p> <p>I believe the fix (which probably needs to be brought to the attention of whoever maintains that code so they can incorporate it) is either to ask for XML instead of JSON output, OR to parse the resulting JSON with appropriate means instead of trying to look at it as XML (not sure how to best implement either change, as I'm not familiar with that code).</p>
0
2009-09-14T14:58:04Z
[ "python", "expat-parser", "yahoo-boss-api" ]
Yahoo BOSS Python Library, ExpatError
1,421,099
<p>I tried to install the Yahoo BOSS mashup framework, but am having trouble running the examples provided. Examples 1, 2, 5, and 6 work, but 3 &amp; 4 give Expat errors. Here is the output from ex3.py:</p> <pre><code>gpython examples/ex3.py examples/ex3.py:33: Warning: 'as' will become a reserved keyword in Python 2.6 Traceback (most recent call last): File "examples/ex3.py", line 27, in &lt;module&gt; digg = db.select(name="dg", udf=titlef, url="http://digg.com/rss_search?search=google+android&amp;area=dig&amp;type=both&amp;section=news") File "/usr/lib/python2.5/site-packages/yos/yql/db.py", line 214, in select tb = create(name, data=data, url=url, keep_standards_prefix=keep_standards_prefix) File "/usr/lib/python2.5/site-packages/yos/yql/db.py", line 201, in create return WebTable(name, d=rest.load(url), keep_standards_prefix=keep_standards_prefix) File "/usr/lib/python2.5/site-packages/yos/crawl/rest.py", line 38, in load return xml2dict.fromstring(dl) File "/usr/lib/python2.5/site-packages/yos/crawl/xml2dict.py", line 41, in fromstring t = ET.fromstring(s) File "/usr/lib/python2.5/xml/etree/ElementTree.py", line 963, in XML parser.feed(text) File "/usr/lib/python2.5/xml/etree/ElementTree.py", line 1245, in feed self._parser.Parse(data, 0) xml.parsers.expat.ExpatError: syntax error: line 1, column 0 </code></pre> <p>It looks like both examples are failing when trying to query Digg.com. Here is the query that is constructed in ex3.py's code: </p> <pre><code>diggf = lambda r: {"title": r["title"]["value"], "diggs": int(r["diggCount"]["value"])} digg = db.select(name="dg", udf=diggf, url="http://digg.com/rss_search?search=google+android&amp;area=dig&amp;type=both&amp;section=news") </code></pre>
0
2009-09-14T11:54:27Z
2,505,220
<p>The problem is the digg search string. It should be "s=". Not "search="</p>
1
2010-03-24T03:49:50Z
[ "python", "expat-parser", "yahoo-boss-api" ]
Python 3-compatibe HTML to text converter preserving basic structure under permissive licence?
1,421,238
<p>I am looking for a relatively simple HTML to text converter which displays links and works on strings.</p> <p>So far I have tried</p> <ul> <li>lynx but performance is too bad,</li> <li>html2text which gives weird and verbose markdown output and is under GPLv3 which is too restrictive for my (BSD-licensed) project,</li> <li><a href="http://effbot.org/librarybook/formatter-example-3.py" rel="nofollow">http://effbot.org/librarybook/formatter-example-3.py</a> using htmllib.HTMLParser with formatter.AbstractFormatter and a custom writer, however htmllib.HTMLParser is drpeceated and has been removed from Python 3.</li> </ul> <p>So is there any simple, performant, Python 3-compatible HTML to text converter under a permissive license such as MIT/BSD/Apache and the like?</p> <p><strong>Edit:</strong> I dont just need something to strip HTML-Tags but also to preserve the basic structure of the HTML, that is output that somewhat resembles that of Lynx.</p>
1
2009-09-14T12:23:52Z
1,421,388
<p>Pyparsing's examples include an <a href="http://pyparsing.wikispaces.com/file/view/htmlStripper.py" rel="nofollow">html stripper</a> and a <a href="http://pyparsing.wikispaces.com/file/view/urlExtractorNew.py" rel="nofollow">URL extractor</a>.</p> <p>Unlike BeautifulSoup and most HTML parsers, Pyparsing does not try to parse the entire HTML document, and return a hierarchical object. Pyparsing is closer to the typical regex scanner/filter engine - but pyparsing's HTML tag expressions are tolerant of many of the tricky variabilities that make regex processing of HTML a nightmare:</p> <ul> <li>unpredictable upper/lower case</li> <li>unpredictable whitespace before and after &lt;, >, and =</li> <li>unexpected attributes (like '')</li> <li>attribute values in single quotes, or unquoted values</li> <li>attributes in varying order</li> </ul>
0
2009-09-14T12:56:50Z
[ "python" ]
Nested While loop in Python
1,421,323
<p>I am a beginner in python programming. I wrote the following program but it doesn't execute as I want it to. Here is the code:</p> <pre><code>b=0 x=0 while b&lt;=10: print 'here is the outer loop\n',b, while x&lt;=15: k=p[x] print'here is the inner loop\n',x, x=x+1 b=b+1 </code></pre> <p>can somebody help me?? I will be grateful indeed! Regards, Gillani</p>
0
2009-09-14T12:43:21Z
1,421,351
<p>Not sure what your problem is, maybe you want to put that <code>x=0</code> right before the inner loop ?</p> <p>Your whole code doesn't look remotely like Python code ... loops like that are better done like this:</p> <pre><code>for b in range(0,11): print 'here is the outer loop',b for x in range(0, 16): #k=p[x] print 'here is the inner loop',x </code></pre>
23
2009-09-14T12:48:49Z
[ "python", "while-loop" ]
Nested While loop in Python
1,421,323
<p>I am a beginner in python programming. I wrote the following program but it doesn't execute as I want it to. Here is the code:</p> <pre><code>b=0 x=0 while b&lt;=10: print 'here is the outer loop\n',b, while x&lt;=15: k=p[x] print'here is the inner loop\n',x, x=x+1 b=b+1 </code></pre> <p>can somebody help me?? I will be grateful indeed! Regards, Gillani</p>
0
2009-09-14T12:43:21Z
1,421,383
<p>Running your code I'm get an error if "'p' is not defind" which means you are trying to use the the array p before anything is in it.</p> <p>Removing that that line lets the code run with output of</p> <pre><code>here is the outer loop 0 here is the inner loop 0 here is the inner loop 1 here is the inner loop 2 here is the inner loop 3 here is the inner loop 4 here is the inner loop 5 here is the inner loop 6 here is the inner loop 7 here is the inner loop 8 here is the inner loop 9 here is the inner loop 10 here is the inner loop 11 here is the inner loop 12 here is the inner loop 13 here is the inner loop 14 here is the inner loop 15 here is the outer loop 1 here is the outer loop 2 here is the outer loop 3 here is the outer loop 4 here is the outer loop 5 here is the outer loop 6 here is the outer loop 7 here is the outer loop 8 here is the outer loop 9 here is the outer loop 10 &gt;&gt;&gt; </code></pre>
0
2009-09-14T12:55:44Z
[ "python", "while-loop" ]
Nested While loop in Python
1,421,323
<p>I am a beginner in python programming. I wrote the following program but it doesn't execute as I want it to. Here is the code:</p> <pre><code>b=0 x=0 while b&lt;=10: print 'here is the outer loop\n',b, while x&lt;=15: k=p[x] print'here is the inner loop\n',x, x=x+1 b=b+1 </code></pre> <p>can somebody help me?? I will be grateful indeed! Regards, Gillani</p>
0
2009-09-14T12:43:21Z
1,421,390
<p>Because you defined the x outside of the outer while loop its scope is also outside of the outer loop and it does not get reset after each outer loop.</p> <p>To fix this move the defixition of x inside the outer loop:</p> <pre><code>b = 0 while b &lt;= 10: x = 0 print b while x &lt;= 15: print x x += 1 b += 1 </code></pre> <p>a simpler way with simple bounds such as this is to use for loops:</p> <pre><code>for b in range(11): print b for x in range(16): print x </code></pre>
10
2009-09-14T12:57:00Z
[ "python", "while-loop" ]
Nested While loop in Python
1,421,323
<p>I am a beginner in python programming. I wrote the following program but it doesn't execute as I want it to. Here is the code:</p> <pre><code>b=0 x=0 while b&lt;=10: print 'here is the outer loop\n',b, while x&lt;=15: k=p[x] print'here is the inner loop\n',x, x=x+1 b=b+1 </code></pre> <p>can somebody help me?? I will be grateful indeed! Regards, Gillani</p>
0
2009-09-14T12:43:21Z
38,857,471
<p>You need to reset your x variable after processing the inner loop. Otherwise your outerloop will run through without firing the inner loop.</p> <pre><code>b=0 x=0 while b&lt;=10: print 'here is the outer loop\n',b, while x&lt;=15: k=p[x] #&lt;--not sure what "p" is here print'here is the inner loop\n',x, x=x+1 x=0 b=b+1 </code></pre>
0
2016-08-09T17:56:48Z
[ "python", "while-loop" ]
How do I get the operating system name in a friendly manner using Python 2.5?
1,421,357
<p>I tried:</p> <pre><code>print os.name </code></pre> <p>And the output I got was:</p> <pre><code>:nt </code></pre> <p>However, I want output more like "Windows 98", or "Linux".</p> <p>After suggestions in this question, I also tried:</p> <pre><code>import os print os.name import platform print platform.system() print platform.release() </code></pre> <p>And my output was:</p> <pre><code>Traceback (most recent call last): File "C:/Documents and Settings/BIU1LR/Desktop/python_programs/program/platform.py", line 3, in &lt;module&gt; import platform File "C:/Documents and Settings/BIU1LR/Desktop/python_programs/program\platform.py", line 4, in &lt;module&gt; print platform.system() AttributeError: 'module' object has no attribute 'system' </code></pre> <p>I am using Python 2.5.2. What am I doing wrong?</p>
7
2009-09-14T12:50:23Z
1,421,365
<p>Try:</p> <pre><code>import platform print platform.system(), platform.release() </code></pre> <p>I tried this on my computer with Python 2.6 and I got this as the output:</p> <pre><code>Windows XP </code></pre> <p>After your latest edits, I see that you called your script platform.py. This is causing a naming problem, as when you call <code>platform.system()</code> and <code>platform.release()</code>, it's looking in your file, and not Python's platform module. If you change the name of your file, all of your problems should be resolved.</p>
36
2009-09-14T12:52:34Z
[ "python" ]
How do I get the operating system name in a friendly manner using Python 2.5?
1,421,357
<p>I tried:</p> <pre><code>print os.name </code></pre> <p>And the output I got was:</p> <pre><code>:nt </code></pre> <p>However, I want output more like "Windows 98", or "Linux".</p> <p>After suggestions in this question, I also tried:</p> <pre><code>import os print os.name import platform print platform.system() print platform.release() </code></pre> <p>And my output was:</p> <pre><code>Traceback (most recent call last): File "C:/Documents and Settings/BIU1LR/Desktop/python_programs/program/platform.py", line 3, in &lt;module&gt; import platform File "C:/Documents and Settings/BIU1LR/Desktop/python_programs/program\platform.py", line 4, in &lt;module&gt; print platform.system() AttributeError: 'module' object has no attribute 'system' </code></pre> <p>I am using Python 2.5.2. What am I doing wrong?</p>
7
2009-09-14T12:50:23Z
1,421,623
<p>it is because you named your program "platform". Hence when importing the module "platform", your program is imported instead in a circular import.</p> <p>Try renaming the file to test_platform.py, and it will work.</p>
14
2009-09-14T13:43:16Z
[ "python" ]
How do I get the operating system name in a friendly manner using Python 2.5?
1,421,357
<p>I tried:</p> <pre><code>print os.name </code></pre> <p>And the output I got was:</p> <pre><code>:nt </code></pre> <p>However, I want output more like "Windows 98", or "Linux".</p> <p>After suggestions in this question, I also tried:</p> <pre><code>import os print os.name import platform print platform.system() print platform.release() </code></pre> <p>And my output was:</p> <pre><code>Traceback (most recent call last): File "C:/Documents and Settings/BIU1LR/Desktop/python_programs/program/platform.py", line 3, in &lt;module&gt; import platform File "C:/Documents and Settings/BIU1LR/Desktop/python_programs/program\platform.py", line 4, in &lt;module&gt; print platform.system() AttributeError: 'module' object has no attribute 'system' </code></pre> <p>I am using Python 2.5.2. What am I doing wrong?</p>
7
2009-09-14T12:50:23Z
3,060,944
<pre><code>import platform platform.dist() </code></pre>
4
2010-06-17T10:47:53Z
[ "python" ]
How do I get the operating system name in a friendly manner using Python 2.5?
1,421,357
<p>I tried:</p> <pre><code>print os.name </code></pre> <p>And the output I got was:</p> <pre><code>:nt </code></pre> <p>However, I want output more like "Windows 98", or "Linux".</p> <p>After suggestions in this question, I also tried:</p> <pre><code>import os print os.name import platform print platform.system() print platform.release() </code></pre> <p>And my output was:</p> <pre><code>Traceback (most recent call last): File "C:/Documents and Settings/BIU1LR/Desktop/python_programs/program/platform.py", line 3, in &lt;module&gt; import platform File "C:/Documents and Settings/BIU1LR/Desktop/python_programs/program\platform.py", line 4, in &lt;module&gt; print platform.system() AttributeError: 'module' object has no attribute 'system' </code></pre> <p>I am using Python 2.5.2. What am I doing wrong?</p>
7
2009-09-14T12:50:23Z
25,814,896
<p>well it depends on the OS: for example I had tested </p> <pre><code> platform.system() - in linux works, AIX works platform.release()- in linux works, AIX gives a weird '1' with non other info platform.dist() - in linux works, AIX gives a nothing '','','' os.name - resolves 'posix' in both :S </code></pre> <p>Windows I really don't test nor care :P</p>
1
2014-09-12T18:51:11Z
[ "python" ]
SQLAlchemy session management in long-running process
1,421,502
<p>Scenario:</p> <ul> <li>A .NET-based application server (<a href="http://global.wonderware.com/EN/Pages/WonderwareSystemPlatform.aspx" rel="nofollow">Wonderware IAS/System Platform</a>) hosts automation objects that communicate with various equipment on the factory floor.</li> <li>CPython is hosted inside this application server (using <a href="http://pythonnet.sourceforge.net" rel="nofollow">Python for .NET</a>).</li> <li>The automation objects have scripting functionality built-in (using a custom, .NET-based language). These scripts call Python functions.</li> </ul> <p>The Python functions are part of a system to track Work-In-Progress on the factory floor. The purpose of the system is to track the produced widgets along the process, ensure that the widgets go through the process in the correct order, and check that certain conditions are met along the process. The widget production history and widget state is stored in a relational database, this is where SQLAlchemy plays its part.</p> <p>For example, when a widget passes a scanner, the automation software triggers the following script (written in the application server's custom scripting language):</p> <pre><code>' wiget_id and scanner_id provided by automation object ' ExecFunction() takes care of calling a CPython function retval = ExecFunction("WidgetScanned", widget_id, scanner_id); ' if the python function raises an Exception, ErrorOccured will be true ' in this case, any errors should cause the production line to stop. if (retval.ErrorOccured) then ProductionLine.Running = False; InformationBoard.DisplayText = "ERROR: " + retval.Exception.Message; InformationBoard.SoundAlarm = True end if; </code></pre> <p>The script calls the <code>WidgetScanned</code> python function:</p> <pre><code># pywip/functions.py from pywip.database import session from pywip.model import Widget, WidgetHistoryItem from pywip import validation, StatusMessage from datetime import datetime def WidgetScanned(widget_id, scanner_id): widget = session.query(Widget).get(widget_id) validation.validate_widget_passed_scanner(widget, scanner) # raises exception on error widget.history.append(WidgetHistoryItem(timestamp=datetime.now(), action=u"SCANNED", scanner_id=scanner_id)) widget.last_scanner = scanner_id widget.last_update = datetime.now() return StatusMessage("OK") # ... there are a dozen similar functions </code></pre> <p>My question is: <strong>How do I best manage SQLAlchemy sessions in this scenario?</strong> The application server is a long-running process, typically running months between restarts. The application server is single-threaded.</p> <p>Currently, I do it the following way:</p> <p>I apply a decorator to the functions I make avaliable to the application server:</p> <pre><code># pywip/iasfunctions.py from pywip import functions def ias_session_handling(func): def _ias_session_handling(*args, **kwargs): try: retval = func(*args, **kwargs) session.commit() return retval except: session.rollback() raise return _ias_session_handling # ... actually I populate this module with decorated versions of all the functions in pywip.functions dynamically WidgetScanned = ias_session_handling(functions.WidgetScanned) </code></pre> <p>Question: <strong>Is the decorator above suitable for handling sessions in a long-running process?</strong> Should I call <code>session.remove()</code>?</p> <p>The SQLAlchemy session object is a scoped session:</p> <pre><code># pywip/database.py from sqlalchemy.orm import scoped_session, sessionmaker session = scoped_session(sessionmaker()) </code></pre> <p>I want to keep the session management out of the basic functions. For two reasons:</p> <ol> <li>There is another family of functions, sequence functions. The sequence functions call several of the basic functions. One sequence function should equal one database transaction.</li> <li>I need to be able to use the library from other environments. a) From a TurboGears web application. In that case, session management is done by TurboGears. b) From an IPython shell. In that case, commit/rollback will be explicit.</li> </ol> <p>(I am truly sorry for the long question. But I felt I needed to explain the scenario. Perhaps not necessary?)</p>
2
2009-09-14T13:18:43Z
1,422,367
<p>The described decorator is suitable for long running applications, but you can run into trouble if you accidentally share objects between requests. To make the errors appear earlier and not corrupt anything it is better to discard the session with session.remove().</p> <pre><code>try: try: retval = func(*args, **kwargs) session.commit() return retval except: session.rollback() raise finally: session.remove() </code></pre> <p>Or if you can use the <code>with</code> context manager:</p> <pre><code>try: with session.registry().transaction: return func(*args, **kwargs) finally: session.remove() </code></pre> <p>By the way, you might want to use <code>.with_lockmode('update')</code> on the query so your validate doesn't run on stale data.</p>
3
2009-09-14T15:42:47Z
[ "python", "sqlalchemy", "wonderware" ]
SQLAlchemy session management in long-running process
1,421,502
<p>Scenario:</p> <ul> <li>A .NET-based application server (<a href="http://global.wonderware.com/EN/Pages/WonderwareSystemPlatform.aspx" rel="nofollow">Wonderware IAS/System Platform</a>) hosts automation objects that communicate with various equipment on the factory floor.</li> <li>CPython is hosted inside this application server (using <a href="http://pythonnet.sourceforge.net" rel="nofollow">Python for .NET</a>).</li> <li>The automation objects have scripting functionality built-in (using a custom, .NET-based language). These scripts call Python functions.</li> </ul> <p>The Python functions are part of a system to track Work-In-Progress on the factory floor. The purpose of the system is to track the produced widgets along the process, ensure that the widgets go through the process in the correct order, and check that certain conditions are met along the process. The widget production history and widget state is stored in a relational database, this is where SQLAlchemy plays its part.</p> <p>For example, when a widget passes a scanner, the automation software triggers the following script (written in the application server's custom scripting language):</p> <pre><code>' wiget_id and scanner_id provided by automation object ' ExecFunction() takes care of calling a CPython function retval = ExecFunction("WidgetScanned", widget_id, scanner_id); ' if the python function raises an Exception, ErrorOccured will be true ' in this case, any errors should cause the production line to stop. if (retval.ErrorOccured) then ProductionLine.Running = False; InformationBoard.DisplayText = "ERROR: " + retval.Exception.Message; InformationBoard.SoundAlarm = True end if; </code></pre> <p>The script calls the <code>WidgetScanned</code> python function:</p> <pre><code># pywip/functions.py from pywip.database import session from pywip.model import Widget, WidgetHistoryItem from pywip import validation, StatusMessage from datetime import datetime def WidgetScanned(widget_id, scanner_id): widget = session.query(Widget).get(widget_id) validation.validate_widget_passed_scanner(widget, scanner) # raises exception on error widget.history.append(WidgetHistoryItem(timestamp=datetime.now(), action=u"SCANNED", scanner_id=scanner_id)) widget.last_scanner = scanner_id widget.last_update = datetime.now() return StatusMessage("OK") # ... there are a dozen similar functions </code></pre> <p>My question is: <strong>How do I best manage SQLAlchemy sessions in this scenario?</strong> The application server is a long-running process, typically running months between restarts. The application server is single-threaded.</p> <p>Currently, I do it the following way:</p> <p>I apply a decorator to the functions I make avaliable to the application server:</p> <pre><code># pywip/iasfunctions.py from pywip import functions def ias_session_handling(func): def _ias_session_handling(*args, **kwargs): try: retval = func(*args, **kwargs) session.commit() return retval except: session.rollback() raise return _ias_session_handling # ... actually I populate this module with decorated versions of all the functions in pywip.functions dynamically WidgetScanned = ias_session_handling(functions.WidgetScanned) </code></pre> <p>Question: <strong>Is the decorator above suitable for handling sessions in a long-running process?</strong> Should I call <code>session.remove()</code>?</p> <p>The SQLAlchemy session object is a scoped session:</p> <pre><code># pywip/database.py from sqlalchemy.orm import scoped_session, sessionmaker session = scoped_session(sessionmaker()) </code></pre> <p>I want to keep the session management out of the basic functions. For two reasons:</p> <ol> <li>There is another family of functions, sequence functions. The sequence functions call several of the basic functions. One sequence function should equal one database transaction.</li> <li>I need to be able to use the library from other environments. a) From a TurboGears web application. In that case, session management is done by TurboGears. b) From an IPython shell. In that case, commit/rollback will be explicit.</li> </ol> <p>(I am truly sorry for the long question. But I felt I needed to explain the scenario. Perhaps not necessary?)</p>
2
2009-09-14T13:18:43Z
3,050,770
<p>Ask your WonderWare administrator to give you access to the Wonderware Historian, you can track the values of the tags pretty easily via MSSQL calls over sqlalchemy that you can poll every so often.</p> <p>Another option is to use the archestra toolkit to listen for the internal tag updates and have a server deployed as a platform in the galaxy which you can listen from.</p>
1
2010-06-16T04:44:49Z
[ "python", "sqlalchemy", "wonderware" ]
How to trigger post-build using setuptools/distutils
1,421,709
<p>I am building an application using py2app/setuptools, so once it creates application bundle I want to take some action on dist folder e.g. create a installer/upload it.</p> <p>Is there a way? I have found some post-install solution but no post-build</p> <p>Alternatively I can call 'python setup.py py2app' from my own script and do that, but it would be better if it can be done in setup.py</p>
6
2009-09-14T13:57:33Z
1,421,744
<p>There are probably ways to do this using setuptools or distutils, but they're likely to be pretty hackish. I'd strongly recommend using one of the following tools if you want to do something like this:</p> <ul> <li><a href="http://www.blueskyonmars.com/projects/paver/" rel="nofollow">paver</a></li> <li><a href="http://pypi.python.org/pypi/zc.buildout" rel="nofollow">zc.buildout</a></li> </ul> <p>Paver is probably the easiest to move to as you will probably be able to use all of your existing setup.py file.</p>
0
2009-09-14T14:02:15Z
[ "python", "setuptools", "distutils", "py2app" ]
How to trigger post-build using setuptools/distutils
1,421,709
<p>I am building an application using py2app/setuptools, so once it creates application bundle I want to take some action on dist folder e.g. create a installer/upload it.</p> <p>Is there a way? I have found some post-install solution but no post-build</p> <p>Alternatively I can call 'python setup.py py2app' from my own script and do that, but it would be better if it can be done in setup.py</p>
6
2009-09-14T13:57:33Z
1,472,629
<p>Can you please clarify what you're trying to do?</p> <blockquote> <p>take some action on dist folder e.g. create a installer/upload it.</p> </blockquote> <p>When you say create a installer, do you mean build a distribution for the package? And when you say upload, do you mean upload to pypi? or somewhere else?</p> <blockquote> <p>I have found some post-install solution but no post-build</p> </blockquote> <p>Are these py2app hooks/callbacks?</p> <blockquote> <p>python setup.py py2app</p> </blockquote> <p>This is not the convention for how distutils is used. It's usually <code>python setup.py install</code>.</p> <p>Answer:</p> <blockquote> <p>py2app target is a dist folder, which I want to package using my installation script and upload to my website </p> </blockquote> <p>Edit:</p> <p>So, you created a package that uses distutils with setup.py.</p> <p>When you run setup.py it creates distributions for this file and places then them in /dist folder.</p> <p>Now you want to upload the built file to your website.</p> <p>To do this, you need a different tool. Something like <a href="http://docs.fabfile.org/0.9/" rel="nofollow">fabric</a>.</p> <p>You can use fabric to create a script that would execute the build command and then upload the built files to your server.</p>
0
2009-09-24T15:59:03Z
[ "python", "setuptools", "distutils", "py2app" ]
How to trigger post-build using setuptools/distutils
1,421,709
<p>I am building an application using py2app/setuptools, so once it creates application bundle I want to take some action on dist folder e.g. create a installer/upload it.</p> <p>Is there a way? I have found some post-install solution but no post-build</p> <p>Alternatively I can call 'python setup.py py2app' from my own script and do that, but it would be better if it can be done in setup.py</p>
6
2009-09-14T13:57:33Z
1,719,797
<p>I <a href="http://stackoverflow.com/questions/1710839/custom-distutils-commands/1712544#1712544">responded to a similar question yesterday</a> about subclassing <strong>distutils.core.Command</strong>.</p> <p>The core of it is that by doing this you are able to precisely control the behavior of each stage of the preparation process, and are able to create your own commands that can do pretty much anything you can think of. </p> <p>Please have a look at that response as I think it will help you out. </p>
4
2009-11-12T03:59:39Z
[ "python", "setuptools", "distutils", "py2app" ]
Set files to ownership of current directory in Python
1,421,807
<p>I'm working on a Python script that creates text files containing size/space information about the directories that the script is run on. The script needs to be run as root, and as a result, it sets the text files that it creates to root's ownership.</p> <p>I know I can change the ownership with os.fchown, but how do I pass fchown the uid and gid of the directory that the script is running on?</p>
0
2009-09-14T14:11:37Z
1,421,900
<p>Use</p> <pre><code>import os, stat info = os.stat(dirpath) uid, gid = info[stat.ST_UID], info[stat.ST_GID] </code></pre>
0
2009-09-14T14:25:15Z
[ "python", "permissions" ]
Which python mpi library to use?
1,422,260
<p>I'm starting work on some simulations using MPI and want to do the programming in Python/scipy. The scipy <a href="http://www.scipy.org/Topical%5FSoftware#head-cf472934357fda4558aafdf558a977c4d59baecb">site</a> lists a number of mpi libraries, but I was hoping to get feedback on quality, ease of use, etc from anyone who has used one.</p>
15
2009-09-14T15:26:04Z
1,422,871
<p>I have heard good things about <a href="http://mpi4py.scipy.org/">mpi4py</a> (but I have never used it myself). That's what a colleague recommended who looked at all the alternatives. He mentioned the completeness as one advantage.</p>
15
2009-09-14T17:20:57Z
[ "python", "mpi" ]
Which python mpi library to use?
1,422,260
<p>I'm starting work on some simulations using MPI and want to do the programming in Python/scipy. The scipy <a href="http://www.scipy.org/Topical%5FSoftware#head-cf472934357fda4558aafdf558a977c4d59baecb">site</a> lists a number of mpi libraries, but I was hoping to get feedback on quality, ease of use, etc from anyone who has used one.</p>
15
2009-09-14T15:26:04Z
2,623,758
<p>Also check whether <a href="http://pymw.sourceforge.net/" rel="nofollow">pymw</a> (master/worker framework) might help you. It supports various backends (MPI via pympi, Boinc, ..)</p>
4
2010-04-12T16:49:18Z
[ "python", "mpi" ]
Which python mpi library to use?
1,422,260
<p>I'm starting work on some simulations using MPI and want to do the programming in Python/scipy. The scipy <a href="http://www.scipy.org/Topical%5FSoftware#head-cf472934357fda4558aafdf558a977c4d59baecb">site</a> lists a number of mpi libraries, but I was hoping to get feedback on quality, ease of use, etc from anyone who has used one.</p>
15
2009-09-14T15:26:04Z
6,897,595
<p>I've used pypar on 64 bit windows server with MPICH2. It is easy to use, requires no special structures or constants and you can send almost any python object, list or dictionary about with no effort. The developer is also available to ask questions about.</p>
2
2011-08-01T11:14:57Z
[ "python", "mpi" ]
GAE load data into datastore without using CSV
1,422,270
<p>I've used bulkloader.Loader to load stuff into the GAE dev and live datastore, but my next thing to to create objects from non-CSV data and push it into the datastore.</p> <p>So say my object is something like:</p> <pre><code>class CainEvent(db.Model): name =db.StringProperty(required=True) birthdate = db.DateProperty() </code></pre> <p>Can anyone give me a simple example on how to do this please?</p>
1
2009-09-14T15:29:12Z
1,422,712
<p>Here's an extremely simplified example of what we're doing to use the bulkloader to load JSON data instead of CSV data:</p> <pre><code>class JSONLoader(bulkloader.Loader): def generate_records(self, filename): for item in json.load(open(filename)): yield item['fields'] </code></pre> <p>In this example, I'm assuming a JSON format that looks something like</p> <pre><code>[ { "fields": [ "a", "b", "c", "d" ] }, { "fields": [ "e", "f", "g", "h" ] } ] </code></pre> <p>which is oversimplified.</p> <p>Basically, all you have to do is create a subclass of bulkloader.Loader and implement (at a minimum) the <code>generate_records</code> method, which should yield lists of strings. This same strategy would work for loading data from XML files or ROT13-encrypted files or whatever.</p> <p>Note that the list of strings yielded by the <code>generate_records</code> method must match up (in length and order) with the "properties" list you provide when you initialize the loader (ie, the second argument to the <code>AlbumLoader.__init__</code> method in <a href="http://code.google.com/appengine/docs/python/tools/uploadingdata.html#Creating%5FLoader%5FClasses" rel="nofollow">this example</a>).</p> <p>This approach actually provides a lot of flexibility: We're overriding the <code>__init__</code> method on our <code>JSONLoader</code> implementation and automatically determining the <code>kind</code> of model we're loading and its list of properties to provide to the <code>bulkloader.Loader</code> parent class.</p>
2
2009-09-14T16:52:21Z
[ "python", "google-app-engine" ]
GAE load data into datastore without using CSV
1,422,270
<p>I've used bulkloader.Loader to load stuff into the GAE dev and live datastore, but my next thing to to create objects from non-CSV data and push it into the datastore.</p> <p>So say my object is something like:</p> <pre><code>class CainEvent(db.Model): name =db.StringProperty(required=True) birthdate = db.DateProperty() </code></pre> <p>Can anyone give me a simple example on how to do this please?</p>
1
2009-09-14T15:29:12Z
1,575,564
<p>You may find <a href="http://blog.notdot.net/2009/9/Advanced-Bulk-Loading-part-3-Alternate-datasources" rel="nofollow">this post</a> useful - it details how to load data direct from an RDBMS, but applies equally to loading from any other source.</p>
0
2009-10-15T22:52:09Z
[ "python", "google-app-engine" ]
fcntl substitute on Windows
1,422,368
<p>I received a Python project (which happens to be a Django project, if that matters,) that uses the <code>fcntl</code> module from the standard library, which seems to be available only on Linux. When I try to run it on my Windows machine, it stops with an <code>ImportError</code>, because this module does not exist here.</p> <p>Is there any way for me to make a small change in the program to make it work on Windows?</p>
41
2009-09-14T15:43:11Z
1,422,436
<p>The substitute of <code>fcntl</code> on windows are <code>win32api</code> calls. The usage is completely different. It is not some switch you can just flip.</p> <p>In other words, porting a <code>fcntl</code>-heavy-user module to windows is not trivial. It requires you to analyze what exactly each <code>fcntl</code> call does and then find the equivalent <code>win32api</code> code, if any. </p> <p>There's also the possibility that some code using <code>fcntl</code> has no windows equivalent, which would require you to change the module api and maybe the structure/paradigm of the program using the module you're porting.</p> <p>If you provide more details about the <code>fcntl</code> calls people can find windows equivalents.</p>
49
2009-09-14T15:54:35Z
[ "python", "windows", "linux" ]
fcntl substitute on Windows
1,422,368
<p>I received a Python project (which happens to be a Django project, if that matters,) that uses the <code>fcntl</code> module from the standard library, which seems to be available only on Linux. When I try to run it on my Windows machine, it stops with an <code>ImportError</code>, because this module does not exist here.</p> <p>Is there any way for me to make a small change in the program to make it work on Windows?</p>
41
2009-09-14T15:43:11Z
9,993,103
<p>Although this does not help you right away, there is an alternative that can work with both Unix (fcntl) and Windows (win32 api calls), called: <strong>portalocker</strong></p> <p>It describes itself as a cross-platform (posix/nt) API for flock-style file locking for Python. It basically maps fcntl to win32 api calls.</p> <p>The original code at <a href="http://code.activestate.com/recipes/65203/" rel="nofollow">http://code.activestate.com/recipes/65203/</a> can now be installed as a separate package - <a href="https://pypi.python.org/pypi/portalocker" rel="nofollow">https://pypi.python.org/pypi/portalocker</a></p>
14
2012-04-03T12:18:58Z
[ "python", "windows", "linux" ]
fcntl substitute on Windows
1,422,368
<p>I received a Python project (which happens to be a Django project, if that matters,) that uses the <code>fcntl</code> module from the standard library, which seems to be available only on Linux. When I try to run it on my Windows machine, it stops with an <code>ImportError</code>, because this module does not exist here.</p> <p>Is there any way for me to make a small change in the program to make it work on Windows?</p>
41
2009-09-14T15:43:11Z
25,471,508
<p>The fcntl module is just used for locking the pinning file, so assuming you don't try multiple access, this can be an acceptable workaround. Place this module in your PYTHONPATH, and it should just work as the official fcntl module.</p> <p>Try using <a href="https://communities.cisco.com/servlet/JiveServlet/download/150596-65641/fcntl.py.zip">this module</a> for development/testing purposes only in windows.</p> <pre><code>def fcntl(fd, op, arg=0): return 0 def ioctl(fd, op, arg=0, mutable_flag=True): if mutable_flag: return 0 else: return "" def flock(fd, op): return def lockf(fd, operation, length=0, start=0, whence=0): return </code></pre>
16
2014-08-24T12:05:33Z
[ "python", "windows", "linux" ]
Django Form Validation Framework on AppEngine: How to strip out HTML etc.?
1,422,674
<p>I'm using the Django Form Validation Framework on AppEngine (<a href="http://code.google.com/appengine/articles/djangoforms.html" rel="nofollow">http://code.google.com/appengine/articles/djangoforms.html</a>), like this:</p> <pre><code>data = MyForm(data=self.request.POST) if data.is_valid(): entity = data.save(commit=False) entity.put() </code></pre> <p>I wonder if there's a way to preprocess the POST data (strip out malicious code, HTML etc.) before storing it. It seems that any form validation library should offer something like that, no?</p> <p>Thanks</p> <p>Hannes</p>
1
2009-09-14T16:43:44Z
1,423,194
<p>Yes, of course. Have you tried reading the forms documentation?</p> <p><a href="http://docs.djangoproject.com/en/dev/ref/forms/validation/" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/forms/validation/</a></p>
0
2009-09-14T18:31:06Z
[ "python", "django", "google-app-engine" ]
Django Form Validation Framework on AppEngine: How to strip out HTML etc.?
1,422,674
<p>I'm using the Django Form Validation Framework on AppEngine (<a href="http://code.google.com/appengine/articles/djangoforms.html" rel="nofollow">http://code.google.com/appengine/articles/djangoforms.html</a>), like this:</p> <pre><code>data = MyForm(data=self.request.POST) if data.is_valid(): entity = data.save(commit=False) entity.put() </code></pre> <p>I wonder if there's a way to preprocess the POST data (strip out malicious code, HTML etc.) before storing it. It seems that any form validation library should offer something like that, no?</p> <p>Thanks</p> <p>Hannes</p>
1
2009-09-14T16:43:44Z
1,423,936
<p>Short answer:</p> <p><code>forms.is_valid()</code> auto populates a dictionary <code>forms.cleaned_data</code> by calling a method called clean(). If you want to do any custom validation define your own 'clean_filed_name' that returns the cleaned field value or raises <code>forms.ValidationError()</code>. On error, the corresponding error on the field is auto populated.</p> <p>Long answer:</p> <p><a href="http://docs.djangoproject.com/en/dev/ref/forms/validation/" rel="nofollow">Refer Documentation</a></p>
2
2009-09-14T21:06:25Z
[ "python", "django", "google-app-engine" ]
Django Form Validation Framework on AppEngine: How to strip out HTML etc.?
1,422,674
<p>I'm using the Django Form Validation Framework on AppEngine (<a href="http://code.google.com/appengine/articles/djangoforms.html" rel="nofollow">http://code.google.com/appengine/articles/djangoforms.html</a>), like this:</p> <pre><code>data = MyForm(data=self.request.POST) if data.is_valid(): entity = data.save(commit=False) entity.put() </code></pre> <p>I wonder if there's a way to preprocess the POST data (strip out malicious code, HTML etc.) before storing it. It seems that any form validation library should offer something like that, no?</p> <p>Thanks</p> <p>Hannes</p>
1
2009-09-14T16:43:44Z
1,642,676
<p>In addition to the answers above, a different perspective: Don't. Store the user input with as little processing as is practical, and sanitize the data on output. Django templates provide filters for this - 'escape' is one that escapes all HTML tags.</p> <p>The advantage of this approach over sanitizing the data at input time is twofold: You can change how you sanitize data at any time without having to 'grandfather in' all your old data, and when a user wants to edit something, you can show them the original data they entered, rather than the 'cleaned up' version. Cleaning up data at the wrong time is also a major cause of things like double-escaping.</p>
1
2009-10-29T10:09:13Z
[ "python", "django", "google-app-engine" ]
How does AMF communication work?
1,422,724
<p>How does Flash communicate with services / scripts on servers via <a href="http://en.wikipedia.org/wiki/Action%5FMessage%5FFormat" rel="nofollow">AMF</a>?</p> <p>Regarding the <a href="http://en.wikipedia.org/wiki/Action%5FMessage%5FFormat#Support%5Ffor%5FAMF" rel="nofollow">AMF libraries</a> for Python / Perl / PHP which are easier to develop than .NET / Java:</p> <ul> <li>do they execute script files, whenever Flash sends an Remote Procedure Call?</li> <li>or do they communicate via sockets, to script classes that are running as services?</li> </ul> <p>Regarding typical AMF functionality:</p> <ul> <li>How is data transferred? is it by method arguments that are automatically serialised?</li> <li>How can servers "<a href="http://en.wikipedia.org/wiki/Push%5Ftechnology" rel="nofollow">push</a>" to clients? do Flash movies have to connect on a socket?</li> </ul> <p>Thanks for your time.</p>
3
2009-09-14T16:53:44Z
1,422,867
<p>The only AMF library I'm familiar with is <a href="http://pyamf.org/">PyAMF</a>, which has been great to work with so far. Here are the answers to your questions for PyAMF:</p> <ul> <li><p>I'd imagine you can run it as a script (do you mean like CGI?), but the easiest IMO is to set up an app server specifically for AMF requests</p></li> <li><p>the easiest way is to define functions in pure python, which PyAMF wraps to serialize incoming / outgoing AMF data</p></li> <li><p>you can communicate via sockets if that's what you need to do, but again, it's the easiest to use pure Python functions; one use for sockets is to keep an open connection and 'push' data to clients, see <a href="http://pyamf.org/wiki/BinarySocket">this</a> example</p></li> </ul> <p>Here's an example of three simple AMF services being served on <code>localhost:8080</code>:</p> <pre><code>from wsgiref import simple_server from pyamf.remoting.gateway.wsgi import WSGIGateway ## amf services ################################################## def echo(data): return data def reverse(data): return data[::-1] def rot13(data): return data.encode('rot13') services = { 'myservice.echo': echo, 'myservice.reverse': reverse, 'myservice.rot13': rot13, } ## server ######################################################## def main(): app = WSGIGateway(services) simple_server.make_server('localhost', 8080, app).serve_forever() if __name__ == '__main__': main() </code></pre> <p>I would definitely recommend PyAMF. Check out the <a href="http://pyamf.org/wiki/Examples">examples</a> to see what it's capable of and what the code looks like.</p>
7
2009-09-14T17:19:40Z
[ "python", "flash", "perl", "actionscript-2", "amf" ]
How does AMF communication work?
1,422,724
<p>How does Flash communicate with services / scripts on servers via <a href="http://en.wikipedia.org/wiki/Action%5FMessage%5FFormat" rel="nofollow">AMF</a>?</p> <p>Regarding the <a href="http://en.wikipedia.org/wiki/Action%5FMessage%5FFormat#Support%5Ffor%5FAMF" rel="nofollow">AMF libraries</a> for Python / Perl / PHP which are easier to develop than .NET / Java:</p> <ul> <li>do they execute script files, whenever Flash sends an Remote Procedure Call?</li> <li>or do they communicate via sockets, to script classes that are running as services?</li> </ul> <p>Regarding typical AMF functionality:</p> <ul> <li>How is data transferred? is it by method arguments that are automatically serialised?</li> <li>How can servers "<a href="http://en.wikipedia.org/wiki/Push%5Ftechnology" rel="nofollow">push</a>" to clients? do Flash movies have to connect on a socket?</li> </ul> <p>Thanks for your time.</p>
3
2009-09-14T16:53:44Z
1,557,230
<blockquote> <p>How does Flash communicate with services / scripts on servers via AMF?</p> </blockquote> <p>Data is transferred over a TCP/IP connection. Sometimes an existing HTTP connection is used, and in other cases a new TCP/IP connection is opened for the AMF data. When the HTTP or additional TCP connections are opened, the sockets interface is probably used. The AMF definitely travels over a TCP connection of some sort, and the sockets interface is practically the only way to open such a connection.</p> <p>The "data" that is transferred consists of ECMA-script (Javascript(tm)) data types such as "integer", "string", "object", and so on.</p> <p>For a technical specification of how the objects are encoded into binary, Adobe has published a specification: <a href="http://opensource.adobe.com/wiki/download/attachments/1114283/amf3%5Fspec%5F05%5F05%5F08.pdf" rel="nofollow" title="AMF 3.0 Spec at Adobe.com">AMF 3.0 Spec at Adobe.com</a> </p> <p>Generally the way an AMF-using client/server system works is something like this:</p> <ol> <li>The client displays some user interface and opens a TCP connection to the server.</li> <li>The server sends some data to the client, which updates its user interface.</li> <li>If the user makes a command, the client sends some data to the server over the TCP connection.</li> <li>Continue steps 2-3 until the user exits.</li> </ol> <p>For example, if the user clicks a "send mail" button in the UI, then the client code might do this:</p> <pre>public class UICommandMessage extends my.CmdMsg { public function UICommandMessage(action:String, arg: String) { this.cmd = action; this.data = String; } }</pre> Then later: <pre> UICommandMessage msg = new UICommandMessage("Button_Press", "Send_Mail"); server_connection.sendMessage(msg); </pre> <p>in the server code, the server is monitoring the connection as well for incoming AMF object. It receives the message, and passes control to an appropriate response function. This is called "dispatching a message".</p> <p>With more information about what you are trying to accomplish, I could give you more useful details.</p>
4
2009-10-12T22:13:36Z
[ "python", "flash", "perl", "actionscript-2", "amf" ]
pytz: Why is normalize needed when converting between timezones?
1,422,880
<p>I'm reading the not so complete <a href="http://pytz.sourceforge.net/">pytz documentation</a> and I'm stuck on understand one part of it.</p> <blockquote> <p>Converting between timezones also needs special attention. This also needs to use the normalize method to ensure the conversion is correct.</p> </blockquote> <pre><code>&gt;&gt;&gt; utc_dt = utc.localize(datetime.utcfromtimestamp(1143408899)) &gt;&gt;&gt; utc_dt.strftime(fmt) '2006-03-26 21:34:59 UTC+0000' &gt;&gt;&gt; au_tz = timezone('Australia/Sydney') &gt;&gt;&gt; au_dt = au_tz.normalize(utc_dt.astimezone(au_tz)) &gt;&gt;&gt; au_dt.strftime(fmt) '2006-03-27 08:34:59 EST+1100' &gt;&gt;&gt; utc_dt2 = utc.normalize(au_dt.astimezone(utc)) &gt;&gt;&gt; utc_dt2.strftime(fmt) '2006-03-26 21:34:59 UTC+0000' </code></pre> <p>I tried this very example <em>without</em> using <code>normalize</code> and it turned out just the same. In my opinion this example doesn't really explain <em>why</em> we have to use <code>normalize</code> when converting between <code>datetime</code> objects in different timezones.</p> <p>Would someone please give me an <strong>example</strong> (like the one above) where the result differs when not using <code>normalize</code>.</p> <p>Thanks</p>
14
2009-09-14T17:22:31Z
1,422,900
<p>From the pytz documentation:</p> <blockquote> <p>In addition, if you perform date arithmetic on local times that cross DST boundaries, the results may be in an incorrect timezone (ie. subtract 1 minute from 2002-10-27 1:00 EST and you get 2002-10-27 0:59 EST instead of the correct 2002-10-27 1:59 EDT). A normalize() method is provided to correct this. Unfortunately these issues cannot be resolved without modifying the Python datetime implementation.</p> </blockquote>
8
2009-09-14T17:26:38Z
[ "python", "timezone", "pytz" ]
pytz: Why is normalize needed when converting between timezones?
1,422,880
<p>I'm reading the not so complete <a href="http://pytz.sourceforge.net/">pytz documentation</a> and I'm stuck on understand one part of it.</p> <blockquote> <p>Converting between timezones also needs special attention. This also needs to use the normalize method to ensure the conversion is correct.</p> </blockquote> <pre><code>&gt;&gt;&gt; utc_dt = utc.localize(datetime.utcfromtimestamp(1143408899)) &gt;&gt;&gt; utc_dt.strftime(fmt) '2006-03-26 21:34:59 UTC+0000' &gt;&gt;&gt; au_tz = timezone('Australia/Sydney') &gt;&gt;&gt; au_dt = au_tz.normalize(utc_dt.astimezone(au_tz)) &gt;&gt;&gt; au_dt.strftime(fmt) '2006-03-27 08:34:59 EST+1100' &gt;&gt;&gt; utc_dt2 = utc.normalize(au_dt.astimezone(utc)) &gt;&gt;&gt; utc_dt2.strftime(fmt) '2006-03-26 21:34:59 UTC+0000' </code></pre> <p>I tried this very example <em>without</em> using <code>normalize</code> and it turned out just the same. In my opinion this example doesn't really explain <em>why</em> we have to use <code>normalize</code> when converting between <code>datetime</code> objects in different timezones.</p> <p>Would someone please give me an <strong>example</strong> (like the one above) where the result differs when not using <code>normalize</code>.</p> <p>Thanks</p>
14
2009-09-14T17:22:31Z
1,422,904
<p>The docs say that normalize is used as a workaround for DST issues:</p> <blockquote> <p>In addition, if you perform date arithmetic on local times that cross DST boundaries, the results may be in an incorrect timezone (ie. subtract 1 minute from 2002-10-27 1:00 EST and you get 2002-10-27 0:59 EST instead of the correct 2002-10-27 1:59 EDT). A normalize() method is provided to correct this.</p> </blockquote> <p>So it's used to correct some edge cases involving DST. If you're not using DST timezones (e.g. UTC) then it's not necessary to use normalize.</p> <p>If you don't use it your conversion could potentially be one hour off under certain circumstances.</p>
5
2009-09-14T17:27:59Z
[ "python", "timezone", "pytz" ]
Python and the built-in heap
1,422,969
<p>At the moment, I am trying to write a priority queue in Python using the built in heapq library. However, I am stuck trying to get a handle on what Python does with the tie-breaking, I want to have a specific condition where I can dictate what happens with the tie-breaking instead of the heapq library that seems to almost pick something off the queue at random. Does anybody know of a way of rewriting the tie-breaking condition or would it be easier to build the priority queue from the ground up?</p>
2
2009-09-14T17:45:13Z
1,423,016
<p><code>heapq</code> uses the intrinsic comparisons on queue items (<code>__le__</code> and friends). The general way to work around this limit is the good old approach known as "decorate/undecorate" -- that's what we used to do in sorting, before the <code>key=</code> parameter was introduced there.</p> <p>To put it simply, you enqueue and dequeue, not just the items you care about ("payload"), but rather the items "decorated" into tuples that start with the "keys" you need <code>heapq</code> to consider. So for example it would be normal to enqueue a tuple like <code>(foo.x, time.time(), foo)</code> if you want prioritization by the <code>x</code> attribute with ties broken by time of insertion in the queue -- of course when you de-queue you "undecorate", there by taking the <code>[-1]</code>th item of the tuple you get by de-queueing.</p> <p>So, just put the "secondary keys" you need to be considered for "tie-breaking" in the "decorated" tuple you enqueue, AFTER the ones whose "ties" you want to break that way.</p>
9
2009-09-14T17:59:03Z
[ "python" ]
web framework compatible with python 3.1 and py-postgresql
1,423,000
<p>I have started learning Python by writing a small application using Python 3.1 and py-postgresql. Now I want to turn it into a web application.</p> <p>But it seems that most frameworks such as web-py, django, zope are still based on Python 2.x. Unfortunately py-postgresql is incompatible with Python 2.x.</p> <p>Do I have to rewrite all my classes and replace py-postgresql with something supported by web-py etc., or is there a framework compatible with Python 3.1?</p> <p>Or maybe py-postgresql is compatible with 2.x but I did not figure it out?</p>
1
2009-09-14T17:56:30Z
1,440,125
<p>Update: this answer is out of date in 2011.</p> <p>Unless you are interested in blazing a new trail while trying to learn Python at all, I'd recommend converting your project to Python 2.x. Hopefully your code doesn't use too many <code>py-postgresql</code> features not found in the widely supported DB-API interface.</p> <p>You should look at <code>psycopg2</code> for a Python 2.x DB-API compatible interface or if you want to go higher-level <a href="http://sqlalchemy.org" rel="nofollow"><code>SQLAlchemy</code></a> which in the svn release can use <code>psycopg2</code> or <code>py-postgresql</code> interchangeably.</p> <p>You might also be interested in <a href="http://pypi.python.org/pypi/3to2/0.1a2" rel="nofollow">3to2</a> which automatically converts Python 3.x code to Python 2.x code when possible.</p> <p>Duplicate of <a href="http://stackoverflow.com/questions/373945/what-web-development-frameworks-support-python-3">#373945 What web development frameworks support Python 3?</a></p>
3
2009-09-17T17:08:02Z
[ "python", "web-applications", "python-3.x", "wsgi" ]
web framework compatible with python 3.1 and py-postgresql
1,423,000
<p>I have started learning Python by writing a small application using Python 3.1 and py-postgresql. Now I want to turn it into a web application.</p> <p>But it seems that most frameworks such as web-py, django, zope are still based on Python 2.x. Unfortunately py-postgresql is incompatible with Python 2.x.</p> <p>Do I have to rewrite all my classes and replace py-postgresql with something supported by web-py etc., or is there a framework compatible with Python 3.1?</p> <p>Or maybe py-postgresql is compatible with 2.x but I did not figure it out?</p>
1
2009-09-14T17:56:30Z
1,443,094
<p>I have just found out about WSGI: a WSGI compatible app can also be written in Python 3.1. The following code runs just fine in Python 3.1:</p> <pre><code>def webapp(environment, start_response): start_response('200 OK', [('content-type', 'text/html')]) return ['Hello, World!'] if __name__ == '__main__': from wsgiref import simple_server simple_server.make_server('', 8080, webapp).serve_forever() </code></pre> <p>The WSGI website has lots of pointers to frameworks. The <a href="http://bottle.paws.de" rel="nofollow">Bottle framework</a> claims "Bottle runs with Python 2.5+ and 3.x (using 2to3)" so I will give that a try.</p>
1
2009-09-18T07:48:22Z
[ "python", "web-applications", "python-3.x", "wsgi" ]
web framework compatible with python 3.1 and py-postgresql
1,423,000
<p>I have started learning Python by writing a small application using Python 3.1 and py-postgresql. Now I want to turn it into a web application.</p> <p>But it seems that most frameworks such as web-py, django, zope are still based on Python 2.x. Unfortunately py-postgresql is incompatible with Python 2.x.</p> <p>Do I have to rewrite all my classes and replace py-postgresql with something supported by web-py etc., or is there a framework compatible with Python 3.1?</p> <p>Or maybe py-postgresql is compatible with 2.x but I did not figure it out?</p>
1
2009-09-14T17:56:30Z
1,448,545
<p>Here's a simplified version of tornado's WSGI server implemented in python 3.</p> <p><a href="http://code.activestate.com/recipes/576906/" rel="nofollow">http://code.activestate.com/recipes/576906/</a></p> <p>probably has some bugs, but can get you started</p>
0
2009-09-19T13:15:46Z
[ "python", "web-applications", "python-3.x", "wsgi" ]
web framework compatible with python 3.1 and py-postgresql
1,423,000
<p>I have started learning Python by writing a small application using Python 3.1 and py-postgresql. Now I want to turn it into a web application.</p> <p>But it seems that most frameworks such as web-py, django, zope are still based on Python 2.x. Unfortunately py-postgresql is incompatible with Python 2.x.</p> <p>Do I have to rewrite all my classes and replace py-postgresql with something supported by web-py etc., or is there a framework compatible with Python 3.1?</p> <p>Or maybe py-postgresql is compatible with 2.x but I did not figure it out?</p>
1
2009-09-14T17:56:30Z
1,934,744
<p>Even though it's not officially released yet, I am currently 'playing around' with CherryPy 3.2.0rc1 with Python 3.1.1 and have had no problems yet. Haven't used it with py-postgresql, but I don't see why it shouldn't work.</p> <p>Hope this helps, Alan</p>
0
2009-12-20T03:27:16Z
[ "python", "web-applications", "python-3.x", "wsgi" ]
What python web frameworks work well with CGI (e.g. on nearlyfreespeech.net)?
1,423,041
<p>From nearlyfreespeech's website, they state that the following don't work well:</p> <ul> <li>mod_python Web application</li> <li>frameworks that depend on persistent processes, including: Ruby On Rails, Django, Zope, and others (some of these will run under CGI, but will run slowly and are suitable only for development purposes)</li> </ul> <p>Are there any Python web frameworks that work well on NearlyFreeSpeech?</p>
5
2009-09-14T18:03:36Z
1,423,084
<p>By the things they reject. I think that twisted.web is still an option there, but I don't have any experience with nearlyfreespeech.net</p>
0
2009-09-14T18:11:23Z
[ "python", "frameworks", "cgi", "nearlyfreespeech" ]
What python web frameworks work well with CGI (e.g. on nearlyfreespeech.net)?
1,423,041
<p>From nearlyfreespeech's website, they state that the following don't work well:</p> <ul> <li>mod_python Web application</li> <li>frameworks that depend on persistent processes, including: Ruby On Rails, Django, Zope, and others (some of these will run under CGI, but will run slowly and are suitable only for development purposes)</li> </ul> <p>Are there any Python web frameworks that work well on NearlyFreeSpeech?</p>
5
2009-09-14T18:03:36Z
1,423,182
<p>WSGI can run on top of CGI, and popular frameworks typically run on top of WSGI, <strong>but</strong> performance is quite another issue -- since a CGI service starts afresh on each hit, any framework you may be using will need to reload from scratch each and every time, and that (in addition to opening a new connection to a DB, etc, which is basically inevitable with CGI) will make things pretty sluggish on anything but the tiniest, lightest frameworks.</p> <p>Maybe something like <a href="http://pythonpaste.org/webob/" rel="nofollow">WebOb</a> might be tolerable, but you'll need to do some tests to check even that (how loaded those servers are is, of course, a big part of the puzzle, and you just can't tell except by testing).</p>
5
2009-09-14T18:27:41Z
[ "python", "frameworks", "cgi", "nearlyfreespeech" ]
What python web frameworks work well with CGI (e.g. on nearlyfreespeech.net)?
1,423,041
<p>From nearlyfreespeech's website, they state that the following don't work well:</p> <ul> <li>mod_python Web application</li> <li>frameworks that depend on persistent processes, including: Ruby On Rails, Django, Zope, and others (some of these will run under CGI, but will run slowly and are suitable only for development purposes)</li> </ul> <p>Are there any Python web frameworks that work well on NearlyFreeSpeech?</p>
5
2009-09-14T18:03:36Z
1,423,207
<p>I got web.py to work on nearly free speech a few years ago by fooling with its WSGI stuff to run on CGI. It was just slightly too slow to be usable though.</p> <p>I've made a few Python web applications hosted on nearly free speech just using the CGI module, and they are actually plenty fast even with high traffic. Example: <a href="http://www.gigbayes.com" rel="nofollow">www.gigbayes.com</a>.</p>
2
2009-09-14T18:34:18Z
[ "python", "frameworks", "cgi", "nearlyfreespeech" ]
What python web frameworks work well with CGI (e.g. on nearlyfreespeech.net)?
1,423,041
<p>From nearlyfreespeech's website, they state that the following don't work well:</p> <ul> <li>mod_python Web application</li> <li>frameworks that depend on persistent processes, including: Ruby On Rails, Django, Zope, and others (some of these will run under CGI, but will run slowly and are suitable only for development purposes)</li> </ul> <p>Are there any Python web frameworks that work well on NearlyFreeSpeech?</p>
5
2009-09-14T18:03:36Z
1,424,853
<p>Well, if what you really need is just free hosting for a Python web app, <a href="http://code.google.com/appengine/" rel="nofollow">Google AppEngine</a> is a nice alternative and you won't be as limited on choice of frameworks.</p>
-2
2009-09-15T02:34:39Z
[ "python", "frameworks", "cgi", "nearlyfreespeech" ]