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 list |
|---|---|---|---|---|---|---|---|---|---|
How to find a thread id in Python | 919,897 | <p>I have a multi-threading Python program, and a utility function, writeLog(message), that writes out a timestamp followed by the message. Unfortunately, the resultant log file gives no indication of which thread is generating which message. </p>
<p>I would like writeLog() to be able to add something to the message to identify which thread is calling it. Obviously I could just make the threads pass this information in, but that would be a lot more work. Is there some thread equivalent of os.getpid() that I could use?</p>
| 68 | 2009-05-28T09:04:24Z | 30,930,569 | <p>I created multiple threads in python, I printed the thread objects, I printed the id using <code>ident</code> variable. I see all the ids are same,</p>
<pre><code><Thread(Thread-1, stopped 140500807628544)>
<Thread(Thread-2, started 140500807628544)>
<Thread(Thread-3, started 140500807628544)>
</code></pre>
| 1 | 2015-06-19T05:31:39Z | [
"python",
"multithreading"
] |
In python, how can you unload generated classes | 919,924 | <p>I am working on a library that loads files (hfd5 - pytables) into an object structure. The actual classes being used for the structure is loaded as a string from the hdf5 file, and then
loaded in this fashion:</p>
<pre><code>class NamespaceHolder(dict):
# stmt is the source code holding all the class defs
def execute(self, stmt):
exec stmt in self
</code></pre>
<p>The problem is, loading multiple classes like this, causes objects to appear in the uncollectible part of the garbage collection, namely the actual class definitions. I can also load this into a global dictionary, but the problem remains of orphaned classes. Is there any way to unload the classes?</p>
<p>The main problem is the class.<strong>mro</strong> attribute, which contains a reference back to the class itself, causing circular references that the garbage collector can't handle.</p>
<p>Here is a small test case to see for yourselves:</p>
<pre><code>import gc
if __name__ == "__main__":
gc.enable()
gc.set_debug(gc.DEBUG_LEAK)
code = """
class DummyA(object):
pass
"""
context = {}
exec code in context
exec code in context
gc.collect()
print len(gc.garbage)
</code></pre>
<p>Just a note: I have already argued against using parsing off text in a file for creating classes earlier, but apparently they are set on using it here and see some benefits I don't, so going away from this solution isn't feasible now.</p>
| 1 | 2009-05-28T09:12:55Z | 920,013 | <p>I think the GC can cope with circular references, however you'll need to do is remove the reference from the globals() dict:</p>
<pre><code>try:
del globals()['DummyA']
except KeyError:
pass
</code></pre>
<p>otherwise there will be a non-circular reference to the class object that will stop it being cleaned up.</p>
| 1 | 2009-05-28T09:37:32Z | [
"python",
"dynamic",
"garbage-collection",
"classloader"
] |
In python, how can you unload generated classes | 919,924 | <p>I am working on a library that loads files (hfd5 - pytables) into an object structure. The actual classes being used for the structure is loaded as a string from the hdf5 file, and then
loaded in this fashion:</p>
<pre><code>class NamespaceHolder(dict):
# stmt is the source code holding all the class defs
def execute(self, stmt):
exec stmt in self
</code></pre>
<p>The problem is, loading multiple classes like this, causes objects to appear in the uncollectible part of the garbage collection, namely the actual class definitions. I can also load this into a global dictionary, but the problem remains of orphaned classes. Is there any way to unload the classes?</p>
<p>The main problem is the class.<strong>mro</strong> attribute, which contains a reference back to the class itself, causing circular references that the garbage collector can't handle.</p>
<p>Here is a small test case to see for yourselves:</p>
<pre><code>import gc
if __name__ == "__main__":
gc.enable()
gc.set_debug(gc.DEBUG_LEAK)
code = """
class DummyA(object):
pass
"""
context = {}
exec code in context
exec code in context
gc.collect()
print len(gc.garbage)
</code></pre>
<p>Just a note: I have already argued against using parsing off text in a file for creating classes earlier, but apparently they are set on using it here and see some benefits I don't, so going away from this solution isn't feasible now.</p>
| 1 | 2009-05-28T09:12:55Z | 920,539 | <p>The gc.set_debug(gc.DEBUG_LEAK) causes the leak. Try this:</p>
<pre><code>import gc
def foo():
code = """
class DummyA(object):
pass
"""
context = {}
exec code in context
exec code in context
gc.collect()
print len(gc.garbage), len(gc.get_objects())
gc.enable()
foo(); foo() # amount of objects doesn't increase
gc.set_debug(gc.DEBUG_LEAK)
foo() # leaks
</code></pre>
| 1 | 2009-05-28T12:07:44Z | [
"python",
"dynamic",
"garbage-collection",
"classloader"
] |
Stuck on official Django Tutorial | 919,927 | <p>I am just started out learning Python and also started looking into Django a little bit. So I copied this piece of code from the tutorial:</p>
<pre><code> # Create your models here.
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.question
def was_published_today(self):
return self.pub_date.date() == datetime.date.today()
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
def ___unicode__(self):
return self.choice #shouldn't this return the choice
</code></pre>
<p>When I play around with it in the shell, I just get the "question" of the Poll object, but for some reason it won't return of the "choice" of the Choice objects. I fail to see the difference. My output on the shell looks like this:</p>
<pre><code>>>> Poll.objects.all()
[<Poll: What is up?>]
>>> Choice.objects.all()
[<Choice: Choice object>, <Choice: Choice object>, <Choice: Choice object>]
>>>
</code></pre>
<p>I was expecting for the Choice objects to return something else than "Choice object". Does anybody have an idea about where I failed and what I should look into?</p>
<p>EDIT: Way to make me feel like an idiot. Yes, the three underscores were the problem. I was looking at that for about an hour now.</p>
| 3 | 2009-05-28T09:13:27Z | 919,945 | <p>You have three underscores before "unicode__" on the Choice class, it should be only two like in your Poll class, like this:</p>
<pre><code>def __unicode__(self):
return u'%s' % self.choice
</code></pre>
| 8 | 2009-05-28T09:18:32Z | [
"python",
"django"
] |
Stuck on official Django Tutorial | 919,927 | <p>I am just started out learning Python and also started looking into Django a little bit. So I copied this piece of code from the tutorial:</p>
<pre><code> # Create your models here.
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.question
def was_published_today(self):
return self.pub_date.date() == datetime.date.today()
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
def ___unicode__(self):
return self.choice #shouldn't this return the choice
</code></pre>
<p>When I play around with it in the shell, I just get the "question" of the Poll object, but for some reason it won't return of the "choice" of the Choice objects. I fail to see the difference. My output on the shell looks like this:</p>
<pre><code>>>> Poll.objects.all()
[<Poll: What is up?>]
>>> Choice.objects.all()
[<Choice: Choice object>, <Choice: Choice object>, <Choice: Choice object>]
>>>
</code></pre>
<p>I was expecting for the Choice objects to return something else than "Choice object". Does anybody have an idea about where I failed and what I should look into?</p>
<p>EDIT: Way to make me feel like an idiot. Yes, the three underscores were the problem. I was looking at that for about an hour now.</p>
| 3 | 2009-05-28T09:13:27Z | 919,949 | <p>Your Unicode method has too many underscores. It should read:</p>
<pre><code>def __unicode__(self):
return u'%s' % self.choice
</code></pre>
| 4 | 2009-05-28T09:19:25Z | [
"python",
"django"
] |
Stuck on official Django Tutorial | 919,927 | <p>I am just started out learning Python and also started looking into Django a little bit. So I copied this piece of code from the tutorial:</p>
<pre><code> # Create your models here.
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.question
def was_published_today(self):
return self.pub_date.date() == datetime.date.today()
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
def ___unicode__(self):
return self.choice #shouldn't this return the choice
</code></pre>
<p>When I play around with it in the shell, I just get the "question" of the Poll object, but for some reason it won't return of the "choice" of the Choice objects. I fail to see the difference. My output on the shell looks like this:</p>
<pre><code>>>> Poll.objects.all()
[<Poll: What is up?>]
>>> Choice.objects.all()
[<Choice: Choice object>, <Choice: Choice object>, <Choice: Choice object>]
>>>
</code></pre>
<p>I was expecting for the Choice objects to return something else than "Choice object". Does anybody have an idea about where I failed and what I should look into?</p>
<p>EDIT: Way to make me feel like an idiot. Yes, the three underscores were the problem. I was looking at that for about an hour now.</p>
| 3 | 2009-05-28T09:13:27Z | 919,951 | <p>Change:</p>
<pre><code>class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
def ___unicode__(self):
return self.choice #shouldn't this return the choice
</code></pre>
<p>To:</p>
<pre><code>class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
def __unicode__(self):
return self.choice #shouldn't this return the choice
</code></pre>
<p>You had too many underscores in the second <code>__unicode__</code> definition</p>
| 3 | 2009-05-28T09:20:03Z | [
"python",
"django"
] |
Stuck on official Django Tutorial | 919,927 | <p>I am just started out learning Python and also started looking into Django a little bit. So I copied this piece of code from the tutorial:</p>
<pre><code> # Create your models here.
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.question
def was_published_today(self):
return self.pub_date.date() == datetime.date.today()
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
def ___unicode__(self):
return self.choice #shouldn't this return the choice
</code></pre>
<p>When I play around with it in the shell, I just get the "question" of the Poll object, but for some reason it won't return of the "choice" of the Choice objects. I fail to see the difference. My output on the shell looks like this:</p>
<pre><code>>>> Poll.objects.all()
[<Poll: What is up?>]
>>> Choice.objects.all()
[<Choice: Choice object>, <Choice: Choice object>, <Choice: Choice object>]
>>>
</code></pre>
<p>I was expecting for the Choice objects to return something else than "Choice object". Does anybody have an idea about where I failed and what I should look into?</p>
<p>EDIT: Way to make me feel like an idiot. Yes, the three underscores were the problem. I was looking at that for about an hour now.</p>
| 3 | 2009-05-28T09:13:27Z | 919,953 | <p>The official Django book is a bit outdated. But the comments to the paragraphs are really useful. It should be two underscores:</p>
<pre><code>___unicode__(self):
</code></pre>
<p>should be <code>__unicode__(self):</code></p>
| 2 | 2009-05-28T09:20:44Z | [
"python",
"django"
] |
Different behavior of python logging module when using mod_python | 919,990 | <p>We have a nasty problem where we see that the python logging module is behaving differently when running with mod_python on our servers. When executing the same code in the shell, or in django with the runserver command or with mod_wsgi, the behavior is correct:</p>
<pre><code>import logging
logger = logging.getLogger('site-errors')
logging.debug('logger=%s' % (logger.__dict__))
logging.debug('logger.parent=%s' % (logger.parent.__dict__))
logger.error('some message that is not logged.')
</code></pre>
<p>We then the following logging:</p>
<blockquote>
<p>2009-05-28 10:36:43,740,DEBUG,error_middleware.py:31,[logger={'name': 'site-errors', 'parent': <logging.RootLogger instance at 0x85f8aac>, 'handlers': [], 'level': 0, 'disabled': 0, 'manager': <logging.Manager instance at 0x85f8aec>, 'propagate': 1, 'filters': []}] </p>
<p>2009-05-28 10:36:43,740,DEBUG,error_middleware.py:32,[logger.parent={'name':
'root', 'parent': None, 'handlers':
[<logging.StreamHandler instance at
0x8ec612c>,
<logging.handlers.RotatingFileHandler
instance at 0x8ec616c>], 'level': 10,
'disabled': 0, 'propagate': 1,
'filters': []}]</p>
</blockquote>
<p>As one can see, no handlers or level is set for the child logger 'site-errors'.</p>
<p>The logging configuration is done in the settings.py:</p>
<pre><code>MONITOR_LOGGING_CONFIG = ROOT + 'error_monitor_logging.conf'
import logging
import logging.config
logging.config.fileConfig(MONITOR_LOGGING_CONFIG)
if CONFIG == CONFIG_DEV:
DB_LOGLEVEL = logging.INFO
else:
DB_LOGLEVEL = logging.WARNING
</code></pre>
<p>The second problem is that we also add a custom handler in the __init__.py that resides that in the folder as error_middleware.py:</p>
<pre><code>import logging
from django.conf import settings
from db_log_handler import DBLogHandler
handler = DBLogHandler()
handler.setLevel(settings.DB_LOGLEVEL)
logging.root.addHandler(handler)
</code></pre>
<p>The custom handler cannot be seen in the logging!</p>
<p>If someone has idea where the problem lies, please let us know! Don't hesistate to ask for additonal information. That will certainly help to solve the problem.</p>
| 1 | 2009-05-28T09:31:42Z | 920,113 | <p>It may be better if you do not configure logging in <code>settings.py</code>.</p>
<p>We configure your logging in our root <code>urls.py</code>. This seems to work out better. I haven't read enough Django source to know why, precisely, it's better, but it's working out well for us. I would add custom handlers here, also. </p>
<p>Also, look closely at <a href="http://code.google.com/p/modwsgi/" rel="nofollow">mod_wsgi</a>. It seems to behave much better than mod_python.</p>
| 5 | 2009-05-28T10:04:46Z | [
"python",
"django",
"logging",
"mod-python"
] |
Different behavior of python logging module when using mod_python | 919,990 | <p>We have a nasty problem where we see that the python logging module is behaving differently when running with mod_python on our servers. When executing the same code in the shell, or in django with the runserver command or with mod_wsgi, the behavior is correct:</p>
<pre><code>import logging
logger = logging.getLogger('site-errors')
logging.debug('logger=%s' % (logger.__dict__))
logging.debug('logger.parent=%s' % (logger.parent.__dict__))
logger.error('some message that is not logged.')
</code></pre>
<p>We then the following logging:</p>
<blockquote>
<p>2009-05-28 10:36:43,740,DEBUG,error_middleware.py:31,[logger={'name': 'site-errors', 'parent': <logging.RootLogger instance at 0x85f8aac>, 'handlers': [], 'level': 0, 'disabled': 0, 'manager': <logging.Manager instance at 0x85f8aec>, 'propagate': 1, 'filters': []}] </p>
<p>2009-05-28 10:36:43,740,DEBUG,error_middleware.py:32,[logger.parent={'name':
'root', 'parent': None, 'handlers':
[<logging.StreamHandler instance at
0x8ec612c>,
<logging.handlers.RotatingFileHandler
instance at 0x8ec616c>], 'level': 10,
'disabled': 0, 'propagate': 1,
'filters': []}]</p>
</blockquote>
<p>As one can see, no handlers or level is set for the child logger 'site-errors'.</p>
<p>The logging configuration is done in the settings.py:</p>
<pre><code>MONITOR_LOGGING_CONFIG = ROOT + 'error_monitor_logging.conf'
import logging
import logging.config
logging.config.fileConfig(MONITOR_LOGGING_CONFIG)
if CONFIG == CONFIG_DEV:
DB_LOGLEVEL = logging.INFO
else:
DB_LOGLEVEL = logging.WARNING
</code></pre>
<p>The second problem is that we also add a custom handler in the __init__.py that resides that in the folder as error_middleware.py:</p>
<pre><code>import logging
from django.conf import settings
from db_log_handler import DBLogHandler
handler = DBLogHandler()
handler.setLevel(settings.DB_LOGLEVEL)
logging.root.addHandler(handler)
</code></pre>
<p>The custom handler cannot be seen in the logging!</p>
<p>If someone has idea where the problem lies, please let us know! Don't hesistate to ask for additonal information. That will certainly help to solve the problem.</p>
| 1 | 2009-05-28T09:31:42Z | 939,645 | <p>The problem is not solved by using mod_wsgi.</p>
<p>I could solve the problem by placing the complete configuration into one file. Mixing file and code configuration seems to create problems with apache (whether using mod_wsgi or mod_python).</p>
<p>To use a custom logging handler with file configuration, I had to do the following:</p>
<pre><code>import logging
import logging.config
logging.custhandlers = sitemonitoring.db_log_handler
logging.config.fileConfig(settings.MONITORING_FILE_CONFIG)
</code></pre>
<p>From the settings.py I cannot import the <code>sitemonitoring.db_log_handler</code>, so I have to place this code in the root <code>urls.py</code>.</p>
<p>In the config file, I refer to the <code>DBLogHandler</code> with the following statement</p>
<pre><code>[handler_db]
class=custhandlers.DBLogHandler()
level=ERROR
args=(,)
</code></pre>
<p>PS: Note that the <code>custhandler</code> 'attribute' is created dynamically and can have another name. This is an advantage of using a dynamic language.</p>
| 0 | 2009-06-02T13:45:13Z | [
"python",
"django",
"logging",
"mod-python"
] |
Different behavior of python logging module when using mod_python | 919,990 | <p>We have a nasty problem where we see that the python logging module is behaving differently when running with mod_python on our servers. When executing the same code in the shell, or in django with the runserver command or with mod_wsgi, the behavior is correct:</p>
<pre><code>import logging
logger = logging.getLogger('site-errors')
logging.debug('logger=%s' % (logger.__dict__))
logging.debug('logger.parent=%s' % (logger.parent.__dict__))
logger.error('some message that is not logged.')
</code></pre>
<p>We then the following logging:</p>
<blockquote>
<p>2009-05-28 10:36:43,740,DEBUG,error_middleware.py:31,[logger={'name': 'site-errors', 'parent': <logging.RootLogger instance at 0x85f8aac>, 'handlers': [], 'level': 0, 'disabled': 0, 'manager': <logging.Manager instance at 0x85f8aec>, 'propagate': 1, 'filters': []}] </p>
<p>2009-05-28 10:36:43,740,DEBUG,error_middleware.py:32,[logger.parent={'name':
'root', 'parent': None, 'handlers':
[<logging.StreamHandler instance at
0x8ec612c>,
<logging.handlers.RotatingFileHandler
instance at 0x8ec616c>], 'level': 10,
'disabled': 0, 'propagate': 1,
'filters': []}]</p>
</blockquote>
<p>As one can see, no handlers or level is set for the child logger 'site-errors'.</p>
<p>The logging configuration is done in the settings.py:</p>
<pre><code>MONITOR_LOGGING_CONFIG = ROOT + 'error_monitor_logging.conf'
import logging
import logging.config
logging.config.fileConfig(MONITOR_LOGGING_CONFIG)
if CONFIG == CONFIG_DEV:
DB_LOGLEVEL = logging.INFO
else:
DB_LOGLEVEL = logging.WARNING
</code></pre>
<p>The second problem is that we also add a custom handler in the __init__.py that resides that in the folder as error_middleware.py:</p>
<pre><code>import logging
from django.conf import settings
from db_log_handler import DBLogHandler
handler = DBLogHandler()
handler.setLevel(settings.DB_LOGLEVEL)
logging.root.addHandler(handler)
</code></pre>
<p>The custom handler cannot be seen in the logging!</p>
<p>If someone has idea where the problem lies, please let us know! Don't hesistate to ask for additonal information. That will certainly help to solve the problem.</p>
| 1 | 2009-05-28T09:31:42Z | 962,224 | <p>You don't appear to have posted all the relevant information - for example, where is your logging configuration file?</p>
<p>You say that:</p>
<blockquote>
<p>When executing the same code in the
shell, or in django with the runserver
command or with mod_wsgi, the behavior
is correct</p>
</blockquote>
<p>You don't make clear whether the logging output you showed is from one of these environments, or whether it's from a mod_python run. It doesn't look wrong - in your code you added handlers to the root, not to logger 'site-errors'. You also set a level on the handler, not the logger - so you wouldn't expect to see a level set for the 'site-errors' logger in the logging output, neh? Levels can be set on both loggers and handlers and they are not the same, though they filter out events in the same way.</p>
<p>The issue about custom handlers is easily explained if you look at the logging documentation for configuration, see</p>
<p><a href="http://docs.python.org/library/logging.html" rel="nofollow">http://docs.python.org/library/logging.html</a> (search for "the class entry indicates")</p>
<p>This explains that any handler class described in the configuration file is eval()'d in the logging packages namespace. So, by binding logging.custhandlers to your custom handlers module and then stating "custhandlers.MyCustomClass" in the config file, the eval() produces the expected result. You could just as well have done</p>
<p>logging.sitemonitoring = sitemonitoring</p>
<p>and specified the handler class as</p>
<p>sitemonitoring.db_log_handler.DBLogHandler</p>
<p>which would work just as well (as long as the db_log_handler subpackage has been imported already).</p>
<p>BTW the reason why people sometimes have problems configuring logging in settings.py is due to Django's import magic causing circular import problems. I generally configure logging in settings.py and it works fine unless you want to import certain bits of Django (e.g. in django.db - because the app import logic is in django.db, you can run into circular import issues if you try to import django.db.x in settings.py).</p>
| 0 | 2009-06-07T16:26:25Z | [
"python",
"django",
"logging",
"mod-python"
] |
Using cookies with python to store searches | 920,278 | <p>Hey i have a webpage for searching a database. i would like to be able to implement cookies using python to store what a user searches for and provide them with a recently searched field when they return. is there a way to implement this using the python Cookie library??</p>
| 0 | 2009-05-28T10:57:27Z | 920,727 | <p>Usually, we do the following.</p>
<ol>
<li><p>Use a framework.</p></li>
<li><p>Establish a session. Ideally, ask for a username of some kind. If you don't want to ask for names or anything, you can try to the browser's IP address as the key for the session (this can turn into a nightmare, but you can try it.)</p></li>
<li><p>Using the session identification (username or IP address), save the searches in a database on your server.</p></li>
<li><p>When the person logs in again, retrieve their query information from your local database.</p></li>
</ol>
<p>Moral of the story. Don't trust the cookie to have anything it but session identification. And even then, it will get hijacked either on purpose or accidentally.</p>
<ul>
<li><p>Intentional hijacking is the way one person poses as another.</p></li>
<li><p>Accident hijacking occurs when multiple people share the same IP address (because they share the same computer).</p></li>
</ul>
| 1 | 2009-05-28T13:04:36Z | [
"python",
"cookies"
] |
Using cookies with python to store searches | 920,278 | <p>Hey i have a webpage for searching a database. i would like to be able to implement cookies using python to store what a user searches for and provide them with a recently searched field when they return. is there a way to implement this using the python Cookie library??</p>
| 0 | 2009-05-28T10:57:27Z | 921,746 | <p>To use cookies you can use whichever API for cookies your framework is using.</p>
<p>Here's a <a href="http://cherrypy.org/" rel="nofollow">CherryPy</a> full working example for doing what you want, store searches and provide them later.</p>
<pre><code>import cherrypy
import json
class Root(object):
def index(self):
last_search = cherrypy.request.cookie.get('terms', None)
if last_search:
last_search = ','.join(json.loads(last_search.value))
else:
last_search = 'None'
return """
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>Search</title>
</head>
<body>
<h1>Search</h1>
<form action="do_search" method="get">
<p>Please type your search terms:
<input type="text" name="query" /></p>
<p>Hint: Last 5 used terms: %s</p>
<p><input type="submit" value="Search &rarr;" /></p>
</form>
</body>
""" % (last_search,)
index.exposed = True
def do_search(self, query):
results = ['some', 'results', 'here', 'simulating', 'a', 'search']
print cherrypy.request.cookie
last_search = cherrypy.request.cookie.get('terms', None)
if last_search:
last_search = json.loads(last_search.value)[-4:] # get last 4
else:
last_search = []
last_search.append(query) # append new term
cherrypy.response.cookie['terms'] = json.dumps(last_search)
return """
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>Search</title>
</head>
<body>
<h1>Search Results for %r</h1>
<p>%s</p>
<p><a href="%s">click here to search again</a>
</p>
</body>
""" % (query, ', '.join(results), cherrypy.url('/'))
do_search.exposed = True
application = cherrypy.tree.mount(Root(), '/')
if __name__ == '__main__':
cherrypy.quickstart()
</code></pre>
<p>NOTES:</p>
<p>It uses <a href="http://docs.python.org/library/json.html" rel="nofollow"><code>json</code></a> to serialize the list and store it in the cookie as a string. Python <code>json</code> was introduced in python 2.6, so if you need it before 2.6, so if you don't have 2.6 you can use <a href="http://pypi.python.org/pypi/simplejson" rel="nofollow"><code>simplejson</code></a> instead to run the example.</p>
<p>Sorry about the HTML in the code. That would ideally be outside the code, in a template file, using a template engine such as jinja2.</p>
| 0 | 2009-05-28T16:11:37Z | [
"python",
"cookies"
] |
Python Cookies question | 920,472 | <pre><code>import cgitb
import Cookie, urllib2
from cookielib import FileCookieJar
cgitb.enable()
c = Cookie.SmartCookie()
c['ini'] = 1
savedc = FileCookieJar()
savedc.add_cookie_header(c.output())
savedc.save()
</code></pre>
<p>shoulden't this save the cookie?...</p>
<p>i've been reading over the python documentation like 1 million times, i just don't get it :(</p>
<p>please help someone :(</p>
| 1 | 2009-05-28T11:49:15Z | 920,602 | <p>Make sure you name the file to store cookies in:</p>
<pre><code>savedc = FileCookieJar('cookies.txt')
</code></pre>
<p><code>add_cookie_header</code> takes a Request object; <code>set_cookie</code> takes a Cookie. As it says in the documentation, <code>FileCookieJar.save</code> "raises NotImplementedError. Subclasses may leave this method unimplemented." Guess you should have tried reading the documentation 1E6+1 times.</p>
| 0 | 2009-05-28T12:32:34Z | [
"python",
"cookies",
"cgi"
] |
Python Cookies question | 920,472 | <pre><code>import cgitb
import Cookie, urllib2
from cookielib import FileCookieJar
cgitb.enable()
c = Cookie.SmartCookie()
c['ini'] = 1
savedc = FileCookieJar()
savedc.add_cookie_header(c.output())
savedc.save()
</code></pre>
<p>shoulden't this save the cookie?...</p>
<p>i've been reading over the python documentation like 1 million times, i just don't get it :(</p>
<p>please help someone :(</p>
| 1 | 2009-05-28T11:49:15Z | 920,697 | <p><strong>Raf</strong>, all I can say is, Egads! The documentation certainly is <em>not</em> clear! I have used Python for years and this simple Stack Overflow question that I thought I'd quickly nab before getting started on real work for the day has taken me more than twenty minutes to answer. :-)</p>
<p>First: it turns out that the "Cookie" library and the "cookielib" library are completely separate and have nothing to do with each other. This is stated in the documentation, but you have to scroll down to the "See Also" section of each documentation page to find this out. It would be helpful if this were at the top of each page instead.</p>
<p>So, when you pass an object from the "Cookie" library into "cookielib", you're confusing the "cookielib" internals because it stores cookies inside of dictionaries and a "Cookie" cookie looks like â guess what! â a dictionary, so "cookielib" confuses it for one of its own internal data structures and saves other cookies inside of it. The error I get as a result is:</p>
<pre><code><type 'exceptions.AttributeError'>: 'str' object has no attribute 'discard'
args = ("'str' object has no attribute 'discard'",)
message = "'str' object has no attribute 'discard'"
</code></pre>
<p>Actually, that's the error I get <em>after</em> sticking a bunch of attributes on the Cookie.Cookie object that don't belong there, but that I added before I realized that I was engaged in the hopeless task of trying to get a Cookie.Cookie to behave like a cookielib.Cookie. :-) The earlier errors were all attribute-missing errors like:</p>
<pre><code><class 'Cookie.CookieError'>: Invalid Attribute name
args = ('Invalid Attribute name',)
message = 'Invalid Attribute name'
</code></pre>
<p>(And I'm putting the errors here in case some poor future soul mixes up the Cookie classes and does the Google searches I just did, none of which turned up any results for the errors I was getting!)</p>
<p>So before we proceed farther, I have to know: are you trying to act like a web <em>server</em>, delivering cookies to clients and trying to get them back intact when the client sends their next request, in which case I should show you how the "Cookie" module works? Or are you writing a web client, for testing or for fun, that messes with the cookies that it sends with a web request to a web site, in which case we should talk about "cookielib"?</p>
| 5 | 2009-05-28T12:57:47Z | [
"python",
"cookies",
"cgi"
] |
When to use While or the For in python | 920,645 | <p>I am currently finding problems in when I should use the <code>while loop</code> or the <code>for loop</code> in python. What it looks like is that people prefer using the <code>for loop</code> <em>(less code lines?)</em>. Is there any specific situation which I should use one or the other? Is it a matter of personal preference? The codes I had read so far made me think there are big differences between then?</p>
| 15 | 2009-05-28T12:44:27Z | 920,652 | <p>The <code>for</code> is the more pythonic choice for iterating a list since it is simpler and easier to read.</p>
<p>For example this:</p>
<pre><code>for i in range(11):
print i
</code></pre>
<p>is much simpler and easier to read than this:</p>
<pre><code>i = 0
while i <= 10:
print i
i = i + 1
</code></pre>
| 8 | 2009-05-28T12:46:14Z | [
"python",
"loops"
] |
When to use While or the For in python | 920,645 | <p>I am currently finding problems in when I should use the <code>while loop</code> or the <code>for loop</code> in python. What it looks like is that people prefer using the <code>for loop</code> <em>(less code lines?)</em>. Is there any specific situation which I should use one or the other? Is it a matter of personal preference? The codes I had read so far made me think there are big differences between then?</p>
| 15 | 2009-05-28T12:44:27Z | 920,686 | <p><code>while</code> is useful in scenarios where the break condition doesn't logically depend on any kind of sequence. For example, consider unpredictable interactions:</p>
<pre><code> while user_is_sleeping():
wait()
</code></pre>
<p>Of course, you <em>could</em> write an appropriate iterator to encapsulate that action and make it accessible via <code>for</code> â but how would that serve readability?¹</p>
<p>In all other cases in Python, use <code>for</code> (or an appropriate higher-order function which encapsulate the loop).</p>
<p>¹ assuming the <code>user_is_sleeping</code> function returns <code>False</code> when false, the example code could be rewritten as the following <code>for</code> loop:</p>
<pre><code>for _ in iter(user_is_sleeping, False):
wait()
</code></pre>
| 12 | 2009-05-28T12:55:01Z | [
"python",
"loops"
] |
When to use While or the For in python | 920,645 | <p>I am currently finding problems in when I should use the <code>while loop</code> or the <code>for loop</code> in python. What it looks like is that people prefer using the <code>for loop</code> <em>(less code lines?)</em>. Is there any specific situation which I should use one or the other? Is it a matter of personal preference? The codes I had read so far made me think there are big differences between then?</p>
| 15 | 2009-05-28T12:44:27Z | 920,692 | <p>Yes, there is a huge difference between while and for.</p>
<p>The <strong>for</strong> statement iterates through a collection or iterable object or generator function.</p>
<p>The <strong>while</strong> statement simply loops until a condition is False.</p>
<p>It isn't preference. It's a question of what your data structures are.</p>
<p>Often, we represent the values we want to process as a <code>range</code> (an actual list), or <code>xrange</code> (which generates the values). This gives us a data structure tailor-made for the <strong>for</strong> statement.</p>
<p>Generally, however, we have a ready-made collection: a set, tuple, list, map or even a string is already an iterable collection, so we simply use a <strong>for</strong> loop.</p>
<p>In a few cases, we might want some functional-programming processing done for us, in which case we can apply that transformation as part of iteration. The <code>sorted</code> and <code>enumerate</code> functions apply a transformation on an iterable that fits naturally with the <strong>for</strong> statement.</p>
<p>If you don't have a tidy data structure to iterate through, or you don't have a generator function that drives your processing, you must use <strong>while</strong>.</p>
| 36 | 2009-05-28T12:55:59Z | [
"python",
"loops"
] |
When to use While or the For in python | 920,645 | <p>I am currently finding problems in when I should use the <code>while loop</code> or the <code>for loop</code> in python. What it looks like is that people prefer using the <code>for loop</code> <em>(less code lines?)</em>. Is there any specific situation which I should use one or the other? Is it a matter of personal preference? The codes I had read so far made me think there are big differences between then?</p>
| 15 | 2009-05-28T12:44:27Z | 920,792 | <p>For loops usually make it clearer what the iteration is doing. You can't always use them directly, but most of the times the iteration logic with the while loop can be wrapped inside a generator func. For example:</p>
<pre><code>def path_to_root(node):
while node is not None:
yield node
node = node.parent
for parent in path_to_root(node):
...
</code></pre>
<p>Instead of</p>
<pre><code>parent = node
while parent is not None:
...
parent = parent.parent
</code></pre>
| 0 | 2009-05-28T13:17:54Z | [
"python",
"loops"
] |
When to use While or the For in python | 920,645 | <p>I am currently finding problems in when I should use the <code>while loop</code> or the <code>for loop</code> in python. What it looks like is that people prefer using the <code>for loop</code> <em>(less code lines?)</em>. Is there any specific situation which I should use one or the other? Is it a matter of personal preference? The codes I had read so far made me think there are big differences between then?</p>
| 15 | 2009-05-28T12:44:27Z | 920,867 | <p>First of all there are differences between the for loop in python and in other languages.
While in python it iterates over a list of values (eg: for value in [4,3,2,7]), in most other languages (C/C++, Java, PHP etc) it acts as a while loop, but easier to read.</p>
<p>For loops are generally used when the number of iterations is known (the length of an array for example), and while loops are used when you don't know how long it will take (for example the <a href="http://en.wikipedia.org/wiki/Bubble%5Fsort" rel="nofollow">bubble sort</a> algorithm which loops as long as the values aren't sorted)</p>
| 1 | 2009-05-28T13:32:43Z | [
"python",
"loops"
] |
When to use While or the For in python | 920,645 | <p>I am currently finding problems in when I should use the <code>while loop</code> or the <code>for loop</code> in python. What it looks like is that people prefer using the <code>for loop</code> <em>(less code lines?)</em>. Is there any specific situation which I should use one or the other? Is it a matter of personal preference? The codes I had read so far made me think there are big differences between then?</p>
| 15 | 2009-05-28T12:44:27Z | 922,851 | <p>Consider processing iterables. You can do it with a <code>for</code> loop:</p>
<pre><code>for i in mylist:
print i
</code></pre>
<p>Or, you can do it with a <code>while</code> loop:</p>
<pre><code>it = mylist.__iter__()
while True:
try:
print it.next()
except StopIteration:
break
</code></pre>
<p>Both of those blocks of code do fundamentally the same thing in fundamentally the same way. But the <code>for</code> loop hides the creation of the iterator and the handling of the <code>StopIteration</code> exception so that you don't need to deal with them yourself.</p>
<p>The only time I can think of that you'd use a <code>while</code> loop to handle an iterable would be if you needed to access the iterator directly for some reason, e.g. you needed to skip over items in the list under some circumstances.</p>
| 2 | 2009-05-28T19:56:04Z | [
"python",
"loops"
] |
The right way to auto filter SQLAlchemy queries? | 920,724 | <p>I've just introspected a pretty nasty schema from a CRM app with sqlalchemy. All of the tables have a deleted column on them and I wanted to auto filter all those entities and relations flagged as deleted. Here's what I came up with:</p>
<p><hr /></p>
<pre><code>class CustomizableQuery(Query):
"""An overridden sqlalchemy.orm.query.Query to filter entities
Filters itself by BinaryExpressions
found in :attr:`CONDITIONS`
"""
CONDITIONS = []
def __init__(self, mapper, session=None):
super(CustomizableQuery, self).__init__(mapper, session)
for cond in self.CONDITIONS:
self._add_criterion(cond)
def _add_criterion(self, criterion):
criterion = self._adapt_clause(criterion, False, True)
if self._criterion is not None:
self._criterion = self._criterion & criterion
else:
self._criterion = criterion
</code></pre>
<p>And it's used like this:</p>
<pre><code>class UndeletedContactQuery(CustomizableQuery):
CONDITIONS = [contacts.c.deleted != True]
def by_email(self, email_address):
return EmailInfo.query.by_module_and_address('Contacts', email_address).contact
def by_username(self, uname):
return self.filter_by(twod_username_c=uname).one()
class Contact(object):
query = session.query_property(UndeletedContactQuery)
Contact.query.by_email('someone@some.com')
</code></pre>
<p>EmailInfo is the class that's mapped to the join table between emails and the other Modules that they're related to.</p>
<p>Here's an example of a mapper:</p>
<pre><code>contacts_map = mapper(Contact, join(contacts, contacts_cstm), {
'_emails': dynamic_loader(EmailInfo,
foreign_keys=[email_join.c.bean_id],
primaryjoin=contacts.c.id==email_join.c.bean_id,
query_class=EmailInfoQuery),
})
class EmailInfoQuery(CustomizableQuery):
CONDITIONS = [email_join.c.deleted != True]
# More methods here
</code></pre>
<p><hr /></p>
<p>This gives me what I want in that I've filtered out all deleted Contacts. I can also use this as the query_class argument to dynamic_loader in my mappers - However...</p>
<ol>
<li>Is there a better way to do this, I'm not really happy with poking around with the internals of a compicated class like Query as I am.</li>
<li>Has anyone solved this in a different way that they can share?</li>
</ol>
| 4 | 2009-05-28T13:03:37Z | 920,752 | <p>You can map to a select. Like this:</p>
<pre><code>mapper(EmailInfo, select([email_join], email_join.c.deleted == False))
</code></pre>
| 6 | 2009-05-28T13:11:18Z | [
"python",
"sqlalchemy",
"sugarcrm"
] |
The right way to auto filter SQLAlchemy queries? | 920,724 | <p>I've just introspected a pretty nasty schema from a CRM app with sqlalchemy. All of the tables have a deleted column on them and I wanted to auto filter all those entities and relations flagged as deleted. Here's what I came up with:</p>
<p><hr /></p>
<pre><code>class CustomizableQuery(Query):
"""An overridden sqlalchemy.orm.query.Query to filter entities
Filters itself by BinaryExpressions
found in :attr:`CONDITIONS`
"""
CONDITIONS = []
def __init__(self, mapper, session=None):
super(CustomizableQuery, self).__init__(mapper, session)
for cond in self.CONDITIONS:
self._add_criterion(cond)
def _add_criterion(self, criterion):
criterion = self._adapt_clause(criterion, False, True)
if self._criterion is not None:
self._criterion = self._criterion & criterion
else:
self._criterion = criterion
</code></pre>
<p>And it's used like this:</p>
<pre><code>class UndeletedContactQuery(CustomizableQuery):
CONDITIONS = [contacts.c.deleted != True]
def by_email(self, email_address):
return EmailInfo.query.by_module_and_address('Contacts', email_address).contact
def by_username(self, uname):
return self.filter_by(twod_username_c=uname).one()
class Contact(object):
query = session.query_property(UndeletedContactQuery)
Contact.query.by_email('someone@some.com')
</code></pre>
<p>EmailInfo is the class that's mapped to the join table between emails and the other Modules that they're related to.</p>
<p>Here's an example of a mapper:</p>
<pre><code>contacts_map = mapper(Contact, join(contacts, contacts_cstm), {
'_emails': dynamic_loader(EmailInfo,
foreign_keys=[email_join.c.bean_id],
primaryjoin=contacts.c.id==email_join.c.bean_id,
query_class=EmailInfoQuery),
})
class EmailInfoQuery(CustomizableQuery):
CONDITIONS = [email_join.c.deleted != True]
# More methods here
</code></pre>
<p><hr /></p>
<p>This gives me what I want in that I've filtered out all deleted Contacts. I can also use this as the query_class argument to dynamic_loader in my mappers - However...</p>
<ol>
<li>Is there a better way to do this, I'm not really happy with poking around with the internals of a compicated class like Query as I am.</li>
<li>Has anyone solved this in a different way that they can share?</li>
</ol>
| 4 | 2009-05-28T13:03:37Z | 925,533 | <p>I'd consider seeing if it was possible to create views for these tables that filter out the deleted elements, and then you might be able to map directly to that view instead of the underlying table, at least for querying operations. However I've never tried this myself!</p>
| 0 | 2009-05-29T11:22:27Z | [
"python",
"sqlalchemy",
"sugarcrm"
] |
Sending Multipart html emails which contain embedded images | 920,910 | <p>I've been playing around with the email module in python but I want to be able to know how to embed images which are included in the html.</p>
<p>So for example if the body is something like</p>
<pre><code><img src="../path/image.png"></img>
</code></pre>
<p>I would like to embed <em>image.png</em> into the email, and the <code>src</code> attribute should be replaced with <code>content-id</code>. Does anybody know how to do this?</p>
| 36 | 2009-05-28T13:45:57Z | 920,928 | <p>Here is an example I found.</p>
<blockquote>
<p><a href="http://code.activestate.com/recipes/473810/"><strong>Recipe 473810: Send an HTML email with embedded image and plain text alternate</strong></a>: </p>
<p>HTML is the method of choice for those
wishing to send emails with rich text,
layout and graphics. Often it is
desirable to embed the graphics within
the message so recipients can display
the message directly, without further
downloads.</p>
<p>Some mail agents don't support HTML or
their users prefer to receive plain
text messages. Senders of HTML
messages should include a plain text
message as an alternate for these
users.</p>
<p>This recipe sends a short HTML message
with a single embedded image and an
alternate plain text message.</p>
</blockquote>
<pre><code># Send an HTML email with an embedded image and a plain text message for
# email clients that don't want to display the HTML.
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
# Define these once; use them twice!
strFrom = 'from@example.com'
strTo = 'to@example.com'
# Create the root message and fill in the from, to, and subject headers
msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = 'test message'
msgRoot['From'] = strFrom
msgRoot['To'] = strTo
msgRoot.preamble = 'This is a multi-part message in MIME format.'
# Encapsulate the plain and HTML versions of the message body in an
# 'alternative' part, so message agents can decide which they want to display.
msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)
msgText = MIMEText('This is the alternative plain text message.')
msgAlternative.attach(msgText)
# We reference the image in the IMG SRC attribute by the ID we give it below
msgText = MIMEText('<b>Some <i>HTML</i> text</b> and an image.<br><img src="cid:image1"><br>Nifty!', 'html')
msgAlternative.attach(msgText)
# This example assumes the image is in the current directory
fp = open('test.jpg', 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
# Define the image's ID as referenced above
msgImage.add_header('Content-ID', '<image1>')
msgRoot.attach(msgImage)
# Send the email (this example assumes SMTP authentication is required)
import smtplib
smtp = smtplib.SMTP()
smtp.connect('smtp.example.com')
smtp.login('exampleuser', 'examplepass')
smtp.sendmail(strFrom, strTo, msgRoot.as_string())
smtp.quit()
</code></pre>
| 82 | 2009-05-28T13:48:27Z | [
"python",
"email",
"mime",
"attachment",
"multipart"
] |
Formatted output in OpenOffice/Microsoft Word with Python | 920,938 | <p>I am working on a project (in Python) that needs formatted, editable output. Since the end-user isn't going to be technically proficient, the output needs to be in a word processor editable format. The formatting is complex (bullet points, paragraphs, bold face, etc).</p>
<p>Is there a way to generate such a report using Python? I feel like there should be a way to do this using Microsoft Word/OpenOffice templates and Python, but I can't find anything advanced enough to get good formatting. Any suggestions?</p>
| 6 | 2009-05-28T13:49:45Z | 920,980 | <p>I know there is an <a href="http://www.rexx.com/~dkuhlman/odtwriter.html" rel="nofollow">odtwriter for docutils</a>. You could generate your output as <a href="http://docutils.sourceforge.net/rst.html" rel="nofollow">reStructuredText</a> and feed it to odtwriter or look into what odtwriter is using on the backend to generate the ODT and use that.</p>
<p>(I'd probably go with generating rst output and then hacking odtwriter to output the stuff I want (and contribute the fixes back to the project), because that's probably a whole lot easier that trying to render your stuff to ODT directly.)</p>
| 1 | 2009-05-28T13:58:03Z | [
"python",
"formatting",
"ms-word",
"ms-office",
"openoffice.org"
] |
Formatted output in OpenOffice/Microsoft Word with Python | 920,938 | <p>I am working on a project (in Python) that needs formatted, editable output. Since the end-user isn't going to be technically proficient, the output needs to be in a word processor editable format. The formatting is complex (bullet points, paragraphs, bold face, etc).</p>
<p>Is there a way to generate such a report using Python? I feel like there should be a way to do this using Microsoft Word/OpenOffice templates and Python, but I can't find anything advanced enough to get good formatting. Any suggestions?</p>
| 6 | 2009-05-28T13:49:45Z | 920,989 | <p>I've used xlwt to create Excel documents using python, but I haven't needed to write word files yet. I've found this package, <a href="http://pypi.python.org/pypi/OOoPy/1.4.4873" rel="nofollow">OOoPy</a>, but I haven't used it.</p>
<p>Also you might want to try outputting html files and having the users open them in Word.</p>
| 1 | 2009-05-28T13:59:56Z | [
"python",
"formatting",
"ms-word",
"ms-office",
"openoffice.org"
] |
Formatted output in OpenOffice/Microsoft Word with Python | 920,938 | <p>I am working on a project (in Python) that needs formatted, editable output. Since the end-user isn't going to be technically proficient, the output needs to be in a word processor editable format. The formatting is complex (bullet points, paragraphs, bold face, etc).</p>
<p>Is there a way to generate such a report using Python? I feel like there should be a way to do this using Microsoft Word/OpenOffice templates and Python, but I can't find anything advanced enough to get good formatting. Any suggestions?</p>
| 6 | 2009-05-28T13:49:45Z | 921,046 | <p>I think OpenOffice has some Python bindings - you should be able to write OO macros in Python.</p>
<p>But I would use HTML instead - Word and OO.org are rather good at editing it and you can write it from Python easily (although Word saves a lot of mess which could complicate parsing it by your Python app).</p>
| 0 | 2009-05-28T14:12:26Z | [
"python",
"formatting",
"ms-word",
"ms-office",
"openoffice.org"
] |
Formatted output in OpenOffice/Microsoft Word with Python | 920,938 | <p>I am working on a project (in Python) that needs formatted, editable output. Since the end-user isn't going to be technically proficient, the output needs to be in a word processor editable format. The formatting is complex (bullet points, paragraphs, bold face, etc).</p>
<p>Is there a way to generate such a report using Python? I feel like there should be a way to do this using Microsoft Word/OpenOffice templates and Python, but I can't find anything advanced enough to get good formatting. Any suggestions?</p>
| 6 | 2009-05-28T13:49:45Z | 921,680 | <p>" The formatting is complex(bullet points, paragraphs, bold face, etc), "</p>
<p>Use <a href="http://docutils.sourceforge.net/docs/user/rst/quickstart.html" rel="nofollow">RST</a>.</p>
<p>It's trivial to produce, since it's plain text.</p>
<p>It's trivial to edit, since it's plain text with a few extra characters to provide structural information.</p>
<p>It formats nicely using a bunch of <a href="http://docutils.sourceforge.net/docs/user/tools.html" rel="nofollow">tools</a>.</p>
| 2 | 2009-05-28T15:59:54Z | [
"python",
"formatting",
"ms-word",
"ms-office",
"openoffice.org"
] |
Formatted output in OpenOffice/Microsoft Word with Python | 920,938 | <p>I am working on a project (in Python) that needs formatted, editable output. Since the end-user isn't going to be technically proficient, the output needs to be in a word processor editable format. The formatting is complex (bullet points, paragraphs, bold face, etc).</p>
<p>Is there a way to generate such a report using Python? I feel like there should be a way to do this using Microsoft Word/OpenOffice templates and Python, but I can't find anything advanced enough to get good formatting. Any suggestions?</p>
| 6 | 2009-05-28T13:49:45Z | 922,117 | <p>A little known, and slightly evil fact: If you create an HTML file, and stick a .doc extension on it, Word will open it as a Word document, and most users will be none the wiser.</p>
<p>Except maybe a very technical person will say, my this is a small Word file! :)</p>
| 3 | 2009-05-28T17:18:42Z | [
"python",
"formatting",
"ms-word",
"ms-office",
"openoffice.org"
] |
Formatted output in OpenOffice/Microsoft Word with Python | 920,938 | <p>I am working on a project (in Python) that needs formatted, editable output. Since the end-user isn't going to be technically proficient, the output needs to be in a word processor editable format. The formatting is complex (bullet points, paragraphs, bold face, etc).</p>
<p>Is there a way to generate such a report using Python? I feel like there should be a way to do this using Microsoft Word/OpenOffice templates and Python, but I can't find anything advanced enough to get good formatting. Any suggestions?</p>
| 6 | 2009-05-28T13:49:45Z | 4,819,302 | <p>Use the <a href="https://github.com/mikemaccana/python-docx" rel="nofollow">Python Docx</a> module for this - 100% Python, tables, images, document properties, headings, paragraphs, and more.</p>
| 2 | 2011-01-27T16:53:28Z | [
"python",
"formatting",
"ms-word",
"ms-office",
"openoffice.org"
] |
Formatted output in OpenOffice/Microsoft Word with Python | 920,938 | <p>I am working on a project (in Python) that needs formatted, editable output. Since the end-user isn't going to be technically proficient, the output needs to be in a word processor editable format. The formatting is complex (bullet points, paragraphs, bold face, etc).</p>
<p>Is there a way to generate such a report using Python? I feel like there should be a way to do this using Microsoft Word/OpenOffice templates and Python, but I can't find anything advanced enough to get good formatting. Any suggestions?</p>
| 6 | 2009-05-28T13:49:45Z | 12,730,111 | <p>You can use QTextDocument, QTextCursor and QTextDocumentWriter in <a href="http://www.riverbankcomputing.co.uk/software/pyqt/download" rel="nofollow">PyQt4</a>. A simple example to show how to write to an odt file:</p>
<pre><code>>>>from pyqt4 import QtGui
# Create a document object
>>>doc = QtGui.QTextDocument()
# Create a cursor pointing to the beginning of the document
>>>cursor = QtGui.QTextCursor(doc)
# Insert some text
>>>cursor.insertText('Hello world')
# Create a writer to save the document
>>>writer = QtGui.QTextDocumentWriter()
>>>writer.supportedDocumentFormats()
[PyQt4.QtCore.QByteArray(b'HTML'), PyQt4.QtCore.QByteArray(b'ODF'), PyQt4.QtCore.QByteArray(b'plaintext')]
>>>odf_format = writer.supportedDocumentFormats()[1]
>>>writer.setFormat(odf_format)
>>>writer.setFileName('hello_world.odt')
>>>writer.write(doc) # Return True if successful
True
</code></pre>
<p>QTextCursor also can insert tables, frames, blocks, images. More information at:
<a href="http://qt-project.org/doc/qt-4.8/qtextcursor.html" rel="nofollow">http://qt-project.org/doc/qt-4.8/qtextcursor.html</a></p>
<p>As a bonus, you also can print to a pdf file by using QPrinter.</p>
| 1 | 2012-10-04T14:56:49Z | [
"python",
"formatting",
"ms-word",
"ms-office",
"openoffice.org"
] |
How to use classes derived from Python's list class | 921,334 | <p>This is a followup to question 912526 - <a href="http://stackoverflow.com/questions/912526/how-do-i-pass-lots-of-variables-to-and-from-a-function-in-python">http://stackoverflow.com/questions/912526/how-do-i-pass-lots-of-variables-to-and-from-a-function-in-python</a>.</p>
<p>There are lots of variables that need to get passed around in the program I'm writing, and from my previous question I understand that I should put these variables into classes, and then pass around the classes.</p>
<p>Some of these variables come in repetetive sets - for a thin film calculation I need to track the optical properties (index of refraction, absorption, thickness, etc) for a number of layers.</p>
<p>Is the best way to store variables like this to create a class derived from a Python list to store the set of classes which each hold the variables for a single layer? And then put the functions that deal with the set of layers in class derived from the list, and the functions that deal with a specific layer in that class? Is there a better way to do this with a single class? </p>
<p>Using the two class approach in the following example, I'm able to set things up so that I can access variables using statments like</p>
<pre><code>n1 = layers[5].n
</code></pre>
<p>This is the best way to do this, right?</p>
<pre><code>#Test passing values to and from functions
class Layers(list):
def add(self,n,k,comment):
self.append( OneLayer(n,k,comment) )
def input_string(self):
input_string = []
for layer in self:
vars = layer.input_string()
for var in vars:
input_string.append( var )
return input_string
def set_layers(self,results):
for layer,i in enumerate(self):
j = i*layer.num_var
layer.set_layer( *results[j:j+2] )
class OneLayer(object):
def __init__(self,n,k,comment):
self.n = n
self.k = k
self.comment = comment
def input_string(self):
return [['f','Index of Refraction',self.n], ['f','Absorption',self.k],['s','Comment',self.comment]]
def set_layer(self,n,k,comment):
self.n = n; self.k=k; self.comment = comment
def num_var(self):
return 3
if __name__ == '__main__':
layers = Layers()
layers.add(1.0,0.0,'This vacuum sucks')
layers.add(1.5,0.0,'BK 7 Glass')
print layers[0].n
print layers.input_string()
layers[1].set_layer(1.77,0.0,'Sapphire')
print layers.input_string()
</code></pre>
<p>I get the following output from this test program:</p>
<pre><code>1.0
[['f', 'Index of Refraction', 1.0], ['f', 'Absorption', 0.0], ['s', 'Comment', 'This vacuum sucks'], ['f', 'Index of Refraction', 1.5], ['f', 'Absorption', 0.0], ['s', 'Comment', 'BK 7 Glass']]
[['f', 'Index of Refraction', 1.0], ['f', 'Absorption', 0.0], ['s', 'Comment', 'This vacuum sucks'], ['f', 'Index of Refraction', 1.77], ['f', 'Absorption', 0.0], ['s', 'Comment', 'Sapphire']]
</code></pre>
| 6 | 2009-05-28T15:05:13Z | 921,510 | <p>There are several issues in your code:</p>
<p>1.If you make any list operation the result will be a native list:</p>
<pre><code>layers1 = Layers()
layers2 = Layers()
layers1 + layers2 -> the result will be a native list
</code></pre>
<p>2.Why define input_string when you can override <a href="http://docs.python.org/reference/datamodel.html#object.__repr__"><code>__repr__</code></a> or <a href="http://docs.python.org/reference/datamodel.html#object.__str__"><code>__str__</code></a></p>
<p>3.Why do you even have to derive from list in this case? You only need to derive from list if you want your class to behave exactly like a list. But in your case you seem to be looking for a container.
All you need to do to get your class to behave similar to a list is to override some special python methods <a href="http://docs.python.org/reference/datamodel.html#emulating-container-types">http://docs.python.org/reference/datamodel.html#emulating-container-types</a></p>
<pre><code>class Layers(object):
def __init__(self, container=None):
if container is None:
container = []
self.container = container
def add(self,n,k,comment):
self.container.append([n,k,comment])
def __str__(self):
return str(self.container)
def __repr__(self):
return str(self.container)
def __getitem__(self, key):
return Layers(self.container[key])
def __len__(self):
return len(self.container)
>>> l = Layers()
>>> l.add(1, 2, 'test')
>>> l.add(1, 2, 'test')
>>> l
[[1, 2, 'test'], [1, 2, 'test']]
>>> l[0]
[1, 2, 'test']
>>> len(l)
2
</code></pre>
| 9 | 2009-05-28T15:31:42Z | [
"python",
"class"
] |
Retrieving all Cookies in Python | 921,532 | <p>How do I read back all of the cookies in Python without knowing their names?</p>
| 14 | 2009-05-28T15:35:09Z | 921,544 | <p>Look at the <code>Cookie:</code> headers in the HTTP response you get, parse their contents with module <code>Cookie</code> in the standard library.</p>
| 3 | 2009-05-28T15:38:04Z | [
"python",
"cookies"
] |
Retrieving all Cookies in Python | 921,532 | <p>How do I read back all of the cookies in Python without knowing their names?</p>
| 14 | 2009-05-28T15:35:09Z | 921,652 | <p>Put <code>os.environ['HTTP_COOKIE']</code> into an array:</p>
<pre><code>#!/usr/bin/env python
import os
if 'HTTP_COOKIE' in os.environ:
cookies = os.environ['HTTP_COOKIE']
cookies = cookies.split('; ')
handler = {}
for cookie in cookies:
cookie = cookie.split('=')
handler[cookie[0]] = cookie[1]
</code></pre>
| 4 | 2009-05-28T15:55:15Z | [
"python",
"cookies"
] |
Retrieving all Cookies in Python | 921,532 | <p>How do I read back all of the cookies in Python without knowing their names?</p>
| 14 | 2009-05-28T15:35:09Z | 921,744 | <p>Not sure if this is what you are looking for, but here is a simple example where you put cookies in a cookiejar and read them back:</p>
<pre><code>from urllib2 import Request, build_opener, HTTPCookieProcessor, HTTPHandler
import cookielib
#Create a CookieJar object to hold the cookies
cj = cookielib.CookieJar()
#Create an opener to open pages using the http protocol and to process cookies.
opener = build_opener(HTTPCookieProcessor(cj), HTTPHandler())
#create a request object to be used to get the page.
req = Request("http://www.about.com")
f = opener.open(req)
#see the first few lines of the page
html = f.read()
print html[:50]
#Check out the cookies
print "the cookies are: "
for cookie in cj:
print cookie
</code></pre>
| 21 | 2009-05-28T16:11:27Z | [
"python",
"cookies"
] |
Retrieving all Cookies in Python | 921,532 | <p>How do I read back all of the cookies in Python without knowing their names?</p>
| 14 | 2009-05-28T15:35:09Z | 30,493,213 | <p>This may be exactly what you are looking for.</p>
<p>Python 3.4</p>
<pre><code>import requests
r = requests.get('http://www.about.com/')
c = r.cookies
i = c.items()
for name, value in i:
print(name, value)
</code></pre>
| 1 | 2015-05-27T21:10:44Z | [
"python",
"cookies"
] |
Learning parser in python | 921,792 | <p>I recall I have read about a parser which you just have to feed some sample lines, for it to know how to parse some text.</p>
<p>It just determines the difference between two lines to know what the variable parts are. I thought it was written in python, but i'm not sure. Does anyone know what library that was?</p>
| 12 | 2009-05-28T16:18:45Z | 922,125 | <p>Conceivably you might mean <a href="http://sourceforge.net/project/showfiles.php?group%5Fid=81259" rel="nofollow">Reverend</a>?</p>
| 2 | 2009-05-28T17:20:43Z | [
"python",
"parsing"
] |
Learning parser in python | 921,792 | <p>I recall I have read about a parser which you just have to feed some sample lines, for it to know how to parse some text.</p>
<p>It just determines the difference between two lines to know what the variable parts are. I thought it was written in python, but i'm not sure. Does anyone know what library that was?</p>
| 12 | 2009-05-28T16:18:45Z | 922,930 | <p>Probably you mean <em><a href="http://code.google.com/p/templatemaker/" rel="nofollow">TemplateMaker</a></em>, I haven't tried it yet, but it builds on well-researched <em>longest-common-substring</em> algorithms and thus should work reasonably... If you are interested in different (more complex) approaches, you can easily find a lot of material on Google Scholar using the query "wrapper induction" or "template induction".</p>
| 10 | 2009-05-28T20:17:54Z | [
"python",
"parsing"
] |
Python and Qt - function reloading | 921,929 | <p>i have an application class inherited from QtGui.QDialog.
I have to reload show-function but save functionality. I take this idea from C#.
There i could do something like this:</p>
<pre><code>static void show()
{
// My code...
base.show();
}
</code></pre>
<p>I want to do something like that but with python and qt (PyQt). Can i do that?</p>
| 0 | 2009-05-28T16:42:12Z | 922,025 | <p>Checkout the <a href="http://docs.python.org/dev/library/functions.html#super" rel="nofollow">super()</a> function but note some <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=236275" rel="nofollow">pitfalls</a>.</p>
| 1 | 2009-05-28T17:00:09Z | [
"python",
"function",
"reloading"
] |
How to make mechanize not fail with forms on this page? | 922,148 | <pre><code>import mechanize
url = 'http://steamcommunity.com'
br=mechanize.Browser(factory=mechanize.RobustFactory())
br.open(url)
print br.request
print br.form
for each in br.forms():
print each
print
</code></pre>
<p>The above code results in:</p>
<pre><code>Traceback (most recent call last):
File "./mech_test.py", line 12, in <module>
for each in br.forms():
File "build/bdist.linux-i686/egg/mechanize/_mechanize.py", line 426, in forms
File "build/bdist.linux-i686/egg/mechanize/_html.py", line 559, in forms
File "build/bdist.linux-i686/egg/mechanize/_html.py", line 228, in forms
mechanize._html.ParseError
</code></pre>
<p>My specific goal is to use the login form, but I can't even get mechanize to recognize that there are any forms. Even using what I think is the most basic method of selecting <em>any</em> form, <code>br.select_form(nr=0)</code>, results in the same traceback. The form's enctype is multipart/form-data if that makes a difference.</p>
<p>I guess that all boils down to a two part question: How can I get mechanize to work with this page, or if it's not possible, what's another way while maintaining cookies?</p>
<p>edit: As mentioned below, this redirects to 'https://steamcommunity.com'.</p>
<p>Mechanize can successfully retrieving the HTML as can be seen with the following code:</p>
<pre><code>url = 'https://steamcommunity.com'
hh = mechanize.HTTPSHandler() # you might want HTTPSHandler, too
hh.set_http_debuglevel(1)
opener = mechanize.build_opener(hh)
response = opener.open(url)
contents = response.readlines()
print contents
</code></pre>
| 4 | 2009-05-28T17:25:21Z | 922,215 | <p>Did you mention that the website is redirecting to an https (ssl) server ?</p>
<p>Well, try to set a new HTTPS handler like this:</p>
<pre><code>mechanize.HTTPSHandler()
</code></pre>
| 2 | 2009-05-28T17:38:11Z | [
"python",
"automation",
"screen-scraping",
"mechanize"
] |
How to make mechanize not fail with forms on this page? | 922,148 | <pre><code>import mechanize
url = 'http://steamcommunity.com'
br=mechanize.Browser(factory=mechanize.RobustFactory())
br.open(url)
print br.request
print br.form
for each in br.forms():
print each
print
</code></pre>
<p>The above code results in:</p>
<pre><code>Traceback (most recent call last):
File "./mech_test.py", line 12, in <module>
for each in br.forms():
File "build/bdist.linux-i686/egg/mechanize/_mechanize.py", line 426, in forms
File "build/bdist.linux-i686/egg/mechanize/_html.py", line 559, in forms
File "build/bdist.linux-i686/egg/mechanize/_html.py", line 228, in forms
mechanize._html.ParseError
</code></pre>
<p>My specific goal is to use the login form, but I can't even get mechanize to recognize that there are any forms. Even using what I think is the most basic method of selecting <em>any</em> form, <code>br.select_form(nr=0)</code>, results in the same traceback. The form's enctype is multipart/form-data if that makes a difference.</p>
<p>I guess that all boils down to a two part question: How can I get mechanize to work with this page, or if it's not possible, what's another way while maintaining cookies?</p>
<p>edit: As mentioned below, this redirects to 'https://steamcommunity.com'.</p>
<p>Mechanize can successfully retrieving the HTML as can be seen with the following code:</p>
<pre><code>url = 'https://steamcommunity.com'
hh = mechanize.HTTPSHandler() # you might want HTTPSHandler, too
hh.set_http_debuglevel(1)
opener = mechanize.build_opener(hh)
response = opener.open(url)
contents = response.readlines()
print contents
</code></pre>
| 4 | 2009-05-28T17:25:21Z | 5,920,926 | <p>Use this secret, i'm sure this is work for you ;)</p>
<pre><code>br = mechanize.Browser(factory=mechanize.DefaultFactory(i_want_broken_xhtml_support=True))
</code></pre>
| 2 | 2011-05-07T12:11:30Z | [
"python",
"automation",
"screen-scraping",
"mechanize"
] |
Which process was responsible for an event signalled by inotify? | 922,200 | <p>I am using <code>pyinotify</code> to detect access, changes, etc. on files in a given directory. Is there an easier way to find out which process was responsible for that - without having to <a href="http://lkml.indiana.edu/hypermail/linux/kernel/0603.1/0166.html" rel="nofollow">patch <code>inotify</code></a>?</p>
| 3 | 2009-05-28T17:35:09Z | 1,450,794 | <p>No, you can't, that information isn't in the <code>struct inotify_event</code> sent by the kernel.</p>
<p>Actually there isn't any guarantee that the process responsible is still running when you get the event.</p>
| 1 | 2009-09-20T11:05:19Z | [
"python",
"inotify",
"pyinotify"
] |
Which process was responsible for an event signalled by inotify? | 922,200 | <p>I am using <code>pyinotify</code> to detect access, changes, etc. on files in a given directory. Is there an easier way to find out which process was responsible for that - without having to <a href="http://lkml.indiana.edu/hypermail/linux/kernel/0603.1/0166.html" rel="nofollow">patch <code>inotify</code></a>?</p>
| 3 | 2009-05-28T17:35:09Z | 1,458,541 | <p>Assuming you are on Linux (pyinotify would tend to indicate this) you could use SELinux (running in permissive mode of course) to wrap a process(es) and log all their file access/creation/deletion/etc.</p>
| 1 | 2009-09-22T07:08:21Z | [
"python",
"inotify",
"pyinotify"
] |
Exporting a zope folder with python | 922,319 | <p>We have two zope servers running our company's internal site. One is the live site and one is the dev site. I'm working on writing a python script that moves everything from the dev server to the live server. Right now the process involves a bunch of steps that are done in the zope management interface. I need to make all that automatic so that running one script handles it all. One thing I need to do is export one folder from the live server so that I can reimport it back into the live site after the update. How can I do this from a python script?</p>
<p>We're using Zope 2.8 and python 2.3.4</p>
| 5 | 2009-05-28T17:55:41Z | 960,024 | <p>You can try to use the functions <code>manage_exportObject</code> and <code>manage_importObject</code> located in the file <code>$ZOPE_HOME/lib/python/OFS/ObjectManager.py</code></p>
<p>Let say we install two Zope 2.8 instances located at:</p>
<ul>
<li><code>/tmp/instance/dev</code> for the development server (port 8080)</li>
<li><code>/tmp/instance/prod</code> for the production server (port 9090)</li>
</ul>
<p>In the ZMI of the development server, I have created two folders <code>/MyFolder1</code> and <code>/MyFolder2</code> containing some page templates. The following Python script exports each folder in .zexp files, and imports them in the ZMI of the production instance:</p>
<pre><code>#!/usr/bin/python
import urllib
import shutil
ids_to_transfer = ['MyFolder1', 'MyFolder2']
for id in ids_to_transfer:
urllib.urlopen('http://admin:password_dev@localhost:8080/manage_exportObject?id=' + id)
shutil.move('/tmp/instance/dev/var/' + id + '.zexp', '/tmp/instance/prod/import/' + id + '.zexp')
urllib.urlopen('http://admin:password_prod@localhost:9090/manage_delObjects?ids=' + id)
urllib.urlopen('http://admin:password_prod@localhost:9090/manage_importObject?file=' + id + '.zexp')
</code></pre>
| 3 | 2009-06-06T16:03:14Z | [
"python",
"zope"
] |
Exporting a zope folder with python | 922,319 | <p>We have two zope servers running our company's internal site. One is the live site and one is the dev site. I'm working on writing a python script that moves everything from the dev server to the live server. Right now the process involves a bunch of steps that are done in the zope management interface. I need to make all that automatic so that running one script handles it all. One thing I need to do is export one folder from the live server so that I can reimport it back into the live site after the update. How can I do this from a python script?</p>
<p>We're using Zope 2.8 and python 2.3.4</p>
| 5 | 2009-05-28T17:55:41Z | 997,279 | <p>To make this more general and allow copying folders not in the root directory I would do something like this:</p>
<pre><code>#!/usr/bin/python
import urllib
import shutil
username_dev = 'admin'
username_prod = 'admin'
password_dev = 'password_dev'
password_prod = 'password_prod'
url_dev = 'localhost:8080'
url_prod = 'localhost:9090'
paths_and_ids_to_transfer = [('level1/level2/','MyFolder1'), ('level1/','MyFolder2')]
for path, id in ids_to_transfer:
urllib.urlopen('http://%s:%s@%s/%smanage_exportObject?id=%s' % (username_dev, password_dev, url_dev, path, id))
shutil.move('/tmp/instance/dev/var/' + id + '.zexp', '/tmp/instance/prod/import/' + id + '.zexp')
urllib.urlopen('http://%s:%s@%s/%smanage_delObjects?ids=%s' % (username_prod, password_prod, url_prod, path, id))
urllib.urlopen('http://%s:%s@%s/%smanage_importObject?file=%s.zexp' % (username_prod, password_prod, url_prod, path, id))
</code></pre>
<p>If I had the rep I would add this to the other answer but alas...
If someone wants to merge them, please go ahead.</p>
| 2 | 2009-06-15T17:17:57Z | [
"python",
"zope"
] |
Exporting a zope folder with python | 922,319 | <p>We have two zope servers running our company's internal site. One is the live site and one is the dev site. I'm working on writing a python script that moves everything from the dev server to the live server. Right now the process involves a bunch of steps that are done in the zope management interface. I need to make all that automatic so that running one script handles it all. One thing I need to do is export one folder from the live server so that I can reimport it back into the live site after the update. How can I do this from a python script?</p>
<p>We're using Zope 2.8 and python 2.3.4</p>
| 5 | 2009-05-28T17:55:41Z | 1,022,056 | <p>If you really move <em>everything</em> you could probably just move the Data.fs instead. But otherwise the import/export above is a good way.</p>
| 0 | 2009-06-20T17:21:05Z | [
"python",
"zope"
] |
How do I deactivate an egg? | 922,323 | <p>I've installed cx_Oracle (repeatedly) and I just can't get it to work on my Intel Mac. How do I deactivate/uninstall it?</p>
| 3 | 2009-05-28T17:55:56Z | 922,381 | <p>You simply delete the <code>.egg</code> file</p>
<p>On OS X they are installed into <code>/Library/Python/2.5/site-packages/</code> - in that folder you should find a file named <code>cx_Oracle.egg</code> or similar. You can simple delete this file and it will be gone.</p>
<p>One way of finding the file is, if you can import the module, simply displaying the <code>repr()</code> of the module:</p>
<pre><code>>>> import urllib
>>> urllib
<module 'urllib' from '/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/urllib.pyc'>
>>> import BeautifulSoup
>>> BeautifulSoup
<module 'BeautifulSoup' from '/Library/Python/2.5/site-packages/BeautifulSoup-3.0.6-py2.5.egg/BeautifulSoup.py'>
</code></pre>
<p>If the import fails, the traceback should show the location of the module also.</p>
<p>One thing to note, if the module installed any command-line tools, you'll have to remove these manually also.. On OS X they are installde in <code>/usr/local/bin/</code> - you can find any tool which uses <code>cx_Oracle</code> using grep:</p>
<pre><code>cd /usr/local/bin/
grep EASY-INSTALL * | grep cx_Oracle
</code></pre>
<p>Or simply..</p>
<pre><code>cd /usr/local/bin/
grep cx_Oracle *
</code></pre>
| 3 | 2009-05-28T18:07:33Z | [
"python",
"uninstall",
"egg"
] |
Is it possible to launch a Paster shell with some modules pre-imported? | 922,351 | <p>Is it possible to run "paster shell blah.ini" (or a variant thereof) and have it automatically load certain libraries?</p>
<p>I hate having to always type "from foo.bar import mystuff" as the first command in every paster shell, and would like the computer to do it for me.</p>
| 5 | 2009-05-28T18:01:54Z | 980,897 | <p>If you set the environment variable PYTHONSTARTUP to the name of a file, it will execute that file on opening the interactive prompt.</p>
<p>I don't know anything about paster shell, but I assume it works similarly.</p>
<p>Alternatively you could look into iPython, which has much more powerful features (particularly when installed with the readline library). For example %run allows you to run a script in the current namespace, or you can use history completion.</p>
<p>Edit:</p>
<p>Okay. Having looked into it a bit more, I'm fairly certain that paster shell just does a set of useful imports, and could be easily replicated with a short script and ipython and then <code>%run myscript.py</code></p>
<p>Edit:</p>
<p>Having looked at the source, it would be very hard to do (I was wrong about the default imports. It parses your config file as well), however if you have Pylons and iPython both installed, then paster shell should use iPython automagically. Double check that both are installed properly, and double check that paster shell isn't using iPython already (it might be looking like normal python prompt).</p>
| 0 | 2009-06-11T12:53:00Z | [
"python",
"pylons",
"paster"
] |
Is it possible to launch a Paster shell with some modules pre-imported? | 922,351 | <p>Is it possible to run "paster shell blah.ini" (or a variant thereof) and have it automatically load certain libraries?</p>
<p>I hate having to always type "from foo.bar import mystuff" as the first command in every paster shell, and would like the computer to do it for me.</p>
| 5 | 2009-05-28T18:01:54Z | 1,008,481 | <p>An option to try would be to create a sitecustomize.py script. If you have this in the same folder as your paster shell, the python interpreter should load it up on startup. </p>
<p>Let me clarify, sitecustomize.py, if found, is <em>always</em> loaded on startup of the interpreter. So if you put it where it can be found, ideally somewhere that is only found when the paster shell starts, then you should be able to add your imports to it and have them be ready.</p>
<p>This is probably your best bet. If the paster shell is a packaged app (a la py2exe) it should still work.</p>
<p>See also:</p>
<p><a href="http://www.rexx.com/~dkuhlman/pylons_quick_site.html#using-an-ipython-embedded-shell" rel="nofollow">http://www.rexx.com/~dkuhlman/pylons_quick_site.html#using-an-ipython-embedded-shell</a>
<a href="http://pylonshq.com/project/pylonshq/ticket/428" rel="nofollow">http://pylonshq.com/project/pylonshq/ticket/428</a></p>
| 2 | 2009-06-17T17:26:46Z | [
"python",
"pylons",
"paster"
] |
How to mark a global as deprecated in Python? | 922,550 | <p><a href="http://wiki.python.org/moin/PythonDecoratorLibrary#Smartdeprecationwarnings.28withvalidfilenames.2Clinenumbers.2Cetc..29">I've seen decorators</a> that let you mark a function a deprecated so that a warning is given whenever that function is used. I'd like to do the same thing but for a global variable, but I can't think of a way to detect global variable accesses. I know about the globals() function, and I could check its contents, but that would just tell me if the global is defined (which it still will be if the function is deprecated and not all out removed) not if it's actually being used. The best alternative I can think of is something like this:</p>
<pre><code># myglobal = 3
myglobal = DEPRECATED(3)
</code></pre>
<p>But besides the problem of how to get DEPRECATED to act exactly like a '3', I'm not sure what DEPRECATED could do that would let you detect every time it's accessed. I think the best it could do is iterate through all of the global's methods (since everything in Python is an object, so even '3' has methods, for converting to string and the like) and 'decorate' them to all be deprecated. But that's not ideal.</p>
<p>Any ideas? Has anyone else tackled this problem?</p>
| 6 | 2009-05-28T18:48:00Z | 922,645 | <p>You could make your module into a class (see e.g <a href="http://stackoverflow.com/questions/880530/can-python-modules-have-properties-the-same-way-that-objects-can">this SO question</a>) and make that deprecated global into a property, so you can execute some of your code when it's accessed and provide the warning you desire. However, this does seem a bit of an overkill.</p>
| 4 | 2009-05-28T19:08:02Z | [
"python",
"hook",
"decorator",
"global",
"deprecated"
] |
How to mark a global as deprecated in Python? | 922,550 | <p><a href="http://wiki.python.org/moin/PythonDecoratorLibrary#Smartdeprecationwarnings.28withvalidfilenames.2Clinenumbers.2Cetc..29">I've seen decorators</a> that let you mark a function a deprecated so that a warning is given whenever that function is used. I'd like to do the same thing but for a global variable, but I can't think of a way to detect global variable accesses. I know about the globals() function, and I could check its contents, but that would just tell me if the global is defined (which it still will be if the function is deprecated and not all out removed) not if it's actually being used. The best alternative I can think of is something like this:</p>
<pre><code># myglobal = 3
myglobal = DEPRECATED(3)
</code></pre>
<p>But besides the problem of how to get DEPRECATED to act exactly like a '3', I'm not sure what DEPRECATED could do that would let you detect every time it's accessed. I think the best it could do is iterate through all of the global's methods (since everything in Python is an object, so even '3' has methods, for converting to string and the like) and 'decorate' them to all be deprecated. But that's not ideal.</p>
<p>Any ideas? Has anyone else tackled this problem?</p>
| 6 | 2009-05-28T18:48:00Z | 922,693 | <p>You can't do this directly, since theres no way of intercepting the module access. However, you can replace that module with an object of your choosing that acts as a proxy, looking for accesses to certain properties:</p>
<pre><code>import sys, warnings
def WrapMod(mod, deprecated):
"""Return a wrapped object that warns about deprecated accesses"""
deprecated = set(deprecated)
class Wrapper(object):
def __getattr__(self, attr):
if attr in deprecated:
warnings.warn("Property %s is deprecated" % attr)
return getattr(mod, attr)
def __setattr__(self, attr, value):
if attr in deprecated:
warnings.warn("Property %s is deprecated" % attr)
return setattr(mod, attr, value)
return Wrapper()
oldVal = 6*9
newVal = 42
sys.modules[__name__] = WrapMod(sys.modules[__name__],
deprecated = ['oldVal'])
</code></pre>
<p>Now, you can use it as:</p>
<pre><code>>>> import mod1
>>> mod1.newVal
42
>>> mod1.oldVal
mod1.py:11: UserWarning: Property oldVal is deprecated
warnings.warn("Property %s is deprecated" % attr)
54
</code></pre>
<p>The downside is that you are now performing two lookups when you access the module, so there is a slight performance hit.</p>
| 13 | 2009-05-28T19:16:29Z | [
"python",
"hook",
"decorator",
"global",
"deprecated"
] |
How to mark a global as deprecated in Python? | 922,550 | <p><a href="http://wiki.python.org/moin/PythonDecoratorLibrary#Smartdeprecationwarnings.28withvalidfilenames.2Clinenumbers.2Cetc..29">I've seen decorators</a> that let you mark a function a deprecated so that a warning is given whenever that function is used. I'd like to do the same thing but for a global variable, but I can't think of a way to detect global variable accesses. I know about the globals() function, and I could check its contents, but that would just tell me if the global is defined (which it still will be if the function is deprecated and not all out removed) not if it's actually being used. The best alternative I can think of is something like this:</p>
<pre><code># myglobal = 3
myglobal = DEPRECATED(3)
</code></pre>
<p>But besides the problem of how to get DEPRECATED to act exactly like a '3', I'm not sure what DEPRECATED could do that would let you detect every time it's accessed. I think the best it could do is iterate through all of the global's methods (since everything in Python is an object, so even '3' has methods, for converting to string and the like) and 'decorate' them to all be deprecated. But that's not ideal.</p>
<p>Any ideas? Has anyone else tackled this problem?</p>
| 6 | 2009-05-28T18:48:00Z | 924,306 | <p>Behold:</p>
<h3>Code</h3>
<pre><code>from types import *
def wrapper(f, warning):
def new(*args, **kwargs):
if not args[0].warned:
print "Deprecated Warning: %s" % warning
args[0].warned = True
return f(*args, **kwargs)
return new
class Deprecated(object):
def __new__(self, o, warning):
print "Creating Deprecated Object"
class temp(o.__class__): pass
temp.__name__ = "Deprecated_%s" % o.__class__.__name__
output = temp.__new__(temp, o)
output.warned = True
wrappable_types = (type(int.__add__), type(zip), FunctionType)
unwrappable_names = ("__str__", "__unicode__", "__repr__", "__getattribute__", "__setattr__")
for method_name in dir(temp):
if not type(getattr(temp, method_name)) in wrappable_types: continue
if method_name in unwrappable_names: continue
setattr(temp, method_name, wrapper(getattr(temp, method_name), warning))
output.warned = False
return output
</code></pre>
<h3>Output</h3>
<pre><code>>>> a=Deprecated(1, "Don't use 1")
Creating Deprecated Object
>>> a+9
Deprecated Warning: Don't use 1
10
>>> a*4
4
>>> 2*a
2
</code></pre>
<p>This can obviously be refined, but the gist is there.</p>
| 4 | 2009-05-29T03:51:55Z | [
"python",
"hook",
"decorator",
"global",
"deprecated"
] |
Unicode problems in PyObjC | 922,562 | <p>I am trying to figure out PyObjC on Mac OS X, and I have written a simple program to print out the names in my Address Book. However, I am having some trouble with the encoding of the output.</p>
<pre><code>#! /usr/bin/env python
# -*- coding: UTF-8 -*-
from AddressBook import *
ab = ABAddressBook.sharedAddressBook()
people = ab.people()
for person in people:
name = person.valueForProperty_("First") + ' ' + person.valueForProperty_("Last")
name
</code></pre>
<p>when I run this program, the output looks something like this:</p>
<pre><code>...snip...
u'Jacob \xc5berg'
u'Fernando Gonzales'
...snip...
</code></pre>
<p>Could someone please explain why the strings are in unicode, but the content looks like that?</p>
<p>I have also noticed that when I try to print the name I get the error</p>
<pre><code>UnicodeEncodeError: 'ascii' codec can't encode character u'\xc5' in position 6: ordinal not in range(128)
</code></pre>
| 3 | 2009-05-28T18:51:32Z | 922,592 | <p>Just writing the variable name sends <code>repr(name)</code> to the standard output and <code>repr()</code> encodes all unicode values.</p>
<p><code>print</code> tries to convert <code>u'Jacob \xc5berg'</code> to ASCII, which doesn't work. Try writing it to a file.</p>
<p>See <a href="http://wiki.python.org/moin/PrintFails" rel="nofollow">Print Fails on the python wiki</a>.</p>
<blockquote>
<p>That means you're using legacy,
limited or misconfigured console. If
you're just trying to play with
unicode at interactive prompt move to
a modern unicode-aware console. Most
modern Python distributions come with
IDLE where you'll be able to print all
unicode characters.</p>
</blockquote>
| 0 | 2009-05-28T18:56:54Z | [
"python",
"osx",
"unicode",
"pyobjc"
] |
Unicode problems in PyObjC | 922,562 | <p>I am trying to figure out PyObjC on Mac OS X, and I have written a simple program to print out the names in my Address Book. However, I am having some trouble with the encoding of the output.</p>
<pre><code>#! /usr/bin/env python
# -*- coding: UTF-8 -*-
from AddressBook import *
ab = ABAddressBook.sharedAddressBook()
people = ab.people()
for person in people:
name = person.valueForProperty_("First") + ' ' + person.valueForProperty_("Last")
name
</code></pre>
<p>when I run this program, the output looks something like this:</p>
<pre><code>...snip...
u'Jacob \xc5berg'
u'Fernando Gonzales'
...snip...
</code></pre>
<p>Could someone please explain why the strings are in unicode, but the content looks like that?</p>
<p>I have also noticed that when I try to print the name I get the error</p>
<pre><code>UnicodeEncodeError: 'ascii' codec can't encode character u'\xc5' in position 6: ordinal not in range(128)
</code></pre>
| 3 | 2009-05-28T18:51:32Z | 922,622 | <pre><code># -*- coding: UTF-8 -*-
</code></pre>
<p>only affects the way Python decodes comments and string literals in your source, <strong>not</strong> the way standard output is configured, etc, etc. If you set your Mac's Terminal to UTF-8 (Terminal, Preferences, Settings, Advanced, International dropdown) and emit Unicode text to it after encoding it in UTF-8 (<code>print name.encode("utf-8")</code>), you should be fine.</p>
| 2 | 2009-05-28T19:02:45Z | [
"python",
"osx",
"unicode",
"pyobjc"
] |
Unicode problems in PyObjC | 922,562 | <p>I am trying to figure out PyObjC on Mac OS X, and I have written a simple program to print out the names in my Address Book. However, I am having some trouble with the encoding of the output.</p>
<pre><code>#! /usr/bin/env python
# -*- coding: UTF-8 -*-
from AddressBook import *
ab = ABAddressBook.sharedAddressBook()
people = ab.people()
for person in people:
name = person.valueForProperty_("First") + ' ' + person.valueForProperty_("Last")
name
</code></pre>
<p>when I run this program, the output looks something like this:</p>
<pre><code>...snip...
u'Jacob \xc5berg'
u'Fernando Gonzales'
...snip...
</code></pre>
<p>Could someone please explain why the strings are in unicode, but the content looks like that?</p>
<p>I have also noticed that when I try to print the name I get the error</p>
<pre><code>UnicodeEncodeError: 'ascii' codec can't encode character u'\xc5' in position 6: ordinal not in range(128)
</code></pre>
| 3 | 2009-05-28T18:51:32Z | 922,647 | <p>Convert it to a unicode string through:</p>
<pre><code>print unicode(name)
</code></pre>
| 0 | 2009-05-28T19:08:02Z | [
"python",
"osx",
"unicode",
"pyobjc"
] |
Unicode problems in PyObjC | 922,562 | <p>I am trying to figure out PyObjC on Mac OS X, and I have written a simple program to print out the names in my Address Book. However, I am having some trouble with the encoding of the output.</p>
<pre><code>#! /usr/bin/env python
# -*- coding: UTF-8 -*-
from AddressBook import *
ab = ABAddressBook.sharedAddressBook()
people = ab.people()
for person in people:
name = person.valueForProperty_("First") + ' ' + person.valueForProperty_("Last")
name
</code></pre>
<p>when I run this program, the output looks something like this:</p>
<pre><code>...snip...
u'Jacob \xc5berg'
u'Fernando Gonzales'
...snip...
</code></pre>
<p>Could someone please explain why the strings are in unicode, but the content looks like that?</p>
<p>I have also noticed that when I try to print the name I get the error</p>
<pre><code>UnicodeEncodeError: 'ascii' codec can't encode character u'\xc5' in position 6: ordinal not in range(128)
</code></pre>
| 3 | 2009-05-28T18:51:32Z | 924,626 | <p>If you run the code in your question in the interactive console the interpreter will print the repr of "name" because of the last statement of the loop.</p>
<p>If you change the last line of the loop from just "name" to "print name" the output should be fine. I've tested this with Terminal.app on a 10.5.7 system. </p>
| 1 | 2009-05-29T06:12:33Z | [
"python",
"osx",
"unicode",
"pyobjc"
] |
Installing/configuring gdbm Python module for cvs2svn? | 922,750 | <p>I am trying to install cvs2svn on a Solaris 10 machine. It has Python 2.4.4 on it. I don't have root access. When I downloaded cvs2svn and tried to run it, it said</p>
<blockquote>
<p>ERROR: cvs2svn uses the anydbm package, which depends on lower level dbm libraries. Your system has dbm, with which cvs2svn is known to have problems. To use cvs2svn, you must install a Python dbm library other than dumbdbm or dbm. See <a href="http://python.org/doc/current/lib/module-anydbm.html" rel="nofollow">http://python.org/doc/current/lib/module-anydbm.html</a> for more information.</p>
</blockquote>
<p>I downloaded gdbm, compiled, and installed it in my home directory. How do I get a Python gdbm module installed that works with anydbm? Google isn't helping...</p>
| 2 | 2009-05-28T19:28:09Z | 992,715 | <p>Set the <code>$PYTHONPATH</code> environment variable to point to the location where you installed <code>gdbm</code>. Then when you run <code>cvs2svn</code>, the anybdm module should find <code>gdbm</code> successfully.</p>
| 0 | 2009-06-14T12:10:31Z | [
"python",
"solaris",
"cvs2svn",
"gdbm"
] |
Installing/configuring gdbm Python module for cvs2svn? | 922,750 | <p>I am trying to install cvs2svn on a Solaris 10 machine. It has Python 2.4.4 on it. I don't have root access. When I downloaded cvs2svn and tried to run it, it said</p>
<blockquote>
<p>ERROR: cvs2svn uses the anydbm package, which depends on lower level dbm libraries. Your system has dbm, with which cvs2svn is known to have problems. To use cvs2svn, you must install a Python dbm library other than dumbdbm or dbm. See <a href="http://python.org/doc/current/lib/module-anydbm.html" rel="nofollow">http://python.org/doc/current/lib/module-anydbm.html</a> for more information.</p>
</blockquote>
<p>I downloaded gdbm, compiled, and installed it in my home directory. How do I get a Python gdbm module installed that works with anydbm? Google isn't helping...</p>
| 2 | 2009-05-28T19:28:09Z | 1,044,879 | <p>I downloaded Python 2.5.1 and compiled it from the source. I made sure my gdbm libraries were in the appropriate paths and used the altinstall into my home directory. I can now run cvs2svn with my private copy of python.</p>
| 2 | 2009-06-25T16:27:44Z | [
"python",
"solaris",
"cvs2svn",
"gdbm"
] |
Installing/configuring gdbm Python module for cvs2svn? | 922,750 | <p>I am trying to install cvs2svn on a Solaris 10 machine. It has Python 2.4.4 on it. I don't have root access. When I downloaded cvs2svn and tried to run it, it said</p>
<blockquote>
<p>ERROR: cvs2svn uses the anydbm package, which depends on lower level dbm libraries. Your system has dbm, with which cvs2svn is known to have problems. To use cvs2svn, you must install a Python dbm library other than dumbdbm or dbm. See <a href="http://python.org/doc/current/lib/module-anydbm.html" rel="nofollow">http://python.org/doc/current/lib/module-anydbm.html</a> for more information.</p>
</blockquote>
<p>I downloaded gdbm, compiled, and installed it in my home directory. How do I get a Python gdbm module installed that works with anydbm? Google isn't helping...</p>
| 2 | 2009-05-28T19:28:09Z | 29,111,972 | <p>To install gdbm for Python, try:</p>
<pre><code>pip install gdbm
</code></pre>
<p>If <code>pip</code> is not present, install it via: <code>easy_install pip</code>.</p>
<p>On OSX, you may try (if <code>brew</code> is installed):</p>
<pre><code>brew install gdbm
</code></pre>
| 0 | 2015-03-18T00:07:46Z | [
"python",
"solaris",
"cvs2svn",
"gdbm"
] |
Syntax Highlight for Mako in Eclipse or TextMate? | 922,771 | <p>Does anyone know of a syntax highlight for Mako templates for Eclipse or for TextMate?</p>
<p>I know that there is a <code>.mako</code> syntax highlighter for the default text editor in Ubuntu.</p>
| 12 | 2009-05-28T19:34:26Z | 922,950 | <p>Claudio,</p>
<p>I don't use mako templates, but a quick google search turned up <a href="http://groups.google.com/group/mako-discuss/browse%5Fthread/thread/796926337af30cf0" rel="nofollow">this article</a> from the mako-discuss google group, which refers to a Colorer library syntax highlighter. This sounds like it might be a decent lead for you.</p>
<p>-matt</p>
| 2 | 2009-05-28T20:21:41Z | [
"python",
"templates",
"mako"
] |
Syntax Highlight for Mako in Eclipse or TextMate? | 922,771 | <p>Does anyone know of a syntax highlight for Mako templates for Eclipse or for TextMate?</p>
<p>I know that there is a <code>.mako</code> syntax highlighter for the default text editor in Ubuntu.</p>
| 12 | 2009-05-28T19:34:26Z | 923,030 | <p>What I ended up doing was naming my Mako Templates with .html suffix and thus getting the usual HTML syntax highlighting etc. that I am used to. Alternatively I could have associated .mako suffix with the HTML handler. While this does not address Mako specifically, it was enough for me, since I find most of the template is plain HTML anyway.</p>
| 2 | 2009-05-28T20:38:05Z | [
"python",
"templates",
"mako"
] |
Syntax Highlight for Mako in Eclipse or TextMate? | 922,771 | <p>Does anyone know of a syntax highlight for Mako templates for Eclipse or for TextMate?</p>
<p>I know that there is a <code>.mako</code> syntax highlighter for the default text editor in Ubuntu.</p>
| 12 | 2009-05-28T19:34:26Z | 929,130 | <p>I just did some <a href="http://www.google.com/search?q=mako%2Bbundle%2Btextmate" rel="nofollow">googlin'</a>. There is a <a href="http://svn.makotemplates.org/contrib/textmate/Mako.tmbundle/" rel="nofollow">Mako bundle</a>.</p>
<p>I installed it under <code>~/Library/Application Support/TextMate/Bundles/</code> like so:</p>
<pre>
cd ~/Library/Application\ Support/TextMate/Bundles/
svn co http://svn.makotemplates.org/contrib/textmate/Mako.tmbundle
</pre>
<p>In TextMate, I did <code>Bundles | Bundle Editor | Reload Bundles</code>, and <code>Mako</code> showed up in the menu.</p>
<p>It adds new HTML language variant: <code>HTML (Mako)</code>, snippets and stuff like that.</p>
<p>Hope this helps.</p>
| 8 | 2009-05-30T06:03:34Z | [
"python",
"templates",
"mako"
] |
Syntax Highlight for Mako in Eclipse or TextMate? | 922,771 | <p>Does anyone know of a syntax highlight for Mako templates for Eclipse or for TextMate?</p>
<p>I know that there is a <code>.mako</code> syntax highlighter for the default text editor in Ubuntu.</p>
| 12 | 2009-05-28T19:34:26Z | 8,544,623 | <p>You can go to:</p>
<ol>
<li>Preferences->General->Editors->File Associations.</li>
<li>Click to add a new file type and type *.mak and click OK.</li>
<li>In File types click on *.mak and under Associated editors add HTML editor(default), Text Editor, Text Editor(studio) and Web Browser.</li>
</ol>
<p>This colors the text, works OK for me :)</p>
<p>P.S. Be sure to have the Aptana plugin installed.</p>
| 1 | 2011-12-17T12:09:00Z | [
"python",
"templates",
"mako"
] |
Syntax Highlight for Mako in Eclipse or TextMate? | 922,771 | <p>Does anyone know of a syntax highlight for Mako templates for Eclipse or for TextMate?</p>
<p>I know that there is a <code>.mako</code> syntax highlighter for the default text editor in Ubuntu.</p>
| 12 | 2009-05-28T19:34:26Z | 28,453,546 | <p>There is a <a href="http://sourceforge.net/projects/makotemplateeditor/%20Mako%20Template%20Editor" rel="nofollow">Mako Template Editor</a> for Eclipse. To install, copy the plugins directory with the jar file into your dropins folder in your Eclipse root folder. That is, a manual installation of a Eclipse plugin in jar format.</p>
| 0 | 2015-02-11T11:44:32Z | [
"python",
"templates",
"mako"
] |
Syntax Highlight for Mako in Eclipse or TextMate? | 922,771 | <p>Does anyone know of a syntax highlight for Mako templates for Eclipse or for TextMate?</p>
<p>I know that there is a <code>.mako</code> syntax highlighter for the default text editor in Ubuntu.</p>
| 12 | 2009-05-28T19:34:26Z | 30,838,894 | <ol>
<li><p>Windows (menu) > Preference > General > Editor > File Associations
Add *.mako in File Types (upper box) and add Html editor in Associated editor (lower box)</p></li>
<li><p>Windows (menu) > Preference > General > Editor > Content Types</p></li>
</ol>
<p>Under Text find HTML and add *.mako in File associations.</p>
| 0 | 2015-06-15T06:48:55Z | [
"python",
"templates",
"mako"
] |
Syntax Highlight for Mako in Eclipse or TextMate? | 922,771 | <p>Does anyone know of a syntax highlight for Mako templates for Eclipse or for TextMate?</p>
<p>I know that there is a <code>.mako</code> syntax highlighter for the default text editor in Ubuntu.</p>
| 12 | 2009-05-28T19:34:26Z | 31,271,028 | <p>The LiClipse plugin (<a href="http://www.liclipse.com/" rel="nofollow">http://www.liclipse.com/</a>), provides Mako support out of the box for Eclipse (and as a note, if you want support for any other language in Eclipse, LiClipse can load any existing TextMate bundle -- <a href="http://www.liclipse.com/textmate_bundles.html" rel="nofollow">http://www.liclipse.com/textmate_bundles.html</a> -- for that).</p>
| 0 | 2015-07-07T14:12:19Z | [
"python",
"templates",
"mako"
] |
Check if input is a list/tuple of strings or a single string | 922,774 | <p>I've a method that I want to be able to accept either a single string (a path, but not necessarily one that exists on the machine running the code) or a list/tuple of strings.</p>
<p>Given that strings act as lists of characters, how do I tell which the method has received?</p>
<p>I'd like to be able to accept either standard or unicode strings for a single entry, and either lists or tuples for multiple, so isinstance doesn't seem to be the answer unless I'm missing a clever trick with it (like taking advantage of common ancestor classes?).</p>
<p>Python version is 2.5</p>
| 17 | 2009-05-28T19:35:21Z | 922,784 | <p>Have you considered <code>varargs</code> syntax? I'm not really sure if this is what you're asking, but would something like <a href="http://stackoverflow.com/questions/836387/how-can-i-tell-if-a-python-variable-is-a-string-or-a-list/836406#836406">this question</a> be along your lines?</p>
| 0 | 2009-05-28T19:36:46Z | [
"python"
] |
Check if input is a list/tuple of strings or a single string | 922,774 | <p>I've a method that I want to be able to accept either a single string (a path, but not necessarily one that exists on the machine running the code) or a list/tuple of strings.</p>
<p>Given that strings act as lists of characters, how do I tell which the method has received?</p>
<p>I'd like to be able to accept either standard or unicode strings for a single entry, and either lists or tuples for multiple, so isinstance doesn't seem to be the answer unless I'm missing a clever trick with it (like taking advantage of common ancestor classes?).</p>
<p>Python version is 2.5</p>
| 17 | 2009-05-28T19:35:21Z | 922,796 | <p>You can check if a variable is a string or unicode string with</p>
<pre><code>isinstance(some_object, basestring)
</code></pre>
<p>This will return <code>True</code> for both strings and unicode strings</p>
<p>Edit:</p>
<p>You could do something like this:</p>
<pre><code>if isinstance(some_object, basestring):
...
elif all(isinstance(item, basestring) for item in some_object): # check iterable for stringness of all items. Will raise TypeError if some_object is not iterable
...
else:
raise TypeError # or something along that line
</code></pre>
<p>Stringness is probably not a word, but I hope you get the idea</p>
| 27 | 2009-05-28T19:39:05Z | [
"python"
] |
Check if input is a list/tuple of strings or a single string | 922,774 | <p>I've a method that I want to be able to accept either a single string (a path, but not necessarily one that exists on the machine running the code) or a list/tuple of strings.</p>
<p>Given that strings act as lists of characters, how do I tell which the method has received?</p>
<p>I'd like to be able to accept either standard or unicode strings for a single entry, and either lists or tuples for multiple, so isinstance doesn't seem to be the answer unless I'm missing a clever trick with it (like taking advantage of common ancestor classes?).</p>
<p>Python version is 2.5</p>
| 17 | 2009-05-28T19:35:21Z | 922,799 | <p>Check the type with isinstance(arg, basestring)</p>
| 3 | 2009-05-28T19:39:30Z | [
"python"
] |
Check if input is a list/tuple of strings or a single string | 922,774 | <p>I've a method that I want to be able to accept either a single string (a path, but not necessarily one that exists on the machine running the code) or a list/tuple of strings.</p>
<p>Given that strings act as lists of characters, how do I tell which the method has received?</p>
<p>I'd like to be able to accept either standard or unicode strings for a single entry, and either lists or tuples for multiple, so isinstance doesn't seem to be the answer unless I'm missing a clever trick with it (like taking advantage of common ancestor classes?).</p>
<p>Python version is 2.5</p>
| 17 | 2009-05-28T19:35:21Z | 922,800 | <p>Type checking:</p>
<pre><code>def func(arg):
if not isinstance(arg, (list, tuple)):
arg = [arg]
# process
func('abc')
func(['abc', '123'])
</code></pre>
<p>Varargs:</p>
<pre><code>def func(*arg):
# process
func('abc')
func('abc', '123')
func(*['abc', '123'])
</code></pre>
| 5 | 2009-05-28T19:39:42Z | [
"python"
] |
Check if input is a list/tuple of strings or a single string | 922,774 | <p>I've a method that I want to be able to accept either a single string (a path, but not necessarily one that exists on the machine running the code) or a list/tuple of strings.</p>
<p>Given that strings act as lists of characters, how do I tell which the method has received?</p>
<p>I'd like to be able to accept either standard or unicode strings for a single entry, and either lists or tuples for multiple, so isinstance doesn't seem to be the answer unless I'm missing a clever trick with it (like taking advantage of common ancestor classes?).</p>
<p>Python version is 2.5</p>
| 17 | 2009-05-28T19:35:21Z | 922,809 | <p>isinstance is an option:</p>
<pre><code>In [2]: isinstance("a", str)
Out[2]: True
In [3]: isinstance([], str)
Out[3]: False
In [4]: isinstance([], list)
Out[4]: True
In [5]: isinstance("", list)
Out[5]: False
</code></pre>
| 2 | 2009-05-28T19:41:12Z | [
"python"
] |
Check if input is a list/tuple of strings or a single string | 922,774 | <p>I've a method that I want to be able to accept either a single string (a path, but not necessarily one that exists on the machine running the code) or a list/tuple of strings.</p>
<p>Given that strings act as lists of characters, how do I tell which the method has received?</p>
<p>I'd like to be able to accept either standard or unicode strings for a single entry, and either lists or tuples for multiple, so isinstance doesn't seem to be the answer unless I'm missing a clever trick with it (like taking advantage of common ancestor classes?).</p>
<p>Python version is 2.5</p>
| 17 | 2009-05-28T19:35:21Z | 26,797,718 | <p>As I like to keep things simple, here is the shortest form that is compatible with both 2.x and 3.x:</p>
<pre><code># trick for py2/3 compatibility
if 'basestring' not in globals():
basestring = str
v = "xx"
if isinstance(v, basestring):
print("is string")
</code></pre>
| 4 | 2014-11-07T09:10:54Z | [
"python"
] |
Check if input is a list/tuple of strings or a single string | 922,774 | <p>I've a method that I want to be able to accept either a single string (a path, but not necessarily one that exists on the machine running the code) or a list/tuple of strings.</p>
<p>Given that strings act as lists of characters, how do I tell which the method has received?</p>
<p>I'd like to be able to accept either standard or unicode strings for a single entry, and either lists or tuples for multiple, so isinstance doesn't seem to be the answer unless I'm missing a clever trick with it (like taking advantage of common ancestor classes?).</p>
<p>Python version is 2.5</p>
| 17 | 2009-05-28T19:35:21Z | 40,032,590 | <p>Can't you do:</p>
<pre><code>(i == list (i) or i == tuple (i))
</code></pre>
<p>It would reply if the input is tuple or list. The only issue is that it doesn't work properly with a tuple holding only one variable.</p>
| 0 | 2016-10-13T23:22:36Z | [
"python"
] |
Writing a kernel mode profiler for processes in python | 922,788 | <p>I would like seek some guidance in writing a "process profiler" which runs in kernel mode. I am asking for a kernel mode profiler is because I run loads of applications and I do not want my profiler to be swapped out.</p>
<p>When I said "process profiler" I mean to something that would monitor resource usage by the process. including usage of threads and their statistics.</p>
<p>And I wish to write this in python. Point me to some modules or helpful resource.</p>
<p>Please provide me guidance/suggestion for doing it.</p>
<h2>Thanks,</h2>
<p>Edit::: Would like to add that currently my interest isto write only for linux. however after i built it i will have to support windows.</p>
| 2 | 2009-05-28T19:37:54Z | 922,814 | <p>It's going to be very difficult to do the process monitoring part in Python, since the python interpreter doesn't run in the kernel.</p>
<p>I suspect there are two easy approaches to this:</p>
<ol>
<li>use the /proc filesystem if you have one (you don't mention your OS)</li>
<li>Use dtrace if you have dtrace (again, without the OS, who knows.)</li>
</ol>
<p><hr /></p>
<p>Okay, following up after the edit.</p>
<p>First, there's no way you're going to be able to write code that runs in the kernel, in python, and is portable between Linux and Windows. Or at least if you were to, it would be a hack that would live in glory forever.</p>
<p>That said, though, if your purpose is to process Python, there are a lot of Python tools available to get information from the Python interpreter at run time.</p>
<p>If instead your desire is to get process information from <em>other</em> processes in general, you're going to need to examine the options available to you in the various OS APIs. Linux has a /proc filesystem; that's a useful start. I suspect Windows has similar APIs, but I don't know them.</p>
<p>If you have to write kernel code, you'll almost certainly need to write it in C or C++.</p>
| 7 | 2009-05-28T19:42:20Z | [
"python",
"kernel"
] |
Writing a kernel mode profiler for processes in python | 922,788 | <p>I would like seek some guidance in writing a "process profiler" which runs in kernel mode. I am asking for a kernel mode profiler is because I run loads of applications and I do not want my profiler to be swapped out.</p>
<p>When I said "process profiler" I mean to something that would monitor resource usage by the process. including usage of threads and their statistics.</p>
<p>And I wish to write this in python. Point me to some modules or helpful resource.</p>
<p>Please provide me guidance/suggestion for doing it.</p>
<h2>Thanks,</h2>
<p>Edit::: Would like to add that currently my interest isto write only for linux. however after i built it i will have to support windows.</p>
| 2 | 2009-05-28T19:37:54Z | 922,875 | <p><strong>don't</strong> try and get python running in kernel space!</p>
<p>You would be much better using an existing tool and getting it to spit out XML that can be sucked into Python. I wouldn't want to port the Python interpreter to kernel-mode (it sounds grim writing it).</p>
<p>The /proc option does sound good.</p>
<p><strong>some code</strong> code that reads proc information to determine memory usage and such. Should get you going:</p>
<p><a href="http://www.pixelbeat.org/scripts/ps_mem.py" rel="nofollow">http://www.pixelbeat.org/scripts/ps_mem.py</a> <strong>reads memory information of processes using Python through /proc/smaps</strong> like charlie suggested.</p>
| 3 | 2009-05-28T20:02:14Z | [
"python",
"kernel"
] |
Writing a kernel mode profiler for processes in python | 922,788 | <p>I would like seek some guidance in writing a "process profiler" which runs in kernel mode. I am asking for a kernel mode profiler is because I run loads of applications and I do not want my profiler to be swapped out.</p>
<p>When I said "process profiler" I mean to something that would monitor resource usage by the process. including usage of threads and their statistics.</p>
<p>And I wish to write this in python. Point me to some modules or helpful resource.</p>
<p>Please provide me guidance/suggestion for doing it.</p>
<h2>Thanks,</h2>
<p>Edit::: Would like to add that currently my interest isto write only for linux. however after i built it i will have to support windows.</p>
| 2 | 2009-05-28T19:37:54Z | 922,904 | <p>have you looked at <code>PSI</code>? (<a href="http://www.psychofx.com/psi/" rel="nofollow">http://www.psychofx.com/psi/</a>)</p>
<p>"PSI is a Python module providing direct access to real-time system and process information. PSI is a Python C extension, providing the most efficient access to system information directly from system calls."</p>
<p>it might give you what you are looking for. .... or at least a starting point.</p>
<hr>
<p>Edit 2014:</p>
<p>I'd recommend checking out <code>psutil</code> instead:
<a href="https://pypi.python.org/pypi/psutil" rel="nofollow">https://pypi.python.org/pypi/psutil</a></p>
<p><code>psutil</code> is actively maintained and has some nifty process monitoring features. <code>PSI</code> seems to be somewhat dead (last release 2009).</p>
| 0 | 2009-05-28T20:10:16Z | [
"python",
"kernel"
] |
Writing a kernel mode profiler for processes in python | 922,788 | <p>I would like seek some guidance in writing a "process profiler" which runs in kernel mode. I am asking for a kernel mode profiler is because I run loads of applications and I do not want my profiler to be swapped out.</p>
<p>When I said "process profiler" I mean to something that would monitor resource usage by the process. including usage of threads and their statistics.</p>
<p>And I wish to write this in python. Point me to some modules or helpful resource.</p>
<p>Please provide me guidance/suggestion for doing it.</p>
<h2>Thanks,</h2>
<p>Edit::: Would like to add that currently my interest isto write only for linux. however after i built it i will have to support windows.</p>
| 2 | 2009-05-28T19:37:54Z | 923,386 | <p>Some of your comments on other answers suggest that you are a relatively inexperienced programmer. Therefore I would strongly suggest that you stay away from kernel programming, as it is very hard even for experienced programmers.</p>
<p>Why would you want to write something that</p>
<ul>
<li>is a very complex system (just look at existing profiling infrastructures and how complex they are)</li>
<li>can not be done in python (I don't know any kernel that would allow execution of python in kernel mode)</li>
<li>already exists (<a href="http://oprofile.sourceforge.net/" rel="nofollow">oprofile</a> on Linux)</li>
</ul>
| 0 | 2009-05-28T21:50:29Z | [
"python",
"kernel"
] |
SPNEGO (kerberos token generation/validation) for SSO using Python | 922,805 | <p>I'm attempting to implement a simple Single Sign On scenario where some of the participating servers will be windows (IIS) boxes. It looks like SPNEGO is a reasonable path for this.</p>
<p>Here's the scenario:</p>
<ul>
<li>User logs in to my SSO service using his username and password. I authenticate him using some mechanism.</li>
<li>At some later time the user wants to access App A.
<ul>
<li>The user's request for App A is intercepted by the SSO service. The SSO service uses SPNEGO to log the user in to App A:
<ul>
<li>The SSO service hits the App A web page, gets a "WWW-Authenticate: Negotiate" response</li>
<li>The SSO service generates a "Authorization: Negotiate xxx" response on behalf of the user, responds to App A. The user is now logged in to App A.</li>
</ul></li>
<li>The SSO service intercepts subsequent user requests for App A, inserting the Authorization header into them before passing them on to App A.</li>
</ul></li>
</ul>
<p>Does that sound right? </p>
<p>I need two things (at least that I can think of now):</p>
<ul>
<li>the ability to generate the "Authorization: Negotiate xxx" token on behalf of the user, preferably using Python</li>
<li>the ability to validate "Authorization: Negotiate xxx" headers in Python (for a later part of the project)</li>
</ul>
| 6 | 2009-05-28T19:40:12Z | 1,001,619 | <p>This is exactly what Apple does with its <a href="http://trac.calendarserver.org/" rel="nofollow">Calendar Server</a>. They have a <a href="http://trac.calendarserver.org/browser/PyKerberos" rel="nofollow">python gssapi</a> library for the kerberos part of the process, in order to implement <a href="http://www.ietf.org/rfc/rfc4559.txt" rel="nofollow">SPNEGO</a>. </p>
<p>Look in CalendarServer/twistedcaldav/authkerb.py for the server auth portion.
The kerberos module (which is a c module), doesn't have any useful docstrings, but PyKerberos/pysrc/kerberos.py has all the function definitions.</p>
<p>Here's the urls for the svn trunks:<br>
<a href="http://svn.calendarserver.org/repository/calendarserver/CalendarServer/trunk" rel="nofollow">http://svn.calendarserver.org/repository/calendarserver/CalendarServer/trunk</a><br>
<a href="http://svn.calendarserver.org/repository/calendarserver/PyKerberos/trunk" rel="nofollow">http://svn.calendarserver.org/repository/calendarserver/PyKerberos/trunk</a></p>
| 8 | 2009-06-16T13:49:51Z | [
"python",
"active-directory",
"single-sign-on",
"kerberos",
"spnego"
] |
SPNEGO (kerberos token generation/validation) for SSO using Python | 922,805 | <p>I'm attempting to implement a simple Single Sign On scenario where some of the participating servers will be windows (IIS) boxes. It looks like SPNEGO is a reasonable path for this.</p>
<p>Here's the scenario:</p>
<ul>
<li>User logs in to my SSO service using his username and password. I authenticate him using some mechanism.</li>
<li>At some later time the user wants to access App A.
<ul>
<li>The user's request for App A is intercepted by the SSO service. The SSO service uses SPNEGO to log the user in to App A:
<ul>
<li>The SSO service hits the App A web page, gets a "WWW-Authenticate: Negotiate" response</li>
<li>The SSO service generates a "Authorization: Negotiate xxx" response on behalf of the user, responds to App A. The user is now logged in to App A.</li>
</ul></li>
<li>The SSO service intercepts subsequent user requests for App A, inserting the Authorization header into them before passing them on to App A.</li>
</ul></li>
</ul>
<p>Does that sound right? </p>
<p>I need two things (at least that I can think of now):</p>
<ul>
<li>the ability to generate the "Authorization: Negotiate xxx" token on behalf of the user, preferably using Python</li>
<li>the ability to validate "Authorization: Negotiate xxx" headers in Python (for a later part of the project)</li>
</ul>
| 6 | 2009-05-28T19:40:12Z | 1,674,918 | <p>Take a look at the <a href="http://spnego.sourceforge.net/credential%5Fdelegation.html" rel="nofollow">http://spnego.sourceforge.net/credential_delegation.html</a> tutorial. It seems to be doing what you are trying to do.</p>
| 1 | 2009-11-04T16:19:56Z | [
"python",
"active-directory",
"single-sign-on",
"kerberos",
"spnego"
] |
SPNEGO (kerberos token generation/validation) for SSO using Python | 922,805 | <p>I'm attempting to implement a simple Single Sign On scenario where some of the participating servers will be windows (IIS) boxes. It looks like SPNEGO is a reasonable path for this.</p>
<p>Here's the scenario:</p>
<ul>
<li>User logs in to my SSO service using his username and password. I authenticate him using some mechanism.</li>
<li>At some later time the user wants to access App A.
<ul>
<li>The user's request for App A is intercepted by the SSO service. The SSO service uses SPNEGO to log the user in to App A:
<ul>
<li>The SSO service hits the App A web page, gets a "WWW-Authenticate: Negotiate" response</li>
<li>The SSO service generates a "Authorization: Negotiate xxx" response on behalf of the user, responds to App A. The user is now logged in to App A.</li>
</ul></li>
<li>The SSO service intercepts subsequent user requests for App A, inserting the Authorization header into them before passing them on to App A.</li>
</ul></li>
</ul>
<p>Does that sound right? </p>
<p>I need two things (at least that I can think of now):</p>
<ul>
<li>the ability to generate the "Authorization: Negotiate xxx" token on behalf of the user, preferably using Python</li>
<li>the ability to validate "Authorization: Negotiate xxx" headers in Python (for a later part of the project)</li>
</ul>
| 6 | 2009-05-28T19:40:12Z | 34,074,210 | <p>I've been searching quite some time for something similar (on Linux), that has lead me to this page several times, yet giving no answer. So here is my solution, I came up with:</p>
<p>The web-server is a Apache with mod_auth_kerb. It is already running in a Active Directory, single sign-on setup since quite some time.
What I was already able to do before:</p>
<ul>
<li>Using chromium with single sign on on Linux (with a proper krb5 setup, with working kinit user@domain)</li>
<li>Having python connect and single sign on using sspi from the pywin32 package, with something like <code>sspi.ClientAuth("Negotiate", targetspn="http/%s" % host)</code></li>
</ul>
<p>The following code snippet completes the puzzle (and my needs), having Python single sign on with Kerberos on Linux (using python-gssapi):</p>
<pre><code>in_token=base64.b64decode(neg_value)
service_name = gssapi.Name("HTTP@%s" % host, gssapi.C_NT_HOSTBASED_SERVICE)
spnegoMechOid = gssapi.oids.OID.mech_from_string("1.3.6.1.5.5.2")
ctx = gssapi.InitContext(service_name,mech_type=spnegoMechOid)
out_token = ctx.step(in_token)
buffer = sspi.AuthenticationBuffer()
outStr = base64.b64encode(out_token)
</code></pre>
| 0 | 2015-12-03T19:10:44Z | [
"python",
"active-directory",
"single-sign-on",
"kerberos",
"spnego"
] |
NameError using execfile in python | 922,897 | <p>My application has a button to execute a python script dynamically using <em>execfile</em>. If I define a function inside the script (eg. <em>spam()</em>) and try to use that function inside another function (eg. <em>eggs()</em>), I get this error: </p>
<pre><code>NameError: global name 'spam' is not defined
</code></pre>
<p>What is the correct way to call the <em>spam()</em> function from within <em>eggs()</em>?</p>
<pre><code>#mainprogram.py
class mainprogram():
def runme(self):
execfile("myscript.py")
>>> this = mainprogram()
>>> this.runme()
# myscript.py
def spam():
print "spam"
def eggs():
spam()
eggs()
</code></pre>
<p>Also, I can't seem to be able to execute a method from my main application in the script. i.e.</p>
<pre><code>#mainprogram.py
class mainprogram():
def on_cmdRunScript_mouseClick( self, event ):
execfile("my2ndscript.py")
def bleh():
print "bleh"
#my2ndscript.py
bleh()
</code></pre>
<p>The error is: </p>
<pre><code>NameError: name 'bleh' is not defined
</code></pre>
<p>What is the correct way to call <em>bleh()</em> from <em>my2ndscript.py</em>?</p>
<p><strong>EDIT</strong>: Updated first issue</p>
| 2 | 2009-05-28T20:07:09Z | 922,912 | <p>Are you sure you posted the actual code you are having trouble with? The first script works fine for me.</p>
<p>The second error is to be expected: the name "bleh" is not defined in the outer block, only within the namespace of "mainprogram"</p>
| 1 | 2009-05-28T20:13:07Z | [
"python",
"class",
"scope",
"namespaces"
] |
NameError using execfile in python | 922,897 | <p>My application has a button to execute a python script dynamically using <em>execfile</em>. If I define a function inside the script (eg. <em>spam()</em>) and try to use that function inside another function (eg. <em>eggs()</em>), I get this error: </p>
<pre><code>NameError: global name 'spam' is not defined
</code></pre>
<p>What is the correct way to call the <em>spam()</em> function from within <em>eggs()</em>?</p>
<pre><code>#mainprogram.py
class mainprogram():
def runme(self):
execfile("myscript.py")
>>> this = mainprogram()
>>> this.runme()
# myscript.py
def spam():
print "spam"
def eggs():
spam()
eggs()
</code></pre>
<p>Also, I can't seem to be able to execute a method from my main application in the script. i.e.</p>
<pre><code>#mainprogram.py
class mainprogram():
def on_cmdRunScript_mouseClick( self, event ):
execfile("my2ndscript.py")
def bleh():
print "bleh"
#my2ndscript.py
bleh()
</code></pre>
<p>The error is: </p>
<pre><code>NameError: name 'bleh' is not defined
</code></pre>
<p>What is the correct way to call <em>bleh()</em> from <em>my2ndscript.py</em>?</p>
<p><strong>EDIT</strong>: Updated first issue</p>
| 2 | 2009-05-28T20:07:09Z | 925,155 | <p>In the second case you will need <code>import</code> (not sure whether "mainprogram.py"
is on your <code>$PYTHONPATH</code>)</p>
<pre><code>#mainprogram.py
class mainprogram:
def runme(self):
execfile("my2ndscript.py")
def bleh(self):
print "bleh"
if __name__ == '__main__':
mainprogram().runme()
#my2ndscript.py
import mainprogram
x = mainprogram.mainprogram()
x.bleh()
</code></pre>
<p>but this will craete second instance of <code>mainprogram</code>. Or better yet:</p>
<pre><code>#mainprogram.py
class mainprogram:
def runme(self):
execfile("my2ndscript.py", globals={'this': self})
def bleh(self):
print "bleh"
if __name__ == '__main__':
mainprogram().runme()
#my2ndscript.py
this.bleh()
</code></pre>
<p>I guess that <code>execfile</code> is not right solution for your problem anyway.
Why don't you use <code>import</code> or <code>__import__</code> (and <code>reload()</code> in case script may change between those clicks).</p>
<pre><code>#mainprogram.py
import my2ndscript
class mainprogram:
def runme(self):
reload(my2ndscript)
my2ndscript.main(self)
def bleh(self):
print "bleh"
if __name__ == '__main__':
mainprogram().runme()
#my2ndscript.py
def main(program):
program.bleh()
</code></pre>
| 2 | 2009-05-29T09:23:23Z | [
"python",
"class",
"scope",
"namespaces"
] |
NameError using execfile in python | 922,897 | <p>My application has a button to execute a python script dynamically using <em>execfile</em>. If I define a function inside the script (eg. <em>spam()</em>) and try to use that function inside another function (eg. <em>eggs()</em>), I get this error: </p>
<pre><code>NameError: global name 'spam' is not defined
</code></pre>
<p>What is the correct way to call the <em>spam()</em> function from within <em>eggs()</em>?</p>
<pre><code>#mainprogram.py
class mainprogram():
def runme(self):
execfile("myscript.py")
>>> this = mainprogram()
>>> this.runme()
# myscript.py
def spam():
print "spam"
def eggs():
spam()
eggs()
</code></pre>
<p>Also, I can't seem to be able to execute a method from my main application in the script. i.e.</p>
<pre><code>#mainprogram.py
class mainprogram():
def on_cmdRunScript_mouseClick( self, event ):
execfile("my2ndscript.py")
def bleh():
print "bleh"
#my2ndscript.py
bleh()
</code></pre>
<p>The error is: </p>
<pre><code>NameError: name 'bleh' is not defined
</code></pre>
<p>What is the correct way to call <em>bleh()</em> from <em>my2ndscript.py</em>?</p>
<p><strong>EDIT</strong>: Updated first issue</p>
| 2 | 2009-05-28T20:07:09Z | 14,722,331 | <p>You're 3 years 8 months wiser since you posted so I'm assuming you'd have figured the first issue out, but given that a solution has not yet been posted (primarily because no one seemed to have a problem with the first issue), the following is my solution.</p>
<h2>[UPDATED]</h2>
<p>The last solution I provided was incorrect. Below I am providing the correct solution and explaining it in detail using code that I executed.</p>
<p><strong>The problem is inherent in Python's <code>execfile()</code> builtin. Its one of the reasons that function has been deprecated in Python 3.x.</strong></p>
<p>When you executed <code>execfile()</code> inside <code>runme()</code>, the objects <code>spam()</code> and <code>eggs()</code> were loaded into method <code>runme()</code>'s namespace, and not into the global namespace <em>(as they should ideally be)</em>. Consider the following code:</p>
<h1>myscript.py</h1>
<pre><code>def spam():
print 'spam'
def eggs():
if 'spam' not in globals():
print 'method spam() is not present in global namespace'
spam()
try:
eggs()
except Exception as e:
print e
</code></pre>
<h1>mainprogram.py</h1>
<pre><code>class mainprogram():
def runme(self):
execfile("myscript.py")
print 'Objects lying in local namespace of runme() are -'
print locals()
this = mainprogram()
this.runme()
</code></pre>
<h1>Interpreter Output</h1>
<pre><code>>>>import mainprogram
method spam() is not present in global namespace
name 'spam' is not defined
Objects lying in local namespace of runme() are -
{'e': NameError("name 'spam' is not defined",), 'spam': <function spam at 0x000000000000002B>, 'eggs': <function eggs at 0x000000000000002C>, 'self': <mainprogram.mainprogram instance at 0x000000000000002D>}
</code></pre>
<p>From the output you can see that <code>spam()</code> is not in the global namespace, but in method <code>runme()</code>'s namespace. So hypothetically, the correct way to call <code>spam()</code> would have been</p>
<pre><code>def eggs():
global this
this.runme.spam()
</code></pre>
<p>However, there is no way to access <code>spam()</code> while it is lying inside <code>runme()</code>'s namespace. The solution, therefore, is to insert <code>spam()</code> in the global namespace as follows:</p>
<h1>myscript.py</h1>
<pre><code>global spam
def spam():
print "spam"
def eggs():
spam()
eggs()
</code></pre>
<p>This will ensure that a reference to object <code>spam()</code> is created inside the <code>globals()</code> dictionary (i.e., the global namespace), making it callable from <code>eggs()</code>.</p>
| 8 | 2013-02-06T05:38:23Z | [
"python",
"class",
"scope",
"namespaces"
] |
NameError using execfile in python | 922,897 | <p>My application has a button to execute a python script dynamically using <em>execfile</em>. If I define a function inside the script (eg. <em>spam()</em>) and try to use that function inside another function (eg. <em>eggs()</em>), I get this error: </p>
<pre><code>NameError: global name 'spam' is not defined
</code></pre>
<p>What is the correct way to call the <em>spam()</em> function from within <em>eggs()</em>?</p>
<pre><code>#mainprogram.py
class mainprogram():
def runme(self):
execfile("myscript.py")
>>> this = mainprogram()
>>> this.runme()
# myscript.py
def spam():
print "spam"
def eggs():
spam()
eggs()
</code></pre>
<p>Also, I can't seem to be able to execute a method from my main application in the script. i.e.</p>
<pre><code>#mainprogram.py
class mainprogram():
def on_cmdRunScript_mouseClick( self, event ):
execfile("my2ndscript.py")
def bleh():
print "bleh"
#my2ndscript.py
bleh()
</code></pre>
<p>The error is: </p>
<pre><code>NameError: name 'bleh' is not defined
</code></pre>
<p>What is the correct way to call <em>bleh()</em> from <em>my2ndscript.py</em>?</p>
<p><strong>EDIT</strong>: Updated first issue</p>
| 2 | 2009-05-28T20:07:09Z | 20,475,760 | <p>Addy689 explained the real problem: it is when calling execfile() <strong><em>from a function</em></strong> that it appears. execfile() works well from the global space. That's why answers are often 'for me it works'.</p>
<p>But the solution to modify the called scripts may not be possible.
So I report here the solution I think the best one, found on another equivalent problem with the exec() function (in that post: <a href="http://stackoverflow.com/a/11754346/1808778">http://stackoverflow.com/a/11754346/1808778</a>). It works the same with execfile()</p>
<pre><code>def callingFunction(filename)
# ...
d = dict(locals(), **globals())
execfile(filename, d, d )
</code></pre>
<p>Advantage of that solution is that we don't need to know the called script: it is the function nammed in <em>if <strong>name</strong> == <strong>main</strong></em> that is executed. </p>
| 4 | 2013-12-09T16:38:09Z | [
"python",
"class",
"scope",
"namespaces"
] |
How can I capture the stdout output of a child process? | 923,079 | <p>I'm trying to write a program in Python and I'm told to run an .exe file. When this .exe file is run it spits out a lot of data and I need a certain line printed out to the screen. I'm pretty sure I need to use <code>subprocess.popen</code> or something similar but I'm new to subprocess and have no clue. Anyone have an easy way for me to get this done?!? Thanks!!</p>
| 7 | 2009-05-28T20:45:45Z | 923,108 | <p>Something like this:</p>
<pre><code>import subprocess
process = subprocess.Popen(["yourcommand"], stdout=subprocess.PIPE)
result = process.communicate()[0]
</code></pre>
| 14 | 2009-05-28T20:49:38Z | [
"python",
"subprocess",
"stdout"
] |
How can I capture the stdout output of a child process? | 923,079 | <p>I'm trying to write a program in Python and I'm told to run an .exe file. When this .exe file is run it spits out a lot of data and I need a certain line printed out to the screen. I'm pretty sure I need to use <code>subprocess.popen</code> or something similar but I'm new to subprocess and have no clue. Anyone have an easy way for me to get this done?!? Thanks!!</p>
| 7 | 2009-05-28T20:45:45Z | 923,127 | <p>@Paolo's solution is perfect if you are interested in printing output after the process has finished executing. In case you want to poll output while the process is running you have to do it this way:</p>
<pre><code>process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
while True:
out = process.stdout.readline(1)
if out == '' and process.poll() != None:
break
if out.startswith('myline'):
sys.stdout.write(out)
sys.stdout.flush()
</code></pre>
| 20 | 2009-05-28T20:52:54Z | [
"python",
"subprocess",
"stdout"
] |
Creating lists of lists in a pythonic way | 923,111 | <p>I'm using a list of lists to store a matrix in python. I tried to initialise a 2x3 Zero matrix as follows.</p>
<pre><code>mat=[[0]*2]*3
</code></pre>
<p>However, when I change the value of one of the items in the matrix, it changes the value of that entry in <em>every</em> row, since the id of each row in <code>mat</code> is the same. For example, after assigning</p>
<pre><code>mat[0][0]=1
</code></pre>
<p><code>mat</code> is <code>[[1, 0], [1, 0], [1, 0]]</code>. </p>
<p>I know I can create the Zero matrix using a loop as follows,</p>
<pre><code>mat=[[0]*2]
for i in range(1,3):
mat.append([0]*2)
</code></pre>
<p>but can anyone show me a more pythonic way?</p>
| 9 | 2009-05-28T20:50:30Z | 923,147 | <p>Try this:</p>
<pre><code>>>> cols = 6
>>> rows = 3
>>> a = [[0]*cols for _ in [0]*rows]
>>> a
[[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]
>>> a[0][3] = 2
>>> a
[[0, 0, 0, 2, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]
</code></pre>
<p>This is also discussed <a href="http://stackoverflow.com/questions/691946/short-and-useful-python-snippets/692458#692458">in this answer</a>:</p>
<pre><code>>>> lst_2d = [[0] * 3 for i in xrange(3)]
>>> lst_2d
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> lst_2d[0][0] = 5
>>> lst_2d
[[5, 0, 0], [0, 0, 0], [0, 0, 0]]
</code></pre>
| 8 | 2009-05-28T20:57:09Z | [
"list",
"matrix",
"python"
] |
Creating lists of lists in a pythonic way | 923,111 | <p>I'm using a list of lists to store a matrix in python. I tried to initialise a 2x3 Zero matrix as follows.</p>
<pre><code>mat=[[0]*2]*3
</code></pre>
<p>However, when I change the value of one of the items in the matrix, it changes the value of that entry in <em>every</em> row, since the id of each row in <code>mat</code> is the same. For example, after assigning</p>
<pre><code>mat[0][0]=1
</code></pre>
<p><code>mat</code> is <code>[[1, 0], [1, 0], [1, 0]]</code>. </p>
<p>I know I can create the Zero matrix using a loop as follows,</p>
<pre><code>mat=[[0]*2]
for i in range(1,3):
mat.append([0]*2)
</code></pre>
<p>but can anyone show me a more pythonic way?</p>
| 9 | 2009-05-28T20:50:30Z | 923,164 | <p>This will work</p>
<pre><code>col = 2
row = 3
[[0] * col for row in xrange(row)]
</code></pre>
| 3 | 2009-05-28T20:59:40Z | [
"list",
"matrix",
"python"
] |
Creating lists of lists in a pythonic way | 923,111 | <p>I'm using a list of lists to store a matrix in python. I tried to initialise a 2x3 Zero matrix as follows.</p>
<pre><code>mat=[[0]*2]*3
</code></pre>
<p>However, when I change the value of one of the items in the matrix, it changes the value of that entry in <em>every</em> row, since the id of each row in <code>mat</code> is the same. For example, after assigning</p>
<pre><code>mat[0][0]=1
</code></pre>
<p><code>mat</code> is <code>[[1, 0], [1, 0], [1, 0]]</code>. </p>
<p>I know I can create the Zero matrix using a loop as follows,</p>
<pre><code>mat=[[0]*2]
for i in range(1,3):
mat.append([0]*2)
</code></pre>
<p>but can anyone show me a more pythonic way?</p>
| 9 | 2009-05-28T20:50:30Z | 923,170 | <p>What about: </p>
<pre><code>m, n = 2, 3
>>> A = [[0]*m for _ in range(n)]
>>> A
[[0, 0], [0, 0], [0, 0]]
>>> A[0][0] = 1
[[1, 0], [0, 0], [0, 0]]
</code></pre>
<p>Aka List comprehension; from the <a href="http://docs.python.org/tutorial/datastructures.html#list-comprehensions" rel="nofollow">docs</a>:</p>
<pre><code>List comprehensions provide a concise way to create lists
without resorting to use of
map(), filter() and/or lambda.
The resulting list definition tends often to be clearer
than lists built using those constructs.
</code></pre>
| 2 | 2009-05-28T21:00:18Z | [
"list",
"matrix",
"python"
] |
Creating lists of lists in a pythonic way | 923,111 | <p>I'm using a list of lists to store a matrix in python. I tried to initialise a 2x3 Zero matrix as follows.</p>
<pre><code>mat=[[0]*2]*3
</code></pre>
<p>However, when I change the value of one of the items in the matrix, it changes the value of that entry in <em>every</em> row, since the id of each row in <code>mat</code> is the same. For example, after assigning</p>
<pre><code>mat[0][0]=1
</code></pre>
<p><code>mat</code> is <code>[[1, 0], [1, 0], [1, 0]]</code>. </p>
<p>I know I can create the Zero matrix using a loop as follows,</p>
<pre><code>mat=[[0]*2]
for i in range(1,3):
mat.append([0]*2)
</code></pre>
<p>but can anyone show me a more pythonic way?</p>
| 9 | 2009-05-28T20:50:30Z | 923,171 | <p>Use a <a href="http://docs.python.org/tutorial/datastructures.html?highlight=list%20comprehension#list-comprehensions">list comprehension</a>:</p>
<pre><code>>>> mat = [[0]*2 for x in xrange(3)]
>>> mat[0][0] = 1
>>> mat
[[1, 0], [0, 0], [0, 0]]
</code></pre>
<p>Or, as a function:</p>
<pre><code>def matrix(rows, cols):
return [[0]*cols for x in xrange(rows)]
</code></pre>
| 9 | 2009-05-28T21:00:21Z | [
"list",
"matrix",
"python"
] |
Creating lists of lists in a pythonic way | 923,111 | <p>I'm using a list of lists to store a matrix in python. I tried to initialise a 2x3 Zero matrix as follows.</p>
<pre><code>mat=[[0]*2]*3
</code></pre>
<p>However, when I change the value of one of the items in the matrix, it changes the value of that entry in <em>every</em> row, since the id of each row in <code>mat</code> is the same. For example, after assigning</p>
<pre><code>mat[0][0]=1
</code></pre>
<p><code>mat</code> is <code>[[1, 0], [1, 0], [1, 0]]</code>. </p>
<p>I know I can create the Zero matrix using a loop as follows,</p>
<pre><code>mat=[[0]*2]
for i in range(1,3):
mat.append([0]*2)
</code></pre>
<p>but can anyone show me a more pythonic way?</p>
| 9 | 2009-05-28T20:50:30Z | 923,177 | <p>I use</p>
<pre><code>mat = [[0 for col in range(3)] for row in range(2)]
</code></pre>
<p>although depending on what you do with the matrix after you create it, you might take a look at using a NumPy array.</p>
| 4 | 2009-05-28T21:03:09Z | [
"list",
"matrix",
"python"
] |
Creating lists of lists in a pythonic way | 923,111 | <p>I'm using a list of lists to store a matrix in python. I tried to initialise a 2x3 Zero matrix as follows.</p>
<pre><code>mat=[[0]*2]*3
</code></pre>
<p>However, when I change the value of one of the items in the matrix, it changes the value of that entry in <em>every</em> row, since the id of each row in <code>mat</code> is the same. For example, after assigning</p>
<pre><code>mat[0][0]=1
</code></pre>
<p><code>mat</code> is <code>[[1, 0], [1, 0], [1, 0]]</code>. </p>
<p>I know I can create the Zero matrix using a loop as follows,</p>
<pre><code>mat=[[0]*2]
for i in range(1,3):
mat.append([0]*2)
</code></pre>
<p>but can anyone show me a more pythonic way?</p>
| 9 | 2009-05-28T20:50:30Z | 2,332,744 | <p>See also <a href="http://stackoverflow.com/questions/2173087/how-to-create-nested-lists-in-python">this question</a> for generalization to an n-levels nested list / n-dimensional matrix.</p>
| 1 | 2010-02-25T08:58:31Z | [
"list",
"matrix",
"python"
] |
Creating lists of lists in a pythonic way | 923,111 | <p>I'm using a list of lists to store a matrix in python. I tried to initialise a 2x3 Zero matrix as follows.</p>
<pre><code>mat=[[0]*2]*3
</code></pre>
<p>However, when I change the value of one of the items in the matrix, it changes the value of that entry in <em>every</em> row, since the id of each row in <code>mat</code> is the same. For example, after assigning</p>
<pre><code>mat[0][0]=1
</code></pre>
<p><code>mat</code> is <code>[[1, 0], [1, 0], [1, 0]]</code>. </p>
<p>I know I can create the Zero matrix using a loop as follows,</p>
<pre><code>mat=[[0]*2]
for i in range(1,3):
mat.append([0]*2)
</code></pre>
<p>but can anyone show me a more pythonic way?</p>
| 9 | 2009-05-28T20:50:30Z | 2,332,830 | <p>Is there anything itertools can't do? :)</p>
<pre><code>>>> from itertools import repeat,izip
>>> rows=3
>>> cols=6
>>> A=map(list,izip(*[repeat(0,rows*cols)]*cols))
>>> A
[[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]
>>> A[0][3] = 2
>>> A
[[0, 0, 0, 2, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]
</code></pre>
| 1 | 2010-02-25T09:15:18Z | [
"list",
"matrix",
"python"
] |
Creating lists of lists in a pythonic way | 923,111 | <p>I'm using a list of lists to store a matrix in python. I tried to initialise a 2x3 Zero matrix as follows.</p>
<pre><code>mat=[[0]*2]*3
</code></pre>
<p>However, when I change the value of one of the items in the matrix, it changes the value of that entry in <em>every</em> row, since the id of each row in <code>mat</code> is the same. For example, after assigning</p>
<pre><code>mat[0][0]=1
</code></pre>
<p><code>mat</code> is <code>[[1, 0], [1, 0], [1, 0]]</code>. </p>
<p>I know I can create the Zero matrix using a loop as follows,</p>
<pre><code>mat=[[0]*2]
for i in range(1,3):
mat.append([0]*2)
</code></pre>
<p>but can anyone show me a more pythonic way?</p>
| 9 | 2009-05-28T20:50:30Z | 2,332,919 | <p>This one is faster than the accepted answer!<br>
Using xrange(rows) instead of [0]*rows makes no difference.</p>
<pre><code>>>> from itertools import repeat
>>> rows,cols = 3,6
>>> a=[x[:] for x in repeat([0]*cols,rows)]
</code></pre>
<p>A variation that doesn't use itertools and runs around the same speed</p>
<pre><code>>>> a=[x[:] for x in [[0]*cols]*rows]
</code></pre>
<p>From ipython:</p>
<pre><code>In [1]: from itertools import repeat
In [2]: rows=cols=10
In [3]: timeit a = [[0]*cols for _ in [0]*rows]
10000 loops, best of 3: 17.8 us per loop
In [4]: timeit a=[x[:] for x in repeat([0]*cols,rows)]
100000 loops, best of 3: 12.7 us per loop
In [5]: rows=cols=100
In [6]: timeit a = [[0]*cols for _ in [0]*rows]
1000 loops, best of 3: 368 us per loop
In [7]: timeit a=[x[:] for x in repeat([0]*cols,rows)]
1000 loops, best of 3: 311 us per loop
</code></pre>
| 6 | 2010-02-25T09:29:17Z | [
"list",
"matrix",
"python"
] |
Creating lists of lists in a pythonic way | 923,111 | <p>I'm using a list of lists to store a matrix in python. I tried to initialise a 2x3 Zero matrix as follows.</p>
<pre><code>mat=[[0]*2]*3
</code></pre>
<p>However, when I change the value of one of the items in the matrix, it changes the value of that entry in <em>every</em> row, since the id of each row in <code>mat</code> is the same. For example, after assigning</p>
<pre><code>mat[0][0]=1
</code></pre>
<p><code>mat</code> is <code>[[1, 0], [1, 0], [1, 0]]</code>. </p>
<p>I know I can create the Zero matrix using a loop as follows,</p>
<pre><code>mat=[[0]*2]
for i in range(1,3):
mat.append([0]*2)
</code></pre>
<p>but can anyone show me a more pythonic way?</p>
| 9 | 2009-05-28T20:50:30Z | 28,047,760 | <p>If the sizes involved are really only 2 and 3,</p>
<pre><code>mat = [[0, 0], [0, 0], [0, 0]]
</code></pre>
<p>is easily best and hasn't been mentioned yet.</p>
| 1 | 2015-01-20T14:26:58Z | [
"list",
"matrix",
"python"
] |
Keeping a session in python while making HTTP requests | 923,296 | <p>I need to write a python script that makes multiple HTTP requests to the same site. Unless I'm wrong (and I may very well be) urllib reauthenticates for every request. For reasons I won't go into I need to be able to authenticate once and then use that session for the rest of my requests. </p>
<p>I'm using python 2.3.4</p>
| 23 | 2009-05-28T21:28:06Z | 923,313 | <p>If you want to keep the authentication you need to reuse the cookie. I'm not sure if urllib2 is available in python 2.3.4 but here is an example on how to do it:</p>
<pre><code>req1 = urllib2.Request(url1)
response = urllib2.urlopen(req1)
cookie = response.headers.get('Set-Cookie')
# Use the cookie is subsequent requests
req2 = urllib2.Request(url2)
req2.add_header('cookie', cookie)
response = urllib2.urlopen(req2)
</code></pre>
| 20 | 2009-05-28T21:32:41Z | [
"python",
"http",
"authentication"
] |
Keeping a session in python while making HTTP requests | 923,296 | <p>I need to write a python script that makes multiple HTTP requests to the same site. Unless I'm wrong (and I may very well be) urllib reauthenticates for every request. For reasons I won't go into I need to be able to authenticate once and then use that session for the rest of my requests. </p>
<p>I'm using python 2.3.4</p>
| 23 | 2009-05-28T21:28:06Z | 925,043 | <p>If this is cookie based authentication use <a href="http://docs.python.org/library/cookielib.html#examples">HTTPCookieProcessor</a>:</p>
<pre><code>import cookielib, urllib2
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
r = opener.open("http://example.com/")
</code></pre>
<p>If this is HTTP authentication use <a href="http://docs.python.org/library/urllib2.html#examples">basic or digest AuthHandler</a>:</p>
<pre><code>import urllib2
# Create an OpenerDirector with support for Basic HTTP Authentication...
auth_handler = urllib2.HTTPBasicAuthHandler()
auth_handler.add_password(realm='PDQ Application',
uri='https://mahler:8092/site-updates.py',
user='klem',
passwd='kadidd!ehopper')
opener = urllib2.build_opener(auth_handler)
# ...and install it globally so it can be used with urlopen.
urllib2.install_opener(opener)
urllib2.urlopen('http://www.example.com/login.html')
</code></pre>
<p>... and use same opener for every request.</p>
| 14 | 2009-05-29T08:48:54Z | [
"python",
"http",
"authentication"
] |
Keeping a session in python while making HTTP requests | 923,296 | <p>I need to write a python script that makes multiple HTTP requests to the same site. Unless I'm wrong (and I may very well be) urllib reauthenticates for every request. For reasons I won't go into I need to be able to authenticate once and then use that session for the rest of my requests. </p>
<p>I'm using python 2.3.4</p>
| 23 | 2009-05-28T21:28:06Z | 10,631,831 | <p>Use <a href="https://github.com/kennethreitz/requests">Requests</a> library. From <a href="http://docs.python-requests.org/en/latest/user/advanced/#session-objects">http://docs.python-requests.org/en/latest/user/advanced/#session-objects</a> :</p>
<blockquote>
<p>The Session object allows you to persist certain parameters across
requests. It also persists cookies across all requests made from the
Session instance.</p>
<pre><code>s = requests.session()
s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')
r = s.get("http://httpbin.org/cookies")
print r.text
# '{"cookies": {"sessioncookie": "123456789"}}'
</code></pre>
</blockquote>
| 23 | 2012-05-17T07:53:27Z | [
"python",
"http",
"authentication"
] |
Scraping Multiple html files to CSV | 923,318 | <p>I am trying to scrape rows off of over 1200 .htm files that are on my hard drive. On my computer they are here 'file:///home/phi/Data/NHL/pl07-08/PL020001.HTM'. These .htm files are sequential from *20001.htm until *21230.htm. My plan is to eventually toss my data in MySQL or SQLite via a spreadsheet app or just straight in if I can get a clean .csv file out of this process.</p>
<p>This is my first attempt at code (Python), scraping, and I just installed Ubuntu 9.04 on my crappy pentium IV. Needless to say I am newb and have some roadblocks.</p>
<p>How do I get mechanize to go through all the files in the directory in order. Can mechanize even do this? Can mechanize/Python/BeautifulSoup read a 'file:///' style url or is there another way to point it to /home/phi/Data/NHL/pl07-08/PL020001.HTM? Is it smart to do this in 100 or 250 file increments or just send all 1230?</p>
<p>I just need rows that start with this "<code><tr class="evenColor"></code>" and end with this "<code></tr></code>". Ideally I only want the rows that contain "SHOT"|"MISS"|"GOAL" within them but I want the whole row (every column). Note that "<strong>GOAL</strong>" is in bold so do I have to specify this? There are 3 tables per htm file.</p>
<p>Also I would like the name of the parent file (pl020001.htm) <strong>to be included in the rows I scrape so I can id them in their own column in the final database</strong>. I don't even know where to begin for that. This is what I have so far: </p>
<pre><code>#/usr/bin/python
from BeautifulSoup import BeautifulSoup
import re
from mechanize import Browser
mech = Browser()
url = "file:///home/phi/Data/NHL/pl07-08/PL020001.HTM"
##but how do I do multiple urls/files? PL02*.HTM?
page = mech.open(url)
html = page.read()
soup = BeautifulSoup(html)
##this confuses me and seems redundant
pl = open("input_file.html","r")
chances = open("chancesforsql.csv,"w")
table = soup.find("table", border=0)
for row in table.findAll 'tr class="evenColor"'
#should I do this instead of before?
outfile = open("shooting.csv", "w")
##how do I end it?
</code></pre>
<p>Should I be using IDLE or something like it? just Terminal in Ubuntu 9.04?</p>
| 2 | 2009-05-28T21:34:57Z | 923,373 | <p>You won't need mechanize. Since I do not exactly know the HTML content, I'd try to see what matches, first. Like this: </p>
<pre><code>import glob
from BeautifulSoup import BeautifulSoup
for filename in glob.glob('/home/phi/Data/*.htm'):
soup = BeautifulSoup(open(filename, "r").read()) # assuming some HTML
for a_tr in soup.findAll("tr", attrs={ "class" : "evenColor" }):
print a_tr
</code></pre>
<p>Then pick the stuff you want and write it to stdout with commas (and redirect it > to a file). Or write the csv via python.</p>
| 1 | 2009-05-28T21:45:59Z | [
"python",
"sqlite",
"screen-scraping",
"beautifulsoup",
"mechanize"
] |
Scraping Multiple html files to CSV | 923,318 | <p>I am trying to scrape rows off of over 1200 .htm files that are on my hard drive. On my computer they are here 'file:///home/phi/Data/NHL/pl07-08/PL020001.HTM'. These .htm files are sequential from *20001.htm until *21230.htm. My plan is to eventually toss my data in MySQL or SQLite via a spreadsheet app or just straight in if I can get a clean .csv file out of this process.</p>
<p>This is my first attempt at code (Python), scraping, and I just installed Ubuntu 9.04 on my crappy pentium IV. Needless to say I am newb and have some roadblocks.</p>
<p>How do I get mechanize to go through all the files in the directory in order. Can mechanize even do this? Can mechanize/Python/BeautifulSoup read a 'file:///' style url or is there another way to point it to /home/phi/Data/NHL/pl07-08/PL020001.HTM? Is it smart to do this in 100 or 250 file increments or just send all 1230?</p>
<p>I just need rows that start with this "<code><tr class="evenColor"></code>" and end with this "<code></tr></code>". Ideally I only want the rows that contain "SHOT"|"MISS"|"GOAL" within them but I want the whole row (every column). Note that "<strong>GOAL</strong>" is in bold so do I have to specify this? There are 3 tables per htm file.</p>
<p>Also I would like the name of the parent file (pl020001.htm) <strong>to be included in the rows I scrape so I can id them in their own column in the final database</strong>. I don't even know where to begin for that. This is what I have so far: </p>
<pre><code>#/usr/bin/python
from BeautifulSoup import BeautifulSoup
import re
from mechanize import Browser
mech = Browser()
url = "file:///home/phi/Data/NHL/pl07-08/PL020001.HTM"
##but how do I do multiple urls/files? PL02*.HTM?
page = mech.open(url)
html = page.read()
soup = BeautifulSoup(html)
##this confuses me and seems redundant
pl = open("input_file.html","r")
chances = open("chancesforsql.csv,"w")
table = soup.find("table", border=0)
for row in table.findAll 'tr class="evenColor"'
#should I do this instead of before?
outfile = open("shooting.csv", "w")
##how do I end it?
</code></pre>
<p>Should I be using IDLE or something like it? just Terminal in Ubuntu 9.04?</p>
| 2 | 2009-05-28T21:34:57Z | 923,460 | <p>MYYN's answer looks like a great start to me. One thing I'd point out that I've had luck with is:</p>
<pre><code>import glob
for file_name in glob.glob('/home/phi/Data/*.htm'):
#read the file and then parse with BeautifulSoup
</code></pre>
<p>I've found both the <code>os</code> and <code>glob</code> imports to be really useful for running through files in a directory.</p>
<p>Also, once you're using a for loop in this way, you have the <code>file_name</code> which you can modify for use in the output file, so that the output filenames will match the input filenames.</p>
| 0 | 2009-05-28T22:11:11Z | [
"python",
"sqlite",
"screen-scraping",
"beautifulsoup",
"mechanize"
] |
Matching text within P tags in HTML | 923,472 | <p>I'd like to match the contents within each paragraph in html using a python regular expression. These paragraphs always have BR tags inside them like so:</p>
<pre><code><p class="thisClass">this is nice <br /><br /> isn't it?</p>
</code></pre>
<p>I'm currently using this pattern:</p>
<pre><code>pattern = re.compile('<p class=\"thisClass\">(.*?)<\/p>')
</code></pre>
<p>Then I'm using:</p>
<pre><code>pattern.findall(html)
</code></pre>
<p>to find all the matches. However, it only matches two of 28 paragraphs I have, and it looks like that's because those two don't have BR tags inside of them and the rest do. What am I doing wrong? What can I do to fix it? Thanks!</p>
| 2 | 2009-05-28T22:16:13Z | 923,494 | <p>I don't think it is failing because of the <code><br/></code> but rather because the paragraph is spread across multiple lines. Use the <a href="http://docs.python.org/library/re.html#re.DOTALL" rel="nofollow">DOTALL</a> mode to fix this:</p>
<pre><code>pattern = re.compile('<p class=\"thisClass\">(.*?)<\/p>', re.DOTALL)
</code></pre>
| 5 | 2009-05-28T22:22:03Z | [
"python",
"html",
"regex"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.