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 |
|---|---|---|---|---|---|---|---|---|---|
How do I access the request object or any other variable in a form's clean() method? | 1,057,252 | <p>I am trying to request.user for a form's clean method, but how can I access the request object? Can I modify the clean method to allow variables input?</p>
| 74 | 2009-06-29T08:49:45Z | 1,057,418 | <p>The usual aproach is to store the request object in a thread-local reference using a middleware. Then you can access this from anywhere in you app, including the Form.clean() method.</p>
<p>Changing the signature of the Form.clean() method means you have you own, modified version of Django, which may not be what you want.</p>
<p>Thank middleware count look something like this:</p>
<pre><code>import threading
_thread_locals = threading.local()
def get_current_request():
return getattr(_thread_locals, 'request', None)
class ThreadLocals(object):
"""
Middleware that gets various objects from the
request object and saves them in thread local storage.
"""
def process_request(self, request):
_thread_locals.request = request
</code></pre>
<p>Register this middleware as described in the <a href="http://docs.djangoproject.com/en/dev/topics/http/middleware/">Django docs</a></p>
| 13 | 2009-06-29T09:34:58Z | [
"python",
"django"
] |
How do I access the request object or any other variable in a form's clean() method? | 1,057,252 | <p>I am trying to request.user for a form's clean method, but how can I access the request object? Can I modify the clean method to allow variables input?</p>
| 74 | 2009-06-29T08:49:45Z | 1,057,640 | <p>The answer by Ber - storing it in threadlocals - is a very bad idea. There's absolutely no reason to do it this way.</p>
<p>A much better way is to override the form's <code>__init__</code> method to take an extra keyword argument, <code>request</code>. This stores the request in the <em>form</em>, where it's required, and from where you can access it in your clean method.</p>
<pre><code>class MyForm(forms.Form):
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
super(MyForm, self).__init__(*args, **kwargs)
def clean(self):
... access the request object via self.request ...
</code></pre>
<p>and in your view:</p>
<pre><code>myform = MyForm(request.POST, request=request)
</code></pre>
| 128 | 2009-06-29T10:36:55Z | [
"python",
"django"
] |
How do I access the request object or any other variable in a form's clean() method? | 1,057,252 | <p>I am trying to request.user for a form's clean method, but how can I access the request object? Can I modify the clean method to allow variables input?</p>
| 74 | 2009-06-29T08:49:45Z | 2,566,785 | <p>You can't always use this method (and its probably bad practice), but if you are only using the form in one view you could scope it inside the view method itself.</p>
<pre><code>def my_view(request):
class ResetForm(forms.Form):
password = forms.CharField(required=True, widget=forms.PasswordInput())
def clean_password(self):
data = self.cleaned_data['password']
if not request.user.check_password(data):
raise forms.ValidationError("The password entered does not match your account password.")
return data
if request.method == 'POST':
form = ResetForm(request.POST, request.FILES)
if form.is_valid():
return HttpResponseRedirect("/")
else:
form = ResetForm()
return render_to_response(request, "reset.html")
</code></pre>
| 1 | 2010-04-02T13:10:40Z | [
"python",
"django"
] |
How do I access the request object or any other variable in a form's clean() method? | 1,057,252 | <p>I am trying to request.user for a form's clean method, but how can I access the request object? Can I modify the clean method to allow variables input?</p>
| 74 | 2009-06-29T08:49:45Z | 6,001,699 | <p>I ran into this particular problem when customizing the admin. I wanted a certain field to be validated based on the particular admin's credentials.</p>
<p>Since I did not want to modify the view to pass the request as an argument to the form, the following is what I did:</p>
<pre><code>class MyCustomForm(forms.ModelForm):
class Meta:
model = MyModel
def clean(self):
# make use of self.request here
class MyModelAdmin(admin.ModelAdmin):
form = MyCustomForm
def get_form(self, request, obj=None, **kwargs):
ModelForm = super(MyModelAdmin, self).get_form(request, obj=obj, **kwargs)
def form_wrapper(*args, **kwargs):
a = ModelForm(*args, **kwargs)
a.request = request
return a
return form_wrapper
</code></pre>
| 6 | 2011-05-14T12:03:34Z | [
"python",
"django"
] |
How do I access the request object or any other variable in a form's clean() method? | 1,057,252 | <p>I am trying to request.user for a form's clean method, but how can I access the request object? Can I modify the clean method to allow variables input?</p>
| 74 | 2009-06-29T08:49:45Z | 6,062,628 | <p><strong>UPDATED 10/25/2011</strong>: I'm now using this with a metaclass instead of method, as Django 1.3 displays some weirdness otherwise.</p>
<pre><code>class MyModelAdmin(admin.ModelAdmin):
form = MyCustomForm
def get_form(self, request, obj=None, **kwargs):
ModelForm = super(MyModelAdmin, self).get_form(request, obj, **kwargs)
class ModelFormMetaClass(ModelForm):
def __new__(cls, *args, **kwargs):
kwargs['request'] = request
return ModelForm(*args, **kwargs)
return ModelFormMetaClass
</code></pre>
<p>Then override <code>MyCustomForm.__init__</code> as follows:</p>
<pre><code>class MyCustomForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
super(MyCustomForm, self).__init__(*args, **kwargs)
</code></pre>
<p>You can then access the request object from any method of <code>ModelForm</code> with <code>self.request</code>.</p>
| 24 | 2011-05-19T17:39:58Z | [
"python",
"django"
] |
How do I access the request object or any other variable in a form's clean() method? | 1,057,252 | <p>I am trying to request.user for a form's clean method, but how can I access the request object? Can I modify the clean method to allow variables input?</p>
| 74 | 2009-06-29T08:49:45Z | 6,416,524 | <p>fresh cheese from cheesebaker@pypi: <a href="http://pypi.python.org/pypi?%3aaction=display&name=django-contrib-requestprovider&version=1.0.1" rel="nofollow">django-requestprovider</a></p>
| 3 | 2011-06-20T19:41:16Z | [
"python",
"django"
] |
How do I access the request object or any other variable in a form's clean() method? | 1,057,252 | <p>I am trying to request.user for a form's clean method, but how can I access the request object? Can I modify the clean method to allow variables input?</p>
| 74 | 2009-06-29T08:49:45Z | 9,974,165 | <p>I have another answer to this question as per your requirement you want to access the user into the clean method of the form.
You can Try this.
View.py</p>
<pre><code>person=User.objects.get(id=person_id)
form=MyForm(request.POST,instance=person)
</code></pre>
<p>forms.py</p>
<pre><code>def __init__(self,*arg,**kwargs):
self.instance=kwargs.get('instance',None)
if kwargs['instance'] is not None:
del kwargs['instance']
super(Myform, self).__init__(*args, **kwargs)
</code></pre>
<p>Now you can access the self.instance in any clean method in form.py</p>
| 1 | 2012-04-02T09:46:31Z | [
"python",
"django"
] |
How do I access the request object or any other variable in a form's clean() method? | 1,057,252 | <p>I am trying to request.user for a form's clean method, but how can I access the request object? Can I modify the clean method to allow variables input?</p>
| 74 | 2009-06-29T08:49:45Z | 16,975,043 | <p>The answer by <a href="http://stackoverflow.com/a/1057640/1623530http://stackoverflow.com/a/1057640/1623530">Daniel Roseman</a> is still the best. However, I would use the first positional argument for the request instead of the keyword argument for a few reasons:</p>
<ol>
<li>You don't run the risk of overriding a kwarg with the same name</li>
<li>The request is optional which is not right. The request attribute should never be None in this context.</li>
<li>You can cleanly pass the args and kwargs to the parent class without having to modify them.</li>
</ol>
<p>Lastly, I would use a more unique name to avoid overriding an existing variable. Thus, My modified answer looks like:</p>
<pre><code>class MyForm(forms.Form):
def __init__(self, request, *args, **kwargs):
self._my_request = request
super(MyForm, self).__init__(*args, **kwargs)
def clean(self):
... access the request object via self._my_request ...
</code></pre>
| 3 | 2013-06-07T01:51:29Z | [
"python",
"django"
] |
How do I access the request object or any other variable in a form's clean() method? | 1,057,252 | <p>I am trying to request.user for a form's clean method, but how can I access the request object? Can I modify the clean method to allow variables input?</p>
| 74 | 2009-06-29T08:49:45Z | 25,930,538 | <p>For what it's worth, if you're using <strong>Class Based Views</strong>, instead of function based views, override <a href="https://docs.djangoproject.com/en/1.7/ref/class-based-views/mixins-editing/#django.views.generic.edit.FormMixin.get_form_kwargs"><code>get_form_kwargs</code></a> in your editing view. Example code for a custom <a href="https://docs.djangoproject.com/en/1.7/ref/class-based-views/generic-editing/#django.views.generic.edit.CreateView">CreateView</a>:</p>
<pre><code>from braces.views import LoginRequiredMixin
class MyModelCreateView(LoginRequiredMixin, CreateView):
template_name = 'example/create.html'
model = MyModel
form_class = MyModelForm
success_message = "%(my_object)s added to your site."
def get_form_kwargs(self):
kw = super(MyModelCreateView, self).get_form_kwargs()
kw['request'] = self.request # the trick!
return kw
def form_valid(self):
# do something
</code></pre>
<p>The above view code will make <code>request</code> available as one of the keyword arguments to the form's <code>__init__</code> constructor function. Therefore in your <code>ModelForm</code> do:</p>
<pre><code>class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
def __init__(self, *args, **kwargs):
# important to "pop" added kwarg before call to parent's constructor
self.request = kwargs.pop('request')
super(MyModelForm, self).__init__(*args, **kwargs)
</code></pre>
| 16 | 2014-09-19T09:20:59Z | [
"python",
"django"
] |
How do I access the request object or any other variable in a form's clean() method? | 1,057,252 | <p>I am trying to request.user for a form's clean method, but how can I access the request object? Can I modify the clean method to allow variables input?</p>
| 74 | 2009-06-29T08:49:45Z | 33,746,731 | <p>For Django admin, in Django 1.8</p>
<pre><code>class MyModelAdmin(admin.ModelAdmin):
...
form = RedirectForm
def get_form(self, request, obj=None, **kwargs):
form = super(MyModelAdmin, self).get_form(request, obj=obj, **kwargs)
form.request = request
return form
</code></pre>
| 5 | 2015-11-16T23:47:56Z | [
"python",
"django"
] |
Loading all modules in a folder in Python | 1,057,431 | <p>Could someone provide me with a good way of importing a whole directory of modules?<br />
I have a structure like this:</p>
<pre><code>/Foo
bar.py
spam.py
eggs.py
</code></pre>
<p>I tried just converting it to a package by adding <code>__init__.py</code> and doing <code>from Foo import *</code> but it didn't work the way I had hoped.</p>
| 122 | 2009-06-29T09:38:15Z | 1,057,446 | <p>Add the <code>__all__</code> Variable to <code>__init__.py</code> containing:</p>
<pre><code>__all__ = ["bar", "spam", "eggs"]
</code></pre>
<p>See also <a href="http://docs.python.org/tutorial/modules.html">http://docs.python.org/tutorial/modules.html</a></p>
| 69 | 2009-06-29T09:42:33Z | [
"python",
"python-import"
] |
Loading all modules in a folder in Python | 1,057,431 | <p>Could someone provide me with a good way of importing a whole directory of modules?<br />
I have a structure like this:</p>
<pre><code>/Foo
bar.py
spam.py
eggs.py
</code></pre>
<p>I tried just converting it to a package by adding <code>__init__.py</code> and doing <code>from Foo import *</code> but it didn't work the way I had hoped.</p>
| 122 | 2009-06-29T09:38:15Z | 1,057,467 | <p>See that your <code>__init__.py</code> defines <code>__all__</code>. The <a href="http://docs.python.org/tutorial/modules.html#packages" rel="nofollow">modules - packages</a> doc says </p>
<blockquote>
<p>The <code>__init__.py</code> files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, <code>__init__.py</code> can just be an empty file, but it can also execute initialization code for the package or set the <code>__all__</code> variable, described later.</p>
<p>...</p>
<p>The only solution is for the package author to provide an explicit index of the package. The import statement uses the following convention: if a packageâs <code>__init__.py</code> code defines a list named <code>__all__</code>, it is taken to be the list of module names that should be imported when from package import * is encountered. It is up to the package author to keep this list up-to-date when a new version of the package is released. Package authors may also decide not to support it, if they donât see a use for importing * from their package. For example, the file <code>sounds/effects/__init__.py</code> could contain the following code:</p>
<p><code>__all__ = ["echo", "surround", "reverse"]</code></p>
<p>This would mean that <code>from sound.effects import *</code> would import the three named submodules of the sound package.</p>
</blockquote>
| 3 | 2009-06-29T09:47:46Z | [
"python",
"python-import"
] |
Loading all modules in a folder in Python | 1,057,431 | <p>Could someone provide me with a good way of importing a whole directory of modules?<br />
I have a structure like this:</p>
<pre><code>/Foo
bar.py
spam.py
eggs.py
</code></pre>
<p>I tried just converting it to a package by adding <code>__init__.py</code> and doing <code>from Foo import *</code> but it didn't work the way I had hoped.</p>
| 122 | 2009-06-29T09:38:15Z | 1,057,534 | <p>List all python (<code>.py</code>) files in the current folder and put them as <code>__all__</code> variable in <code>__init__.py</code></p>
<pre><code>from os.path import dirname, basename, isfile
import glob
modules = glob.glob(dirname(__file__)+"/*.py")
__all__ = [ basename(f)[:-3] for f in modules if isfile(f)]
</code></pre>
| 215 | 2009-06-29T10:06:25Z | [
"python",
"python-import"
] |
Loading all modules in a folder in Python | 1,057,431 | <p>Could someone provide me with a good way of importing a whole directory of modules?<br />
I have a structure like this:</p>
<pre><code>/Foo
bar.py
spam.py
eggs.py
</code></pre>
<p>I tried just converting it to a package by adding <code>__init__.py</code> and doing <code>from Foo import *</code> but it didn't work the way I had hoped.</p>
| 122 | 2009-06-29T09:38:15Z | 1,057,765 | <p>Make the Foo directory a package by adding an <code>__init__.py</code>. In that <code>__init__.py</code> add:</p>
<pre><code>import bar
import eggs
import spam
</code></pre>
<p>Since you want it dynamic (which may or may not be a good idea), list all py-files with list dir and import them with something like this:</p>
<pre><code>import os
for module in os.listdir(os.path.dirname(__file__)):
if module == '__init__.py' or module[-3:] != '.py':
continue
__import__(module[:-3], locals(), globals())
del module
</code></pre>
<p>Then, from your code do this:</p>
<pre><code>import Foo
</code></pre>
<p>You can now access the modules with</p>
<pre><code>Foo.bar
Foo.eggs
Foo.spam
</code></pre>
<p>etc. from Foo import * is not a good idea for several reasons, including name clashes and making it hard to analyze the code.</p>
| 30 | 2009-06-29T11:10:40Z | [
"python",
"python-import"
] |
Loading all modules in a folder in Python | 1,057,431 | <p>Could someone provide me with a good way of importing a whole directory of modules?<br />
I have a structure like this:</p>
<pre><code>/Foo
bar.py
spam.py
eggs.py
</code></pre>
<p>I tried just converting it to a package by adding <code>__init__.py</code> and doing <code>from Foo import *</code> but it didn't work the way I had hoped.</p>
| 122 | 2009-06-29T09:38:15Z | 4,933,232 | <p>Look at the pkgutil module from the standard library. It will let you do exactly what you want as long as you have an <code>__init__.py</code> file in the directory. The <code>__init__.py</code> file can be empty.</p>
| 1 | 2011-02-08T12:51:32Z | [
"python",
"python-import"
] |
Loading all modules in a folder in Python | 1,057,431 | <p>Could someone provide me with a good way of importing a whole directory of modules?<br />
I have a structure like this:</p>
<pre><code>/Foo
bar.py
spam.py
eggs.py
</code></pre>
<p>I tried just converting it to a package by adding <code>__init__.py</code> and doing <code>from Foo import *</code> but it didn't work the way I had hoped.</p>
| 122 | 2009-06-29T09:38:15Z | 8,556,471 | <p>Expanding on Mihail's answer, I believe the non-hackish way (as in, not handling the file paths directly) is the following:</p>
<ol>
<li>create an empty <code>__init__.py</code> file under <code>Foo/</code></li>
<li>Execute</li>
</ol>
<pre class="lang-py prettyprint-override"><code>import pkgutil
import sys
def load_all_modules_from_dir(dirname):
for importer, package_name, _ in pkgutil.iter_modules([dirname]):
full_package_name = '%s.%s' % (dirname, package_name)
if full_package_name not in sys.modules:
module = importer.find_module(package_name
).load_module(full_package_name)
print module
load_all_modules_from_dir('Foo')
</code></pre>
<p>You'll get:</p>
<pre><code><module 'Foo.bar' from '/home/.../Foo/bar.pyc'>
<module 'Foo.spam' from '/home/.../Foo/spam.pyc'>
</code></pre>
| 27 | 2011-12-19T02:11:12Z | [
"python",
"python-import"
] |
Loading all modules in a folder in Python | 1,057,431 | <p>Could someone provide me with a good way of importing a whole directory of modules?<br />
I have a structure like this:</p>
<pre><code>/Foo
bar.py
spam.py
eggs.py
</code></pre>
<p>I tried just converting it to a package by adding <code>__init__.py</code> and doing <code>from Foo import *</code> but it didn't work the way I had hoped.</p>
| 122 | 2009-06-29T09:38:15Z | 9,560,906 | <p>I got tired of this problem myself, so I wrote a package called automodinit to fix it. You can get it from <a href="http://pypi.python.org/pypi/automodinit/" rel="nofollow">http://pypi.python.org/pypi/automodinit/</a>. </p>
<p>Usage is like this:</p>
<ol>
<li>Include the <code>automodinit</code> package into your <code>setup.py</code> dependencies.</li>
<li>Replace all __init__.py files like this:</li>
</ol>
<pre>
__all__ = ["I will get rewritten"]
# Don't modify the line above, or this line!
import automodinit
automodinit.automodinit(__name__, __file__, globals())
del automodinit
# Anything else you want can go after here, it won't get modified.
</pre>
<p>That's it! From now on importing a module will set __all__ to
a list of .py[co] files in the module and will also import each
of those files as though you had typed:</p>
<pre><code>for x in __all__: import x
</code></pre>
<p>Therefore the effect of "from M import *" matches exactly "import M".</p>
<p><code>automodinit</code> is happy running from inside ZIP archives and is therefore ZIP safe.</p>
<p>Niall</p>
| 14 | 2012-03-05T02:24:09Z | [
"python",
"python-import"
] |
Loading all modules in a folder in Python | 1,057,431 | <p>Could someone provide me with a good way of importing a whole directory of modules?<br />
I have a structure like this:</p>
<pre><code>/Foo
bar.py
spam.py
eggs.py
</code></pre>
<p>I tried just converting it to a package by adding <code>__init__.py</code> and doing <code>from Foo import *</code> but it didn't work the way I had hoped.</p>
| 122 | 2009-06-29T09:38:15Z | 11,729,584 | <p>I have also encountered this problem and this was my solution:</p>
<pre><code>import os
def loadImports(path):
files = os.listdir(path)
imps = []
for i in range(len(files)):
name = files[i].split('.')
if len(name) > 1:
if name[1] == 'py' and name[0] != '__init__':
name = name[0]
imps.append(name)
file = open(path+'__init__.py','w')
toWrite = '__all__ = '+str(imps)
file.write(toWrite)
file.close()
</code></pre>
<p>This function creates a file named <code>__init__.py</code> in the path containing an <code>__all__</code> variable holding every module in the folder.
Example:
I have a folder named <code>Test</code>
which contains:</p>
<pre><code>Foo.py
Bar.py
</code></pre>
<p>So in the script I want the modules to be imported into I will write:</p>
<pre><code>loadImports('Test/')
from Test import *
</code></pre>
<p>This will import everything from <code>Test</code> and the <code>__init__.py</code> file in <code>Test</code> will now contain:</p>
<pre><code>all = ['Foo','Bar']
</code></pre>
| 5 | 2012-07-30T21:06:25Z | [
"python",
"python-import"
] |
Loading all modules in a folder in Python | 1,057,431 | <p>Could someone provide me with a good way of importing a whole directory of modules?<br />
I have a structure like this:</p>
<pre><code>/Foo
bar.py
spam.py
eggs.py
</code></pre>
<p>I tried just converting it to a package by adding <code>__init__.py</code> and doing <code>from Foo import *</code> but it didn't work the way I had hoped.</p>
| 122 | 2009-06-29T09:38:15Z | 20,753,073 | <h2>Python, include all files under a directory:</h2>
<p>For newbies who just can't get it to work who need their hands held.</p>
<ol>
<li><p>Make a folder /home/el/foo and make a file <code>main.py</code> under /home/el/foo Put this code in there:</p>
<pre><code>from hellokitty import *
spam.spamfunc()
ham.hamfunc()
</code></pre></li>
<li><p>Make a directory <code>/home/el/foo/hellokitty</code></p></li>
<li><p>Make a file <code>__init__.py</code> under <code>/home/el/foo/hellokitty</code> and put this code in there:</p>
<pre><code>__all__ = ["spam", "ham"]
</code></pre></li>
<li><p>Make two python files: <code>spam.py</code> and <code>ham.py</code> under <code>/home/el/foo/hellokitty</code></p></li>
<li><p>Define a function inside spam.py:</p>
<pre><code>def spamfunc():
print "Spammity spam"
</code></pre></li>
<li><p>Define a function inside ham.py:</p>
<pre><code>def hamfunc():
print "Upgrade from baloney"
</code></pre></li>
<li><p>Run it:</p>
<pre><code>el@apollo:/home/el/foo$ python main.py
spammity spam
Upgrade from baloney
</code></pre></li>
</ol>
| 17 | 2013-12-24T00:08:56Z | [
"python",
"python-import"
] |
Loading all modules in a folder in Python | 1,057,431 | <p>Could someone provide me with a good way of importing a whole directory of modules?<br />
I have a structure like this:</p>
<pre><code>/Foo
bar.py
spam.py
eggs.py
</code></pre>
<p>I tried just converting it to a package by adding <code>__init__.py</code> and doing <code>from Foo import *</code> but it didn't work the way I had hoped.</p>
| 122 | 2009-06-29T09:38:15Z | 24,196,410 | <p><a href="http://stackoverflow.com/a/1057534/281545">Anurag Uniyal answer</a> with suggested improvements!</p>
<pre><code>#!/usr/bin/python
# -*- encoding: utf-8 -*-
import os
import glob
all_list = list()
for f in glob.glob(os.path.dirname(__file__)+"/*.py"):
if os.path.isfile(f) and not os.path.basename(f).startswith('_'):
all_list.append(os.path.basename(f)[:-3])
__all__ = all_list
</code></pre>
| 3 | 2014-06-13T01:28:24Z | [
"python",
"python-import"
] |
Loading all modules in a folder in Python | 1,057,431 | <p>Could someone provide me with a good way of importing a whole directory of modules?<br />
I have a structure like this:</p>
<pre><code>/Foo
bar.py
spam.py
eggs.py
</code></pre>
<p>I tried just converting it to a package by adding <code>__init__.py</code> and doing <code>from Foo import *</code> but it didn't work the way I had hoped.</p>
| 122 | 2009-06-29T09:38:15Z | 24,526,390 | <p>This is the best way i've found so far:</p>
<pre><code>from os.path import dirname, join, isdir, abspath, basename
from glob import glob
pwd = dirname(__file__)
for x in glob(join(pwd, '*.py')):
if not x.startswith('__'):
__import__(basename(x)[:-3], globals(), locals())
</code></pre>
| 3 | 2014-07-02T08:30:27Z | [
"python",
"python-import"
] |
Loading all modules in a folder in Python | 1,057,431 | <p>Could someone provide me with a good way of importing a whole directory of modules?<br />
I have a structure like this:</p>
<pre><code>/Foo
bar.py
spam.py
eggs.py
</code></pre>
<p>I tried just converting it to a package by adding <code>__init__.py</code> and doing <code>from Foo import *</code> but it didn't work the way I had hoped.</p>
| 122 | 2009-06-29T09:38:15Z | 27,006,389 | <p>I've created a module for that, which doesn't rely on <code>__init__.py</code> (or any other auxiliary file) and makes me type only the following two lines:</p>
<pre><code>import importdir
importdir.do("Foo", globals())
</code></pre>
<p>Feel free to re-use or contribute: <a href="http://gitlab.com/aurelien-lourot/importdir" rel="nofollow">http://gitlab.com/aurelien-lourot/importdir</a></p>
| 0 | 2014-11-18T23:46:56Z | [
"python",
"python-import"
] |
Loading all modules in a folder in Python | 1,057,431 | <p>Could someone provide me with a good way of importing a whole directory of modules?<br />
I have a structure like this:</p>
<pre><code>/Foo
bar.py
spam.py
eggs.py
</code></pre>
<p>I tried just converting it to a package by adding <code>__init__.py</code> and doing <code>from Foo import *</code> but it didn't work the way I had hoped.</p>
| 122 | 2009-06-29T09:38:15Z | 27,015,444 | <p>Anurag's example with a couple of corrections:</p>
<pre><code>import os, glob
modules = glob.glob(os.path.join(os.path.dirname(__file__), "*.py"))
__all__ = [os.path.basename(f)[:-3] for f in modules if not f.endswith("__init__.py")]
</code></pre>
| 3 | 2014-11-19T11:13:09Z | [
"python",
"python-import"
] |
Loading all modules in a folder in Python | 1,057,431 | <p>Could someone provide me with a good way of importing a whole directory of modules?<br />
I have a structure like this:</p>
<pre><code>/Foo
bar.py
spam.py
eggs.py
</code></pre>
<p>I tried just converting it to a package by adding <code>__init__.py</code> and doing <code>from Foo import *</code> but it didn't work the way I had hoped.</p>
| 122 | 2009-06-29T09:38:15Z | 36,231,122 | <p>I know I'm updating a quite old post, and I tried using <code>automodinit</code>, but found out it's setup process is broken for python3. So, based on Luca's answer, I came up with a simpler answer - which might not work with .zip - to this issue, so I figured I should share it here:</p>
<p>within the <code>__init__.py</code> module from <code>yourpackage</code>:</p>
<pre><code>#!/usr/bin/env python
import os, pkgutil
__all__ = list(module for _, module, _ in pkgutil.iter_modules([os.path.split(__file__)[0])
</code></pre>
<p>and within another package below <code>yourpackage</code>:</p>
<pre><code>from yourpackage import *
</code></pre>
<p>Then you'll have all the modules that are placed within the package loaded, and if you write a new module, it'll be automagically imported as well. Of course, use that kind of things with care, with great powers comes great responsibilities.</p>
| 1 | 2016-03-26T02:54:58Z | [
"python",
"python-import"
] |
Loading all modules in a folder in Python | 1,057,431 | <p>Could someone provide me with a good way of importing a whole directory of modules?<br />
I have a structure like this:</p>
<pre><code>/Foo
bar.py
spam.py
eggs.py
</code></pre>
<p>I tried just converting it to a package by adding <code>__init__.py</code> and doing <code>from Foo import *</code> but it didn't work the way I had hoped.</p>
| 122 | 2009-06-29T09:38:15Z | 37,684,402 | <pre><code>import pkgutil
__path__ = pkgutil.extend_path(__path__, __name__)
for imp, module, ispackage in pkgutil.walk_packages(path=__path__, prefix=__name__+'.'):
__import__(module)
</code></pre>
| 1 | 2016-06-07T16:15:03Z | [
"python",
"python-import"
] |
How to code a Download/Upload Speed Monitor in PHP,Python, or Java? | 1,057,449 | <p>I have to code a up/download speed monitor. It will obtain the current download and upload transfer speed of the computer which it has been installed and post it to another server periodically.
c
But I don't have an idea about how to catch instant transfer rates of a computer. As you know some of network monitoring programs can trace it but I could not find anything written in PHP, Python or Java?</p>
| 3 | 2009-06-29T09:43:13Z | 1,057,517 | <p>You don't say which operating system you're interested in.</p>
<p>A quick google turned up this: <a href="http://excess.org/speedometer/" rel="nofollow">http://excess.org/speedometer/</a></p>
<p>"Measure and display the rate of data across a network connection or data being stored in a file"</p>
<p>Opensource, written in Python</p>
| 3 | 2009-06-29T10:02:50Z | [
"java",
"php",
"python",
"networking"
] |
How to code a Download/Upload Speed Monitor in PHP,Python, or Java? | 1,057,449 | <p>I have to code a up/download speed monitor. It will obtain the current download and upload transfer speed of the computer which it has been installed and post it to another server periodically.
c
But I don't have an idea about how to catch instant transfer rates of a computer. As you know some of network monitoring programs can trace it but I could not find anything written in PHP, Python or Java?</p>
| 3 | 2009-06-29T09:43:13Z | 1,063,081 | <p><a href="http://netresearch.ics.uci.edu/kfujii/jpcap/doc/index.html" rel="nofollow">JPCAP</a> (a java packet capture library-sniffer) is suitable for this job and I've done it.</p>
| 1 | 2009-06-30T11:02:21Z | [
"java",
"php",
"python",
"networking"
] |
Django/Python: How do i transfer a class's attributes to another via a for loop? (Form->Model Instance) | 1,057,477 | <p>I wish to update a model instance from a form I have.</p>
<p>The form is a ModelForm, so it has the same attributes as the model instance, how do I transfer the attributes from the form instance to the model instance instead of doing this:</p>
<p>modelinstance.name = form.name
.
.
.
.</p>
<p>A for loop perhaps? :)</p>
<p>Thanks!</p>
| 1 | 2009-06-29T09:50:48Z | 1,057,495 | <p>Call the save() method of the form.
Specifically instantiate the form with keyword argument <code>instance</code> like this:</p>
<pre><code>>>> a = Article.objects.get(pk=1)
>>> f = ArticleForm(instance=a)
>>> f.save()
</code></pre>
<p>Taken from here: <a href="http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method</a></p>
| 6 | 2009-06-29T09:56:00Z | [
"python",
"django"
] |
How to do windows API calls in Python 3.1? | 1,057,496 | <p>Has anyone found a version of <a href="http://python.net/crew/mhammond/win32/" rel="nofollow">pywin32</a> for python 3.x? The latest available appears to be for 2.6.</p>
<p>Alternatively, how would I "roll my own" windows API calls in Python 3.1?</p>
| 5 | 2009-06-29T09:56:42Z | 1,057,573 | <p>You should be able to do everything with <a href="http://docs.python.org/library/ctypes.html">ctypes</a>, if a bit cumbersomely.</p>
<p>Here's an example of getting the "common application data" folder:</p>
<pre><code>from ctypes import windll, wintypes
_SHGetFolderPath = windll.shell32.SHGetFolderPathW
path_buf = wintypes.create_unicode_buffer(255)
csidl = 35
_SHGetFolderPath(0, csidl, 0, 0, path_buf)
print(path_buf.value)
</code></pre>
<p>Result:</p>
<pre><code>C:\Documents and Settings\All Users\Application Data
</code></pre>
| 8 | 2009-06-29T10:14:52Z | [
"python",
"winapi",
"python-3.x"
] |
How to do windows API calls in Python 3.1? | 1,057,496 | <p>Has anyone found a version of <a href="http://python.net/crew/mhammond/win32/" rel="nofollow">pywin32</a> for python 3.x? The latest available appears to be for 2.6.</p>
<p>Alternatively, how would I "roll my own" windows API calls in Python 3.1?</p>
| 5 | 2009-06-29T09:56:42Z | 1,057,742 | <p>There are pywin32 available for 3.0. Python 3.1 was release two days ago, so if you need pywin32 for that you either need to wait a bit, or compile them from source.</p>
<p><a href="http://sourceforge.net/project/showfiles.php?group_id=78018&package_id=79063">http://sourceforge.net/project/showfiles.php?group_id=78018&package_id=79063</a></p>
| 5 | 2009-06-29T11:04:52Z | [
"python",
"winapi",
"python-3.x"
] |
How to call a data member of the base class if it is being overwritten as a property in the derived class? | 1,057,518 | <p>This question is similar to <a href="http://stackoverflow.com/questions/1021464/python-how-to-call-a-property-of-the-base-class-if-this-property-is-being-overwr">this other one</a>, with the difference that the data member in the base class is <em>not</em> wrapped by the descriptor protocol.</p>
<p>In other words, how can I access a member of the base class if I am overriding its name with a property in the derived class?</p>
<pre><code>class Base(object):
def __init__(self):
self.foo = 5
class Derived(Base):
def __init__(self):
Base.__init__(self)
@property
def foo(self):
return 1 + self.foo # doesn't work of course!
@foo.setter
def foo(self, f):
self._foo = f
bar = Base()
print bar.foo
foobar = Derived()
print foobar.foo
</code></pre>
<p>Please note that I also need to define a setter because otherwise the assignment of self.foo in the base class doesn't work.</p>
<p>All in all the descriptor protocol doesn't seem to interact well with inheritance...</p>
| 5 | 2009-06-29T10:03:17Z | 1,057,601 | <p>Defining</p>
<pre><code>def __init__(self):
self.foo = 5
</code></pre>
<p>in <code>Base</code> makes <code>foo</code> a member (attribute) of the <em>instance</em>, not of the class. The <em>class</em> <code>Base</code> has no knowledge of <code>foo</code>, so there is no way to access it by something like a <code>super()</code> call.</p>
<p>This is not necessary, however. When you instanciate</p>
<pre><code>foobar = Derived()
</code></pre>
<p>and the <code>__init__()</code> method of the base class calls</p>
<pre><code>self.foo = 5
</code></pre>
<p>this will not result in the creation / overwriting of the attribute, but instead in <code>Derived</code>'s setter being called, meaning</p>
<pre><code>self.foo.fset(5)
</code></pre>
<p>and thus <code>self._foo = 5</code>. So if you put</p>
<pre><code>return 1 + self._foo
</code></pre>
<p>in your getter, you pretty much get what you want. If you need the value that <code>self.foo</code> is set to in <code>Base</code>'s constructor, just look at <code>_foo</code>, which was set correctly by the <code>@foo.setter</code>.</p>
| 4 | 2009-06-29T10:24:25Z | [
"python",
"inheritance",
"overloading",
"descriptor"
] |
How to call a data member of the base class if it is being overwritten as a property in the derived class? | 1,057,518 | <p>This question is similar to <a href="http://stackoverflow.com/questions/1021464/python-how-to-call-a-property-of-the-base-class-if-this-property-is-being-overwr">this other one</a>, with the difference that the data member in the base class is <em>not</em> wrapped by the descriptor protocol.</p>
<p>In other words, how can I access a member of the base class if I am overriding its name with a property in the derived class?</p>
<pre><code>class Base(object):
def __init__(self):
self.foo = 5
class Derived(Base):
def __init__(self):
Base.__init__(self)
@property
def foo(self):
return 1 + self.foo # doesn't work of course!
@foo.setter
def foo(self, f):
self._foo = f
bar = Base()
print bar.foo
foobar = Derived()
print foobar.foo
</code></pre>
<p>Please note that I also need to define a setter because otherwise the assignment of self.foo in the base class doesn't work.</p>
<p>All in all the descriptor protocol doesn't seem to interact well with inheritance...</p>
| 5 | 2009-06-29T10:03:17Z | 1,057,603 | <p>once you have property with same name 'foo' it overrides the behaviour of access of name 'foo'
only way out seems that you explicitly set 'foo' in <strong>dict</strong></p>
<p>btw: I use python 2.5 hence had to change code a bit</p>
<pre><code>class Base(object):
def __init__(self):
self.foo = 5
class Derived(Base):
def __init__(self):
Base.__init__(self)
def g_foo(self):
return 1 + self.__dict__['foo'] # works now!
def s_foo(self, f):
self.__dict__['foo'] = f
self._foo = f
foo = property(g_foo, s_foo)
bar = Base()
print bar.foo
foobar = Derived()
print foobar.foo
</code></pre>
| 0 | 2009-06-29T10:25:12Z | [
"python",
"inheritance",
"overloading",
"descriptor"
] |
How to call a data member of the base class if it is being overwritten as a property in the derived class? | 1,057,518 | <p>This question is similar to <a href="http://stackoverflow.com/questions/1021464/python-how-to-call-a-property-of-the-base-class-if-this-property-is-being-overwr">this other one</a>, with the difference that the data member in the base class is <em>not</em> wrapped by the descriptor protocol.</p>
<p>In other words, how can I access a member of the base class if I am overriding its name with a property in the derived class?</p>
<pre><code>class Base(object):
def __init__(self):
self.foo = 5
class Derived(Base):
def __init__(self):
Base.__init__(self)
@property
def foo(self):
return 1 + self.foo # doesn't work of course!
@foo.setter
def foo(self, f):
self._foo = f
bar = Base()
print bar.foo
foobar = Derived()
print foobar.foo
</code></pre>
<p>Please note that I also need to define a setter because otherwise the assignment of self.foo in the base class doesn't work.</p>
<p>All in all the descriptor protocol doesn't seem to interact well with inheritance...</p>
| 5 | 2009-06-29T10:03:17Z | 1,057,656 | <p>Life is simpler if you use delegation instead of inheritance. This is Python. You aren't obligated to inherit from <code>Base</code>.</p>
<pre><code>class LooksLikeDerived( object ):
def __init__( self ):
self.base= Base()
@property
def foo(self):
return 1 + self.base.foo # always works
@foo.setter
def foo(self, f):
self.base.foo = f
</code></pre>
<p>But what about other methods of Base? You duplicate the names in <code>LooksLikeDerived</code> and simply.</p>
<pre><code>def someMethodOfBase( self, *args, **kw ):
return self.base.someMethodOfBase( *args **kw )
</code></pre>
<p>Yes, it doesn't feel "DRY". However, it prevents a lot of problems when "wrapping" some class in new functionality like you're trying to do.</p>
| 9 | 2009-06-29T10:41:40Z | [
"python",
"inheritance",
"overloading",
"descriptor"
] |
How to call a data member of the base class if it is being overwritten as a property in the derived class? | 1,057,518 | <p>This question is similar to <a href="http://stackoverflow.com/questions/1021464/python-how-to-call-a-property-of-the-base-class-if-this-property-is-being-overwr">this other one</a>, with the difference that the data member in the base class is <em>not</em> wrapped by the descriptor protocol.</p>
<p>In other words, how can I access a member of the base class if I am overriding its name with a property in the derived class?</p>
<pre><code>class Base(object):
def __init__(self):
self.foo = 5
class Derived(Base):
def __init__(self):
Base.__init__(self)
@property
def foo(self):
return 1 + self.foo # doesn't work of course!
@foo.setter
def foo(self, f):
self._foo = f
bar = Base()
print bar.foo
foobar = Derived()
print foobar.foo
</code></pre>
<p>Please note that I also need to define a setter because otherwise the assignment of self.foo in the base class doesn't work.</p>
<p>All in all the descriptor protocol doesn't seem to interact well with inheritance...</p>
| 5 | 2009-06-29T10:03:17Z | 1,058,209 | <pre><code>class Foo(object):
def __new__(cls, *args, **kw):
return object.__new__(cls, *args, **kw)
def __init__(self):
self.foo = 5
class Bar(Foo):
def __new__(cls, *args, **kw):
self = object.__new__(cls, *args, **kw)
self.__foo = Foo.__new__(Foo)
return self
def __init__(self):
Foo.__init__(self)
@property
def foo(self):
return 1 + self.__foo.foo
@foo.setter
def foo(self, foo):
self.__foo.foo = foo
bar = Bar()
bar.foo = 10
print bar.foo
</code></pre>
| 1 | 2009-06-29T13:13:45Z | [
"python",
"inheritance",
"overloading",
"descriptor"
] |
How to call a data member of the base class if it is being overwritten as a property in the derived class? | 1,057,518 | <p>This question is similar to <a href="http://stackoverflow.com/questions/1021464/python-how-to-call-a-property-of-the-base-class-if-this-property-is-being-overwr">this other one</a>, with the difference that the data member in the base class is <em>not</em> wrapped by the descriptor protocol.</p>
<p>In other words, how can I access a member of the base class if I am overriding its name with a property in the derived class?</p>
<pre><code>class Base(object):
def __init__(self):
self.foo = 5
class Derived(Base):
def __init__(self):
Base.__init__(self)
@property
def foo(self):
return 1 + self.foo # doesn't work of course!
@foo.setter
def foo(self, f):
self._foo = f
bar = Base()
print bar.foo
foobar = Derived()
print foobar.foo
</code></pre>
<p>Please note that I also need to define a setter because otherwise the assignment of self.foo in the base class doesn't work.</p>
<p>All in all the descriptor protocol doesn't seem to interact well with inheritance...</p>
| 5 | 2009-06-29T10:03:17Z | 1,061,081 | <p>Honestly, the thing to look at here is that you're trying to twist your code around a design that is simply poor. The property descriptors handle the request for a 'foo' attribute, and you want to bypass these completely, which is just wrong. You're already causing Base.<strong>init</strong> to assign foobar._foo = 5, so thats exactly where the getter needs to look, too.</p>
<p>class Base(object):
def <strong>init</strong>(self):
self.foo = 5</p>
<pre><code>class Derived(Base):
def __init__(self):
Base.__init__(self)
@property
def foo(self):
return 1 + self._foo # DOES work of course!
@foo.setter
def foo(self, f):
self._foo = f
bar = Base()
print bar.foo
foobar = Derived()
print foobar.foo
</code></pre>
| 0 | 2009-06-29T23:31:53Z | [
"python",
"inheritance",
"overloading",
"descriptor"
] |
Using pipes to communicate data between two anonymous python scripts | 1,057,576 | <p>Consider this at the windows commandline.</p>
<pre><code>scriptA.py | scriptB.py
</code></pre>
<p>I want to send a dictionary object from scriptA.py to scriptB.py by pickle:ing it and sending it over a pipe. But I don't know how to accomplish this.</p>
<p>I've read some posts about this subject here, but usually there's answers along these line:</p>
<pre><code>Popen( "scriptA.py"´, ..., and so on )
</code></pre>
<p>But I don't actually know the name of "scriptA.py". I just want to get hold of the ready pipe object and send/receive the databuffer.</p>
<p>I've tried sys.stdout/stdout, but I get file-descriptor errors and basically haven't tried that track very far. </p>
<p>The process is simple:</p>
<p>scriptA.py:</p>
<ul>
<li>(1) Pickle/Serialize dictionary into stringbuffer</li>
<li>(2) Send stringbuffer over pipe</li>
</ul>
<p>scriptB.py</p>
<ul>
<li>(3) Receive stringbuffer from pipe</li>
<li>(4) Unpickle/Deserialize stringbuffer into dictionary</li>
</ul>
| 1 | 2009-06-29T10:15:31Z | 1,057,597 | <p>When you say this to a shell</p>
<pre><code>scriptA.py | scriptB.py
</code></pre>
<p>The shell connects them with a pipe. You do NOTHING and it works perfectly.</p>
<p>Everything that <code>scriptA.py</code> writes to sys.stdout goes to <code>scriptB.py</code></p>
<p>Everything that <code>scriptB.py</code> reads from sys.stdin came from <code>scriptA.py</code></p>
<p>They're already connected. </p>
<p>So, how do you pass a dictionary from stdout in A to stdin in B?</p>
<ol>
<li><p><a href="http://docs.python.org/library/pickle.html">Pickle</a>. <code>scriptA.py</code> dumps the dictionary to stdout. <code>scriptB.py</code> loads the dictionary from stdin.</p></li>
<li><p><a href="http://docs.python.org/library/json.html">JSON</a>. <code>scriptA.py</code> dumps the dictionary to stdout. <code>scriptB.py</code> loads the dictionary from stdin.</p></li>
</ol>
<p>This is already built-in to Python and takes very, very little code.</p>
<p>In scriptA, <code>json.dump( {}, sys.stdout )</code> or <code>pickle.dump( {}, sys.stdout )</code></p>
<p>In scriptB, <code>json.load( sys.stdin )</code> or <code>pickle.load( sys.stdin )</code></p>
| 6 | 2009-06-29T10:23:27Z | [
"python",
"windows",
"pipe"
] |
Using pipes to communicate data between two anonymous python scripts | 1,057,576 | <p>Consider this at the windows commandline.</p>
<pre><code>scriptA.py | scriptB.py
</code></pre>
<p>I want to send a dictionary object from scriptA.py to scriptB.py by pickle:ing it and sending it over a pipe. But I don't know how to accomplish this.</p>
<p>I've read some posts about this subject here, but usually there's answers along these line:</p>
<pre><code>Popen( "scriptA.py"´, ..., and so on )
</code></pre>
<p>But I don't actually know the name of "scriptA.py". I just want to get hold of the ready pipe object and send/receive the databuffer.</p>
<p>I've tried sys.stdout/stdout, but I get file-descriptor errors and basically haven't tried that track very far. </p>
<p>The process is simple:</p>
<p>scriptA.py:</p>
<ul>
<li>(1) Pickle/Serialize dictionary into stringbuffer</li>
<li>(2) Send stringbuffer over pipe</li>
</ul>
<p>scriptB.py</p>
<ul>
<li>(3) Receive stringbuffer from pipe</li>
<li>(4) Unpickle/Deserialize stringbuffer into dictionary</li>
</ul>
| 1 | 2009-06-29T10:15:31Z | 1,057,598 | <p>The pipe just puts stdout of A to stdin of B.</p>
<p>A does:</p>
<pre><code>import sys
sys.stdout.writelines(output)
</code></pre>
<p>B just does:</p>
<pre><code>import sys
input = sys.stdin.readlines()
</code></pre>
| 2 | 2009-06-29T10:23:28Z | [
"python",
"windows",
"pipe"
] |
Using pipes to communicate data between two anonymous python scripts | 1,057,576 | <p>Consider this at the windows commandline.</p>
<pre><code>scriptA.py | scriptB.py
</code></pre>
<p>I want to send a dictionary object from scriptA.py to scriptB.py by pickle:ing it and sending it over a pipe. But I don't know how to accomplish this.</p>
<p>I've read some posts about this subject here, but usually there's answers along these line:</p>
<pre><code>Popen( "scriptA.py"´, ..., and so on )
</code></pre>
<p>But I don't actually know the name of "scriptA.py". I just want to get hold of the ready pipe object and send/receive the databuffer.</p>
<p>I've tried sys.stdout/stdout, but I get file-descriptor errors and basically haven't tried that track very far. </p>
<p>The process is simple:</p>
<p>scriptA.py:</p>
<ul>
<li>(1) Pickle/Serialize dictionary into stringbuffer</li>
<li>(2) Send stringbuffer over pipe</li>
</ul>
<p>scriptB.py</p>
<ul>
<li>(3) Receive stringbuffer from pipe</li>
<li>(4) Unpickle/Deserialize stringbuffer into dictionary</li>
</ul>
| 1 | 2009-06-29T10:15:31Z | 1,057,602 | <p>When you are piping something, you are (generally) feeding the standard output of one program into the standard input of another. I think you should keep trying this path.</p>
<p>If you're having trouble just being able to read the output of your first script with your second, check out <a href="http://stackoverflow.com/questions/965210/python-simple-reading-lines-from-a-pipe">this question</a>.</p>
| 0 | 2009-06-29T10:24:29Z | [
"python",
"windows",
"pipe"
] |
Bad pipe filedescriptor when reading from stdin in python | 1,057,638 | <p><strong>Duplicate of <a href="http://stackoverflow.com/questions/466801/python-piping-on-windows-why-does-this-not-work">this</a> question. Vote to close.</strong></p>
<p>Consider this at the windows commandline.</p>
<pre><code>scriptA.py | scriptB.py
</code></pre>
<p>In scriptA.py:</p>
<pre><code>sys.stdout.write( "hello" )
</code></pre>
<p>In scriptB.py:</p>
<pre><code>print sys.stdin.read()
</code></pre>
<p>This generates the following error:</p>
<pre><code>c:\> scriptA.py | scriptB.py
close failed: [Errno 22] Invalid argument
Traceback (most recent call last):
File "c:\scriptB.py", line 20, in <module>
print sys.stdin.read()
IOError: [Errno 9] Bad file descriptor
</code></pre>
<p>The "close failed" message seems to come from execution of scriptA.py.</p>
<p>It doesn't matter if I use sys.stdin.read(), sys.stdin.read(1), sys.stdin.readlines() etc etc.</p>
<p>What's wrong?</p>
<p><strong>Duplicate of <a href="http://stackoverflow.com/questions/466801/python-piping-on-windows-why-does-this-not-work">this</a> question. Vote to close.</strong></p>
| 2 | 2009-06-29T10:36:37Z | 1,057,681 | <p>It seems that stdin/stdout redirect does not work when starting from a file association.
This is not specific to python, but a problem caused by win32 cmd.exe.</p>
<p>See: <a href="http://mail.python.org/pipermail/python-bugs-list/2004-August/024920.html">http://mail.python.org/pipermail/python-bugs-list/2004-August/024920.html</a></p>
| 7 | 2009-06-29T10:48:54Z | [
"python",
"windows",
"pipe"
] |
Using Python to replace MATLAB: how to import data? | 1,057,666 | <p>I want to use some Python libraries to replace MATLAB. How could I import Excel data in Python (for example using <a href="http://en.wikipedia.org/wiki/NumPy" rel="nofollow">NumPy</a>) to use them?</p>
<p>I don't know if Python is a credible alternative to MATLAB, but I want to try it. Is there a a tutorial?</p>
| 11 | 2009-06-29T10:44:24Z | 1,057,715 | <p>There's <a href="http://en.wikipedia.org/wiki/Matplotlib" rel="nofollow">Matplotlib</a> for plots and the <a href="http://docs.python.org/library/csv.html" rel="nofollow">csv module</a> for reading <a href="http://en.wikipedia.org/wiki/Microsoft_Excel" rel="nofollow">Excel</a> data (assuming you can dump to <a href="http://en.wikipedia.org/wiki/Comma-separated_values" rel="nofollow">CSV</a>).</p>
<p>Here's <a href="http://vnoel.wordpress.com/2008/05/03/bye-matlab-hello-python-thanks-sage/" rel="nofollow">a tutorial</a> about replacing <a href="http://en.wikipedia.org/wiki/MATLAB" rel="nofollow">MATLAB</a> with Python.</p>
| 3 | 2009-06-29T10:58:24Z | [
"python",
"excel",
"matlab",
"numpy"
] |
Using Python to replace MATLAB: how to import data? | 1,057,666 | <p>I want to use some Python libraries to replace MATLAB. How could I import Excel data in Python (for example using <a href="http://en.wikipedia.org/wiki/NumPy" rel="nofollow">NumPy</a>) to use them?</p>
<p>I don't know if Python is a credible alternative to MATLAB, but I want to try it. Is there a a tutorial?</p>
| 11 | 2009-06-29T10:44:24Z | 1,057,748 | <p>Depending on what kind of computations you are doing with <a href="http://en.wikipedia.org/wiki/MATLAB" rel="nofollow">MATLAB</a> (and on which toolboxes you are using), Python could be a good alternative to MATLAB.</p>
<p>Python + <a href="http://en.wikipedia.org/wiki/NumPy" rel="nofollow">NumPy</a> + <a href="http://en.wikipedia.org/wiki/SciPy" rel="nofollow">SciPy</a> + <a href="http://en.wikipedia.org/wiki/Matplotlib" rel="nofollow">Matplotlib</a> are the right combination to start.</p>
<p>For the data, you can, for example, save your data directly in text file (assuming that you are not directly concerned by floating-point precision issues) and read it in <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29" rel="nofollow">Python</a>.</p>
<p>If your data are <a href="http://en.wikipedia.org/wiki/Microsoft_Excel" rel="nofollow">Excel</a> data, where each value is separated by a ";", you can for example read the file line by line, and use the split() method (with ";" as argument) to get each value.</p>
<p>For MATLAB up to version 7.1, it is possible to directly load .mat files from Python with the <a href="http://www.scipy.org/doc/api_docs/SciPy.io.mio.html" rel="nofollow">scipy.io.matlab.mio</a> module.</p>
| 11 | 2009-06-29T11:06:15Z | [
"python",
"excel",
"matlab",
"numpy"
] |
Using Python to replace MATLAB: how to import data? | 1,057,666 | <p>I want to use some Python libraries to replace MATLAB. How could I import Excel data in Python (for example using <a href="http://en.wikipedia.org/wiki/NumPy" rel="nofollow">NumPy</a>) to use them?</p>
<p>I don't know if Python is a credible alternative to MATLAB, but I want to try it. Is there a a tutorial?</p>
| 11 | 2009-06-29T10:44:24Z | 1,057,797 | <p>If you come from the <a href="http://en.wikipedia.org/wiki/MATLAB" rel="nofollow">MATLAB</a> world, <a href="http://www.scipy.org/PyLab" rel="nofollow">Pylab</a> will ease your transition. Once you have converted your data to ASCII, <code>pylab.load()</code> will do the rest:</p>
<pre><code>pylab.load(fname, comments='#', delimiter=None, converters=None,
skiprows=0, usecols=None, unpack=False,
dtype=<type 'numpy.float64'>)
</code></pre>
| 3 | 2009-06-29T11:22:04Z | [
"python",
"excel",
"matlab",
"numpy"
] |
Using Python to replace MATLAB: how to import data? | 1,057,666 | <p>I want to use some Python libraries to replace MATLAB. How could I import Excel data in Python (for example using <a href="http://en.wikipedia.org/wiki/NumPy" rel="nofollow">NumPy</a>) to use them?</p>
<p>I don't know if Python is a credible alternative to MATLAB, but I want to try it. Is there a a tutorial?</p>
| 11 | 2009-06-29T10:44:24Z | 1,059,072 | <p>I had a look at <a href="http://mlabwrap.sourceforge.net/" rel="nofollow">mlabwrap</a> as a step to easing some <a href="http://en.wikipedia.org/wiki/MATLAB" rel="nofollow">MATLAB</a> developers into using Python more.</p>
<p>But I have been unable to cleanly build it, and I don't run production installs here, so I'm dead in the water.</p>
| 2 | 2009-06-29T15:55:29Z | [
"python",
"excel",
"matlab",
"numpy"
] |
Using Python to replace MATLAB: how to import data? | 1,057,666 | <p>I want to use some Python libraries to replace MATLAB. How could I import Excel data in Python (for example using <a href="http://en.wikipedia.org/wiki/NumPy" rel="nofollow">NumPy</a>) to use them?</p>
<p>I don't know if Python is a credible alternative to MATLAB, but I want to try it. Is there a a tutorial?</p>
| 11 | 2009-06-29T10:44:24Z | 1,173,639 | <p>There are probably hundreds of ways you could import text data into Python.</p>
<p>But since you want to replace <a href="http://en.wikipedia.org/wiki/MATLAB" rel="nofollow">MATLAB</a>, you're going be using <a href="http://en.wikipedia.org/wiki/NumPy" rel="nofollow">NumPy</a> and probably <a href="http://en.wikipedia.org/wiki/SciPy" rel="nofollow">SciPy</a>.</p>
<p>Keep things simple: use NumPy's standard text-loading:</p>
<pre><code>import numpy
imported_array = numpy.loadtxt('file.txt',delimiter='\t') # Assuming tab-delimiter
print imported_array.shape
</code></pre>
| 3 | 2009-07-23T18:30:04Z | [
"python",
"excel",
"matlab",
"numpy"
] |
Using Python to replace MATLAB: how to import data? | 1,057,666 | <p>I want to use some Python libraries to replace MATLAB. How could I import Excel data in Python (for example using <a href="http://en.wikipedia.org/wiki/NumPy" rel="nofollow">NumPy</a>) to use them?</p>
<p>I don't know if Python is a credible alternative to MATLAB, but I want to try it. Is there a a tutorial?</p>
| 11 | 2009-06-29T10:44:24Z | 4,027,010 | <p>If you saved you data in <a href="http://en.wikipedia.org/wiki/MATLAB" rel="nofollow">MATLAB</a> format, use:</p>
<pre><code>from scipy.io import loadmat
datafile = "yourfile.mat"
data = loadmat(datafile, matlab_compatible=True)
var1 = data['nameOfYourVariable'].squeeze()
var2 = data['nameOfYourOtherVariable'].squeeze()
</code></pre>
| 1 | 2010-10-26T18:56:15Z | [
"python",
"excel",
"matlab",
"numpy"
] |
Using Python to replace MATLAB: how to import data? | 1,057,666 | <p>I want to use some Python libraries to replace MATLAB. How could I import Excel data in Python (for example using <a href="http://en.wikipedia.org/wiki/NumPy" rel="nofollow">NumPy</a>) to use them?</p>
<p>I don't know if Python is a credible alternative to MATLAB, but I want to try it. Is there a a tutorial?</p>
| 11 | 2009-06-29T10:44:24Z | 9,805,334 | <blockquote>
<p>"I don't know if Python is a credible alternative to MATLAB"</p>
</blockquote>
<p>For me (experimental physics) Python is not only a full replacement for <a href="http://en.wikipedia.org/wiki/MATLAB" rel="nofollow">MATLAB</a> (when including <a href="http://en.wikipedia.org/wiki/SciPy" rel="nofollow">SciPy</a> and <a href="http://en.wikipedia.org/wiki/Matplotlib" rel="nofollow">Matplotlib</a> as mentioned above), but it is useful for many things other than data crunching and visualisation (such are general programming needs).</p>
<blockquote>
<p>"I'm going to try SAGE."</p>
</blockquote>
<p>It is worth noting that there are a couple of servers running <a href="http://en.wikipedia.org/wiki/Sage_%28mathematics_software%29" rel="nofollow">Sage</a> which offer the notebook environmet (check <a href="http://www.sagenb.org/" rel="nofollow">Try Sage online</a> in <a href="http://www.sagemath.org/" rel="nofollow">http://www.sagemath.org/</a>). This is pretty neat given the fact that all you need it is an Internet browser and access (no installation required).</p>
<p>As for the question as interpreted by Kevin Buchs (in another answer), reading proprietary Excel to Python can be done in several methods, some are platform (OS) dependent:</p>
<ol>
<li>A nice resource (platform independent) - <a href="http://www.python-excel.org/" rel="nofollow">http://www.python-excel.org/</a></li>
<li>An example using <a href="https://pypi.python.org/pypi/xlrd" rel="nofollow">xlrd</a> which I once found useful (this is what I used when I needed it): <a href="http://code.activestate.com/recipes/483742/" rel="nofollow">http://code.activestate.com/recipes/483742/</a> for an example based on xlrd (platform independent)</li>
<li><a href="http://pyexcelerator.sourceforge.net/" rel="nofollow">pyexcelerator</a> is another option.</li>
</ol>
<p>I hope this helps. If not, I can try to arrange some example code myself (though the ones I have are over six years old...). I personally prefer, as was proposed in the other answers, to use the CSV or ASCII format.</p>
| 1 | 2012-03-21T13:12:26Z | [
"python",
"excel",
"matlab",
"numpy"
] |
Using Python to replace MATLAB: how to import data? | 1,057,666 | <p>I want to use some Python libraries to replace MATLAB. How could I import Excel data in Python (for example using <a href="http://en.wikipedia.org/wiki/NumPy" rel="nofollow">NumPy</a>) to use them?</p>
<p>I don't know if Python is a credible alternative to MATLAB, but I want to try it. Is there a a tutorial?</p>
| 11 | 2009-06-29T10:44:24Z | 25,717,165 | <p>Pandas is a Python data analysis library that can import/export from Excel pretty easily. Here's how to do it:</p>
<p><a href="http://pandas.pydata.org/pandas-docs/stable/10min.html#excel" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/10min.html#excel</a></p>
<p>Crash course:</p>
<pre><code>import pandas as pd
data = pd.read_excel('foo.xlsx', 'Sheet1', index_col=None, na_values=['NA'])
</code></pre>
| 2 | 2014-09-08T03:44:12Z | [
"python",
"excel",
"matlab",
"numpy"
] |
python+encryption: Encrypting session key using public key | 1,057,768 | <p>I want to encrypt the session key using the public key. How does the PGP software do this?
Can somebody specify the procedure or function of encryption in Python?</p>
| 3 | 2009-06-29T11:11:15Z | 1,059,366 | <p>See <a href="http://ubuntuforums.org/showthread.php?t=687173" rel="nofollow">this post</a> for background information about the basic technology. That post is about encryption in general - for information about using gpg from Python, see <a href="http://stackoverflow.com/questions/1020320/how-to-do-pgp-in-python-generate-keys-encrypt-decrypt/1053752#1053752">this</a>, for example.</p>
| 1 | 2009-06-29T17:03:04Z | [
"python",
"encryption",
"public-key"
] |
python+encryption: Encrypting session key using public key | 1,057,768 | <p>I want to encrypt the session key using the public key. How does the PGP software do this?
Can somebody specify the procedure or function of encryption in Python?</p>
| 3 | 2009-06-29T11:11:15Z | 1,060,144 | <p>There's also the PyCrypto module that looks exactly like what you are looking for: <a href="http://www.dlitz.net/software/pycrypto/" rel="nofollow">http://www.dlitz.net/software/pycrypto/</a> the API docs are here: <a href="http://www.dlitz.net/software/pycrypto/apidoc/" rel="nofollow">http://www.dlitz.net/software/pycrypto/apidoc/</a> and some nice docs with basic examples of encrypting/decrypting here: <a href="http://www.dlitz.net/software/pycrypto/doc/" rel="nofollow">http://www.dlitz.net/software/pycrypto/doc/</a>.</p>
<p>I'll confess I haven't used this module, but it seems like you would establish a session with a public key, then use that to encrypt/decrypt the channel with a Crypto.PublicKey object. Then do the usual activity of generating a session key, communicating that over whatever channel you have. Finally, switch the channel to a Crypto.Cipher object using the session key.</p>
<p>Also, be sure to be very, very careful about how you obtain the value for your session key if security is a real concern, particularly on multiuser or only partially trusted machine.</p>
| 2 | 2009-06-29T19:48:44Z | [
"python",
"encryption",
"public-key"
] |
python+encryption: Encrypting session key using public key | 1,057,768 | <p>I want to encrypt the session key using the public key. How does the PGP software do this?
Can somebody specify the procedure or function of encryption in Python?</p>
| 3 | 2009-06-29T11:11:15Z | 1,184,661 | <p>See <a href="http://stackoverflow.com/questions/90413/what-is-the-best-easiest-to-use-encryption-library-in-python">What is the best/easiest to use encryption library in python</a>, which mentions a <a href="http://stackoverflow.com/questions/90413/what-is-the-best-easiest-to-use-encryption-library-in-python/90959#90959">PGP-compatible
solution</a>, <a href="http://www.gnupg.org/related%5Fsoftware/gpgme/index.en.html" rel="nofollow">gpgme</a>.</p>
<p>For reasons I ignore, nobody in <a href="http://stackoverflow.com/questions/1020320/how-to-do-pgp-in-python-generate-keys-encrypt-decrypt/1053752">How to do PGP in Python (generate keys, encrypt/decrypt)</a> mentioned gpgme...</p>
| 0 | 2009-07-26T13:56:02Z | [
"python",
"encryption",
"public-key"
] |
How can I import a package using __import__() when the package name is only known at runtime? | 1,057,843 | <p>I have a messages folder(package) with <code>__init__.py</code> file and another module <code>messages_en.py</code> inside it. In <code>__init__.py</code> if I import <code>messages_en</code> it works, but <code>__import__</code> fails with "ImportError: No module named messages_en"</p>
<pre><code>import messages_en # it works
messages = __import__('messages_en') # it doesn't ?
</code></pre>
<p>I used to think 'import x' is just another way of saying <code>__import__('x')</code></p>
| 13 | 2009-06-29T11:35:00Z | 1,057,891 | <p><code>__import__</code> is an internal function called by import statement. In everyday coding you don't need (or want) to call <code>__import__</code></p>
<p>from python documentation:</p>
<p>For example, the statement <code>import spam</code> results in bytecode resembling the following code:</p>
<pre><code>spam = __import__('spam', globals(), locals(), [], -1)
</code></pre>
<p>On the other hand, the statement <code>from spam.ham import eggs, sausage as saus</code> results in</p>
<pre><code>_temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], -1)
eggs = _temp.eggs
saus = _temp.sausage
</code></pre>
<p>more info:
<a href="http://docs.python.org/library/functions.html">http://docs.python.org/library/functions.html</a></p>
| 13 | 2009-06-29T11:46:41Z | [
"python",
"python-import"
] |
How can I import a package using __import__() when the package name is only known at runtime? | 1,057,843 | <p>I have a messages folder(package) with <code>__init__.py</code> file and another module <code>messages_en.py</code> inside it. In <code>__init__.py</code> if I import <code>messages_en</code> it works, but <code>__import__</code> fails with "ImportError: No module named messages_en"</p>
<pre><code>import messages_en # it works
messages = __import__('messages_en') # it doesn't ?
</code></pre>
<p>I used to think 'import x' is just another way of saying <code>__import__('x')</code></p>
| 13 | 2009-06-29T11:35:00Z | 1,057,898 | <p>If it is a path problem, you should use the <code>level</code> argument (from <a href="http://docs.python.org/2/library/functions.html?highlight=__import__#__import__">docs</a>):</p>
<pre><code>__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module
Level is used to determine whether to perform
absolute or relative imports. -1 is the original strategy of attempting
both absolute and relative imports, 0 is absolute, a positive number
is the number of parent directories to search relative to the current module.
</code></pre>
| 19 | 2009-06-29T11:49:01Z | [
"python",
"python-import"
] |
How can I import a package using __import__() when the package name is only known at runtime? | 1,057,843 | <p>I have a messages folder(package) with <code>__init__.py</code> file and another module <code>messages_en.py</code> inside it. In <code>__init__.py</code> if I import <code>messages_en</code> it works, but <code>__import__</code> fails with "ImportError: No module named messages_en"</p>
<pre><code>import messages_en # it works
messages = __import__('messages_en') # it doesn't ?
</code></pre>
<p>I used to think 'import x' is just another way of saying <code>__import__('x')</code></p>
| 13 | 2009-06-29T11:35:00Z | 1,057,908 | <p>You could try this:</p>
<pre><code>messages == __import__('Foo.messages_en', fromlist=['messages_en'])
</code></pre>
| 0 | 2009-06-29T11:53:31Z | [
"python",
"python-import"
] |
How can I import a package using __import__() when the package name is only known at runtime? | 1,057,843 | <p>I have a messages folder(package) with <code>__init__.py</code> file and another module <code>messages_en.py</code> inside it. In <code>__init__.py</code> if I import <code>messages_en</code> it works, but <code>__import__</code> fails with "ImportError: No module named messages_en"</p>
<pre><code>import messages_en # it works
messages = __import__('messages_en') # it doesn't ?
</code></pre>
<p>I used to think 'import x' is just another way of saying <code>__import__('x')</code></p>
| 13 | 2009-06-29T11:35:00Z | 2,799,005 | <p>Be sure to append the modules directory to your python path.</p>
<p>Your path (the list of directories Python goes through to search for modules and files) is stored in the path attribute of the sys module. Since the path is a list you can use the append method to add new directories to the path. </p>
<p>For instance, to add the directory /home/me/mypy to the path:</p>
<pre><code>import sys
sys.path.append("/home/me/mypy")
</code></pre>
| 3 | 2010-05-09T20:07:42Z | [
"python",
"python-import"
] |
How can I import a package using __import__() when the package name is only known at runtime? | 1,057,843 | <p>I have a messages folder(package) with <code>__init__.py</code> file and another module <code>messages_en.py</code> inside it. In <code>__init__.py</code> if I import <code>messages_en</code> it works, but <code>__import__</code> fails with "ImportError: No module named messages_en"</p>
<pre><code>import messages_en # it works
messages = __import__('messages_en') # it doesn't ?
</code></pre>
<p>I used to think 'import x' is just another way of saying <code>__import__('x')</code></p>
| 13 | 2009-06-29T11:35:00Z | 13,175,052 | <p>Adding the globals argument is sufficient for me:</p>
<pre><code>__import__('messages_en', globals=globals())
</code></pre>
<p>In fact, only <code>__name__</code> is needed here:</p>
<pre><code>__import__('messages_en', globals={"__name__": __name__})
</code></pre>
| 14 | 2012-11-01T10:22:54Z | [
"python",
"python-import"
] |
How can I import a package using __import__() when the package name is only known at runtime? | 1,057,843 | <p>I have a messages folder(package) with <code>__init__.py</code> file and another module <code>messages_en.py</code> inside it. In <code>__init__.py</code> if I import <code>messages_en</code> it works, but <code>__import__</code> fails with "ImportError: No module named messages_en"</p>
<pre><code>import messages_en # it works
messages = __import__('messages_en') # it doesn't ?
</code></pre>
<p>I used to think 'import x' is just another way of saying <code>__import__('x')</code></p>
| 13 | 2009-06-29T11:35:00Z | 30,736,067 | <p>You need to manually import the top package of your dynamic package path.</p>
<p>For example in the beginning of the file i write:</p>
<pre><code>import sites
</code></pre>
<p>then later in code this works for me:</p>
<pre><code>target = 'some.dynamic.path'
my_module = __import__ ('sites.%s.fabfile' % target, fromlist=["sites.%s" % target])
</code></pre>
| 0 | 2015-06-09T15:12:53Z | [
"python",
"python-import"
] |
Importing methods for a Python class | 1,057,934 | <p>I wonder if it's possible to keep methods for a Python class in a different file from the class definition, something like this:</p>
<p><code>main_module.py:</code></p>
<pre><code>class Instrument(Object):
# Some import statement?
def __init__(self):
self.flag = True
def direct_method(self,arg1):
self.external_method(arg1, arg2)
</code></pre>
<p><code>to_import_from.py:</code></p>
<pre><code>def external_method(self, arg1, arg2):
if self.flag:
#doing something
#...many more methods
</code></pre>
<p>In my case, <code>to_import_from.py</code> is machine-generated, and contains many methods. I would rather not copy-paste these into main_module.py or import them one by one, but have them all recognized as methods of the Instrument class, just as if they had been defined there:</p>
<pre><code>>>> instr = Instrument()
>>> instr.direct_method(arg1)
>>> instr.external_method(arg1, arg2)
</code></pre>
<p>Thanks!</p>
| 8 | 2009-06-29T12:01:57Z | 1,057,953 | <p>I don't think what you want is directly possible in Python. </p>
<p>You could, however, try one of the following.</p>
<ol>
<li>When generating <code>to_import_from.py</code>, add the non-generated stuff there too. This way,
all methods are in the same class definition.</li>
<li>Have <code>to_import_from.py</code> contain a base class definition which the the Instrument class
inherits.</li>
</ol>
<p>In other words, in <code>to_import_from.py</code>:</p>
<pre><code>class InstrumentBase(object):
def external_method(self, arg1, arg2):
if self.flag:
...
</code></pre>
<p>and then in <code>main_module.py</code>:</p>
<pre><code>import to_import_from
class Instrument(to_import_from.InstrumentBase):
def __init__(self):
...
</code></pre>
| 5 | 2009-06-29T12:09:07Z | [
"python",
"import",
"methods"
] |
Importing methods for a Python class | 1,057,934 | <p>I wonder if it's possible to keep methods for a Python class in a different file from the class definition, something like this:</p>
<p><code>main_module.py:</code></p>
<pre><code>class Instrument(Object):
# Some import statement?
def __init__(self):
self.flag = True
def direct_method(self,arg1):
self.external_method(arg1, arg2)
</code></pre>
<p><code>to_import_from.py:</code></p>
<pre><code>def external_method(self, arg1, arg2):
if self.flag:
#doing something
#...many more methods
</code></pre>
<p>In my case, <code>to_import_from.py</code> is machine-generated, and contains many methods. I would rather not copy-paste these into main_module.py or import them one by one, but have them all recognized as methods of the Instrument class, just as if they had been defined there:</p>
<pre><code>>>> instr = Instrument()
>>> instr.direct_method(arg1)
>>> instr.external_method(arg1, arg2)
</code></pre>
<p>Thanks!</p>
| 8 | 2009-06-29T12:01:57Z | 1,057,956 | <p>I'm sorry that this is kind of a <a href="https://stackoverflow.fogbugz.com/default.asp?W29025" rel="nofollow">"You shouldn't be putting nails in the wall" answer</a>, but you're missing the point of python class definitions. You should rather put the class with all its methods in its own python file, and in your <code>main_module.py</code> do</p>
<pre><code>from instrument import Instrument
</code></pre>
<p>If you plan on using the methods for several classes, you should consider subclassing. In your case, the machine generated file could contain the base class that <code>Instrument</code> inherits from.</p>
<p>Finally, give your class a good docstring that explains the API to its user, so there is no need for a "header file" used as an overview of your class.</p>
| 3 | 2009-06-29T12:09:24Z | [
"python",
"import",
"methods"
] |
Importing methods for a Python class | 1,057,934 | <p>I wonder if it's possible to keep methods for a Python class in a different file from the class definition, something like this:</p>
<p><code>main_module.py:</code></p>
<pre><code>class Instrument(Object):
# Some import statement?
def __init__(self):
self.flag = True
def direct_method(self,arg1):
self.external_method(arg1, arg2)
</code></pre>
<p><code>to_import_from.py:</code></p>
<pre><code>def external_method(self, arg1, arg2):
if self.flag:
#doing something
#...many more methods
</code></pre>
<p>In my case, <code>to_import_from.py</code> is machine-generated, and contains many methods. I would rather not copy-paste these into main_module.py or import them one by one, but have them all recognized as methods of the Instrument class, just as if they had been defined there:</p>
<pre><code>>>> instr = Instrument()
>>> instr.direct_method(arg1)
>>> instr.external_method(arg1, arg2)
</code></pre>
<p>Thanks!</p>
| 8 | 2009-06-29T12:01:57Z | 1,057,967 | <p>you can do this with the <code>__getattr__</code> method</p>
<p>external.py</p>
<pre><code>def external_function(arg):
print("external", arg)
</code></pre>
<p>main.py:</p>
<pre><code>import external
class Instrument(object):
def __getattr__(self, name):
if hasattr(external, name):
return getattr(external, name)
else:
return Object.__getattr__(self, name)
def direct_method(self, arg):
print("internal", arg)
i = Instrument()
i.direct_method("foo")
i.external_function("foo")
</code></pre>
| 4 | 2009-06-29T12:12:21Z | [
"python",
"import",
"methods"
] |
Importing methods for a Python class | 1,057,934 | <p>I wonder if it's possible to keep methods for a Python class in a different file from the class definition, something like this:</p>
<p><code>main_module.py:</code></p>
<pre><code>class Instrument(Object):
# Some import statement?
def __init__(self):
self.flag = True
def direct_method(self,arg1):
self.external_method(arg1, arg2)
</code></pre>
<p><code>to_import_from.py:</code></p>
<pre><code>def external_method(self, arg1, arg2):
if self.flag:
#doing something
#...many more methods
</code></pre>
<p>In my case, <code>to_import_from.py</code> is machine-generated, and contains many methods. I would rather not copy-paste these into main_module.py or import them one by one, but have them all recognized as methods of the Instrument class, just as if they had been defined there:</p>
<pre><code>>>> instr = Instrument()
>>> instr.direct_method(arg1)
>>> instr.external_method(arg1, arg2)
</code></pre>
<p>Thanks!</p>
| 8 | 2009-06-29T12:01:57Z | 1,057,976 | <p>What you're doing is extending a base class with some "machine-generated" code.</p>
<p>Choice 1. Extend a base class with machine-generated code.</p>
<p>machine_generated.py</p>
<pre><code># Start of boilerplate #
import main_module
class Instrument_Implementation( main_module.Instrument_Abstraction ):
def direct_method(self,arg1):
# End of boilerplate #
...the real code...
</code></pre>
<p>Your application can then <code>import machine_generated</code> and use <code>machine_generated.Instrument_Implementation</code>.</p>
<p>Choice 2. Simply use first-class functions.</p>
<p>machine_generated.py</p>
<pre><code>def external_method(self, arg1, arg2):
...the real code...
</code></pre>
<p>main_module.py</p>
<pre><code>import machine_generated
class Instrument( object ):
def direct_method(self,arg1):
return machine_generator.external_method( arg1, ... )
</code></pre>
<p>Your application can <code>import main_module</code> and use <code>main_module.Instrument</code>.</p>
| 2 | 2009-06-29T12:13:30Z | [
"python",
"import",
"methods"
] |
Importing methods for a Python class | 1,057,934 | <p>I wonder if it's possible to keep methods for a Python class in a different file from the class definition, something like this:</p>
<p><code>main_module.py:</code></p>
<pre><code>class Instrument(Object):
# Some import statement?
def __init__(self):
self.flag = True
def direct_method(self,arg1):
self.external_method(arg1, arg2)
</code></pre>
<p><code>to_import_from.py:</code></p>
<pre><code>def external_method(self, arg1, arg2):
if self.flag:
#doing something
#...many more methods
</code></pre>
<p>In my case, <code>to_import_from.py</code> is machine-generated, and contains many methods. I would rather not copy-paste these into main_module.py or import them one by one, but have them all recognized as methods of the Instrument class, just as if they had been defined there:</p>
<pre><code>>>> instr = Instrument()
>>> instr.direct_method(arg1)
>>> instr.external_method(arg1, arg2)
</code></pre>
<p>Thanks!</p>
| 8 | 2009-06-29T12:01:57Z | 1,058,132 | <p>It's easier than you think:</p>
<pre><code>class Instrument(Object):
def __init__(self):
self.flag = True
def direct_method(self,arg1):
self.external_method(arg1, arg2)
import to_import_from
Instrument.external_method = to_import_from.external_method
</code></pre>
<p>Done!</p>
<p>Although having the machine generated code generate a class definition and subclassing from it would be a neater solution.</p>
| 6 | 2009-06-29T12:57:04Z | [
"python",
"import",
"methods"
] |
Importing methods for a Python class | 1,057,934 | <p>I wonder if it's possible to keep methods for a Python class in a different file from the class definition, something like this:</p>
<p><code>main_module.py:</code></p>
<pre><code>class Instrument(Object):
# Some import statement?
def __init__(self):
self.flag = True
def direct_method(self,arg1):
self.external_method(arg1, arg2)
</code></pre>
<p><code>to_import_from.py:</code></p>
<pre><code>def external_method(self, arg1, arg2):
if self.flag:
#doing something
#...many more methods
</code></pre>
<p>In my case, <code>to_import_from.py</code> is machine-generated, and contains many methods. I would rather not copy-paste these into main_module.py or import them one by one, but have them all recognized as methods of the Instrument class, just as if they had been defined there:</p>
<pre><code>>>> instr = Instrument()
>>> instr.direct_method(arg1)
>>> instr.external_method(arg1, arg2)
</code></pre>
<p>Thanks!</p>
| 8 | 2009-06-29T12:01:57Z | 1,058,212 | <p>Here's my try. I think a nicer approach could be made with metaclasses...</p>
<p>to_import_from.py :</p>
<pre><code>def external_method(self, arg1, arg2):
if self.flag:
print "flag is set"
else :
print "flag is not set"
</code></pre>
<p>instrument.py :</p>
<pre><code>import imp
import os
import inspect
import new
import pdb
class MethodImporter(object) :
def __init__(self, path_to_module) :
self.load_module(path_to_module)
def load_module(self, path_to_module) :
name = os.path.basename(path_to_module)
module_file = file(path_to_module,"r")
self.module = imp.load_module(name, module_file , path_to_module, ('','r',imp.PY_SOURCE))
print "Module %s imported" % self.module
for method_name, method_object in inspect.getmembers(self.module, inspect.isfunction) :
print "adding method %s to %s" % (method_name, self)
setattr(self, method_name, new.instancemethod(method_object, self, self.__class__))
class Instrument(MethodImporter):
def __init__(self):
super(Instrument,self).__init__("./to_import_from.py")
self.flag = True
def direct_method(self,arg1):
self.external_method(arg1, arg2)
</code></pre>
<p>when you run this code</p>
<pre><code>arg1, arg2 = 1, 2
instr = Instrument()
instr.direct_method(arg1)
instr.external_method(arg1, arg2)
</code></pre>
<p>here's the output :</p>
<pre><code>Module <module 'to_import_from.py' from './to_import_from.pyc'> imported
adding method external_method to <__main__.Instrument object at 0x2ddeb0>
flag is set
flag is set
</code></pre>
| 0 | 2009-06-29T13:14:46Z | [
"python",
"import",
"methods"
] |
Importing methods for a Python class | 1,057,934 | <p>I wonder if it's possible to keep methods for a Python class in a different file from the class definition, something like this:</p>
<p><code>main_module.py:</code></p>
<pre><code>class Instrument(Object):
# Some import statement?
def __init__(self):
self.flag = True
def direct_method(self,arg1):
self.external_method(arg1, arg2)
</code></pre>
<p><code>to_import_from.py:</code></p>
<pre><code>def external_method(self, arg1, arg2):
if self.flag:
#doing something
#...many more methods
</code></pre>
<p>In my case, <code>to_import_from.py</code> is machine-generated, and contains many methods. I would rather not copy-paste these into main_module.py or import them one by one, but have them all recognized as methods of the Instrument class, just as if they had been defined there:</p>
<pre><code>>>> instr = Instrument()
>>> instr.direct_method(arg1)
>>> instr.external_method(arg1, arg2)
</code></pre>
<p>Thanks!</p>
| 8 | 2009-06-29T12:01:57Z | 1,058,221 | <p>Technically, yes this is possible, but solving it this way is not really idiomatic python, and there are likely better solutions. Here's an example of how to do so:</p>
<pre><code>import to_import_from
class Instrument(object):
locals().update(dict((k,v) for (k,v) in
to_import_from.__dict__.iteritems() if callable(v)))
def __init__(self):
self.flag = True
def direct_method(self,arg1):
self.external_method(arg1, arg2)
</code></pre>
<p>That will import all callable functions defined in <code>to_import_from</code> as methods of the <code>Instrument</code> class, as well as adding some more methods. Note: if you also want to copy global variables as instance variables, you'll need to refine the check. Also note that it adds <em>all</em> callable objects it finds in to_import_from's namespace, including imports from other modules (ie <code>from module import some_func</code> style imports)</p>
<p>However, this isn't a terribly nice way to do it. Better would be to instead tweak your code generation to <em>produce</em> a class, and have your class inherit from it. This avoids the unneccessary copying of methods into Instrument's namespace, and instead uses normal inheritcance. ie:</p>
<pre><code>class Instrument(to_import_from.BaseClass):
# Add new methods here.
</code></pre>
| 0 | 2009-06-29T13:15:57Z | [
"python",
"import",
"methods"
] |
Importing methods for a Python class | 1,057,934 | <p>I wonder if it's possible to keep methods for a Python class in a different file from the class definition, something like this:</p>
<p><code>main_module.py:</code></p>
<pre><code>class Instrument(Object):
# Some import statement?
def __init__(self):
self.flag = True
def direct_method(self,arg1):
self.external_method(arg1, arg2)
</code></pre>
<p><code>to_import_from.py:</code></p>
<pre><code>def external_method(self, arg1, arg2):
if self.flag:
#doing something
#...many more methods
</code></pre>
<p>In my case, <code>to_import_from.py</code> is machine-generated, and contains many methods. I would rather not copy-paste these into main_module.py or import them one by one, but have them all recognized as methods of the Instrument class, just as if they had been defined there:</p>
<pre><code>>>> instr = Instrument()
>>> instr.direct_method(arg1)
>>> instr.external_method(arg1, arg2)
</code></pre>
<p>Thanks!</p>
| 8 | 2009-06-29T12:01:57Z | 1,059,377 | <p>People seem to be overthinking this. Methods are just function valued local variables in class construction scope. So the following works fine:</p>
<pre><code>class Instrument(Object):
# load external methods
from to_import_from import *
def __init__(self):
self.flag = True
def direct_method(self,arg1):
self.external_method(arg1, arg2)
</code></pre>
| 4 | 2009-06-29T17:06:06Z | [
"python",
"import",
"methods"
] |
Execute a prepared statement in sqlalchemy | 1,058,037 | <p>I have to run 40K requests against a username:</p>
<pre><code>SELECT * from user WHERE login = :login
</code></pre>
<p>It's slow, so I figured I would just use a prepared statement.</p>
<p>So I do</p>
<pre><code>e = sqlalchemy.create_engine(...)
c = e.connect()
c.execute("PREPARE userinfo(text) AS SELECT * from user WHERE login = $1")
r = c.execute("EXECUTE userinfo('bob')")
for x in r:
do_foo()
</code></pre>
<p>But I have a:</p>
<pre><code>InterfaceError: (InterfaceError) cursor already closed None None
</code></pre>
<p>I don't understand why I get an exception</p>
| 1 | 2009-06-29T12:29:11Z | 1,058,123 | <p>From <a href="http://www.mail-archive.com/sqlalchemy@googlegroups.com/msg08278.html" rel="nofollow" title="Connection Already Closed">this discussion</a>, it might be a good idea to check your paster debug logs in case there is a better error message there.</p>
| 1 | 2009-06-29T12:54:30Z | [
"python",
"sqlalchemy"
] |
Execute a prepared statement in sqlalchemy | 1,058,037 | <p>I have to run 40K requests against a username:</p>
<pre><code>SELECT * from user WHERE login = :login
</code></pre>
<p>It's slow, so I figured I would just use a prepared statement.</p>
<p>So I do</p>
<pre><code>e = sqlalchemy.create_engine(...)
c = e.connect()
c.execute("PREPARE userinfo(text) AS SELECT * from user WHERE login = $1")
r = c.execute("EXECUTE userinfo('bob')")
for x in r:
do_foo()
</code></pre>
<p>But I have a:</p>
<pre><code>InterfaceError: (InterfaceError) cursor already closed None None
</code></pre>
<p>I don't understand why I get an exception</p>
| 1 | 2009-06-29T12:29:11Z | 1,058,199 | <p>Not sure how to solve your cursor related error message, but I dont think a prepared staement will solve your performance issue - as long as your using SQL server 2005 or later the execution plan for <code>SELECT * from user WHERE login = $login</code> will already be re-used and there will be no performance gain from the prepared statement. I dont know about MySql or other SQL database servers, but I suspect they too have similar optimisations for Ad-Hoc queries that make the prepared statement redundant.</p>
<p>It sounds like the cause of the performance hit is more down to the fact that you are making 40,000 round trips to the database - you should try and rewrite the query so that you are only executing one SQL statement with a list of the login names. Am I right in thinking that MySql supports an aray data type? If it doesnt (or you are using Microsoft SQL) you should look into passing in some sort of delimited list of usernames.</p>
| 1 | 2009-06-29T13:12:23Z | [
"python",
"sqlalchemy"
] |
What should I call this function composition? | 1,058,273 | <p>What should 'foo' be called, given the following?</p>
<p>x.items is a set, y.values is a set.</p>
<p>function a(key) returns an ordered list of x.items</p>
<p>function b(x.item) returns a single y.value</p>
<p>Define foo(a, b), which returns a function, d, such that d(key) returns a list of y.values defined by: map(b, a(key)).</p>
<p>This feels like a fairly common and generic function composition but I don't know what to call it.</p>
| 1 | 2009-06-29T13:22:43Z | 1,058,290 | <p>I would call it <strong>function compositor</strong> or something like that</p>
| 1 | 2009-06-29T13:25:49Z | [
"python",
"math",
"functional-programming"
] |
What should I call this function composition? | 1,058,273 | <p>What should 'foo' be called, given the following?</p>
<p>x.items is a set, y.values is a set.</p>
<p>function a(key) returns an ordered list of x.items</p>
<p>function b(x.item) returns a single y.value</p>
<p>Define foo(a, b), which returns a function, d, such that d(key) returns a list of y.values defined by: map(b, a(key)).</p>
<p>This feels like a fairly common and generic function composition but I don't know what to call it.</p>
| 1 | 2009-06-29T13:22:43Z | 1,058,328 | <p>The synergy engine.</p>
| 0 | 2009-06-29T13:31:41Z | [
"python",
"math",
"functional-programming"
] |
What should I call this function composition? | 1,058,273 | <p>What should 'foo' be called, given the following?</p>
<p>x.items is a set, y.values is a set.</p>
<p>function a(key) returns an ordered list of x.items</p>
<p>function b(x.item) returns a single y.value</p>
<p>Define foo(a, b), which returns a function, d, such that d(key) returns a list of y.values defined by: map(b, a(key)).</p>
<p>This feels like a fairly common and generic function composition but I don't know what to call it.</p>
| 1 | 2009-06-29T13:22:43Z | 1,058,402 | <p>Here's are example names for a, b, and foo that might help (I don't like these, but they're sort of like what I'm getting at):</p>
<pre>
items_by_key(key)
value_by_item(item)
values_by_key(items_by_key, value_by_item)
</pre>
| 0 | 2009-06-29T13:44:00Z | [
"python",
"math",
"functional-programming"
] |
What should I call this function composition? | 1,058,273 | <p>What should 'foo' be called, given the following?</p>
<p>x.items is a set, y.values is a set.</p>
<p>function a(key) returns an ordered list of x.items</p>
<p>function b(x.item) returns a single y.value</p>
<p>Define foo(a, b), which returns a function, d, such that d(key) returns a list of y.values defined by: map(b, a(key)).</p>
<p>This feels like a fairly common and generic function composition but I don't know what to call it.</p>
| 1 | 2009-06-29T13:22:43Z | 1,100,571 | <pre><code> function a(key) returns an ordered list of x.items
function b(x.item) returns a single y.value
</code></pre>
<p>Except for the ordering, a() is in practice a filter, i.e. it "filters" or "selects" items from x.items according to a key. b() is a normal map, or function. Thus, I would choose for 'foo' the name "composeFilterWithMap", or "composeSelectorWithMap" or a similar name. </p>
| 2 | 2009-07-08T21:14:27Z | [
"python",
"math",
"functional-programming"
] |
What should I call this function composition? | 1,058,273 | <p>What should 'foo' be called, given the following?</p>
<p>x.items is a set, y.values is a set.</p>
<p>function a(key) returns an ordered list of x.items</p>
<p>function b(x.item) returns a single y.value</p>
<p>Define foo(a, b), which returns a function, d, such that d(key) returns a list of y.values defined by: map(b, a(key)).</p>
<p>This feels like a fairly common and generic function composition but I don't know what to call it.</p>
| 1 | 2009-06-29T13:22:43Z | 1,107,216 | <p>I would call that function <strong>permuted_values</strong></p>
<p>What you are doing is equivalent to iterating over a hash map using a permutation based on your key.</p>
| 1 | 2009-07-10T01:02:41Z | [
"python",
"math",
"functional-programming"
] |
How to add hooks in twisted.web (or twisted.web2)? | 1,058,300 | <p>How can I add a hook before and after processing a request on twisted.web (twisted.web2 is fine too)? The equivalent of webpy's:</p>
<pre><code>app = web.application(urls, globals())
app.add_processor(web.loadhook(my_attach_callback))
app.add_processor(web.unloadhook(my_detach_callback))
</code></pre>
<p>Thanks!</p>
| 2 | 2009-06-29T13:27:28Z | 4,069,597 | <p>One approach Twisted Web allows is to insert an extra resource into the resource hierarchy the only purpose of which is to run your custom hooks, rather than to actually handle a segment of the request URL as resources typically do.</p>
<p>You can find an implementation of this approach in <a href="http://twistedmatrix.com/trac/browser/tags/releases/twisted-10.1.0/twisted/web/_auth/wrapper.py#L68" rel="nofollow">twisted/web/_auth/wrapper.py</a> which implements the HTTPAuthSessionWrapper resource (exposed publicly in twisted.web.guard). Note the first line of <code>getChildWithDefault</code> which ensures the resource doesn't consume one of the request segments. This allows it to sit in the resource hierarchy, modify behavior, but not otherwise change the way URLs are dispatched.</p>
| 1 | 2010-11-01T14:09:38Z | [
"python",
"callback",
"hook",
"twisted"
] |
Unicode problems with web pages in Python's urllib | 1,058,302 | <p>I seem to have the all-familiar problem of correctly reading and viewing a web page. It looks like Python reads the page in UTF-8 but when I try to convert it to something more viewable (iso-8859-1) I get this error:</p>
<pre><code>UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position 2: ordinal not in range(128)
</code></pre>
<p>The code looks like this:</p>
<pre><code>#!/usr/bin/python
from urllib import urlopen
import re
url_address = 'http://www.eurohockey.net/players/show_player.cgi?serial=4722'
finished = 0
begin_record = 0
col = 0
str = ''
for line in urlopen(url_address):
if '</tr' in line:
begin_record = 0
print str
str = ''
continue
if begin_record == 1:
col = col + 1
tmp_match = re.search('<td>(.+)</td>', line.strip())
str = str + ';' + unicode(tmp_match.group(1), 'iso-8859-1')
if '<tr class=\"even\"' in line or '<tr class=\"odd\"' in line:
begin_record = 1
col = 0
continue
</code></pre>
<p>How should I handle the contents? Firefox at least thinks it's iso-8859-1 and it would make sense looking at the contents of that page. The error comes from the 'ä' character clearly. </p>
<p>And if I was to save that data to a database, should I not bother with changing the codec and then converting when showing it? </p>
| 1 | 2009-06-29T13:27:41Z | 1,058,532 | <p>That text is indeed iso-88591-1, and I can decode it without a problem, and indeed your code runs without a hitch.</p>
<p>Your error, however, is an ENCODE error, not a decode error. And you don't do any encoding in your code, so. Possibly you have gotten encoding and decoding confused, it's a common problem.</p>
<p>You DECODE from Latin1 to Unicode. You ENCODE the other way. Remember that Latin1, UTF8 etc are called "encodings".</p>
| 1 | 2009-06-29T14:11:18Z | [
"python",
"unicode"
] |
Unicode problems with web pages in Python's urllib | 1,058,302 | <p>I seem to have the all-familiar problem of correctly reading and viewing a web page. It looks like Python reads the page in UTF-8 but when I try to convert it to something more viewable (iso-8859-1) I get this error:</p>
<pre><code>UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position 2: ordinal not in range(128)
</code></pre>
<p>The code looks like this:</p>
<pre><code>#!/usr/bin/python
from urllib import urlopen
import re
url_address = 'http://www.eurohockey.net/players/show_player.cgi?serial=4722'
finished = 0
begin_record = 0
col = 0
str = ''
for line in urlopen(url_address):
if '</tr' in line:
begin_record = 0
print str
str = ''
continue
if begin_record == 1:
col = col + 1
tmp_match = re.search('<td>(.+)</td>', line.strip())
str = str + ';' + unicode(tmp_match.group(1), 'iso-8859-1')
if '<tr class=\"even\"' in line or '<tr class=\"odd\"' in line:
begin_record = 1
col = 0
continue
</code></pre>
<p>How should I handle the contents? Firefox at least thinks it's iso-8859-1 and it would make sense looking at the contents of that page. The error comes from the 'ä' character clearly. </p>
<p>And if I was to save that data to a database, should I not bother with changing the codec and then converting when showing it? </p>
| 1 | 2009-06-29T13:27:41Z | 1,058,592 | <p>As noted by Lennart, your problem is not the decoding. It is trying to encode into "ascii", which is often a problem with <code>print</code> statements. I suspect the line</p>
<pre><code>print str
</code></pre>
<p>is your problem. You need to encode the str into whatever your console is using to have that line work.</p>
| 3 | 2009-06-29T14:21:03Z | [
"python",
"unicode"
] |
Unicode problems with web pages in Python's urllib | 1,058,302 | <p>I seem to have the all-familiar problem of correctly reading and viewing a web page. It looks like Python reads the page in UTF-8 but when I try to convert it to something more viewable (iso-8859-1) I get this error:</p>
<pre><code>UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position 2: ordinal not in range(128)
</code></pre>
<p>The code looks like this:</p>
<pre><code>#!/usr/bin/python
from urllib import urlopen
import re
url_address = 'http://www.eurohockey.net/players/show_player.cgi?serial=4722'
finished = 0
begin_record = 0
col = 0
str = ''
for line in urlopen(url_address):
if '</tr' in line:
begin_record = 0
print str
str = ''
continue
if begin_record == 1:
col = col + 1
tmp_match = re.search('<td>(.+)</td>', line.strip())
str = str + ';' + unicode(tmp_match.group(1), 'iso-8859-1')
if '<tr class=\"even\"' in line or '<tr class=\"odd\"' in line:
begin_record = 1
col = 0
continue
</code></pre>
<p>How should I handle the contents? Firefox at least thinks it's iso-8859-1 and it would make sense looking at the contents of that page. The error comes from the 'ä' character clearly. </p>
<p>And if I was to save that data to a database, should I not bother with changing the codec and then converting when showing it? </p>
| 1 | 2009-06-29T13:27:41Z | 1,058,995 | <p>It doesn't look like Python is "reading it in UTF-8" at all. As already pointed out, you have an encoding problem, NOT a decoding problem. It is impossible for that error to have arisen from that line that you say. When asking a question like this, always give the full traceback and error message.</p>
<p>Kathy's suspicion is correct; in fact the <code>print str</code> line is the only possible source of that error, and that can only happen when sys.stdout.encoding is not set so Python punts on 'ascii'.</p>
<p>Variables that may affect the outcome are what version of Python you are using, what platform you are running on and exactly how you run your script -- none of which you have told us; please do.</p>
<p>Example: I'm using Python 2.6.2 on Windows XP and I'm running your script with some diagnostic additions:
(1) <code>import sys; print sys.stdout.encoding</code> up near the front
(2) <code>print repr(str)</code> before <code>print str</code> so that I can see what you've got before it crashes.</p>
<p>In a Command Prompt window, if I do <code>\python26\python hockey.py</code> it prints <code>cp850</code> as the encoding and just works.</p>
<p>However if I do</p>
<pre><code>\python26\python hockey.py | more
</code></pre>
<p>or</p>
<pre><code>\python26\python hockey.py >hockey.txt
</code></pre>
<p>it prints <code>None</code> as the encoding and crashes with your error message on the first line with the a-with-diaeresis:</p>
<pre><code>C:\junk>\python26\python hockey.py >hockey.txt
Traceback (most recent call last):
File "hockey.py", line 18, in <module>
print str
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position 2: ordinal not in range(128)
</code></pre>
<p>If that fits your case, the fix in general is to explicitly encode your output with an encoding suited to the display mechanism you plan to use.</p>
| 2 | 2009-06-29T15:42:05Z | [
"python",
"unicode"
] |
Coding a coroutine in Python to display "odd" and "even" numbers inifinitely | 1,058,383 | <p>I have scratchy ideas of Generators, Iterators and Coroutines. (from PEPs and other tutorials). I want to implement a coroutine- in which routine1 will print odd and routine2 will print even numbers infinitely in a fashion such as:</p>
<pre><code>routine1:
print odd
yield to routine2
routune2:
print even
yield to routine1
</code></pre>
<p>Have some rough ideas of the code that should do this, but not able to get it in shape. I <em>do not</em> want the code. But, I would appreciate pseudo code style pointers for the same. Thank you.</p>
| 0 | 2009-06-29T13:42:04Z | 1,058,481 | <p>You yield back to the method that called you. Hence you can't yield to routine 1. You just yield. You could let routine 1 call routine 2, and routine 2 can yield and hence return back to routine 1.</p>
| 1 | 2009-06-29T13:59:03Z | [
"python"
] |
Coding a coroutine in Python to display "odd" and "even" numbers inifinitely | 1,058,383 | <p>I have scratchy ideas of Generators, Iterators and Coroutines. (from PEPs and other tutorials). I want to implement a coroutine- in which routine1 will print odd and routine2 will print even numbers infinitely in a fashion such as:</p>
<pre><code>routine1:
print odd
yield to routine2
routune2:
print even
yield to routine1
</code></pre>
<p>Have some rough ideas of the code that should do this, but not able to get it in shape. I <em>do not</em> want the code. But, I would appreciate pseudo code style pointers for the same. Thank you.</p>
| 0 | 2009-06-29T13:42:04Z | 1,058,610 | <p><a href="http://www.python.org/dev/peps/pep-0342/" rel="nofollow">PEP 342</a>, "Coroutines via Enhanced Generators", gives as its example 3 'A simple co-routine scheduler or "trampoline" that lets coroutines "call" other coroutines by yielding the coroutine they wish to invoke.' -- you don't need that much generality (or any of the generality aspects PEP 342 first introduced), for this very specific task, given that the coroutines are not communicating anything to each other, there's only two of them, their order of succession is perfectly regular, there is no termination, etc, etc... but a small subset of that code is still worth implementing as it shows you more about coroutines than this extremely simple example could on its own.</p>
<p>The two coroutines should probably be two instances from the same generator function differing just in starting point (no point in writing that <code>while True:</code> loop twice after all, given how simple its body will be;-). As you'll see, the interesting part is the trampoline, even though you can and should make it vastly simpler than the general one in PEP 342.</p>
| 2 | 2009-06-29T14:24:11Z | [
"python"
] |
Flags in Python | 1,058,434 | <p>I'm working with a large matrix (250x250x30 = 1,875,000 cells), and I'd like a way to set an arbitrary number of flags for each cell in this matrix, in some manner that's easy to use and reasonably space efficient.</p>
<p>My original plan was a 250x250x30 list array, where each element was something like: <code>["FLAG1","FLAG8","FLAG12"]</code>. I then changed it to storing just integers instead: <code>[1,8,12]</code>. These integers are mapped internally by getter/setter functions to the original flag strings. This only uses 250mb with 8 flags per point, which is fine in terms of memory.</p>
<p>My question is: am I missing another obvious way to structure this sort of data?</p>
<p>Thanks all for your suggestions. I ended up rolling a few suggestions into one, sadly I can only pick one answer and have to live with upvoting the others:</p>
<p>EDIT: erm the initial code I had here (using sets as the base element of a 3d numpy array) used A LOT of memory. This new version uses around 500mb when filled with <code>randint(0,2**1000)</code>.</p>
<pre><code>import numpy
FLAG1=2**0
FLAG2=2**1
FLAG3=2**2
FLAG4=2**3
(x,y,z) = (250,250,30)
array = numpy.zeros((x,y,z), dtype=object)
def setFlag(location,flag):
array[location] |= flag
def unsetFlag(location,flag):
array[location] &= ~flag
</code></pre>
| 4 | 2009-06-29T13:49:38Z | 1,058,452 | <p><a href="http://en.wikipedia.org/wiki/Bit%5Farray" rel="nofollow">BitSet</a> is what you want, since it allows you to store many flags at once using only an fixed size integer (Int type)</p>
| 1 | 2009-06-29T13:53:34Z | [
"python",
"matrix",
"numpy",
"flags"
] |
Flags in Python | 1,058,434 | <p>I'm working with a large matrix (250x250x30 = 1,875,000 cells), and I'd like a way to set an arbitrary number of flags for each cell in this matrix, in some manner that's easy to use and reasonably space efficient.</p>
<p>My original plan was a 250x250x30 list array, where each element was something like: <code>["FLAG1","FLAG8","FLAG12"]</code>. I then changed it to storing just integers instead: <code>[1,8,12]</code>. These integers are mapped internally by getter/setter functions to the original flag strings. This only uses 250mb with 8 flags per point, which is fine in terms of memory.</p>
<p>My question is: am I missing another obvious way to structure this sort of data?</p>
<p>Thanks all for your suggestions. I ended up rolling a few suggestions into one, sadly I can only pick one answer and have to live with upvoting the others:</p>
<p>EDIT: erm the initial code I had here (using sets as the base element of a 3d numpy array) used A LOT of memory. This new version uses around 500mb when filled with <code>randint(0,2**1000)</code>.</p>
<pre><code>import numpy
FLAG1=2**0
FLAG2=2**1
FLAG3=2**2
FLAG4=2**3
(x,y,z) = (250,250,30)
array = numpy.zeros((x,y,z), dtype=object)
def setFlag(location,flag):
array[location] |= flag
def unsetFlag(location,flag):
array[location] &= ~flag
</code></pre>
| 4 | 2009-06-29T13:49:38Z | 1,058,466 | <p>Your solution is fine if every single cell is going to have a flag. However if you are working with a sparse dataset where only a small subsection of your cells will have flags what you really want is a dictionary. You would want to set up the dictonary so the key is a tuple for the location of the cell and the value is a list of flags like you have in your solution.</p>
<pre><code>allFlags = {(1,1,1):[1,2,3], (250,250,30):[4,5,6]}
</code></pre>
<p>Here we have the 1,1,1 cell have the flags 1,2, and 3 and the cell 250,250,30 have the flags 4,5, and 6</p>
<p>edit- fixed key tuples, thanks Andre, and dictionary syntax.</p>
| 7 | 2009-06-29T13:56:34Z | [
"python",
"matrix",
"numpy",
"flags"
] |
Flags in Python | 1,058,434 | <p>I'm working with a large matrix (250x250x30 = 1,875,000 cells), and I'd like a way to set an arbitrary number of flags for each cell in this matrix, in some manner that's easy to use and reasonably space efficient.</p>
<p>My original plan was a 250x250x30 list array, where each element was something like: <code>["FLAG1","FLAG8","FLAG12"]</code>. I then changed it to storing just integers instead: <code>[1,8,12]</code>. These integers are mapped internally by getter/setter functions to the original flag strings. This only uses 250mb with 8 flags per point, which is fine in terms of memory.</p>
<p>My question is: am I missing another obvious way to structure this sort of data?</p>
<p>Thanks all for your suggestions. I ended up rolling a few suggestions into one, sadly I can only pick one answer and have to live with upvoting the others:</p>
<p>EDIT: erm the initial code I had here (using sets as the base element of a 3d numpy array) used A LOT of memory. This new version uses around 500mb when filled with <code>randint(0,2**1000)</code>.</p>
<pre><code>import numpy
FLAG1=2**0
FLAG2=2**1
FLAG3=2**2
FLAG4=2**3
(x,y,z) = (250,250,30)
array = numpy.zeros((x,y,z), dtype=object)
def setFlag(location,flag):
array[location] |= flag
def unsetFlag(location,flag):
array[location] &= ~flag
</code></pre>
| 4 | 2009-06-29T13:49:38Z | 1,058,488 | <p>Consider using Flyweight pattern to share cell properties:</p>
<p><a href="http://en.wikipedia.org/wiki/Flyweight%5Fpattern" rel="nofollow">http://en.wikipedia.org/wiki/Flyweight_pattern</a></p>
| 3 | 2009-06-29T14:00:25Z | [
"python",
"matrix",
"numpy",
"flags"
] |
Flags in Python | 1,058,434 | <p>I'm working with a large matrix (250x250x30 = 1,875,000 cells), and I'd like a way to set an arbitrary number of flags for each cell in this matrix, in some manner that's easy to use and reasonably space efficient.</p>
<p>My original plan was a 250x250x30 list array, where each element was something like: <code>["FLAG1","FLAG8","FLAG12"]</code>. I then changed it to storing just integers instead: <code>[1,8,12]</code>. These integers are mapped internally by getter/setter functions to the original flag strings. This only uses 250mb with 8 flags per point, which is fine in terms of memory.</p>
<p>My question is: am I missing another obvious way to structure this sort of data?</p>
<p>Thanks all for your suggestions. I ended up rolling a few suggestions into one, sadly I can only pick one answer and have to live with upvoting the others:</p>
<p>EDIT: erm the initial code I had here (using sets as the base element of a 3d numpy array) used A LOT of memory. This new version uses around 500mb when filled with <code>randint(0,2**1000)</code>.</p>
<pre><code>import numpy
FLAG1=2**0
FLAG2=2**1
FLAG3=2**2
FLAG4=2**3
(x,y,z) = (250,250,30)
array = numpy.zeros((x,y,z), dtype=object)
def setFlag(location,flag):
array[location] |= flag
def unsetFlag(location,flag):
array[location] &= ~flag
</code></pre>
| 4 | 2009-06-29T13:49:38Z | 1,058,506 | <p>You can define some constants with different, power of two values as:</p>
<pre><code>FLAG1 = 0x01
FLAG8 = 0x02
FLAG12 = 0x04
...
</code></pre>
<p>And use them with boolean logic to store the flags in only one integer, p.e.:</p>
<pre><code>flags = FLAG1 | FLAG8
</code></pre>
<p>To check if a flag is enabled, you can use the <code>&</code> operator:</p>
<pre><code>flag1_enabled = flags & FLAG1
</code></pre>
<p>If the flag is enabled, this expression will return a non-zero value, that will be evaluated as True in any boolean operation. If the flag is disabled, the expression will return 0, that is evaluated as False in boolean operations.</p>
| 5 | 2009-06-29T14:04:42Z | [
"python",
"matrix",
"numpy",
"flags"
] |
Flags in Python | 1,058,434 | <p>I'm working with a large matrix (250x250x30 = 1,875,000 cells), and I'd like a way to set an arbitrary number of flags for each cell in this matrix, in some manner that's easy to use and reasonably space efficient.</p>
<p>My original plan was a 250x250x30 list array, where each element was something like: <code>["FLAG1","FLAG8","FLAG12"]</code>. I then changed it to storing just integers instead: <code>[1,8,12]</code>. These integers are mapped internally by getter/setter functions to the original flag strings. This only uses 250mb with 8 flags per point, which is fine in terms of memory.</p>
<p>My question is: am I missing another obvious way to structure this sort of data?</p>
<p>Thanks all for your suggestions. I ended up rolling a few suggestions into one, sadly I can only pick one answer and have to live with upvoting the others:</p>
<p>EDIT: erm the initial code I had here (using sets as the base element of a 3d numpy array) used A LOT of memory. This new version uses around 500mb when filled with <code>randint(0,2**1000)</code>.</p>
<pre><code>import numpy
FLAG1=2**0
FLAG2=2**1
FLAG3=2**2
FLAG4=2**3
(x,y,z) = (250,250,30)
array = numpy.zeros((x,y,z), dtype=object)
def setFlag(location,flag):
array[location] |= flag
def unsetFlag(location,flag):
array[location] &= ~flag
</code></pre>
| 4 | 2009-06-29T13:49:38Z | 1,058,524 | <p>I would generally use a <a href="http://numpy.scipy.org/" rel="nofollow">numpy</a> array (presumably of short ints, 2 bytes each, since you may need more than 256 distinct values) -- that would take less than 4MB for the <2 million cells.</p>
<p>If for some reason I couldn't afford the numpy dependency (e.g on App Engine, which doesn't support numpy), I'd use the standard library <a href="http://docs.python.org/library/array.html" rel="nofollow">array</a> module - it only supports 1-dimensional arrays, but it's just as space-efficient as numpy for large homogeneous arrays, and the getter/setter routines you mention can perfectly well "linearize" a 3-items tuple that's your natural index into the single integer index into the 1-D array.</p>
<p>In general, consider numpy (or array) any time you have large homogeneous, dense vectors or matrices of numbers -- Python built-in lists are highly wasteful of space in this use case (due to their generality which you're not using and don't need here!-), and saving memory indirectly translates to saving time too (better caching, fewer levels of indirection, etc, etc).</p>
| 4 | 2009-06-29T14:09:34Z | [
"python",
"matrix",
"numpy",
"flags"
] |
Flags in Python | 1,058,434 | <p>I'm working with a large matrix (250x250x30 = 1,875,000 cells), and I'd like a way to set an arbitrary number of flags for each cell in this matrix, in some manner that's easy to use and reasonably space efficient.</p>
<p>My original plan was a 250x250x30 list array, where each element was something like: <code>["FLAG1","FLAG8","FLAG12"]</code>. I then changed it to storing just integers instead: <code>[1,8,12]</code>. These integers are mapped internally by getter/setter functions to the original flag strings. This only uses 250mb with 8 flags per point, which is fine in terms of memory.</p>
<p>My question is: am I missing another obvious way to structure this sort of data?</p>
<p>Thanks all for your suggestions. I ended up rolling a few suggestions into one, sadly I can only pick one answer and have to live with upvoting the others:</p>
<p>EDIT: erm the initial code I had here (using sets as the base element of a 3d numpy array) used A LOT of memory. This new version uses around 500mb when filled with <code>randint(0,2**1000)</code>.</p>
<pre><code>import numpy
FLAG1=2**0
FLAG2=2**1
FLAG3=2**2
FLAG4=2**3
(x,y,z) = (250,250,30)
array = numpy.zeros((x,y,z), dtype=object)
def setFlag(location,flag):
array[location] |= flag
def unsetFlag(location,flag):
array[location] &= ~flag
</code></pre>
| 4 | 2009-06-29T13:49:38Z | 1,058,542 | <p>Taking Robbie's suggestion one step further...</p>
<pre><code>flags = set()
x, y, flag = 34, 201, 3
flags.add((x, y, flag)) # set flag 3 at position (34, 201)
if (3, 2, 1) in flags: # check if flag 1 is at position (3, 2)
# do something
else:
# do something else
</code></pre>
<p>You can also create a helper class.</p>
<pre><code>class Flags(object):
def __init__(self):
self.data = set()
def add(self, x, y, flag):
self.data.add((x, y, flag))
def remove(self, x, y, flag):
self.data.remove((x, y, flag))
def contains(self, x, y, flag):
return (x, y, flag) in self.data
</code></pre>
<p>You could also implement Python's special methods like <code>__contains__</code> to make it easier to work with.</p>
| 1 | 2009-06-29T14:13:39Z | [
"python",
"matrix",
"numpy",
"flags"
] |
How to get a nested element in beautiful soup | 1,058,599 | <p>I am struggling with the syntax required to grab some hrefs in a td.
The table, tr and td elements dont have any class's or id's.</p>
<p>If I wanted to grab the anchor in this example, what would I need?</p>
<p>< tr >
< td > < a >...</p>
<p>Thanks</p>
| 10 | 2009-06-29T14:22:55Z | 1,058,691 | <p>Something like this?</p>
<pre>
<code>
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(html)
anchors = [td.find('a') for td in soup.findAll('td')]
</code>
</pre>
<p>That should find the first "a" inside each "td" in the html you provide. You can tweak <code>td.find</code> to be more specific or else use <code>findAll</code> if you have several links inside each td.</p>
<p>UPDATE: re Daniele's comment, if you want to make sure you don't have any <code>None</code>'s in the list, then you could modify the list comprehension thus:</p>
<pre>
<code>
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(html)
anchors = [a for a in (td.find('a') for td in soup.findAll('td')) if a]
</code>
</pre>
<p>Which basically just adds a check to see if you have an actual element returned by <code>td.find('a')</code>.</p>
| 11 | 2009-06-29T14:37:15Z | [
"python",
"beautifulsoup"
] |
How to get a nested element in beautiful soup | 1,058,599 | <p>I am struggling with the syntax required to grab some hrefs in a td.
The table, tr and td elements dont have any class's or id's.</p>
<p>If I wanted to grab the anchor in this example, what would I need?</p>
<p>< tr >
< td > < a >...</p>
<p>Thanks</p>
| 10 | 2009-06-29T14:22:55Z | 1,058,693 | <p>As per the docs, you first make a parse tree:</p>
<pre><code>import BeautifulSoup
html = "<html><body><tr><td><a href='foo'/></td></tr></body></html>"
soup = BeautifulSoup.BeautifulSoup(html)
</code></pre>
<p>and then you search in it, for example for <code><a></code> tags whose immediate parent is a <code><td></code>:</p>
<pre><code>for ana in soup.findAll('a'):
if ana.parent.name == 'td':
print ana["href"]
</code></pre>
| 12 | 2009-06-29T14:37:27Z | [
"python",
"beautifulsoup"
] |
How do I select a random element from an array in Python? | 1,058,712 | <p>The first examples that I googled didn't work. This should be trivial, right?</p>
| 34 | 2009-06-29T14:42:22Z | 1,058,725 | <pre><code>import random
random.choice([1, 2, 3])
</code></pre>
| 20 | 2009-06-29T14:44:32Z | [
"python",
"arrays",
"random"
] |
How do I select a random element from an array in Python? | 1,058,712 | <p>The first examples that I googled didn't work. This should be trivial, right?</p>
| 34 | 2009-06-29T14:42:22Z | 1,058,727 | <pre><code>import random
random.choice (mylist)
</code></pre>
| 88 | 2009-06-29T14:44:38Z | [
"python",
"arrays",
"random"
] |
How do I select a random element from an array in Python? | 1,058,712 | <p>The first examples that I googled didn't work. This should be trivial, right?</p>
| 34 | 2009-06-29T14:42:22Z | 1,058,764 | <p>Here's the documentation link: <a href="http://docs.python.org/library/random.html#random.choice">http://docs.python.org/library/random.html#random.choice</a></p>
| 7 | 2009-06-29T14:50:57Z | [
"python",
"arrays",
"random"
] |
How to append two strings in Python? | 1,058,902 | <p>I have done this operation millions of times, just using the <code>+</code> operator! I have no idea why it is not working this time, it is overwriting the first part of the string with the new one! I have a list of strings and just want to concatenate them in one single string! If I run the program from Eclipse it works, from the command-line it doesn't!
The list is:</p>
<pre><code>["UNH+1+XYZ:08:2:1A+%CONVID%'&\r", "ORG+1A+77499505:PARAF0103+++A+FR:EUR++11730788+1A'&\r", "DUM'&\r", "FPT+CC::::::::N'&\r", "CCD+CA:123:123'&\r", "CPY+++AF'&\r", "MON+123:1.00:EUR'&\r", "UNT+8+1'\r"]
</code></pre>
<p>I want to discard the first and the last elements, the code is:</p>
<pre><code> ediMsg = ""
count = 1
print "extract_the_info, lineList ",lineList
print "extract_the_info, len(lineList) ",len(lineList)
while (count < (len(lineList)-1)):
temp = ""
# ediMsg = ediMsg+str(lineList[count])
# print "Count "+str(count)+" ediMsg ",ediMsg
print "line value : ",lineList[count]
temp = lineList[count]
ediMsg += " "+temp
print "ediMsg : ",ediMsg
count += 1
print "count ",count
</code></pre>
<p>Look at the output:</p>
<pre><code>extract_the_info, lineList ["UNH+1+TCCARQ:08:2:1A+%CONVID%'&\r", "ORG+1A+77499505:PARAF0103+++A+FR:EUR++11730788+1A'&\r", "DUM'&\r", "FPT+CC::::::::N'&\r", "CCD+CA:123:123'&\r", "CPY+++AF'&\r", "MON+123:1.00:EUR'&\r", "UNT+8+1'\r"]
extract_the_info, len(lineList) 8
line value : ORG+1A+77499505:PARAF0103+++A+FR:EUR++11730788+1A'&
ediMsg : ORG+1A+77499505:PARAF0103+++A+FR:EUR++11730788+1A'&
count 2
line value : DUM'&
DUM'& : ORG+1A+77499505:PARAF0103+++A+FR:EUR++11730788+1A'&
count 3
line value : FPT+CC::::::::N'&
FPT+CC::::::::N'&+1A+77499505:PARAF0103+++A+FR:EUR++11730788+1A'&
count 4
line value : CCD+CA:123:123'&
CCD+CA:123:123'&PARAF0103+++A+FR:EUR++11730788+1A'&
count 5
line value : CPY+++AF'&
CPY+++AF'&2839000000027:0450'&PARAF0103+++A+FR:EUR++11730788+1A'&
count 6
line value : MON+123:1.00:EUR'&
MON+123:1.00:EUR'&00027:0450'&PARAF0103+++A+FR:EUR++11730788+1A'&
count 7
MON+712:1.00:EUR'&00027:0450'&FR:EUR++11730788+1A'&
</code></pre>
<p>Why is it doing so!?</p>
| 2 | 2009-06-29T15:22:32Z | 1,058,922 | <p>You should use the following and forget about this nightmare:</p>
<pre><code>''.join(list_of_strings)
</code></pre>
| 19 | 2009-06-29T15:26:25Z | [
"python",
"string"
] |
How to append two strings in Python? | 1,058,902 | <p>I have done this operation millions of times, just using the <code>+</code> operator! I have no idea why it is not working this time, it is overwriting the first part of the string with the new one! I have a list of strings and just want to concatenate them in one single string! If I run the program from Eclipse it works, from the command-line it doesn't!
The list is:</p>
<pre><code>["UNH+1+XYZ:08:2:1A+%CONVID%'&\r", "ORG+1A+77499505:PARAF0103+++A+FR:EUR++11730788+1A'&\r", "DUM'&\r", "FPT+CC::::::::N'&\r", "CCD+CA:123:123'&\r", "CPY+++AF'&\r", "MON+123:1.00:EUR'&\r", "UNT+8+1'\r"]
</code></pre>
<p>I want to discard the first and the last elements, the code is:</p>
<pre><code> ediMsg = ""
count = 1
print "extract_the_info, lineList ",lineList
print "extract_the_info, len(lineList) ",len(lineList)
while (count < (len(lineList)-1)):
temp = ""
# ediMsg = ediMsg+str(lineList[count])
# print "Count "+str(count)+" ediMsg ",ediMsg
print "line value : ",lineList[count]
temp = lineList[count]
ediMsg += " "+temp
print "ediMsg : ",ediMsg
count += 1
print "count ",count
</code></pre>
<p>Look at the output:</p>
<pre><code>extract_the_info, lineList ["UNH+1+TCCARQ:08:2:1A+%CONVID%'&\r", "ORG+1A+77499505:PARAF0103+++A+FR:EUR++11730788+1A'&\r", "DUM'&\r", "FPT+CC::::::::N'&\r", "CCD+CA:123:123'&\r", "CPY+++AF'&\r", "MON+123:1.00:EUR'&\r", "UNT+8+1'\r"]
extract_the_info, len(lineList) 8
line value : ORG+1A+77499505:PARAF0103+++A+FR:EUR++11730788+1A'&
ediMsg : ORG+1A+77499505:PARAF0103+++A+FR:EUR++11730788+1A'&
count 2
line value : DUM'&
DUM'& : ORG+1A+77499505:PARAF0103+++A+FR:EUR++11730788+1A'&
count 3
line value : FPT+CC::::::::N'&
FPT+CC::::::::N'&+1A+77499505:PARAF0103+++A+FR:EUR++11730788+1A'&
count 4
line value : CCD+CA:123:123'&
CCD+CA:123:123'&PARAF0103+++A+FR:EUR++11730788+1A'&
count 5
line value : CPY+++AF'&
CPY+++AF'&2839000000027:0450'&PARAF0103+++A+FR:EUR++11730788+1A'&
count 6
line value : MON+123:1.00:EUR'&
MON+123:1.00:EUR'&00027:0450'&PARAF0103+++A+FR:EUR++11730788+1A'&
count 7
MON+712:1.00:EUR'&00027:0450'&FR:EUR++11730788+1A'&
</code></pre>
<p>Why is it doing so!?</p>
| 2 | 2009-06-29T15:22:32Z | 1,058,952 | <p>I just gave it a quick look. It seems your problem arises when you are printing the text. I haven't done such things for a long time, but probably you only get the last line when you print. If you check the actual variable, I'm sure you'll find that the value is correct.</p>
<p>By last line, I'm talking about the \r you got in the text strings.</p>
| 5 | 2009-06-29T15:32:06Z | [
"python",
"string"
] |
How to append two strings in Python? | 1,058,902 | <p>I have done this operation millions of times, just using the <code>+</code> operator! I have no idea why it is not working this time, it is overwriting the first part of the string with the new one! I have a list of strings and just want to concatenate them in one single string! If I run the program from Eclipse it works, from the command-line it doesn't!
The list is:</p>
<pre><code>["UNH+1+XYZ:08:2:1A+%CONVID%'&\r", "ORG+1A+77499505:PARAF0103+++A+FR:EUR++11730788+1A'&\r", "DUM'&\r", "FPT+CC::::::::N'&\r", "CCD+CA:123:123'&\r", "CPY+++AF'&\r", "MON+123:1.00:EUR'&\r", "UNT+8+1'\r"]
</code></pre>
<p>I want to discard the first and the last elements, the code is:</p>
<pre><code> ediMsg = ""
count = 1
print "extract_the_info, lineList ",lineList
print "extract_the_info, len(lineList) ",len(lineList)
while (count < (len(lineList)-1)):
temp = ""
# ediMsg = ediMsg+str(lineList[count])
# print "Count "+str(count)+" ediMsg ",ediMsg
print "line value : ",lineList[count]
temp = lineList[count]
ediMsg += " "+temp
print "ediMsg : ",ediMsg
count += 1
print "count ",count
</code></pre>
<p>Look at the output:</p>
<pre><code>extract_the_info, lineList ["UNH+1+TCCARQ:08:2:1A+%CONVID%'&\r", "ORG+1A+77499505:PARAF0103+++A+FR:EUR++11730788+1A'&\r", "DUM'&\r", "FPT+CC::::::::N'&\r", "CCD+CA:123:123'&\r", "CPY+++AF'&\r", "MON+123:1.00:EUR'&\r", "UNT+8+1'\r"]
extract_the_info, len(lineList) 8
line value : ORG+1A+77499505:PARAF0103+++A+FR:EUR++11730788+1A'&
ediMsg : ORG+1A+77499505:PARAF0103+++A+FR:EUR++11730788+1A'&
count 2
line value : DUM'&
DUM'& : ORG+1A+77499505:PARAF0103+++A+FR:EUR++11730788+1A'&
count 3
line value : FPT+CC::::::::N'&
FPT+CC::::::::N'&+1A+77499505:PARAF0103+++A+FR:EUR++11730788+1A'&
count 4
line value : CCD+CA:123:123'&
CCD+CA:123:123'&PARAF0103+++A+FR:EUR++11730788+1A'&
count 5
line value : CPY+++AF'&
CPY+++AF'&2839000000027:0450'&PARAF0103+++A+FR:EUR++11730788+1A'&
count 6
line value : MON+123:1.00:EUR'&
MON+123:1.00:EUR'&00027:0450'&PARAF0103+++A+FR:EUR++11730788+1A'&
count 7
MON+712:1.00:EUR'&00027:0450'&FR:EUR++11730788+1A'&
</code></pre>
<p>Why is it doing so!?</p>
| 2 | 2009-06-29T15:22:32Z | 1,058,957 | <p>While the two answers are correct (use " ".join()), your problem (besides <em>very</em> ugly python code) is this:</p>
<p>Your strings end in "\r", which is a carriage return. Everything is fine, but when you print to the console, "\r" will make printing continue from the start <em>of the same line</em>, hence overwrite what was written on that line so far.</p>
| 31 | 2009-06-29T15:32:26Z | [
"python",
"string"
] |
How to append two strings in Python? | 1,058,902 | <p>I have done this operation millions of times, just using the <code>+</code> operator! I have no idea why it is not working this time, it is overwriting the first part of the string with the new one! I have a list of strings and just want to concatenate them in one single string! If I run the program from Eclipse it works, from the command-line it doesn't!
The list is:</p>
<pre><code>["UNH+1+XYZ:08:2:1A+%CONVID%'&\r", "ORG+1A+77499505:PARAF0103+++A+FR:EUR++11730788+1A'&\r", "DUM'&\r", "FPT+CC::::::::N'&\r", "CCD+CA:123:123'&\r", "CPY+++AF'&\r", "MON+123:1.00:EUR'&\r", "UNT+8+1'\r"]
</code></pre>
<p>I want to discard the first and the last elements, the code is:</p>
<pre><code> ediMsg = ""
count = 1
print "extract_the_info, lineList ",lineList
print "extract_the_info, len(lineList) ",len(lineList)
while (count < (len(lineList)-1)):
temp = ""
# ediMsg = ediMsg+str(lineList[count])
# print "Count "+str(count)+" ediMsg ",ediMsg
print "line value : ",lineList[count]
temp = lineList[count]
ediMsg += " "+temp
print "ediMsg : ",ediMsg
count += 1
print "count ",count
</code></pre>
<p>Look at the output:</p>
<pre><code>extract_the_info, lineList ["UNH+1+TCCARQ:08:2:1A+%CONVID%'&\r", "ORG+1A+77499505:PARAF0103+++A+FR:EUR++11730788+1A'&\r", "DUM'&\r", "FPT+CC::::::::N'&\r", "CCD+CA:123:123'&\r", "CPY+++AF'&\r", "MON+123:1.00:EUR'&\r", "UNT+8+1'\r"]
extract_the_info, len(lineList) 8
line value : ORG+1A+77499505:PARAF0103+++A+FR:EUR++11730788+1A'&
ediMsg : ORG+1A+77499505:PARAF0103+++A+FR:EUR++11730788+1A'&
count 2
line value : DUM'&
DUM'& : ORG+1A+77499505:PARAF0103+++A+FR:EUR++11730788+1A'&
count 3
line value : FPT+CC::::::::N'&
FPT+CC::::::::N'&+1A+77499505:PARAF0103+++A+FR:EUR++11730788+1A'&
count 4
line value : CCD+CA:123:123'&
CCD+CA:123:123'&PARAF0103+++A+FR:EUR++11730788+1A'&
count 5
line value : CPY+++AF'&
CPY+++AF'&2839000000027:0450'&PARAF0103+++A+FR:EUR++11730788+1A'&
count 6
line value : MON+123:1.00:EUR'&
MON+123:1.00:EUR'&00027:0450'&PARAF0103+++A+FR:EUR++11730788+1A'&
count 7
MON+712:1.00:EUR'&00027:0450'&FR:EUR++11730788+1A'&
</code></pre>
<p>Why is it doing so!?</p>
| 2 | 2009-06-29T15:22:32Z | 1,058,974 | <p>The problem is not with the concatenation of the strings (although that could use some cleaning up), but in your printing. The \r in your string has a special meaning and will overwrite previously printed strings.</p>
<p>Use repr(), as such:</p>
<pre><code>...
print "line value : ", repr(lineList[count])
temp = lineList[count]
ediMsg += " "+temp
print "ediMsg : ", repr(ediMsg)
...
</code></pre>
<p>to print out your result, that will make sure any special characters doesn't mess up the output.</p>
| 11 | 2009-06-29T15:37:49Z | [
"python",
"string"
] |
How to append two strings in Python? | 1,058,902 | <p>I have done this operation millions of times, just using the <code>+</code> operator! I have no idea why it is not working this time, it is overwriting the first part of the string with the new one! I have a list of strings and just want to concatenate them in one single string! If I run the program from Eclipse it works, from the command-line it doesn't!
The list is:</p>
<pre><code>["UNH+1+XYZ:08:2:1A+%CONVID%'&\r", "ORG+1A+77499505:PARAF0103+++A+FR:EUR++11730788+1A'&\r", "DUM'&\r", "FPT+CC::::::::N'&\r", "CCD+CA:123:123'&\r", "CPY+++AF'&\r", "MON+123:1.00:EUR'&\r", "UNT+8+1'\r"]
</code></pre>
<p>I want to discard the first and the last elements, the code is:</p>
<pre><code> ediMsg = ""
count = 1
print "extract_the_info, lineList ",lineList
print "extract_the_info, len(lineList) ",len(lineList)
while (count < (len(lineList)-1)):
temp = ""
# ediMsg = ediMsg+str(lineList[count])
# print "Count "+str(count)+" ediMsg ",ediMsg
print "line value : ",lineList[count]
temp = lineList[count]
ediMsg += " "+temp
print "ediMsg : ",ediMsg
count += 1
print "count ",count
</code></pre>
<p>Look at the output:</p>
<pre><code>extract_the_info, lineList ["UNH+1+TCCARQ:08:2:1A+%CONVID%'&\r", "ORG+1A+77499505:PARAF0103+++A+FR:EUR++11730788+1A'&\r", "DUM'&\r", "FPT+CC::::::::N'&\r", "CCD+CA:123:123'&\r", "CPY+++AF'&\r", "MON+123:1.00:EUR'&\r", "UNT+8+1'\r"]
extract_the_info, len(lineList) 8
line value : ORG+1A+77499505:PARAF0103+++A+FR:EUR++11730788+1A'&
ediMsg : ORG+1A+77499505:PARAF0103+++A+FR:EUR++11730788+1A'&
count 2
line value : DUM'&
DUM'& : ORG+1A+77499505:PARAF0103+++A+FR:EUR++11730788+1A'&
count 3
line value : FPT+CC::::::::N'&
FPT+CC::::::::N'&+1A+77499505:PARAF0103+++A+FR:EUR++11730788+1A'&
count 4
line value : CCD+CA:123:123'&
CCD+CA:123:123'&PARAF0103+++A+FR:EUR++11730788+1A'&
count 5
line value : CPY+++AF'&
CPY+++AF'&2839000000027:0450'&PARAF0103+++A+FR:EUR++11730788+1A'&
count 6
line value : MON+123:1.00:EUR'&
MON+123:1.00:EUR'&00027:0450'&PARAF0103+++A+FR:EUR++11730788+1A'&
count 7
MON+712:1.00:EUR'&00027:0450'&FR:EUR++11730788+1A'&
</code></pre>
<p>Why is it doing so!?</p>
| 2 | 2009-06-29T15:22:32Z | 1,058,982 | <p>'\r' is the carriage return character. When you're printing out a string, a '\r' will cause the next characters to go at the start of the line.</p>
<p>Change this:</p>
<pre><code>print "ediMsg : ",ediMsg
</code></pre>
<p>to:</p>
<pre><code>print "ediMsg : ",repr(ediMsg)
</code></pre>
<p>and you will see the embedded <code>\r</code> values.</p>
<p>And while your code works, <em>please</em> change it to the one-liner:</p>
<pre><code>ediMsg = ' '.join(lineList[1:-1])
</code></pre>
| 8 | 2009-06-29T15:39:59Z | [
"python",
"string"
] |
How to append two strings in Python? | 1,058,902 | <p>I have done this operation millions of times, just using the <code>+</code> operator! I have no idea why it is not working this time, it is overwriting the first part of the string with the new one! I have a list of strings and just want to concatenate them in one single string! If I run the program from Eclipse it works, from the command-line it doesn't!
The list is:</p>
<pre><code>["UNH+1+XYZ:08:2:1A+%CONVID%'&\r", "ORG+1A+77499505:PARAF0103+++A+FR:EUR++11730788+1A'&\r", "DUM'&\r", "FPT+CC::::::::N'&\r", "CCD+CA:123:123'&\r", "CPY+++AF'&\r", "MON+123:1.00:EUR'&\r", "UNT+8+1'\r"]
</code></pre>
<p>I want to discard the first and the last elements, the code is:</p>
<pre><code> ediMsg = ""
count = 1
print "extract_the_info, lineList ",lineList
print "extract_the_info, len(lineList) ",len(lineList)
while (count < (len(lineList)-1)):
temp = ""
# ediMsg = ediMsg+str(lineList[count])
# print "Count "+str(count)+" ediMsg ",ediMsg
print "line value : ",lineList[count]
temp = lineList[count]
ediMsg += " "+temp
print "ediMsg : ",ediMsg
count += 1
print "count ",count
</code></pre>
<p>Look at the output:</p>
<pre><code>extract_the_info, lineList ["UNH+1+TCCARQ:08:2:1A+%CONVID%'&\r", "ORG+1A+77499505:PARAF0103+++A+FR:EUR++11730788+1A'&\r", "DUM'&\r", "FPT+CC::::::::N'&\r", "CCD+CA:123:123'&\r", "CPY+++AF'&\r", "MON+123:1.00:EUR'&\r", "UNT+8+1'\r"]
extract_the_info, len(lineList) 8
line value : ORG+1A+77499505:PARAF0103+++A+FR:EUR++11730788+1A'&
ediMsg : ORG+1A+77499505:PARAF0103+++A+FR:EUR++11730788+1A'&
count 2
line value : DUM'&
DUM'& : ORG+1A+77499505:PARAF0103+++A+FR:EUR++11730788+1A'&
count 3
line value : FPT+CC::::::::N'&
FPT+CC::::::::N'&+1A+77499505:PARAF0103+++A+FR:EUR++11730788+1A'&
count 4
line value : CCD+CA:123:123'&
CCD+CA:123:123'&PARAF0103+++A+FR:EUR++11730788+1A'&
count 5
line value : CPY+++AF'&
CPY+++AF'&2839000000027:0450'&PARAF0103+++A+FR:EUR++11730788+1A'&
count 6
line value : MON+123:1.00:EUR'&
MON+123:1.00:EUR'&00027:0450'&PARAF0103+++A+FR:EUR++11730788+1A'&
count 7
MON+712:1.00:EUR'&00027:0450'&FR:EUR++11730788+1A'&
</code></pre>
<p>Why is it doing so!?</p>
| 2 | 2009-06-29T15:22:32Z | 1,059,010 | <p>Your problem <strong>is</strong> printing, and it <strong>is not</strong> string manipulation. Try using '\n' as last char instead of '\r' in each string in:</p>
<pre><code>lineList = [
"UNH+1+TCCARQ:08:2:1A+%CONVID%'&\r",
"ORG+1A+77499505:PARAF0103+++A+FR:EUR++11730788+1A'&\r",
"DUM'&\r",
"FPT+CC::::::::N'&\r",
"CCD+CA:5132839000000027:0450'&\r",
"CPY+++AF'&\r",
"MON+712:1.00:EUR'&\r",
"UNT+8+1'\r"
]
</code></pre>
| 7 | 2009-06-29T15:44:39Z | [
"python",
"string"
] |
Mule vs ActiveMQ for Python | 1,058,986 | <p>I need to manged several servers, network services, appalication server (Apache, Tomcat) and manage them (start stop, install software).</p>
<p>I would like to use Python, since C++ seems to complex and less productive for thing task. In am not sure which middleware to use. ActiveMQ and Mule seem to be a good choice, although written in Java. I understand better ActiveMQ and I know very little about ESB.</p>
<p>Any advice? Any option for Python?</p>
<p>I saw that there is beanstalk, but is too simple and unflexible. I need a messageing system for the coordination, plus a way to send tar.gz file to the server (software packages).</p>
<p>I was there was a messsaging solution native in Python.</p>
| -1 | 2009-06-29T15:40:41Z | 1,059,225 | <p><strong>An example python "script" that manages various services on multiple remote servers:</strong></p>
<p>What follows is a hacked together script that can be used to manage various services on servers that you have SSH access to.</p>
<p>You will ideally want to have an ssh-agent running, or you will be typing your passphrase a lot of times.</p>
<p>For commands that require elevated privileges on the remote machine, you can see that "sudo" is called. This means that you need to modify your sudoers file on each remote machine, and add entries like this (assuming your username == <code>deploy</code>):</p>
<pre><code>Defaults:deploy !requiretty
Defaults:deploy !authenticate
deploy ALL=\
/sbin/service httpd status,\
/sbin/service httpd configtest,\
/sbin/service httpd graceful
</code></pre>
<p>The first two lines allow the <code>deploy</code> user to run <code>sudo</code> without having a tty or re-typing the password -- which means it can be run straight over ssh without any further input. Here is an example python command to take advantage of <code>sudo</code> on a remote:</p>
<pre><code>CommandResult = subprocess.call(('ssh', UH, 'sudo /sbin/service httpd graceful'))
</code></pre>
<p>Anyway, this is not a "straight" answer to your question, but rather an illustration of how easy you can use python and a couple of other techniques to create a systems management tool that is 100% tailored to your specific needs.</p>
<p>And by the way, the following script does "tell you loud and clear" if any of the commands returned an exit status > 0, so you can analyze the output yourself. </p>
<p><sup>This was hacked together when a project I was working with started using a load balancer and it was no longer equitable to run all the commands on each server. You could modify or extend this to work with rsync to deploy files, or even deploy updates to the scripts that you host on the remote servers to "do the work". </sup></p>
<pre><code>#!/usr/bin/python
from optparse import OptionParser
import subprocess
import sys
def die(sMessage):
print
print sMessage
print
sys.exit(2)
###################################################################################################
# Settings
# The user@host: for the SourceURLs (NO TRAILING SLASH)
RemoteUsers = [
"deploy@ac10.example.com",
"deploy@ac11.example.com",
]
###################################################################################################
# Global Variables
# optparse.Parser instance
Parser = None
# optparse.Values instance full of command line options
Opt = None
# List of command line arguments
Arg = None
###################################################################################################
Parser = OptionParser(usage="%prog [options] [Command[, Subcommand]]")
Parser.add_option("--interactive",
dest = "Interactive",
action = "store_true",
default = False,
help = "Ask before doing each operation."
)
# Parse command line
Opt, Arg = Parser.parse_args()
def HelpAndExit():
print "This command is used to run commands on the application servers."
print
print "Usage:"
print " deploy-control [--interactive] Command"
print
print "Options:"
print " --interactive :: will ask before executing each operation"
print
print "Servers:"
for s in RemoteUsers: print " " + s
print
print "Web Server Commands:"
print " deploy-control httpd status"
print " deploy-control httpd configtest"
print " deploy-control httpd graceful"
print " deploy-control loadbalancer in"
print " deploy-control loadbalancer out"
print
print "App Server Commands:"
print " deploy-control 6x6server status"
print " deploy-control 6x6server stop"
print " deploy-control 6x6server start"
print " deploy-control 6x6server status"
print " deploy-control wb4server stop"
print " deploy-control wb4server start"
print " deploy-control wb4server restart"
print " deploy-control wb4server restart"
print
print "System Commands:"
print " deploy-control disk usage"
print " deploy-control uptime"
print
sys.exit(2)
def YesNo(sPrompt):
while True:
s = raw_input(sPrompt)
if s in ('y', 'yes'):
return True
elif s in ('n', 'no'):
return False
else:
print "Invalid input!"
# Implicitly verified below in if/else
Command = tuple(Arg)
if Command in (('help',), ()):
HelpAndExit()
ResultList = []
###################################################################################################
for UH in RemoteUsers:
print "-"*80
print "Running %s command on: %s" % (Command, UH)
if Opt.Interactive and not YesNo("Do you want to run this command? "):
print "Skipping!"
print
continue
#----------------------------------------------------------------------------------------------
if Command == ('httpd', 'configtest'):
CommandResult = subprocess.call(('ssh', UH, 'sudo /sbin/service httpd configtest'))
#----------------------------------------------------------------------------------------------
elif Command == ('httpd', 'graceful'):
CommandResult = subprocess.call(('ssh', UH, 'sudo /sbin/service httpd graceful'))
#----------------------------------------------------------------------------------------------
elif Command == ('httpd', 'status'):
CommandResult = subprocess.call(('ssh', UH, 'sudo /sbin/service httpd status'))
#----------------------------------------------------------------------------------------------
elif Command == ('loadbalancer', 'in'):
CommandResult = subprocess.call(('ssh', UH, 'bin-slave/loadbalancer-in'))
#----------------------------------------------------------------------------------------------
elif Command == ('loadbalancer', 'out'):
CommandResult = subprocess.call(('ssh', UH, 'bin-slave/loadbalancer-out'))
#----------------------------------------------------------------------------------------------
elif Command == ('disk', 'usage'):
CommandResult = subprocess.call(('ssh', UH, 'df -h'))
#----------------------------------------------------------------------------------------------
elif Command == ('uptime',):
CommandResult = subprocess.call(('ssh', UH, 'uptime'))
#----------------------------------------------------------------------------------------------
elif Command == ('6x6server', 'status'):
CommandResult = subprocess.call(('ssh', UH, 'bin-slave/6x6server-status'))
if CommandResult > 0:
print "Servers not running!!!"
#----------------------------------------------------------------------------------------------
elif Command == ('6x6server', 'stop'):
CommandResult = subprocess.call(('ssh', UH, 'bin-slave/6x6server-stop'))
#----------------------------------------------------------------------------------------------
elif Command == ('6x6server', 'start'):
CommandResult = subprocess.call(('ssh', UH, 'bin-slave/6x6server-start'))
#----------------------------------------------------------------------------------------------
elif Command == ('6x6server', 'restart'):
CommandResult = subprocess.call(('ssh', UH, 'bin-slave/6x6server-restart'))
#----------------------------------------------------------------------------------------------
elif Command == ('wb4server', 'status'):
CommandResult = subprocess.call(('ssh', UH, 'bin-slave/wb4server-status'))
if CommandResult > 0:
print "Servers not running!!!"
#----------------------------------------------------------------------------------------------
elif Command == ('wb4server', 'stop'):
CommandResult = subprocess.call(('ssh', UH, 'bin-slave/wb4server-stop'))
#----------------------------------------------------------------------------------------------
elif Command == ('wb4server', 'start'):
CommandResult = subprocess.call(('ssh', UH, 'bin-slave/wb4server-start'))
#----------------------------------------------------------------------------------------------
elif Command == ('wb4server', 'restart'):
CommandResult = subprocess.call(('ssh', UH, 'bin-slave/wb4server-restart'))
#----------------------------------------------------------------------------------------------
else:
print
print "#"*80
print
print "Error: invalid command"
print
HelpAndExit()
#----------------------------------------------------------------------------------------------
ResultList.append(CommandResult)
print
###################################################################################################
if any(ResultList):
print "#"*80
print "#"*80
print "#"*80
print
print "ERRORS FOUND. SEE ABOVE"
print
sys.exit(0)
else:
print "-"*80
print
print "Looks OK!"
print
sys.exit(1)
</code></pre>
| 1 | 2009-06-29T16:29:14Z | [
"python",
"messaging"
] |
wxPython RichTextCtrl much slower than tkInter Text? | 1,059,214 | <p>I've made a small tool that parses a chunk of text, does some simple processing (retrieves values from a dictionary, a few regex, etc.) and then spits the results.</p>
<p>In order to make easier to read the results, I made two graphic ports, one with tkInter and other with wxPython, so the output is nicely displayed in a Text Area with some words having different colours.</p>
<p>The tkInter implementation uses <code>Tkinter.Text</code> object and to apply the colours to the words uses tags (configured with the method <code>Tkinter.Text.tag_config</code> and passing them to <code>Tkinter.Text.insert</code>), and the measured while outputting about 400 different coloured words is < 0.02s.</p>
<p>The wxPython implementation uses <code>wx.richtext.RichTextCtrl</code> and to apply the colours to the words uses <code>wx.richtext.RichTextCtrl.BeginTextColour</code> and then <code>wx.richtext.RichTextCtrl.AppendText</code>; the performance is ridiculous, it takes abut 1.4s to do the same job that only took 0.02s to the tkInter port.</p>
<p>Is this an intrinsic problem of the RichTextCtrl widget, the wxPython bindings, or there is some way to speed it up?</p>
<p>Thanks!</p>
| 0 | 2009-06-29T16:26:18Z | 1,070,836 | <p>It kind of avoids the question slightly, but could you use wxStyledTextCtrl instead?</p>
| 0 | 2009-07-01T19:14:24Z | [
"python",
"performance",
"wxpython",
"tkinter",
"richtextediting"
] |
wxPython RichTextCtrl much slower than tkInter Text? | 1,059,214 | <p>I've made a small tool that parses a chunk of text, does some simple processing (retrieves values from a dictionary, a few regex, etc.) and then spits the results.</p>
<p>In order to make easier to read the results, I made two graphic ports, one with tkInter and other with wxPython, so the output is nicely displayed in a Text Area with some words having different colours.</p>
<p>The tkInter implementation uses <code>Tkinter.Text</code> object and to apply the colours to the words uses tags (configured with the method <code>Tkinter.Text.tag_config</code> and passing them to <code>Tkinter.Text.insert</code>), and the measured while outputting about 400 different coloured words is < 0.02s.</p>
<p>The wxPython implementation uses <code>wx.richtext.RichTextCtrl</code> and to apply the colours to the words uses <code>wx.richtext.RichTextCtrl.BeginTextColour</code> and then <code>wx.richtext.RichTextCtrl.AppendText</code>; the performance is ridiculous, it takes abut 1.4s to do the same job that only took 0.02s to the tkInter port.</p>
<p>Is this an intrinsic problem of the RichTextCtrl widget, the wxPython bindings, or there is some way to speed it up?</p>
<p>Thanks!</p>
| 0 | 2009-06-29T16:26:18Z | 1,189,222 | <p>I'm copying here the comment that solved the problem:</p>
<blockquote>
<p>Have you tried using Freeze() and
Thaw() to only update the display
after you are done appending the
coloured text? â mghie Jun 30 at 7:20</p>
</blockquote>
| 1 | 2009-07-27T16:32:18Z | [
"python",
"performance",
"wxpython",
"tkinter",
"richtextediting"
] |
Searching across multiple tables (best practices) | 1,059,253 | <p>I have property management application consisting of tables:</p>
<pre><code>tenants
landlords
units
properties
vendors-contacts
</code></pre>
<p>Basically I want one search field to search them all rather than having to select which category I am searching. Would this be an acceptable solution (technology wise?)</p>
<p>Will searching across 5 tables be OK in the long run and not bog down the server? What's the best way of accomplishing this?</p>
<p>Using PostgreSQL</p>
| 2 | 2009-06-29T16:36:05Z | 1,059,280 | <p>Why not create a view which is a union of the tables which aggregates the columns you want to search on into one, and then search on that aggregated column?</p>
<p>You could do something like this:</p>
<pre><code>select 'tenants:' + ltrim(str(t.Id)), <shared fields> from Tenants as t union
select 'landlords:' + ltrim(str(l.Id)), <shared fields> from Tenants as l union
...
</code></pre>
<p>This requires some logic to be embedded from the client querying; it has to know how to fabricate the key that it's looking for in order to search on a <em>single</em> field.</p>
<p>That said, it's probably better if you just have a separate column which contains a "type" value (e.g. landlord, tenant) and then filter on both the type and the ID, as it will be computationally less expensive (and can be optimized better).</p>
| 7 | 2009-06-29T16:42:14Z | [
"python",
"sql",
"mysql",
"postgresql",
"pylons"
] |
Searching across multiple tables (best practices) | 1,059,253 | <p>I have property management application consisting of tables:</p>
<pre><code>tenants
landlords
units
properties
vendors-contacts
</code></pre>
<p>Basically I want one search field to search them all rather than having to select which category I am searching. Would this be an acceptable solution (technology wise?)</p>
<p>Will searching across 5 tables be OK in the long run and not bog down the server? What's the best way of accomplishing this?</p>
<p>Using PostgreSQL</p>
| 2 | 2009-06-29T16:36:05Z | 1,059,284 | <p>You should be fine, and there's really no other good (easy) way to do this. Just make sure the fields you are searching on are properly indexed though.</p>
| 1 | 2009-06-29T16:42:44Z | [
"python",
"sql",
"mysql",
"postgresql",
"pylons"
] |
Searching across multiple tables (best practices) | 1,059,253 | <p>I have property management application consisting of tables:</p>
<pre><code>tenants
landlords
units
properties
vendors-contacts
</code></pre>
<p>Basically I want one search field to search them all rather than having to select which category I am searching. Would this be an acceptable solution (technology wise?)</p>
<p>Will searching across 5 tables be OK in the long run and not bog down the server? What's the best way of accomplishing this?</p>
<p>Using PostgreSQL</p>
| 2 | 2009-06-29T16:36:05Z | 1,059,286 | <p>You want to use <a href="http://www.postgresql.org/docs/8.3/static/textsearch.html" rel="nofollow">the built-in full text search</a> or a separate product like <a href="http://lucene.apache.org/java/docs/" rel="nofollow">Lucene</a>. This is optimised for unstructured searches over heterogeneous data.</p>
<p>Also, don't forget that normal indices cannot be used for <code>something LIKE '%...%'</code>. Using a full text search engine will also be able to do efficient substring searches.</p>
| 4 | 2009-06-29T16:43:21Z | [
"python",
"sql",
"mysql",
"postgresql",
"pylons"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.