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 do I prevent execution of arbitrary commands from a Django app making system calls?
| 768,677
|
<p>I have a Django application I'm developing that must make a system call to an external program on the server. In creating the command for the system call, the application takes values from a form and uses them as parameters for the call. I suppose this means that one can essentially use bogus parameters and write arbitrary commands for the shell to execute (e.g., just place a semicolon and then <code>rm -rf *</code>).</p>
<p>This is bad. While most users aren't malicious, it is a potential security problem. How does one handle these potential points of exploit?</p>
<p><strong>EDIT</strong> (for clarification): The users will see a form that is split up with various fields for each of the parameters and options. However some fields will be available as open text fields. All of these fields are combined and fed to <code>subprocess.check_call()</code>. Technically, though, this isn't separated too far from just handing the users a command prompt. This has got to be fairly common, so what do other developers do to sanitize input so that they don't get a <a href="http://xkcd.com/327/" rel="nofollow">Bobby Tables</a>.</p>
| 5
|
2009-04-20T15:03:41Z
| 768,881
|
<p>To do this, you must do the following. If you don't know what "options" and "arguments" are, read the <a href="http://docs.python.org/library/optparse.html#background" rel="nofollow">optparse background</a>.</p>
<p>Each "Command" or "Request" is actually an instance of a model. Define your Request model with all of the parameters someone might provide.</p>
<ol>
<li><p>For simple options, you must provide a field with a specific list of CHOICES. For options that are "on" or "off" (<code>-x</code> in the command-line) you should provide a CHOICE list with two human-understandable values ("Do X" and "Do not do X".)</p></li>
<li><p>For options with a value, you must provide a field that takes the option's value. You must write a Form with the validation for this field. We'll return to option value validation in a bit.</p></li>
<li><p>For arguments, you have a second Model (with an FK to the first). This may be as simple as a single FilePath field, or may be more complex. Again, you may have to provide a Form to validate instances of this Model, also.</p></li>
</ol>
<p>Option validation varies by what kind of option it is. You must narrow the acceptable values to be narrowest possible set of characters and write a parser that is absolutely sure of passing only valid characters.</p>
<p>Your options will fall into the same categories as the option types in optparse -- string, int, long, choice, float and complex. Note that int, long, float and complex have validation rules already defined by Django's Models and Forms. Choice is a special kind of string, already supported by Django's Models and Forms.</p>
<p>What's left are "strings". Define the allowed strings. Write a regex for those strings. Validate using the regex. Most of the time, you can never accept quotes (<code>"</code>, <code>'</code> or `) in any form. </p>
<p>Final step. Your Model has a method which emits the command as a sequence of strings all ready for <code>subprocess.Popen</code>.</p>
<p><hr /></p>
<p><strong>Edit</strong></p>
<p>This is the backbone of our app. It's so common, we have a single Model with numerous Forms, each for a special batch command that gets run. The Model is pretty generic. The Forms are pretty specific ways to build the Model object. That's the way Django is designed to work, and it helps to fit with Django's well-thought-out design patterns.</p>
<p>Any field that is "available as open text fields" is a mistake. Each field that's "open" must have a regex to specify what is permitted. If you can't formalize a regex, you have to rethink what you're doing.</p>
<p>A field that cannot be constrained with a regex absolutely cannot be a command-line parameter. Period. It must be stored to a file to database column before being used.</p>
<p><hr /></p>
<p><strong>Edit</strong></p>
<p>Like this.</p>
<pre><code>class MySubprocessCommandClass( models.Model ):
myOption_1 = models.CharField( choice = OPTION_1_CHOICES, max_length=2 )
myOption_2 = models.CharField( max_length=20 )
etc.
def theCommand( self ):
return [ "theCommand", "-p", self.myOption_1, "-r", self.myOption_2, etc. ]
</code></pre>
<p>Your form is a ModelForm for this Model.</p>
<p>You don't have to <code>save()</code> the instances of the model. We save them so that we can create a log of precisely what was run.</p>
| 4
|
2009-04-20T15:52:19Z
|
[
"python",
"django",
"security"
] |
How to use a python api on iPhone?
| 768,941
|
<p>There is an "<a href="http://code.google.com/p/plurkapipy/" rel="nofollow">Unofficial Plurk API in Python</a>".
<a href="http://www.plurk.com/" rel="nofollow">Plurk</a> is a twitter-like website.</p>
<p>Can I use the API(python) from Objective-C? Or i have to port them?</p>
| 1
|
2009-04-20T16:07:44Z
| 768,956
|
<p>The iPhone SDK will not allow you to run any Python code. You need to convert it to C, C++, Objective-C or ObjectiveC++.</p>
| 2
|
2009-04-20T16:10:18Z
|
[
"iphone",
"python",
"objective-c"
] |
How to use a python api on iPhone?
| 768,941
|
<p>There is an "<a href="http://code.google.com/p/plurkapipy/" rel="nofollow">Unofficial Plurk API in Python</a>".
<a href="http://www.plurk.com/" rel="nofollow">Plurk</a> is a twitter-like website.</p>
<p>Can I use the API(python) from Objective-C? Or i have to port them?</p>
| 1
|
2009-04-20T16:07:44Z
| 768,957
|
<p>Apple's iPhone developer license prohibits applications that use interpreted code. So, python is out, unfortunately.</p>
| 4
|
2009-04-20T16:10:23Z
|
[
"iphone",
"python",
"objective-c"
] |
How to use a python api on iPhone?
| 768,941
|
<p>There is an "<a href="http://code.google.com/p/plurkapipy/" rel="nofollow">Unofficial Plurk API in Python</a>".
<a href="http://www.plurk.com/" rel="nofollow">Plurk</a> is a twitter-like website.</p>
<p>Can I use the API(python) from Objective-C? Or i have to port them?</p>
| 1
|
2009-04-20T16:07:44Z
| 768,984
|
<p>The way I see it, one option is to try this <a href="http://www.saurik.com/id/5" rel="nofollow">this</a>.</p>
<p>Alternatively, <a href="http://code.google.com/p/plurkapipy/source/browse/trunk/plurkapi.py" rel="nofollow">ths plurk api</a> (which is really more of a python-automated abstraction than an API) isn't very big and is unlikely to take very long to port. Apart from being exceptionally simple code. The author's done all the legwork, defining urls and associated functions and so on.</p>
| 3
|
2009-04-20T16:16:28Z
|
[
"iphone",
"python",
"objective-c"
] |
How to use a python api on iPhone?
| 768,941
|
<p>There is an "<a href="http://code.google.com/p/plurkapipy/" rel="nofollow">Unofficial Plurk API in Python</a>".
<a href="http://www.plurk.com/" rel="nofollow">Plurk</a> is a twitter-like website.</p>
<p>Can I use the API(python) from Objective-C? Or i have to port them?</p>
| 1
|
2009-04-20T16:07:44Z
| 769,048
|
<p>Check these links :</p>
<p>iPhone Applications in Python: <a href="http://www.saurik.com/id/5" rel="nofollow">http://www.saurik.com/id/5</a></p>
<p>PyObjC: <a href="http://pyobjc.sourceforge.net/" rel="nofollow">http://pyobjc.sourceforge.net/</a></p>
| 4
|
2009-04-20T16:31:33Z
|
[
"iphone",
"python",
"objective-c"
] |
How to use a python api on iPhone?
| 768,941
|
<p>There is an "<a href="http://code.google.com/p/plurkapipy/" rel="nofollow">Unofficial Plurk API in Python</a>".
<a href="http://www.plurk.com/" rel="nofollow">Plurk</a> is a twitter-like website.</p>
<p>Can I use the API(python) from Objective-C? Or i have to port them?</p>
| 1
|
2009-04-20T16:07:44Z
| 769,150
|
<p>Unfortunately, you can only do what Apple allows you to do (they are VERY controlling). However, if you jail break your device (this violates your usage agreement with Apple) you can do many, many things with what I consider to be an amazing device (unfortunatly, Apple limits it's true possibilities). </p>
| -6
|
2009-04-20T16:52:32Z
|
[
"iphone",
"python",
"objective-c"
] |
How to use a python api on iPhone?
| 768,941
|
<p>There is an "<a href="http://code.google.com/p/plurkapipy/" rel="nofollow">Unofficial Plurk API in Python</a>".
<a href="http://www.plurk.com/" rel="nofollow">Plurk</a> is a twitter-like website.</p>
<p>Can I use the API(python) from Objective-C? Or i have to port them?</p>
| 1
|
2009-04-20T16:07:44Z
| 2,533,724
|
<p>Well, Plurk has an official API now, and I wrote an Objective-C library to connect to Plurk. Maybe you are interested to give it a try.</p>
<p><a href="http://github.com/zonble/ObjectivePlurk" rel="nofollow">http://github.com/zonble/ObjectivePlurk</a></p>
| 1
|
2010-03-28T17:04:01Z
|
[
"iphone",
"python",
"objective-c"
] |
Persistent Windows in PyGTK
| 769,175
|
<p>Is there a way to force a gtk.Window object to ignore the Window Manager's show/hide commands, such as "iconify" and "show desktop?"</p>
<p>I'm trying to create a persistent window, stuck to the desktop, that will not disappear with all other windows when the desktop is exposed.</p>
<p><strong>EDIT:</strong> I guess what I'm wondering specifically is whether or not it's possible to reproduce the behavior found in applications such as docks, desktop widgets, system trays, etc. using PyGTK?</p>
| 1
|
2009-04-20T16:57:57Z
| 771,431
|
<p>You've got it backwards; it's not the window manager telling the window to minimize, by sending it a command. The window manager <strong>owns</strong> the window, if it wants to stop mapping a window, it will just do it, without asking the window for permission.</p>
<p>So I would think that the answer is "no".</p>
| 2
|
2009-04-21T07:21:36Z
|
[
"python",
"gtk",
"pygtk",
"x11"
] |
Persistent Windows in PyGTK
| 769,175
|
<p>Is there a way to force a gtk.Window object to ignore the Window Manager's show/hide commands, such as "iconify" and "show desktop?"</p>
<p>I'm trying to create a persistent window, stuck to the desktop, that will not disappear with all other windows when the desktop is exposed.</p>
<p><strong>EDIT:</strong> I guess what I'm wondering specifically is whether or not it's possible to reproduce the behavior found in applications such as docks, desktop widgets, system trays, etc. using PyGTK?</p>
| 1
|
2009-04-20T16:57:57Z
| 783,713
|
<p>Try setting the <a href="http://library.gnome.org/devel/gdk/unstable/gdk-Windows.html#GdkWindowTypeHint" rel="nofollow"><code>GdkWindowTypeHint</code></a> on the <code>GtkWindow</code>:</p>
<pre><code>gtk_window_set_type_hint(the_window, GDK_WINDOW_TYPE_HINT_UTILITY);
</code></pre>
<p>There's also various methods for not having your window listed in pagers or taskbars and have it show up on all desktop. Keep in mind that all this behavior depends on support from the window manager. Unless you use something really old, this should not pose a problem though.</p>
| 1
|
2009-04-23T22:03:24Z
|
[
"python",
"gtk",
"pygtk",
"x11"
] |
Persistent Windows in PyGTK
| 769,175
|
<p>Is there a way to force a gtk.Window object to ignore the Window Manager's show/hide commands, such as "iconify" and "show desktop?"</p>
<p>I'm trying to create a persistent window, stuck to the desktop, that will not disappear with all other windows when the desktop is exposed.</p>
<p><strong>EDIT:</strong> I guess what I'm wondering specifically is whether or not it's possible to reproduce the behavior found in applications such as docks, desktop widgets, system trays, etc. using PyGTK?</p>
| 1
|
2009-04-20T16:57:57Z
| 1,030,408
|
<p>Not having received a "this is how to do this" answer and having done a bit more research I can say that -- as far as I know -- there is no easy way to achieve this sort of functionality with PyGTK. The best options are to set window manager hints and leave it up to the WM to do what you want (hopefully).</p>
| 0
|
2009-06-23T02:40:24Z
|
[
"python",
"gtk",
"pygtk",
"x11"
] |
Persistent Windows in PyGTK
| 769,175
|
<p>Is there a way to force a gtk.Window object to ignore the Window Manager's show/hide commands, such as "iconify" and "show desktop?"</p>
<p>I'm trying to create a persistent window, stuck to the desktop, that will not disappear with all other windows when the desktop is exposed.</p>
<p><strong>EDIT:</strong> I guess what I'm wondering specifically is whether or not it's possible to reproduce the behavior found in applications such as docks, desktop widgets, system trays, etc. using PyGTK?</p>
| 1
|
2009-04-20T16:57:57Z
| 5,474,070
|
<p>I think <code>gtk_window_set_type_hint(window, GDK_WINDOW_TYPE_HINT_SPLASHSCREEN)</code> is what you want. It is also <code>GDK_WINDOW_TYPE_HINT_DOCK</code>, but then the window stay on top of all, and you can't send it back.</p>
| 0
|
2011-03-29T14:23:44Z
|
[
"python",
"gtk",
"pygtk",
"x11"
] |
Persistent Windows in PyGTK
| 769,175
|
<p>Is there a way to force a gtk.Window object to ignore the Window Manager's show/hide commands, such as "iconify" and "show desktop?"</p>
<p>I'm trying to create a persistent window, stuck to the desktop, that will not disappear with all other windows when the desktop is exposed.</p>
<p><strong>EDIT:</strong> I guess what I'm wondering specifically is whether or not it's possible to reproduce the behavior found in applications such as docks, desktop widgets, system trays, etc. using PyGTK?</p>
| 1
|
2009-04-20T16:57:57Z
| 19,255,102
|
<p>From the <a href="http://www.pygtk.org/docs/pygtk/gdk-constants.html#gdk-window-type-hint-constants" rel="nofollow">list of window type hints</a>, only a two are still shown when you click the show desktop button:</p>
<ul>
<li>gtk.gdk.WINDOW_TYPE_HINT_DESKTOP</li>
<li>gtk.gdk.WINDOW_TYPE_HINT_DOCK</li>
</ul>
<p>Both of these cause your window to lose decorations (i.e. no borders or titlebar) so moving/resizing is up to your app. DESKTOP causes the window to be always behind other windows. DOCK causes it to be always in front.</p>
<p>Choosing SPLASHSCREEN give you an undecorated window that still hides when you click show desktop.</p>
<p>If you want a borderless, immobile window that still shows when the user clicks "show desktop" use:</p>
<pre><code>window.set_type_hint(gtk.gdk.WINDOW_TYPE_HINT_DOCK)
</code></pre>
<p>before you call window.show(). Once the window has been displayed, you can't change its type.</p>
| 1
|
2013-10-08T18:07:54Z
|
[
"python",
"gtk",
"pygtk",
"x11"
] |
Dynamic Loading of Python Modules
| 769,534
|
<p>I'm trying to dynamically load modules I've created.</p>
<p>Right now this works properly:</p>
<pre><code>import structures.index
</code></pre>
<p>But if I try the same thing by importing it dynamically, it fails.</p>
<pre><code>struct = __import__("structures.index")
</code></pre>
<p>Error supplied is:</p>
<pre><code>Error ('No module named structures.index',)
</code></pre>
<p>Any ideas why?</p>
<p><hr /></p>
<p>Edit: When using full scope (it sort of works?):</p>
<pre><code>struct = __import__("neoform.structures.index")
</code></pre>
<p>This doesn't throw any errors, however, it isn't loading the index module, it's loading the "neoform" module instead.</p>
<p>The result of "struct" is:</p>
<pre><code><module 'neoform' from '/neoform/__init__.py'>
</code></pre>
<p>Also, as a side question, how can I then instantiate a class within a dynamically loaded module? (assuming all the modules contain a common class name).</p>
<p>Edit: Solution: (thanks coonj & Rick) This ended up being what worked. Not sure why (yet), but the <code>fromlist</code> had to be something "anything apparently, since it worked when I put the letter "a" as a value (strange, given that the file only had 1 class in it).</p>
<pre><code>def get_struct_module(self, name):
try:
return = __import__("neoform.structures." + name, fromlist='*')
except ImportError, e:
self.out.add("Could not load struct: neoform.structure." + name + "\n\n" + "Error " + str(e.args))
</code></pre>
| 3
|
2009-04-20T18:34:04Z
| 769,565
|
<p>Java programmer here, but I think you need the <a href="http://docs.python.org/library/imp.html" rel="nofollow">imp module</a></p>
| 1
|
2009-04-20T18:41:13Z
|
[
"python",
"dynamic",
"module",
"loading"
] |
Dynamic Loading of Python Modules
| 769,534
|
<p>I'm trying to dynamically load modules I've created.</p>
<p>Right now this works properly:</p>
<pre><code>import structures.index
</code></pre>
<p>But if I try the same thing by importing it dynamically, it fails.</p>
<pre><code>struct = __import__("structures.index")
</code></pre>
<p>Error supplied is:</p>
<pre><code>Error ('No module named structures.index',)
</code></pre>
<p>Any ideas why?</p>
<p><hr /></p>
<p>Edit: When using full scope (it sort of works?):</p>
<pre><code>struct = __import__("neoform.structures.index")
</code></pre>
<p>This doesn't throw any errors, however, it isn't loading the index module, it's loading the "neoform" module instead.</p>
<p>The result of "struct" is:</p>
<pre><code><module 'neoform' from '/neoform/__init__.py'>
</code></pre>
<p>Also, as a side question, how can I then instantiate a class within a dynamically loaded module? (assuming all the modules contain a common class name).</p>
<p>Edit: Solution: (thanks coonj & Rick) This ended up being what worked. Not sure why (yet), but the <code>fromlist</code> had to be something "anything apparently, since it worked when I put the letter "a" as a value (strange, given that the file only had 1 class in it).</p>
<pre><code>def get_struct_module(self, name):
try:
return = __import__("neoform.structures." + name, fromlist='*')
except ImportError, e:
self.out.add("Could not load struct: neoform.structure." + name + "\n\n" + "Error " + str(e.args))
</code></pre>
| 3
|
2009-04-20T18:34:04Z
| 769,610
|
<p>I'm not sure what "it fails" means, so I'll just mention that <code>__import__('structures.index')</code> should, in fact, work, but it doesn't assign the module name in the current scope. To do that (and then use a class in the dynamically imported module), you'll have to use:</p>
<pre><code>structures = __import__('structures.index')
structures.index.SomeClass(...)
</code></pre>
<p>The complete details on <code>__import__</code> are available <a href="http://docs.python.org/library/functions.html#%5F%5Fimport%5F%5F">here</a>.</p>
<p><strong>Edit: (based on question edit)</strong></p>
<p>To import <code>neoform.structures.index</code>, and return the <code>index</code> module, you would do the following:</p>
<pre><code>structures = __import__('neoform.structures.index',
fromlist=['does not in fact matter what goes here!'])
</code></pre>
<p>So if you have a list of package names <code>packages</code>, you can import their <code>index</code> modules and instantiate some <code>MyClass</code> class for each using the following code:</p>
<pre><code>modules = [ __import__('neoform.%s.index' % pkg, fromlist=['a'])
for pkg in packages ]
objects = [ m.MyClass() for m in modules ]
</code></pre>
| 10
|
2009-04-20T18:50:01Z
|
[
"python",
"dynamic",
"module",
"loading"
] |
Dynamic Loading of Python Modules
| 769,534
|
<p>I'm trying to dynamically load modules I've created.</p>
<p>Right now this works properly:</p>
<pre><code>import structures.index
</code></pre>
<p>But if I try the same thing by importing it dynamically, it fails.</p>
<pre><code>struct = __import__("structures.index")
</code></pre>
<p>Error supplied is:</p>
<pre><code>Error ('No module named structures.index',)
</code></pre>
<p>Any ideas why?</p>
<p><hr /></p>
<p>Edit: When using full scope (it sort of works?):</p>
<pre><code>struct = __import__("neoform.structures.index")
</code></pre>
<p>This doesn't throw any errors, however, it isn't loading the index module, it's loading the "neoform" module instead.</p>
<p>The result of "struct" is:</p>
<pre><code><module 'neoform' from '/neoform/__init__.py'>
</code></pre>
<p>Also, as a side question, how can I then instantiate a class within a dynamically loaded module? (assuming all the modules contain a common class name).</p>
<p>Edit: Solution: (thanks coonj & Rick) This ended up being what worked. Not sure why (yet), but the <code>fromlist</code> had to be something "anything apparently, since it worked when I put the letter "a" as a value (strange, given that the file only had 1 class in it).</p>
<pre><code>def get_struct_module(self, name):
try:
return = __import__("neoform.structures." + name, fromlist='*')
except ImportError, e:
self.out.add("Could not load struct: neoform.structure." + name + "\n\n" + "Error " + str(e.args))
</code></pre>
| 3
|
2009-04-20T18:34:04Z
| 769,622
|
<p>To import sub-modules, you need to specify them in the <code>fromlist</code> arg of <code>__import__()</code> <br>Fo example, the equivalent of:</p>
<pre><code>import structures.index
</code></pre>
<p>is:</p>
<pre><code>structures = __import__('structures', fromlist=['index'])
</code></pre>
<p>To do this in a map is a little more tricky...</p>
<pre><code>import mod1.index
import mod2.index
import mod3.index
</code></pre>
<p>For those imports, you would want to define a new function to get the <code>index</code> sub-module from each module:</p>
<pre><code>def getIndexMods(mod_names):
mod_list = map(lambda x: __import__(x, fromlist='index'))
index_mods = [mod.index for mod in mod_list]
return index_mods
</code></pre>
<p>Now, you can do this to get references to all index modules:</p>
<pre><code>index_mods = getIndexMods(['mod1', 'mod2', 'mod3'])
</code></pre>
<p>Also, if you want to grab sub-modules that are not named 'index' then you could do this:</p>
<pre><code>mod1, mod2, mod3 = map(lambda x,y: __import__(x, fromlist=y),
['mod1', 'mod2', 'mod3'], ['index1', 'index2', 'index3'])
</code></pre>
| 4
|
2009-04-20T18:52:45Z
|
[
"python",
"dynamic",
"module",
"loading"
] |
Dynamic Loading of Python Modules
| 769,534
|
<p>I'm trying to dynamically load modules I've created.</p>
<p>Right now this works properly:</p>
<pre><code>import structures.index
</code></pre>
<p>But if I try the same thing by importing it dynamically, it fails.</p>
<pre><code>struct = __import__("structures.index")
</code></pre>
<p>Error supplied is:</p>
<pre><code>Error ('No module named structures.index',)
</code></pre>
<p>Any ideas why?</p>
<p><hr /></p>
<p>Edit: When using full scope (it sort of works?):</p>
<pre><code>struct = __import__("neoform.structures.index")
</code></pre>
<p>This doesn't throw any errors, however, it isn't loading the index module, it's loading the "neoform" module instead.</p>
<p>The result of "struct" is:</p>
<pre><code><module 'neoform' from '/neoform/__init__.py'>
</code></pre>
<p>Also, as a side question, how can I then instantiate a class within a dynamically loaded module? (assuming all the modules contain a common class name).</p>
<p>Edit: Solution: (thanks coonj & Rick) This ended up being what worked. Not sure why (yet), but the <code>fromlist</code> had to be something "anything apparently, since it worked when I put the letter "a" as a value (strange, given that the file only had 1 class in it).</p>
<pre><code>def get_struct_module(self, name):
try:
return = __import__("neoform.structures." + name, fromlist='*')
except ImportError, e:
self.out.add("Could not load struct: neoform.structure." + name + "\n\n" + "Error " + str(e.args))
</code></pre>
| 3
|
2009-04-20T18:34:04Z
| 769,748
|
<p>Why on earth would you replace</p>
<pre><code>import structures.index
</code></pre>
<p>with</p>
<pre><code>map(__import__, ["structures.index"])
</code></pre>
<p>The first one (a) works, (b) <em>is</em> dynamic and (c) is directly supported. What possible use case is there for replacing easy-to-change, plain-text source with something more complex?</p>
<p>In short: don't do this. It doesn't have any value.</p>
<p><hr /></p>
<p><strong>Edit</strong></p>
<p>The "I'm getting the import from a database" is a noble effort, but still not sensible. What code block depends on those imports? That whole code block -- imports and all -- is what you want to execute. That whole code block -- imports, statements and everything -- should be a plain old python module file.</p>
<p>Import that block of code from the file system. Use the database to identify which file, the author of the file -- anything you want to use the database for. But simply import and execute the module the simplest possible way.</p>
| 0
|
2009-04-20T19:23:19Z
|
[
"python",
"dynamic",
"module",
"loading"
] |
Dynamic Loading of Python Modules
| 769,534
|
<p>I'm trying to dynamically load modules I've created.</p>
<p>Right now this works properly:</p>
<pre><code>import structures.index
</code></pre>
<p>But if I try the same thing by importing it dynamically, it fails.</p>
<pre><code>struct = __import__("structures.index")
</code></pre>
<p>Error supplied is:</p>
<pre><code>Error ('No module named structures.index',)
</code></pre>
<p>Any ideas why?</p>
<p><hr /></p>
<p>Edit: When using full scope (it sort of works?):</p>
<pre><code>struct = __import__("neoform.structures.index")
</code></pre>
<p>This doesn't throw any errors, however, it isn't loading the index module, it's loading the "neoform" module instead.</p>
<p>The result of "struct" is:</p>
<pre><code><module 'neoform' from '/neoform/__init__.py'>
</code></pre>
<p>Also, as a side question, how can I then instantiate a class within a dynamically loaded module? (assuming all the modules contain a common class name).</p>
<p>Edit: Solution: (thanks coonj & Rick) This ended up being what worked. Not sure why (yet), but the <code>fromlist</code> had to be something "anything apparently, since it worked when I put the letter "a" as a value (strange, given that the file only had 1 class in it).</p>
<pre><code>def get_struct_module(self, name):
try:
return = __import__("neoform.structures." + name, fromlist='*')
except ImportError, e:
self.out.add("Could not load struct: neoform.structure." + name + "\n\n" + "Error " + str(e.args))
</code></pre>
| 3
|
2009-04-20T18:34:04Z
| 770,159
|
<p>Use full scope ("neoform.structures.index") with this helper method.</p>
<pre><code>def import_module(name):
mod = __import__(name)
components = name.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
return mod
module = import_module("neoform.structures.index")
# do stuff with module
</code></pre>
| 3
|
2009-04-20T21:23:16Z
|
[
"python",
"dynamic",
"module",
"loading"
] |
Dynamic Loading of Python Modules
| 769,534
|
<p>I'm trying to dynamically load modules I've created.</p>
<p>Right now this works properly:</p>
<pre><code>import structures.index
</code></pre>
<p>But if I try the same thing by importing it dynamically, it fails.</p>
<pre><code>struct = __import__("structures.index")
</code></pre>
<p>Error supplied is:</p>
<pre><code>Error ('No module named structures.index',)
</code></pre>
<p>Any ideas why?</p>
<p><hr /></p>
<p>Edit: When using full scope (it sort of works?):</p>
<pre><code>struct = __import__("neoform.structures.index")
</code></pre>
<p>This doesn't throw any errors, however, it isn't loading the index module, it's loading the "neoform" module instead.</p>
<p>The result of "struct" is:</p>
<pre><code><module 'neoform' from '/neoform/__init__.py'>
</code></pre>
<p>Also, as a side question, how can I then instantiate a class within a dynamically loaded module? (assuming all the modules contain a common class name).</p>
<p>Edit: Solution: (thanks coonj & Rick) This ended up being what worked. Not sure why (yet), but the <code>fromlist</code> had to be something "anything apparently, since it worked when I put the letter "a" as a value (strange, given that the file only had 1 class in it).</p>
<pre><code>def get_struct_module(self, name):
try:
return = __import__("neoform.structures." + name, fromlist='*')
except ImportError, e:
self.out.add("Could not load struct: neoform.structure." + name + "\n\n" + "Error " + str(e.args))
</code></pre>
| 3
|
2009-04-20T18:34:04Z
| 2,492,480
|
<pre><code>>>> import imp
>>> fm = imp.find_module('index', ['./structures']) # for submodule
>>> mymod = imp.load_module('structures.index', *fm)
>>> mymod
<module 'structures.index' from './structures/index.pyc'>
>>> x = mymod.insideIndex()
Initialising index class...
</code></pre>
<p>Voila!</p>
| 1
|
2010-03-22T13:21:44Z
|
[
"python",
"dynamic",
"module",
"loading"
] |
Dynamic Loading of Python Modules
| 769,534
|
<p>I'm trying to dynamically load modules I've created.</p>
<p>Right now this works properly:</p>
<pre><code>import structures.index
</code></pre>
<p>But if I try the same thing by importing it dynamically, it fails.</p>
<pre><code>struct = __import__("structures.index")
</code></pre>
<p>Error supplied is:</p>
<pre><code>Error ('No module named structures.index',)
</code></pre>
<p>Any ideas why?</p>
<p><hr /></p>
<p>Edit: When using full scope (it sort of works?):</p>
<pre><code>struct = __import__("neoform.structures.index")
</code></pre>
<p>This doesn't throw any errors, however, it isn't loading the index module, it's loading the "neoform" module instead.</p>
<p>The result of "struct" is:</p>
<pre><code><module 'neoform' from '/neoform/__init__.py'>
</code></pre>
<p>Also, as a side question, how can I then instantiate a class within a dynamically loaded module? (assuming all the modules contain a common class name).</p>
<p>Edit: Solution: (thanks coonj & Rick) This ended up being what worked. Not sure why (yet), but the <code>fromlist</code> had to be something "anything apparently, since it worked when I put the letter "a" as a value (strange, given that the file only had 1 class in it).</p>
<pre><code>def get_struct_module(self, name):
try:
return = __import__("neoform.structures." + name, fromlist='*')
except ImportError, e:
self.out.add("Could not load struct: neoform.structure." + name + "\n\n" + "Error " + str(e.args))
</code></pre>
| 3
|
2009-04-20T18:34:04Z
| 15,423,470
|
<p>Really late post here. But I was searching for this question on google. I did some trial and error. Not sure if this snippet will help but here it is. Using it for Flask site. </p>
<pre><code>modules = ['frontend', 'admin']
for module in modules:
mod = __init__('controllers.%s' % module, fromlist=[module])
app.register_blueprint(mod.blueprint_mod)
# or
from importlib import import_module
modules = ['frontend', 'admin']
for module in modules:
mod = import_module('controllers.%s' % module)
app.regitster_blueprint(mod.blueprint_mod)
</code></pre>
| 0
|
2013-03-15T02:00:00Z
|
[
"python",
"dynamic",
"module",
"loading"
] |
How do I load entry-points for a defined set of eggs with Python setuptools?
| 769,766
|
<p>I would like to use the entry point functionality in setuptools.</p>
<p>There are a number of occasions where I would like to tightly control the list of eggs that are run, and thence the extensions that contribute to a set of entry points:</p>
<ul>
<li>egg integration testing, where I want to run multiple test suites on different combinations of eggs.</li>
<li>scanning a single directory of eggs/plugins so as to run two different instances of the same program, but with different eggs.</li>
<li>development time, where I am developing one or more egg, and would like to run the program as part of the normal edit-run cycle.</li>
</ul>
<p>I have looked through the setuptools documentation, and while it doesn't say that this is not possible, I must have missed something saying how to do it. </p>
<p>What is the best way to approach deploying plugins differently to the default system-wide discovery?</p>
| 0
|
2009-04-20T19:27:37Z
| 1,000,651
|
<p>We're solving something similar, ability to use setup.py develop if You're mere user without access to global site-packages. So far, we solved it with virtualenv.</p>
<p>I'd say it will help for your case too: have minimal system-wide install (or explicitly exclude it), create virtual environment with eggs you want and test there.</p>
<p>(Or, for integration tests, create clean environment, install egg and test all dependencies are installed).</p>
<p>For 2, I'm not sure, but it should work too, with multiple virtualenvs. For 3, setup.py develop is the way to go.</p>
| 0
|
2009-06-16T10:20:14Z
|
[
"python",
"setuptools",
"distutils",
"egg"
] |
The lines that stand out in a file, but aren't exact duplicates
| 769,775
|
<p>I'm combing a webapp's log file for statements that stand out.</p>
<p>Most of the lines are similar and uninteresting. I'd pass them through Unix <code>uniq</code>, however that filters nothing, as all the lines are slightly different: they all have a different timestamp, similar statements might print a different user ID, etc.</p>
<p>What's a way and/or tool to get just the lines that are notably different from any other? (But, again, not precise duplicates)</p>
<p>I was thinking about playing with Python's <a href="http://docs.python.org/library/difflib.html" rel="nofollow">difflib</a> but that seems geared toward diffing two files, rather than all pairs of lines in the same file.</p>
<p>[EDIT]</p>
<p>I assumed the solution would give a uniqueness score for each line. So by "notably different" I meant, I choose a threshold that the uniqueness score must exceed for any line to be included in the output.</p>
<p>Based on that, if there are other viable ways to define it, please discuss. Also, the method doesn't have to have 100% accuracy and recall.</p>
<p>[/EDIT]</p>
<p>Examples:</p>
<p>I'd prefer answers that are as general purpose as possible. I know I can strip away the timestamp at the beginning. Stripping the end is more challenging, as its language may be absolutely unlike anything else in the file. These sorts of details are why I shied from concrete examples before, but because some people asked...</p>
<p>Similar 1:</p>
<pre><code>2009-04-20 00:03:57 INFO com.foo.Bar - URL:/graph?id=1234
2009-04-20 00:04:02 INFO com.foo.Bar - URL:/graph?id=asdfghjk
</code></pre>
<p>Similar 2:</p>
<pre><code>2009-04-20 00:05:59 INFO com.baz.abc.Accessor - Cache /path/to/some/dir hits: 3466 / 16534, 0.102818% misses
2009-04-20 00:06:00 INFO com.baz.abc.Accessor - Cache /path/to/some/different/dir hits: 4352685 / 271315, 0.004423% misses
</code></pre>
<p>Different 1:</p>
<pre><code>2009-04-20 00:03:57 INFO com.foo.Bar - URL:/graph?id=1234
2009-04-20 00:05:59 INFO com.baz.abc.Accessor - Cache /path/to/some/dir hits: 3466 / 16534, 0.102818% misses
</code></pre>
<p>In the Different 1 case, I'd like both lines returned but not other lines like them. In other words, those 2 lines are distinct types (then I can later ask for only statistically rare line types). The edit distance is much bigger between those two, for one thing.</p>
| 3
|
2009-04-20T19:30:37Z
| 769,790
|
<p>Define "notably different". Then have a look at <a href="http://en.wikipedia.org/wiki/Edit%5Fdistance" rel="nofollow">"edit distance" measures</a>.</p>
| 3
|
2009-04-20T19:35:08Z
|
[
"python",
"algorithm",
"unix",
"grep",
"nlp"
] |
The lines that stand out in a file, but aren't exact duplicates
| 769,775
|
<p>I'm combing a webapp's log file for statements that stand out.</p>
<p>Most of the lines are similar and uninteresting. I'd pass them through Unix <code>uniq</code>, however that filters nothing, as all the lines are slightly different: they all have a different timestamp, similar statements might print a different user ID, etc.</p>
<p>What's a way and/or tool to get just the lines that are notably different from any other? (But, again, not precise duplicates)</p>
<p>I was thinking about playing with Python's <a href="http://docs.python.org/library/difflib.html" rel="nofollow">difflib</a> but that seems geared toward diffing two files, rather than all pairs of lines in the same file.</p>
<p>[EDIT]</p>
<p>I assumed the solution would give a uniqueness score for each line. So by "notably different" I meant, I choose a threshold that the uniqueness score must exceed for any line to be included in the output.</p>
<p>Based on that, if there are other viable ways to define it, please discuss. Also, the method doesn't have to have 100% accuracy and recall.</p>
<p>[/EDIT]</p>
<p>Examples:</p>
<p>I'd prefer answers that are as general purpose as possible. I know I can strip away the timestamp at the beginning. Stripping the end is more challenging, as its language may be absolutely unlike anything else in the file. These sorts of details are why I shied from concrete examples before, but because some people asked...</p>
<p>Similar 1:</p>
<pre><code>2009-04-20 00:03:57 INFO com.foo.Bar - URL:/graph?id=1234
2009-04-20 00:04:02 INFO com.foo.Bar - URL:/graph?id=asdfghjk
</code></pre>
<p>Similar 2:</p>
<pre><code>2009-04-20 00:05:59 INFO com.baz.abc.Accessor - Cache /path/to/some/dir hits: 3466 / 16534, 0.102818% misses
2009-04-20 00:06:00 INFO com.baz.abc.Accessor - Cache /path/to/some/different/dir hits: 4352685 / 271315, 0.004423% misses
</code></pre>
<p>Different 1:</p>
<pre><code>2009-04-20 00:03:57 INFO com.foo.Bar - URL:/graph?id=1234
2009-04-20 00:05:59 INFO com.baz.abc.Accessor - Cache /path/to/some/dir hits: 3466 / 16534, 0.102818% misses
</code></pre>
<p>In the Different 1 case, I'd like both lines returned but not other lines like them. In other words, those 2 lines are distinct types (then I can later ask for only statistically rare line types). The edit distance is much bigger between those two, for one thing.</p>
| 3
|
2009-04-20T19:30:37Z
| 769,791
|
<p>You could try a bit of code that counts words, and then sorts lines by those having the least common words. </p>
<p>If that doesn't do the trick, you can add in some smarts to filter out time stamps and numbers. </p>
<p>Your problem is similar to an earlier question on <a href="http://stackoverflow.com/questions/742711/shorten-a-text-and-only-keep-important-sentences">generating summaries of news stories</a>.</p>
| 2
|
2009-04-20T19:35:15Z
|
[
"python",
"algorithm",
"unix",
"grep",
"nlp"
] |
The lines that stand out in a file, but aren't exact duplicates
| 769,775
|
<p>I'm combing a webapp's log file for statements that stand out.</p>
<p>Most of the lines are similar and uninteresting. I'd pass them through Unix <code>uniq</code>, however that filters nothing, as all the lines are slightly different: they all have a different timestamp, similar statements might print a different user ID, etc.</p>
<p>What's a way and/or tool to get just the lines that are notably different from any other? (But, again, not precise duplicates)</p>
<p>I was thinking about playing with Python's <a href="http://docs.python.org/library/difflib.html" rel="nofollow">difflib</a> but that seems geared toward diffing two files, rather than all pairs of lines in the same file.</p>
<p>[EDIT]</p>
<p>I assumed the solution would give a uniqueness score for each line. So by "notably different" I meant, I choose a threshold that the uniqueness score must exceed for any line to be included in the output.</p>
<p>Based on that, if there are other viable ways to define it, please discuss. Also, the method doesn't have to have 100% accuracy and recall.</p>
<p>[/EDIT]</p>
<p>Examples:</p>
<p>I'd prefer answers that are as general purpose as possible. I know I can strip away the timestamp at the beginning. Stripping the end is more challenging, as its language may be absolutely unlike anything else in the file. These sorts of details are why I shied from concrete examples before, but because some people asked...</p>
<p>Similar 1:</p>
<pre><code>2009-04-20 00:03:57 INFO com.foo.Bar - URL:/graph?id=1234
2009-04-20 00:04:02 INFO com.foo.Bar - URL:/graph?id=asdfghjk
</code></pre>
<p>Similar 2:</p>
<pre><code>2009-04-20 00:05:59 INFO com.baz.abc.Accessor - Cache /path/to/some/dir hits: 3466 / 16534, 0.102818% misses
2009-04-20 00:06:00 INFO com.baz.abc.Accessor - Cache /path/to/some/different/dir hits: 4352685 / 271315, 0.004423% misses
</code></pre>
<p>Different 1:</p>
<pre><code>2009-04-20 00:03:57 INFO com.foo.Bar - URL:/graph?id=1234
2009-04-20 00:05:59 INFO com.baz.abc.Accessor - Cache /path/to/some/dir hits: 3466 / 16534, 0.102818% misses
</code></pre>
<p>In the Different 1 case, I'd like both lines returned but not other lines like them. In other words, those 2 lines are distinct types (then I can later ask for only statistically rare line types). The edit distance is much bigger between those two, for one thing.</p>
| 3
|
2009-04-20T19:30:37Z
| 769,799
|
<p>I don't know a tool for you but if <em>I</em> were going to roll my own, I'd approach it like this:</p>
<p>Presumably the log lines have a well defined structure, no? So</p>
<ul>
<li>parse the lines on that structure</li>
<li>write a number of very basic relevance filters (functions that just return a simple number from the parsed structure)</li>
<li>run the parsed lines through a set of filters, and cut on the basis of the total score</li>
<li>possibly sort the remaining lines into various bins by the results of more filters</li>
<li>generate reports, dump bins to files, or other output</li>
</ul>
<p>If you are familiar with the unix tool <code>procmail</code>, I'm suggesting a similar treatment customized for your data.</p>
<p><hr /></p>
<p>As zacherates notes in the comments, your filters will typically ignore time stamps (and possibly IP address), and just concentrate on the content: for example <em>really</em> long http requests might represent an attack...or whatever applies to your domain.</p>
<p>Your binning filters might be as simple as a hash on a few selected fields, or you might try to do something with <a href="http://stackoverflow.com/questions/769775/the-lines-that-stand-out-in-a-file-but-arent-exact-duplicates/769790#769790">Charlie Martin's suggestion</a> and used edit distance measures.</p>
| 2
|
2009-04-20T19:37:47Z
|
[
"python",
"algorithm",
"unix",
"grep",
"nlp"
] |
The lines that stand out in a file, but aren't exact duplicates
| 769,775
|
<p>I'm combing a webapp's log file for statements that stand out.</p>
<p>Most of the lines are similar and uninteresting. I'd pass them through Unix <code>uniq</code>, however that filters nothing, as all the lines are slightly different: they all have a different timestamp, similar statements might print a different user ID, etc.</p>
<p>What's a way and/or tool to get just the lines that are notably different from any other? (But, again, not precise duplicates)</p>
<p>I was thinking about playing with Python's <a href="http://docs.python.org/library/difflib.html" rel="nofollow">difflib</a> but that seems geared toward diffing two files, rather than all pairs of lines in the same file.</p>
<p>[EDIT]</p>
<p>I assumed the solution would give a uniqueness score for each line. So by "notably different" I meant, I choose a threshold that the uniqueness score must exceed for any line to be included in the output.</p>
<p>Based on that, if there are other viable ways to define it, please discuss. Also, the method doesn't have to have 100% accuracy and recall.</p>
<p>[/EDIT]</p>
<p>Examples:</p>
<p>I'd prefer answers that are as general purpose as possible. I know I can strip away the timestamp at the beginning. Stripping the end is more challenging, as its language may be absolutely unlike anything else in the file. These sorts of details are why I shied from concrete examples before, but because some people asked...</p>
<p>Similar 1:</p>
<pre><code>2009-04-20 00:03:57 INFO com.foo.Bar - URL:/graph?id=1234
2009-04-20 00:04:02 INFO com.foo.Bar - URL:/graph?id=asdfghjk
</code></pre>
<p>Similar 2:</p>
<pre><code>2009-04-20 00:05:59 INFO com.baz.abc.Accessor - Cache /path/to/some/dir hits: 3466 / 16534, 0.102818% misses
2009-04-20 00:06:00 INFO com.baz.abc.Accessor - Cache /path/to/some/different/dir hits: 4352685 / 271315, 0.004423% misses
</code></pre>
<p>Different 1:</p>
<pre><code>2009-04-20 00:03:57 INFO com.foo.Bar - URL:/graph?id=1234
2009-04-20 00:05:59 INFO com.baz.abc.Accessor - Cache /path/to/some/dir hits: 3466 / 16534, 0.102818% misses
</code></pre>
<p>In the Different 1 case, I'd like both lines returned but not other lines like them. In other words, those 2 lines are distinct types (then I can later ask for only statistically rare line types). The edit distance is much bigger between those two, for one thing.</p>
| 3
|
2009-04-20T19:30:37Z
| 770,603
|
<p>I wonder if you could just focus on the part that defines uniqueness for you. In this case, it seems that the part defining uniqueness is just the middle part:</p>
<pre>
2009-04-20 00:03:57 INFO com.foo.Bar - URL:/graph?id=1234
^---------------------^
2009-04-20 00:05:59 INFO com.baz.abc.Accessor - Cache /path/to/some/dir hits: 3466 / 16534, 0.102818% misses
^--------------------------------^
</pre>
<p>I would then compare exactly this part, perhaps using a regular expression (just the parenthesized group; how to access sub-matches like this is language dependent):</p>
<pre><code>/^.{20}(\w+\s+[\w\.-]+\s+-\s+\w+)/
</code></pre>
| 0
|
2009-04-21T00:26:14Z
|
[
"python",
"algorithm",
"unix",
"grep",
"nlp"
] |
The lines that stand out in a file, but aren't exact duplicates
| 769,775
|
<p>I'm combing a webapp's log file for statements that stand out.</p>
<p>Most of the lines are similar and uninteresting. I'd pass them through Unix <code>uniq</code>, however that filters nothing, as all the lines are slightly different: they all have a different timestamp, similar statements might print a different user ID, etc.</p>
<p>What's a way and/or tool to get just the lines that are notably different from any other? (But, again, not precise duplicates)</p>
<p>I was thinking about playing with Python's <a href="http://docs.python.org/library/difflib.html" rel="nofollow">difflib</a> but that seems geared toward diffing two files, rather than all pairs of lines in the same file.</p>
<p>[EDIT]</p>
<p>I assumed the solution would give a uniqueness score for each line. So by "notably different" I meant, I choose a threshold that the uniqueness score must exceed for any line to be included in the output.</p>
<p>Based on that, if there are other viable ways to define it, please discuss. Also, the method doesn't have to have 100% accuracy and recall.</p>
<p>[/EDIT]</p>
<p>Examples:</p>
<p>I'd prefer answers that are as general purpose as possible. I know I can strip away the timestamp at the beginning. Stripping the end is more challenging, as its language may be absolutely unlike anything else in the file. These sorts of details are why I shied from concrete examples before, but because some people asked...</p>
<p>Similar 1:</p>
<pre><code>2009-04-20 00:03:57 INFO com.foo.Bar - URL:/graph?id=1234
2009-04-20 00:04:02 INFO com.foo.Bar - URL:/graph?id=asdfghjk
</code></pre>
<p>Similar 2:</p>
<pre><code>2009-04-20 00:05:59 INFO com.baz.abc.Accessor - Cache /path/to/some/dir hits: 3466 / 16534, 0.102818% misses
2009-04-20 00:06:00 INFO com.baz.abc.Accessor - Cache /path/to/some/different/dir hits: 4352685 / 271315, 0.004423% misses
</code></pre>
<p>Different 1:</p>
<pre><code>2009-04-20 00:03:57 INFO com.foo.Bar - URL:/graph?id=1234
2009-04-20 00:05:59 INFO com.baz.abc.Accessor - Cache /path/to/some/dir hits: 3466 / 16534, 0.102818% misses
</code></pre>
<p>In the Different 1 case, I'd like both lines returned but not other lines like them. In other words, those 2 lines are distinct types (then I can later ask for only statistically rare line types). The edit distance is much bigger between those two, for one thing.</p>
| 3
|
2009-04-20T19:30:37Z
| 770,695
|
<p>I think you want to break this into fields, sort by the "severity level" field and the next field (looks like "class"). I'd use Haskell:</p>
<pre>
module Main where
import Data.List (nubBy, sortBy)
sortAndNub s = nubBy fields2and3
$ sortBy fields2and3comp
$ map words $ lines s
fields2and3 a b = fieldEq 2 a b
&& fieldEq 3 a b
fieldEq f a b = a!!f == (b!!f)
fields2and3comp a b = case compare (a!!2) (b!!2) of
LT -> LT
GT -> GT
EQ -> compare (a!!3) (b!!3)
main = interact $ unlines.(map unwords).sortAndNub
</pre>
| 0
|
2009-04-21T01:16:32Z
|
[
"python",
"algorithm",
"unix",
"grep",
"nlp"
] |
The lines that stand out in a file, but aren't exact duplicates
| 769,775
|
<p>I'm combing a webapp's log file for statements that stand out.</p>
<p>Most of the lines are similar and uninteresting. I'd pass them through Unix <code>uniq</code>, however that filters nothing, as all the lines are slightly different: they all have a different timestamp, similar statements might print a different user ID, etc.</p>
<p>What's a way and/or tool to get just the lines that are notably different from any other? (But, again, not precise duplicates)</p>
<p>I was thinking about playing with Python's <a href="http://docs.python.org/library/difflib.html" rel="nofollow">difflib</a> but that seems geared toward diffing two files, rather than all pairs of lines in the same file.</p>
<p>[EDIT]</p>
<p>I assumed the solution would give a uniqueness score for each line. So by "notably different" I meant, I choose a threshold that the uniqueness score must exceed for any line to be included in the output.</p>
<p>Based on that, if there are other viable ways to define it, please discuss. Also, the method doesn't have to have 100% accuracy and recall.</p>
<p>[/EDIT]</p>
<p>Examples:</p>
<p>I'd prefer answers that are as general purpose as possible. I know I can strip away the timestamp at the beginning. Stripping the end is more challenging, as its language may be absolutely unlike anything else in the file. These sorts of details are why I shied from concrete examples before, but because some people asked...</p>
<p>Similar 1:</p>
<pre><code>2009-04-20 00:03:57 INFO com.foo.Bar - URL:/graph?id=1234
2009-04-20 00:04:02 INFO com.foo.Bar - URL:/graph?id=asdfghjk
</code></pre>
<p>Similar 2:</p>
<pre><code>2009-04-20 00:05:59 INFO com.baz.abc.Accessor - Cache /path/to/some/dir hits: 3466 / 16534, 0.102818% misses
2009-04-20 00:06:00 INFO com.baz.abc.Accessor - Cache /path/to/some/different/dir hits: 4352685 / 271315, 0.004423% misses
</code></pre>
<p>Different 1:</p>
<pre><code>2009-04-20 00:03:57 INFO com.foo.Bar - URL:/graph?id=1234
2009-04-20 00:05:59 INFO com.baz.abc.Accessor - Cache /path/to/some/dir hits: 3466 / 16534, 0.102818% misses
</code></pre>
<p>In the Different 1 case, I'd like both lines returned but not other lines like them. In other words, those 2 lines are distinct types (then I can later ask for only statistically rare line types). The edit distance is much bigger between those two, for one thing.</p>
| 3
|
2009-04-20T19:30:37Z
| 770,822
|
<p>Perhaps you could do a basic calculation of "words the same"/"all words"?</p>
<p>e.g. (including an offset to allow you to ignore the timestamp and the word 'INFO', if that's always the same):</p>
<pre><code>def score(s1, s2, offset=26):
words1 = re.findall('\w+', s1[offset:])
words2 = re.findall('\w+', s2[offset:])
return float(len(set(words1) & set(words2)))/max(len(set(words1)), len(set(words2)))
</code></pre>
<p>Given:</p>
<pre><code>>>> s1
'2009-04-20 00:03:57 INFO com.foo.Bar - URL:/graph?id=1234'
>>> s2
'2009-04-20 00:04:02 INFO com.foo.Bar - URL:/graph?id=asdfghjk'
>>> s3
'2009-04-20 00:05:59 INFO com.baz.abc.Accessor - Cache /path/to/some/dir hits: 3466 / 16534, 0.102818% misses'
>>> s4
'2009-04-20 00:06:00 INFO com.baz.abc.Accessor - Cache /path/to/some/different/dir hits: 4352685 / 271315, 0.004423% misses'
</code></pre>
<p>This yields:</p>
<pre><code>>>> score(s1,s2)
0.8571428571428571
>>> score(s3,s4)
0.75
>>> score(s1,s3)
0.066666666666666666
</code></pre>
<p>You've still got to decide which lines to compare. Also the use of set() may distort the scores slightly â the price of a simple algorithm :-)</p>
| 1
|
2009-04-21T02:21:56Z
|
[
"python",
"algorithm",
"unix",
"grep",
"nlp"
] |
Multiple projects from one setup.py?
| 769,793
|
<p>My current <a href="http://github.com/dbr/tvdb%5Fapi/blob/fa55575e26b188de9b9b9f0c41d52c2a45400796/setup.py">setup.py</a> (using setuptools) installs two things, one is <code>tvdb_api</code> (an API wrapper), the other is <code>tvnamer</code> (a command line script)</p>
<p>I wish to make the two available separately, so a user can do..</p>
<pre><code>easy_install tvdb_api
</code></pre>
<p>..to only get the API wrapper, or..</p>
<pre><code>easy_install tvnamer
</code></pre>
<p>..to install tvnamer (and tvdb_api, as a requirement)</p>
<p>Is this possible without having two separate <code>setup.py</code> scripts? Can you have two separate PyPi packages that come from the same <code>python setup.py upload</code> command..?</p>
| 6
|
2009-04-20T19:35:26Z
| 770,247
|
<p><code>setup.py</code> is just a regular Python file, which by convention sets up packages. By convention, <code>setup.py</code> contains a call to the setuptools or distutils <code>setup()</code> function. If you want to use one <code>setup.py</code> for two packages, you can call a different <code>setup()</code> function based on a command-line argument:</p>
<pre><code>import sys
if len(sys.argv) > 1 and sys.argv[1] == 'script':
setup(name='tvnamer', ...)
else:
setup(name='tvdb_api', ...)
</code></pre>
<p>Practically, though, I'd recommend just writing two scripts.</p>
| 7
|
2009-04-20T21:45:32Z
|
[
"python",
"setuptools"
] |
How do I use AND in a Django filter?
| 769,843
|
<p>How do I create an "AND" filter to retrieve objects in Django? e.g I would like to retrieve a row which has a combination of two words in a single field.</p>
<p>For example the following SQL query does exactly that when I run it on mysql database:</p>
<pre><code>select * from myapp_question
where ((question like '%software%') and (question like '%java%'))
</code></pre>
<p>How do you accomplish this in Django using filters?</p>
| 16
|
2009-04-20T19:55:11Z
| 769,849
|
<pre><code>mymodel.objects.filter(first_name__icontains="Foo", first_name__icontains="Bar")
</code></pre>
| 34
|
2009-04-20T19:57:38Z
|
[
"python",
"django"
] |
How do I use AND in a Django filter?
| 769,843
|
<p>How do I create an "AND" filter to retrieve objects in Django? e.g I would like to retrieve a row which has a combination of two words in a single field.</p>
<p>For example the following SQL query does exactly that when I run it on mysql database:</p>
<pre><code>select * from myapp_question
where ((question like '%software%') and (question like '%java%'))
</code></pre>
<p>How do you accomplish this in Django using filters?</p>
| 16
|
2009-04-20T19:55:11Z
| 769,862
|
<p>You can chain filter expressions in Django:</p>
<pre><code>q = Question.objects.filter(question__contains='software').filter(question__contains='java')
</code></pre>
<p>You can find more info in the Django docs at "<a href="http://docs.djangoproject.com/en/dev/topics/db/queries/#id1">Chaining Filters</a>".</p>
| 8
|
2009-04-20T20:01:38Z
|
[
"python",
"django"
] |
How do I use AND in a Django filter?
| 769,843
|
<p>How do I create an "AND" filter to retrieve objects in Django? e.g I would like to retrieve a row which has a combination of two words in a single field.</p>
<p>For example the following SQL query does exactly that when I run it on mysql database:</p>
<pre><code>select * from myapp_question
where ((question like '%software%') and (question like '%java%'))
</code></pre>
<p>How do you accomplish this in Django using filters?</p>
| 16
|
2009-04-20T19:55:11Z
| 770,078
|
<p>For thoroughness sake, let's just mention the <a href="http://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects"><code>Q</code></a> object method:</p>
<pre><code>from django.db.models import Q
criterion1 = Q(question__contains="software")
criterion2 = Q(question__contains="java")
q = Question.objects.filter(criterion1 & criterion2)
</code></pre>
<p>Note the other answers here are simpler and better adapted for your use case, but if anyone with a similar but slightly more complex problem (such as needing "not" or "or") sees this, it's good to have the reference right here.</p>
| 37
|
2009-04-20T21:04:52Z
|
[
"python",
"django"
] |
Python selecting a value in a combo box and HTTP POST
| 769,948
|
<p>In Python, I'm trying to read the values on <a href="http://utahcritseries.com/RawResults.aspx" rel="nofollow">http://utahcritseries.com/RawResults.aspx</a>. How can I read years other than the default of 2002?</p>
<p>So far, using mechanize, I've been able to reference the SELECT and list all of its available options/values but am unsure how to change its value and resubmit the form.</p>
<p>I'm sure this is a common issue and is frequently asked, but I'm not sure what I should even be searching for.</p>
| 1
|
2009-04-20T20:29:50Z
| 769,966
|
<p>With problems relating to AJAX-loading of pages, use <a href="http://getfirebug.com/" rel="nofollow">Firebug!</a></p>
<p>Install and open Firebug (it's a Firefox plugin), go to the Net page, and make sure "All" is selected. Open the URL and change the select box, and see what is sent to the server, and what is received.</p>
<p>It seems the catchily-named field <code>ctl00$ContentPlaceHolder1$ddlSeries</code> is what is responsible.. Does the following work..?</p>
<pre><code>import urllib
postdata = {'ctl00$ContentPlaceHolder1$ddlSeries': 9}
src = urllib.urlopen(
"http://utahcritseries.com/RawResults.aspx",
data = urllib.urlencode(postdata)
).read()
print src
</code></pre>
| 0
|
2009-04-20T20:35:14Z
|
[
"asp.net",
"python",
"http",
"web-scraping"
] |
Python selecting a value in a combo box and HTTP POST
| 769,948
|
<p>In Python, I'm trying to read the values on <a href="http://utahcritseries.com/RawResults.aspx" rel="nofollow">http://utahcritseries.com/RawResults.aspx</a>. How can I read years other than the default of 2002?</p>
<p>So far, using mechanize, I've been able to reference the SELECT and list all of its available options/values but am unsure how to change its value and resubmit the form.</p>
<p>I'm sure this is a common issue and is frequently asked, but I'm not sure what I should even be searching for.</p>
| 1
|
2009-04-20T20:29:50Z
| 801,934
|
<p>So how about this:</p>
<pre><code>from mechanize import Browser
year="2005"
br=Browser()
br.open("http://utahcritseries.com/RawResults.aspx")
br.select_form(name="aspnetForm")
control=br.form.find_control("ctl00$ContentPlaceHolder1$ddlSeries")
control.set_value_by_label((year,))
response2=br.submit()
print response2.read()
</code></pre>
| 1
|
2009-04-29T11:32:11Z
|
[
"asp.net",
"python",
"http",
"web-scraping"
] |
Global HotKeys in Win&X11
| 770,049
|
<p>I need to make a global hotkey for my application, and it should work under X11 and Windows.</p>
| 3
|
2009-04-20T20:55:11Z
| 770,077
|
<p>What GUI toolkit are you using? Generally, global hot keys are handled by the Desktop environment or Window Manager - I dont believe that Python's builtin toolkit (tkinter) can make global hotkeys. You might look at <a href="http://python-xlib.sourceforge.net/" rel="nofollow">xlib</a> for Unix and a win lib for windows.</p>
| 4
|
2009-04-20T21:03:24Z
|
[
"python",
"hotkeys"
] |
Global HotKeys in Win&X11
| 770,049
|
<p>I need to make a global hotkey for my application, and it should work under X11 and Windows.</p>
| 3
|
2009-04-20T20:55:11Z
| 8,340,605
|
<p>Just an addition - on windows, if you are using wxpython in your application, you can register your <a href="http://wxpython.org/docs/api/wx.Window-class.html#RegisterHotKey" rel="nofollow">hotkey</a>.
Example is <a href="http://wiki.wxpython.org/RegisterHotKey" rel="nofollow">here</a></p>
| 0
|
2011-12-01T11:26:36Z
|
[
"python",
"hotkeys"
] |
Python Cmd module, subclassing issue
| 770,134
|
<p>I'm trying to work out what's not working in this code:</p>
<pre><code>#!/usr/bin/python
import cmd
class My_class (cmd.Cmd):
"""docstring for Twitter_handler"""
def __init__(self):
super(My_class, self).__init__()
if __name__ == '__main__':
my_handler = My_class()
</code></pre>
<p>Here's the error I get</p>
<pre><code>Traceback (most recent call last):
File "main.py", line 12, in <module>
my_handler = My_class()
File "main.py", line 9, in __init__
super(My_class, self).__init__()
TypeError: super() argument 1 must be type, not classobj
</code></pre>
<p>If I change the superclass of "My_class" to an object it works fine. Where am I going wrong?</p>
| 5
|
2009-04-20T21:18:36Z
| 770,183
|
<p><a href="http://docs.python.org/library/functions.html#super">super()</a> only works for <a href="http://docs.python.org/reference/datamodel.html#newstyle">new-style classes</a></p>
| 9
|
2009-04-20T21:30:39Z
|
[
"python"
] |
Python Cmd module, subclassing issue
| 770,134
|
<p>I'm trying to work out what's not working in this code:</p>
<pre><code>#!/usr/bin/python
import cmd
class My_class (cmd.Cmd):
"""docstring for Twitter_handler"""
def __init__(self):
super(My_class, self).__init__()
if __name__ == '__main__':
my_handler = My_class()
</code></pre>
<p>Here's the error I get</p>
<pre><code>Traceback (most recent call last):
File "main.py", line 12, in <module>
my_handler = My_class()
File "main.py", line 9, in __init__
super(My_class, self).__init__()
TypeError: super() argument 1 must be type, not classobj
</code></pre>
<p>If I change the superclass of "My_class" to an object it works fine. Where am I going wrong?</p>
| 5
|
2009-04-20T21:18:36Z
| 770,189
|
<p>cmd.Cmd is not a new style class in Python 2.5, 2.6, 2.7.</p>
<p>Note that your code does <em>not</em> raise an exception in Python 3.0.</p>
| 7
|
2009-04-20T21:32:19Z
|
[
"python"
] |
Python Cmd module, subclassing issue
| 770,134
|
<p>I'm trying to work out what's not working in this code:</p>
<pre><code>#!/usr/bin/python
import cmd
class My_class (cmd.Cmd):
"""docstring for Twitter_handler"""
def __init__(self):
super(My_class, self).__init__()
if __name__ == '__main__':
my_handler = My_class()
</code></pre>
<p>Here's the error I get</p>
<pre><code>Traceback (most recent call last):
File "main.py", line 12, in <module>
my_handler = My_class()
File "main.py", line 9, in __init__
super(My_class, self).__init__()
TypeError: super() argument 1 must be type, not classobj
</code></pre>
<p>If I change the superclass of "My_class" to an object it works fine. Where am I going wrong?</p>
| 5
|
2009-04-20T21:18:36Z
| 34,025,770
|
<p>So if <a href="http://docs.python.org/library/functions.html#super" rel="nofollow">super()</a> doesn't work use :</p>
<pre><code>import cmd
class My_class(cmd.Cmd):
def __init__(self):
cmd.Cmd.__init__(self)
</code></pre>
| 2
|
2015-12-01T16:57:43Z
|
[
"python"
] |
Python Cmd module, subclassing issue
| 770,134
|
<p>I'm trying to work out what's not working in this code:</p>
<pre><code>#!/usr/bin/python
import cmd
class My_class (cmd.Cmd):
"""docstring for Twitter_handler"""
def __init__(self):
super(My_class, self).__init__()
if __name__ == '__main__':
my_handler = My_class()
</code></pre>
<p>Here's the error I get</p>
<pre><code>Traceback (most recent call last):
File "main.py", line 12, in <module>
my_handler = My_class()
File "main.py", line 9, in __init__
super(My_class, self).__init__()
TypeError: super() argument 1 must be type, not classobj
</code></pre>
<p>If I change the superclass of "My_class" to an object it works fine. Where am I going wrong?</p>
| 5
|
2009-04-20T21:18:36Z
| 36,985,714
|
<p>You can still use <code>super()</code> if your <code>MyClass</code> extends <code>object</code>. This works even though the <code>cmd.Cmd</code> module is <em>not</em> a new-style class. Like this:</p>
<pre><code>#!/usr/bin/python
import cmd
class My_class (cmd.Cmd, object):
"""docstring for Twitter_handler"""
def __init__(self):
super(My_class, self).__init__()
if __name__ == '__main__':
my_handler = My_class()
</code></pre>
| 1
|
2016-05-02T15:08:36Z
|
[
"python"
] |
How do I structure Python code into modules/packages?
| 770,320
|
<p>Assume I have this barebones structure:</p>
<pre><code>project/
main.py
providers/
__init.py__
acme1.py
acme2.py
acme3.py
acme4.py
acme5.py
acme6.py
</code></pre>
<p>Assume that <code>main.py</code> contains (partial):</p>
<pre><code>if complexcondition():
print providers.acme5.get()
</code></pre>
<p>Where <code>__init__.py</code> is empty and <code>acme*.py</code> contain (partial):</p>
<pre><code>def get():
value=complexcalculation()
return value
</code></pre>
<p>How do I change these files to work?</p>
<p>Note: If the answer is "import acme1", "import acme2", and so on in <code>__init__.py</code>, is there a way to accomplish that without listing them all by hand?</p>
| 3
|
2009-04-20T22:10:08Z
| 770,359
|
<p>This question asked today, <a href="http://stackoverflow.com/questions/769534/dynamic-loading-of-python-modules">Dynamic Loading of Python Modules</a>, should have your answer.</p>
| 3
|
2009-04-20T22:28:51Z
|
[
"python",
"module",
"package"
] |
How do I structure Python code into modules/packages?
| 770,320
|
<p>Assume I have this barebones structure:</p>
<pre><code>project/
main.py
providers/
__init.py__
acme1.py
acme2.py
acme3.py
acme4.py
acme5.py
acme6.py
</code></pre>
<p>Assume that <code>main.py</code> contains (partial):</p>
<pre><code>if complexcondition():
print providers.acme5.get()
</code></pre>
<p>Where <code>__init__.py</code> is empty and <code>acme*.py</code> contain (partial):</p>
<pre><code>def get():
value=complexcalculation()
return value
</code></pre>
<p>How do I change these files to work?</p>
<p>Note: If the answer is "import acme1", "import acme2", and so on in <code>__init__.py</code>, is there a way to accomplish that without listing them all by hand?</p>
| 3
|
2009-04-20T22:10:08Z
| 770,787
|
<p>If I'm reading your question correctly, it looks like you're not trying to do any dynamic importing (like in the question that Van Gale mentioned) but are actually trying to just import all of the modules in the providers package. If that's the case, in <code>__init__.py</code> you would want to have this statement:</p>
<pre><code>__all__ = ["acme1", "acme2", "acme3", "acme4", "acme5", "acme6"]
</code></pre>
<p>Then to import everything you would use from ... import *</p>
<pre><code>from providers import *
</code></pre>
<p>And then instead of using the package name explicitly in the code, you would just call the imported classes</p>
<pre><code>acme1.get()
acme2.get()
</code></pre>
<p>If you have enough modules in the providers package that it becomes a problem populating the <code>__all__</code> list, you may want to look into breaking them up into smaller packages or storing the data some other way. I personally wouldn't want to have to deal with dynamic importing schennagins every time I wanted to re-use the package.</p>
| 5
|
2009-04-21T02:06:01Z
|
[
"python",
"module",
"package"
] |
How do I structure Python code into modules/packages?
| 770,320
|
<p>Assume I have this barebones structure:</p>
<pre><code>project/
main.py
providers/
__init.py__
acme1.py
acme2.py
acme3.py
acme4.py
acme5.py
acme6.py
</code></pre>
<p>Assume that <code>main.py</code> contains (partial):</p>
<pre><code>if complexcondition():
print providers.acme5.get()
</code></pre>
<p>Where <code>__init__.py</code> is empty and <code>acme*.py</code> contain (partial):</p>
<pre><code>def get():
value=complexcalculation()
return value
</code></pre>
<p>How do I change these files to work?</p>
<p>Note: If the answer is "import acme1", "import acme2", and so on in <code>__init__.py</code>, is there a way to accomplish that without listing them all by hand?</p>
| 3
|
2009-04-20T22:10:08Z
| 4,943,557
|
<p>hey! two years later but... maybe could be helpfull to some one</p>
<p>make your <strong>providers/__init__.py</strong> like that:</p>
<pre><code>import os
import glob
module_path = os.path.dirname(__file__)
files = glob.glob(os.path.join(module_path, 'acme*.py'))
__all__ = [os.path.basename(f)[:-3] for f in files]
</code></pre>
<p>you don't have to change it later if add or remove any <strong>providers/acme*.py</strong> </p>
<p>then use <code>from providers import *</code> in <strong>main.py</strong></p>
| 6
|
2011-02-09T10:25:23Z
|
[
"python",
"module",
"package"
] |
importing gaeutilities or any other module by dev_appserver
| 770,385
|
<p>I'm developing a gae application on a windows machine. to have session handling I downloaded gaeutilities and added its path (C:\Python25\Lib\site-packages\gaeutilities-1.2.1) to the registry ("PythonPath" item under python25).</p>
<p>in my code this is how I import the gaeutilities Session class:</p>
<p>from appengine_utilities.sessions import Session</p>
<p>when gae engine (dev_appserver.py) tries to import it, an exception is raised, stating an importerror and "no module named appengine_utilities.sessions"</p>
<p>on the other hand, pyscripter can find the module (autocomplete becomes available for the Session class), and I can import the module within the python interpreter (the same one that dev_appserver uses, python 2.5.4).</p>
<p>for a remedy, I created a PYTHONPATH environmental variable and also added the path to it. nothing changes. </p>
<p>I'm lost. what am I doing wrong?</p>
<p>important edit: I have found myself to be totally unable to import any 3rd party gae modules. PYTHONPATH is correct, sys.path is correct, registry is correct, still dev_appserver complains of importerror.</p>
| 0
|
2009-04-20T22:39:05Z
| 771,165
|
<p>Strange.</p>
<p>I would start troubleshooting by making 100% sure that the <code>sys.path</code> that <code>dev_appserver.py</code> uses does include <code>C:\Python25\Lib\site-packages\gaeutilities-1.2.1</code>.</p>
<p>I suggest you display <code>sys.path</code> in a HTML view served by <code>dev_appserver.py</code>.</p>
<p>Check permissions on gaeutilities-1.2.1 directory and subdirectories. Perhaps the python interpreter is unable to create <code>*.pyc</code> files or something like that.</p>
<p>Another suggestion:</p>
<p>Put the <code>appengines_utilities</code> folder in your application directory (the directory that contains your app.yaml file). I guess you need all third-party stuff there anyway if you want to upload the code to google's servers.</p>
| 1
|
2009-04-21T05:33:16Z
|
[
"python",
"google-app-engine",
"import"
] |
What is the best secure way to allow a user to delete a model instance that they added to the db?
| 770,427
|
<p>I would like to give users access to delete a model instance that they added to the db. In the django docs it says allowing someone to delete from the template is not a good practice. Is there a secure way to let a user click a "delete this" link from the template and remove that model instance? How should I go about doing that?</p>
| 0
|
2009-04-20T23:00:29Z
| 770,451
|
<p><a href="http://stackoverflow.com/questions/679013/get-vs-post-best-practices/679042">Check out this question</a> for discussion related to what you are asking about.</p>
<p>Essentially, when you normally click on a link on the page the browser makes a <code>GET</code> request to the server to get the next page's contents. Just like there is a lot of pushing towards semantically relevant CSS layouts, it is also important that your page requests are semantically relevant. The problem with using links to remove items is that it is making a <code>GET</code> request to <code>DELETE</code> something in the database. From this comes the problem that some search engines might index your links and accidentally erase content. There also comes the problem of <a href="http://en.wikipedia.org/wiki/Cross-site%5Frequest%5Fforgery" rel="nofollow">cross-site request forgeries</a> which can make an unsuspecting user make a command to a website without being aware. So the proper way to handle this is by following the rule that <strong>any request that modifies state in the server should be processed via POST</strong>. As such, instead of doing this:</p>
<pre><code><a href="{% url remove_item item.id %}">Delete Item</a>
</code></pre>
<p>It is better to do this:</p>
<pre><code><form action='{% url remove_item %}' method='POST' id='form'>
<input type='hidden' name='action' value='delete'>
<input type='hidden' name='id' value='{{ item.id }}'>
<input type="submit" value="Delete Item">
</form>
</code></pre>
<p>If you would like to keep your links while maintaining the <code>POST</code>, you'd have to resort to Javascript:</p>
<pre><code><a href="#" onclick="document.getElementById('form').submit(); return false;">Delete Item</a>
</code></pre>
<p>Unsightly, yes, but it's for the best. Your Django view would then do something like this:</p>
<pre><code>def remove_item(request):
if request.method == 'POST':
## remove item
</code></pre>
<p>Furthermore, as Scott mentions, Django has some built in stuff to help you avoid the cross-site request forgeries I mentioned above, since it is still possible to do it even if you are doing a POST (just slightly harder). The way to avoid this is to have some kind of token tied to the form that needs to be validated server side before allowing the action to be taken. Check out the <a href="http://docs.djangoproject.com/en/1.0/ref/contrib/csrf/#module-django.contrib.csrf" rel="nofollow">CsrfMiddleware</a> class for more details on that. It will essentially automate some of that work out of it for you.</p>
<h2>Additional Reading</h2>
<ul>
<li><a href="http://www.w3.org/2001/tag/doc/whenToUseGet.html" rel="nofollow">URIs, Addressability, and the use of HTTP GET and POST</a></li>
<li><a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html" rel="nofollow">9.1.1 Safe Methods, HTTP 1.1, RFC 2616</a></li>
<li><a href="http://www.w3.org/TR/webarch/" rel="nofollow">Architecture of the World Wide Web, Volume One</a></li>
<li><a href="http://www.thefutureoftheweb.com/blog/using-post-method-with-a-regular-link" rel="nofollow">Using POST with a regular link</a></li>
<li><a href="http://www.codinghorror.com/blog/archives/001171.html" rel="nofollow">Cross-Site Request Forgeries and You</a></li>
</ul>
| 7
|
2009-04-20T23:13:38Z
|
[
"python",
"django"
] |
What is the best secure way to allow a user to delete a model instance that they added to the db?
| 770,427
|
<p>I would like to give users access to delete a model instance that they added to the db. In the django docs it says allowing someone to delete from the template is not a good practice. Is there a secure way to let a user click a "delete this" link from the template and remove that model instance? How should I go about doing that?</p>
| 0
|
2009-04-20T23:00:29Z
| 771,066
|
<p>Have the user submit a POST request to delete that model instance. These kinds of changes should never be possible via GET requests, so that people can't link each other to unwittingly performing changes on the site.</p>
<p>In your view, check that request.user is the same as the author of that particular model instance. You could also check that the HTTP_REFERRER is not set to another site if you were really worried.</p>
<p>Your security issue here is Cross Site Request Forgery. Django provides CsrfMiddleware which will actually add security to your forms to prevent this kind of attack. But it only works as long as you're not allowing permanent changes to take place via GET requests.</p>
| 0
|
2009-04-21T04:42:18Z
|
[
"python",
"django"
] |
Python - Overridding print()
| 770,657
|
<p>I'm using mod_wsgi and was wondering if it's possible to over-write the print() command (since it's useless).</p>
<p>Doing this doesn't work:</p>
<pre><code>print = myPrintFunction
</code></pre>
<p>Since it's a syntax error. :(</p>
| 4
|
2009-04-21T00:53:23Z
| 770,664
|
<p>Would</p>
<pre><code>import sys
sys.stdout = MyFileWrapper()
</code></pre>
<p>or something similar work?</p>
| 5
|
2009-04-21T00:56:06Z
|
[
"python",
"python-3.x",
"mod-wsgi",
"wsgi"
] |
Python - Overridding print()
| 770,657
|
<p>I'm using mod_wsgi and was wondering if it's possible to over-write the print() command (since it's useless).</p>
<p>Doing this doesn't work:</p>
<pre><code>print = myPrintFunction
</code></pre>
<p>Since it's a syntax error. :(</p>
| 4
|
2009-04-21T00:53:23Z
| 770,665
|
<p>Print is not a function in Python 2.x, so this is not directly possible.</p>
<p>You can, however, <a href="http://code.activestate.com/recipes/119404/" rel="nofollow">override sys.stdout</a>.</p>
<p>If you are on Python 3.0 in which <a href="http://docs.python.org/3.0/whatsnew/3.0.html#print-is-a-function" rel="nofollow">print is now a function</a> what you have would then work, assuming you have the right signature. Also see <a href="http://stackoverflow.com/questions/550470/overload-print-python">a related question</a> in this site.</p>
| 13
|
2009-04-21T00:56:16Z
|
[
"python",
"python-3.x",
"mod-wsgi",
"wsgi"
] |
Python - Overridding print()
| 770,657
|
<p>I'm using mod_wsgi and was wondering if it's possible to over-write the print() command (since it's useless).</p>
<p>Doing this doesn't work:</p>
<pre><code>print = myPrintFunction
</code></pre>
<p>Since it's a syntax error. :(</p>
| 4
|
2009-04-21T00:53:23Z
| 773,242
|
<p>If you are using 3.0, print is a function. If you are using 2.6, you can <code>from __future__ import print_function</code> and continue with a print function.</p>
<p>If <= 2.5, you can replace stdout like others have suggested, but be very careful if your wsgi server will call your app in multiple threads simultaneously. You <strong>WILL</strong> end up with simultaneous requests being sent down the same pipe.</p>
<p>I haven't tested it, but you could try something like this:</p>
<pre><code>import sys
import threading
class ThreadedStdout(object):
def __init__(self):
self.local = threading.local()
def register(self, fh):
self.local.fh = fh
def write(self, stuff):
self.local.fh.write(stuff)
sys.stdout = ThreadedStdout()
def app(environ, start):
sys.stdout.register(environ['wsgi.stdout'])
# Whatever.
</code></pre>
| 1
|
2009-04-21T15:40:05Z
|
[
"python",
"python-3.x",
"mod-wsgi",
"wsgi"
] |
Python - Overridding print()
| 770,657
|
<p>I'm using mod_wsgi and was wondering if it's possible to over-write the print() command (since it's useless).</p>
<p>Doing this doesn't work:</p>
<pre><code>print = myPrintFunction
</code></pre>
<p>Since it's a syntax error. :(</p>
| 4
|
2009-04-21T00:53:23Z
| 1,037,841
|
<p>It is worth noting that use of 'print' to sys.stdout in Apache/mod_wsgi was deliberately restricted. This is because a portable WSGI application should not use either sys.stdin or sys.stdout as some WSGI implementations use them to communicate to the server.</p>
<p>Apache/mod_wsgi is therefore trying to force you to write your WSGI application such that it will be portable to other WSGI implementations.</p>
<p>Unfortunately, too many people seem not to care about writing good code and so mod_wsgi 3.0 will allow you to write to sys.stdout and thus use 'print' without redirecting output to 'sys.stderr' as you should be doing.</p>
<p>Either way, the mod_wsgi documentation details how to remove the restriction in versions of mod_wsgi prior to 3.0. In particular, see documentation about the WSGIRestrictStdout directive. The documentation about debugging techniques also talks about the issue and about mapping sys.stdout to sys.stderr.</p>
<p>You can read a commentary which summaries this issue at:</p>
<p><a href="http://blog.dscpl.com.au/2009/04/wsgi-and-printing-to-standard-output.html" rel="nofollow">http://blog.dscpl.com.au/2009/04/wsgi-and-printing-to-standard-output.html</a></p>
| 1
|
2009-06-24T11:43:58Z
|
[
"python",
"python-3.x",
"mod-wsgi",
"wsgi"
] |
Python - Overridding print()
| 770,657
|
<p>I'm using mod_wsgi and was wondering if it's possible to over-write the print() command (since it's useless).</p>
<p>Doing this doesn't work:</p>
<pre><code>print = myPrintFunction
</code></pre>
<p>Since it's a syntax error. :(</p>
| 4
|
2009-04-21T00:53:23Z
| 1,818,572
|
<p>While you can redirect stdout to different sources like file for logging, as Paolo mentions, you probably wouldn't need it. I didn't need it. If you really needed to log stuff, you would be using logging itself in the first place, wouldn't you? Also, even when <strong>you</strong> don't print a thing, the third party libraries you use may do. Just redirect it and get going.</p>
<p>The simplest solution to this problem is to redirect all stdout into stderr. In the wsgi configuration file, just redirect as necessary.</p>
<pre><code>sys.stdout = sys.stderr
</code></pre>
| 0
|
2009-11-30T08:49:04Z
|
[
"python",
"python-3.x",
"mod-wsgi",
"wsgi"
] |
What does python3 do with the methods passed to the "key" argument of sorted()?
| 770,845
|
<p>I have a question about how python treats the methods passed to sorted(). Consider the following small script:</p>
<pre><code>#!/usr/bin/env python3
import random
class SortClass:
def __init__(self):
self.x = random.choice(range(10))
self.y = random.choice(range(10))
def getX(self):
return self.x
def getY(self):
return self.y
if __name__ == "__main__":
sortList = [SortClass() for i in range(10)]
sortedList = sorted(sortList, key = SortClass.getX)
for object in sortedList:
print("X:", object.getX(),"Y:",object.getY())
</code></pre>
<p>Which gives output similar to the following:</p>
<pre><code>X: 1 Y: 5
X: 1 Y: 6
X: 1 Y: 5
X: 2 Y: 8
X: 2 Y: 1
X: 3 Y: 6
X: 4 Y: 2
X: 5 Y: 4
X: 6 Y: 2
X: 8 Y: 0
</code></pre>
<p>This script sorts the SortClass objects according to the value of each instance's x field. Notice, however, that the "key" argument of sorted points to SortClass.getX, not to any particular instance of SortClass. I'm a bit confused as to how python actually uses the method passed as "key". Does calling getX() like this work because the objects passed to it are of the same type as the "self" argument? Is this a safe use of the "key" argument?</p>
| 4
|
2009-04-21T02:37:47Z
| 770,875
|
<p>Methods on classes are just functions.</p>
<pre><code>class MyClass(object):
... def my_method(self): pass
...
>>> MyClass.my_method
<function my_method at 0x661c38>
</code></pre>
<p>When you fetch a method from an instance of a class, Python uses some magic (called descriptors) to return a bound method. Bound methods automatically insert the instance as the first argument when they are called.</p>
<pre><code>>>> MyClass().my_method
<bound method MyClass.my_method of <__main__.myClass object at 0x6e2498>>
</code></pre>
<p>However, as you have noticed, you can also directly call the function with an instance as the first argument: <code>MyClass.my_method(MyClass())</code></p>
<p>That's what happening with <code>sorted()</code>. Python calls the function SortedClass.getx with the item in the list which happens to be an instance of SortedClass.</p>
<p>(By the way, there are better ways to do what you are doing. First of all, don't use methods to expose attributes like <code>getX</code>. Use properties or plain attributes. Also, look at <code>operator.itemgetter</code> and <code>operator.methodcaller</code>.)</p>
| 8
|
2009-04-21T02:55:17Z
|
[
"python",
"python-3.x",
"sorted"
] |
What does python3 do with the methods passed to the "key" argument of sorted()?
| 770,845
|
<p>I have a question about how python treats the methods passed to sorted(). Consider the following small script:</p>
<pre><code>#!/usr/bin/env python3
import random
class SortClass:
def __init__(self):
self.x = random.choice(range(10))
self.y = random.choice(range(10))
def getX(self):
return self.x
def getY(self):
return self.y
if __name__ == "__main__":
sortList = [SortClass() for i in range(10)]
sortedList = sorted(sortList, key = SortClass.getX)
for object in sortedList:
print("X:", object.getX(),"Y:",object.getY())
</code></pre>
<p>Which gives output similar to the following:</p>
<pre><code>X: 1 Y: 5
X: 1 Y: 6
X: 1 Y: 5
X: 2 Y: 8
X: 2 Y: 1
X: 3 Y: 6
X: 4 Y: 2
X: 5 Y: 4
X: 6 Y: 2
X: 8 Y: 0
</code></pre>
<p>This script sorts the SortClass objects according to the value of each instance's x field. Notice, however, that the "key" argument of sorted points to SortClass.getX, not to any particular instance of SortClass. I'm a bit confused as to how python actually uses the method passed as "key". Does calling getX() like this work because the objects passed to it are of the same type as the "self" argument? Is this a safe use of the "key" argument?</p>
| 4
|
2009-04-21T02:37:47Z
| 7,810,979
|
<p>+1 for Benjamin's answer.</p>
<p>Also, read the Sorting HowTo if you want to master sorting in Python: <a href="http://docs.python.org/howto/sorting.html" rel="nofollow">http://docs.python.org/howto/sorting.html</a></p>
| 0
|
2011-10-18T17:02:04Z
|
[
"python",
"python-3.x",
"sorted"
] |
Django Custom Template Tags In Google App Engine
| 770,854
|
<p>I am trying to include the following Tag In Google App Engine Web Application:</p>
<p><a href="http://www.djangosnippets.org/snippets/1357/">http://www.djangosnippets.org/snippets/1357/</a></p>
<p>Is there any configuration of this file to make it work with Google App Engine?</p>
<p>Cause I followed the Django Template tutorials: <a href="http://docs.djangoproject.com/en/dev/howto/custom-template-tags/">http://docs.djangoproject.com/en/dev/howto/custom-template-tags/</a></p>
<p>and have this structure:</p>
<pre><code>templatetags/
__init__.py
range_template.py
</code></pre>
<p>in the Template file, I have {%load range_template%}</p>
<p>But I am getting the error:</p>
<p>TemplateSyntaxError: 'range_template' is not a valid tag library: Could not load template library from django.templatetags.range_template, No module named range_template</p>
<p>The other thing that might be a problem why this ain't working is, the INSTALL_APPS settings.py file. Not sure how to configure it.</p>
<p>I have a settings.py file in the root of my application and included this:</p>
<p>INSTALLED_APPS = ('templatetags')</p>
<p>Any advice would be greatly appreciated.</p>
| 10
|
2009-04-21T02:39:47Z
| 770,898
|
<p>try doing the following:</p>
<pre><code>$ python ./manage.py startapp foo
</code></pre>
<p>Add foo to installed apps:</p>
<pre><code>INSTALLED_APPS += ('foo',)
</code></pre>
<p>And move your templatetags directory into your foo app. Something like:</p>
<pre><code>./djangoproject
__init__.py
settings.py
urls.py
etc..
foo/
__init__.py
templatetags/
__init__.py
range_template.py
</code></pre>
<p>Django convention is that template tag code resides in apps, in directories named templatetags (<a href="http://docs.djangoproject.com/en/dev/howto/custom-template-tags/" rel="nofollow">see docs</a>). I assume the same would be true for GAE.</p>
| 4
|
2009-04-21T03:09:52Z
|
[
"python",
"django",
"google-app-engine"
] |
Django Custom Template Tags In Google App Engine
| 770,854
|
<p>I am trying to include the following Tag In Google App Engine Web Application:</p>
<p><a href="http://www.djangosnippets.org/snippets/1357/">http://www.djangosnippets.org/snippets/1357/</a></p>
<p>Is there any configuration of this file to make it work with Google App Engine?</p>
<p>Cause I followed the Django Template tutorials: <a href="http://docs.djangoproject.com/en/dev/howto/custom-template-tags/">http://docs.djangoproject.com/en/dev/howto/custom-template-tags/</a></p>
<p>and have this structure:</p>
<pre><code>templatetags/
__init__.py
range_template.py
</code></pre>
<p>in the Template file, I have {%load range_template%}</p>
<p>But I am getting the error:</p>
<p>TemplateSyntaxError: 'range_template' is not a valid tag library: Could not load template library from django.templatetags.range_template, No module named range_template</p>
<p>The other thing that might be a problem why this ain't working is, the INSTALL_APPS settings.py file. Not sure how to configure it.</p>
<p>I have a settings.py file in the root of my application and included this:</p>
<p>INSTALLED_APPS = ('templatetags')</p>
<p>Any advice would be greatly appreciated.</p>
| 10
|
2009-04-21T02:39:47Z
| 1,812,439
|
<p>In case someone searches for this, I wrote a small article in 2008 about this: <a href="http://daily.profeth.de/2008/04/using-custom-django-template-helpers.html" rel="nofollow">http://daily.profeth.de/2008/04/using-custom-django-template-helpers.html</a></p>
| 4
|
2009-11-28T12:36:51Z
|
[
"python",
"django",
"google-app-engine"
] |
Django Custom Template Tags In Google App Engine
| 770,854
|
<p>I am trying to include the following Tag In Google App Engine Web Application:</p>
<p><a href="http://www.djangosnippets.org/snippets/1357/">http://www.djangosnippets.org/snippets/1357/</a></p>
<p>Is there any configuration of this file to make it work with Google App Engine?</p>
<p>Cause I followed the Django Template tutorials: <a href="http://docs.djangoproject.com/en/dev/howto/custom-template-tags/">http://docs.djangoproject.com/en/dev/howto/custom-template-tags/</a></p>
<p>and have this structure:</p>
<pre><code>templatetags/
__init__.py
range_template.py
</code></pre>
<p>in the Template file, I have {%load range_template%}</p>
<p>But I am getting the error:</p>
<p>TemplateSyntaxError: 'range_template' is not a valid tag library: Could not load template library from django.templatetags.range_template, No module named range_template</p>
<p>The other thing that might be a problem why this ain't working is, the INSTALL_APPS settings.py file. Not sure how to configure it.</p>
<p>I have a settings.py file in the root of my application and included this:</p>
<p>INSTALLED_APPS = ('templatetags')</p>
<p>Any advice would be greatly appreciated.</p>
| 10
|
2009-04-21T02:39:47Z
| 3,168,700
|
<p>Please make sure to restart the development server after following the above step</p>
| 1
|
2010-07-02T19:46:58Z
|
[
"python",
"django",
"google-app-engine"
] |
Installing Django on Shared Server: No module named MySQLdb?
| 770,904
|
<p>I'm getting this error</p>
<pre><code>Traceback (most recent call last):
File "/home/<username>/flup/server/fcgi_base.py", line 558, in run
File "/home/<username>/flup/server/fcgi_base.py", line 1116, in handler
File "/home/<username>/python/django/django/core/handlers/wsgi.py", line 241, in __call__
response = self.get_response(request)
File "/home/<username>/python/django/django/core/handlers/base.py", line 73, in get_response
response = middleware_method(request)
File "/home/<username>/python/django/django/contrib/sessions/middleware.py", line 10, in process_request
engine = import_module(settings.SESSION_ENGINE)
File "/home/<username>/python/django/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/home/<username>/python/django/django/contrib/sessions/backends/db.py", line 2, in ?
from django.contrib.sessions.models import Session
File "/home/<username>/python/django/django/contrib/sessions/models.py", line 4, in ?
from django.db import models
File "/home/<username>/python/django/django/db/__init__.py", line 41, in ?
backend = load_backend(settings.DATABASE_ENGINE)
File "/home/<username>/python/django/django/db/__init__.py", line 17, in load_backend
return import_module('.base', 'django.db.backends.%s' % backend_name)
File "/home/<username>/python/django/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/home/<username>/python/django/django/db/backends/mysql/base.py", line 13, in ?
raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb
</code></pre>
<p>when I try to run this script on my shared server</p>
<pre><code>#!/usr/bin/python
import sys, os
sys.path.insert(0, "/home/<username>/python/django")
sys.path.insert(0, "/home/<username>/python/django/www") # projects directory
os.chdir("/home/<username>/python/django/www/<project>")
os.environ['DJANGO_SETTINGS_MODULE'] = "<project>.settings"
from django.core.servers.fastcgi import runfastcgi
runfastcgi(method="threaded", daemonize="false")
</code></pre>
<p>But, my web host just installed <code>MySQLdb</code> for me a few hours ago. When I run python from the shell I can import <code>MySQLdb</code> just fine. Why would this script report that it can't find it?</p>
| 1
|
2009-04-21T03:13:44Z
| 770,936
|
<p>Is it possible that you have the wrong DATABASE_ENGINE setting in your settings.py? It should be mysql and not mysqldb there.</p>
| 1
|
2009-04-21T03:28:56Z
|
[
"python",
"django",
"mysql"
] |
Installing Django on Shared Server: No module named MySQLdb?
| 770,904
|
<p>I'm getting this error</p>
<pre><code>Traceback (most recent call last):
File "/home/<username>/flup/server/fcgi_base.py", line 558, in run
File "/home/<username>/flup/server/fcgi_base.py", line 1116, in handler
File "/home/<username>/python/django/django/core/handlers/wsgi.py", line 241, in __call__
response = self.get_response(request)
File "/home/<username>/python/django/django/core/handlers/base.py", line 73, in get_response
response = middleware_method(request)
File "/home/<username>/python/django/django/contrib/sessions/middleware.py", line 10, in process_request
engine = import_module(settings.SESSION_ENGINE)
File "/home/<username>/python/django/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/home/<username>/python/django/django/contrib/sessions/backends/db.py", line 2, in ?
from django.contrib.sessions.models import Session
File "/home/<username>/python/django/django/contrib/sessions/models.py", line 4, in ?
from django.db import models
File "/home/<username>/python/django/django/db/__init__.py", line 41, in ?
backend = load_backend(settings.DATABASE_ENGINE)
File "/home/<username>/python/django/django/db/__init__.py", line 17, in load_backend
return import_module('.base', 'django.db.backends.%s' % backend_name)
File "/home/<username>/python/django/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/home/<username>/python/django/django/db/backends/mysql/base.py", line 13, in ?
raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb
</code></pre>
<p>when I try to run this script on my shared server</p>
<pre><code>#!/usr/bin/python
import sys, os
sys.path.insert(0, "/home/<username>/python/django")
sys.path.insert(0, "/home/<username>/python/django/www") # projects directory
os.chdir("/home/<username>/python/django/www/<project>")
os.environ['DJANGO_SETTINGS_MODULE'] = "<project>.settings"
from django.core.servers.fastcgi import runfastcgi
runfastcgi(method="threaded", daemonize="false")
</code></pre>
<p>But, my web host just installed <code>MySQLdb</code> for me a few hours ago. When I run python from the shell I can import <code>MySQLdb</code> just fine. Why would this script report that it can't find it?</p>
| 1
|
2009-04-21T03:13:44Z
| 771,002
|
<p>You are missing the python-mysql db driver on your python path.
see if you can figure out the pythonpath WSGI is seeing... which can be different from what you are experiencing in shell</p>
| 2
|
2009-04-21T04:05:10Z
|
[
"python",
"django",
"mysql"
] |
Python $OUTPUT_RECORD_SEPARATOR and $INPUT_RECORD_SEPARATOR equivalent
| 770,925
|
<p>Does Python have an equivalent to the $OUTPUT_RECORD_SEPARATOR or $\ in Perl?</p>
<p><strong>UPDATE:</strong>
I totally had this wrong... I was looking for a Python equivalent to a $INPUT_RECORD_SEPARATOR if there is such a thing?
Something that you can override so that when you do a readline() type call its looking for something other than the newline char. Sorry about botching the original question.</p>
| 0
|
2009-04-21T03:23:33Z
| 771,086
|
<p>You could use the ''.join method. e.g.</p>
<pre><code># print 'foo', 'bar', 'baz' separated by spaces
print 'foo', 'bar', 'baz'
# print separated by commas
print ', '.join(['foo', 'bar', 'baz'])
</code></pre>
<p>EDIT:</p>
<p>Ok, I misunderstood the purpose of <code>OUTPUT_RECORD_SEPARATOR</code>, so ''.join is not what you want.</p>
<p><code>print 'foo'</code> is equivalent to <code>sys.stdout.write('foo'+'\n')</code>, so you could roll your own print function:</p>
<pre><code>def myprint(*args, end='\n'):
sys.stdout.write(' '.join(args) + end)
</code></pre>
<p>Or go one step further with a factory function:</p>
<pre><code>def make_printer(end):
def myprint(*args, end='\n'):
sys.stdout.write(' '.join(args) + end)
return myprint
# usage:
p = make_printer('#')
p('foo', 'bar', 'baz')
</code></pre>
<p>Finally, if you're daring, you could override sys.stdout:</p>
<pre><code>sys.old_stdout = sys.stdout
class MyWrite(object):
def __init__(self, end='\n'):
self.end = end
def write(self, s):
sys.old_stdout.write(s.replace('\n', self.end))
</code></pre>
<p>This will cause <code>print</code> statements to produce the alternative line ending. Usage:</p>
<pre><code>sys.stdout = MyWrite('!\n')
print 'foo'
# prints: foo!
</code></pre>
<p>Note that you may need to override more than just write() â or at least provide redirects for things like MyWrite.flush() to sys.old_stdout.flush().</p>
| 1
|
2009-04-21T04:53:20Z
|
[
"python",
"file-io"
] |
Python $OUTPUT_RECORD_SEPARATOR and $INPUT_RECORD_SEPARATOR equivalent
| 770,925
|
<p>Does Python have an equivalent to the $OUTPUT_RECORD_SEPARATOR or $\ in Perl?</p>
<p><strong>UPDATE:</strong>
I totally had this wrong... I was looking for a Python equivalent to a $INPUT_RECORD_SEPARATOR if there is such a thing?
Something that you can override so that when you do a readline() type call its looking for something other than the newline char. Sorry about botching the original question.</p>
| 0
|
2009-04-21T03:23:33Z
| 771,101
|
<p>Python 3's print function has <code>sep</code> and <code>end</code> arguments.</p>
<pre><code>print('foo', 'bar', 'baz', sep='|', end='#')
</code></pre>
<p>Note that in Python 3, <code>print</code> is no longer a statement, it is a function.</p>
| 1
|
2009-04-21T04:58:48Z
|
[
"python",
"file-io"
] |
Python $OUTPUT_RECORD_SEPARATOR and $INPUT_RECORD_SEPARATOR equivalent
| 770,925
|
<p>Does Python have an equivalent to the $OUTPUT_RECORD_SEPARATOR or $\ in Perl?</p>
<p><strong>UPDATE:</strong>
I totally had this wrong... I was looking for a Python equivalent to a $INPUT_RECORD_SEPARATOR if there is such a thing?
Something that you can override so that when you do a readline() type call its looking for something other than the newline char. Sorry about botching the original question.</p>
| 0
|
2009-04-21T03:23:33Z
| 771,585
|
<p>In Python pre-3, you can suppress standard separator appending ',' at end of line:</p>
<pre><code>print yourVar, #these 3 lines print without any newline separator
print yourVar,
print yourVar,
</code></pre>
<p>if you want to use non-standard separator, suppress normal one and print yours:</p>
<pre><code>print yourVar, yourSep,
print yourVar, yourSep,
print yourVar, yourSep,
</code></pre>
| 0
|
2009-04-21T08:20:06Z
|
[
"python",
"file-io"
] |
Python $OUTPUT_RECORD_SEPARATOR and $INPUT_RECORD_SEPARATOR equivalent
| 770,925
|
<p>Does Python have an equivalent to the $OUTPUT_RECORD_SEPARATOR or $\ in Perl?</p>
<p><strong>UPDATE:</strong>
I totally had this wrong... I was looking for a Python equivalent to a $INPUT_RECORD_SEPARATOR if there is such a thing?
Something that you can override so that when you do a readline() type call its looking for something other than the newline char. Sorry about botching the original question.</p>
| 0
|
2009-04-21T03:23:33Z
| 804,825
|
<p>If what you want is to have any of <code>\r</code>, <code>\n</code>, or <code>\r\n</code> in the input to be seen as a newline, then you can use âuniversal newline supportâ in your âopen()â call.</p>
<p>In <a href="http://docs.python.org/2.6/library/functions.html#open" rel="nofollow">Python 2.6 open()</a>, this needs to be explicitly enabled by adding âUâ to the mode string:</p>
<pre><code>in_file = open('foo.txt', 'rU')
</code></pre>
<p>It also depends on this support being available in the Python interpreter; but the docs say this is available by default.</p>
<p>In <a href="http://docs.python.org/3.0/library/functions.html#open" rel="nofollow">Python 3.0 open()</a>, universal newline behaviour is always available, and is the default behaviour; you can choose a different behaviour with different values for the <code>newline</code> parameter.</p>
<p>If you want input to interpret records terminated by something other than a newline, then you don't want âreadlinesâ (which, per the name, reads lines specifically, not records generally) and AFAIK will have to implement your own record-reading code.</p>
| 1
|
2009-04-29T23:53:13Z
|
[
"python",
"file-io"
] |
Python $OUTPUT_RECORD_SEPARATOR and $INPUT_RECORD_SEPARATOR equivalent
| 770,925
|
<p>Does Python have an equivalent to the $OUTPUT_RECORD_SEPARATOR or $\ in Perl?</p>
<p><strong>UPDATE:</strong>
I totally had this wrong... I was looking for a Python equivalent to a $INPUT_RECORD_SEPARATOR if there is such a thing?
Something that you can override so that when you do a readline() type call its looking for something other than the newline char. Sorry about botching the original question.</p>
| 0
|
2009-04-21T03:23:33Z
| 816,648
|
<pre><code>open('file').read().split(your_separator_of_choice)
</code></pre>
<p>the only difference with <code>readlines()</code> here is that resulting list items won't have separator preserved at the end.</p>
| 0
|
2009-05-03T09:13:07Z
|
[
"python",
"file-io"
] |
(Python) socket.gaierror: [Errno 11001] getaddrinfo failed
| 771,247
|
<p>I'm not sure whats wrong with this code I keep getting that socket.gaierror error ;\ .</p>
<pre><code>import sys
import socket
import random
filename = "whoiservers.txt"
server_name = random.choice(list(open(filename)))
print "connecting to %s..." % server_name
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((server_name, 43))
s.send(sys.argv[1] + "\r\n")
response = ''
while True:
d = s.recv(4096)
response += d
if d == '':
break
s.close()
print
print response
s.connect((server_name, 43))
File "<string>", line 1, in connect
socket.gaierror: [Errno 11001] getaddrinfo failed
</code></pre>
<h3>Update:</h3>
<p>After adding <code>server_name = random.choice(list(open(filename)))[:-1]</code> I dont get that socket.gaierror anymore but I get:</p>
<blockquote>
<p>socket.error: [Errno 10060] A connection attempt failed because the connected pa
rty did not properly respond after a period of time, or established connection f
ailed because connected host has failed to respond</p>
</blockquote>
| 3
|
2009-04-21T06:18:24Z
| 771,311
|
<p>I think the problem is a newline at the end of <code>server_name</code>.</p>
<p>If the format of your file <code>whoiservers.txt</code> is one hostname on each line then you need to strip the newline at the end of the hostname before passing it to <code>s.connect()</code></p>
<p>So, for example, change the open line to:</p>
<pre><code>server_name = random.choice(list(open(filename)))[:-1]
</code></pre>
| 5
|
2009-04-21T06:41:13Z
|
[
"python",
"sockets"
] |
(Python) socket.gaierror: [Errno 11001] getaddrinfo failed
| 771,247
|
<p>I'm not sure whats wrong with this code I keep getting that socket.gaierror error ;\ .</p>
<pre><code>import sys
import socket
import random
filename = "whoiservers.txt"
server_name = random.choice(list(open(filename)))
print "connecting to %s..." % server_name
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((server_name, 43))
s.send(sys.argv[1] + "\r\n")
response = ''
while True:
d = s.recv(4096)
response += d
if d == '':
break
s.close()
print
print response
s.connect((server_name, 43))
File "<string>", line 1, in connect
socket.gaierror: [Errno 11001] getaddrinfo failed
</code></pre>
<h3>Update:</h3>
<p>After adding <code>server_name = random.choice(list(open(filename)))[:-1]</code> I dont get that socket.gaierror anymore but I get:</p>
<blockquote>
<p>socket.error: [Errno 10060] A connection attempt failed because the connected pa
rty did not properly respond after a period of time, or established connection f
ailed because connected host has failed to respond</p>
</blockquote>
| 3
|
2009-04-21T06:18:24Z
| 774,040
|
<p>Perhaps you have a firewall in between you and these servers that is blocking the request? The last error you posted leads one to believe that it cannot connect to the server at all...</p>
| 0
|
2009-04-21T18:49:49Z
|
[
"python",
"sockets"
] |
GStrings in Python
| 771,312
|
<p>Groovy has a concept of GStrings. I can write code like this:</p>
<pre><code>def greeting = 'Hello World'
println """This is my first program ${greeting}"""
</code></pre>
<p>I can access the value of a variable from within the String. </p>
<p>How can I do this in Python?</p>
<p>--
Thanks</p>
| 2
|
2009-04-21T06:41:27Z
| 771,323
|
<pre><code>d = {'greeting': 'Hello World'}
print "This is my first program %(greeting)s" % d
</code></pre>
| 3
|
2009-04-21T06:45:23Z
|
[
"python",
"gstring"
] |
GStrings in Python
| 771,312
|
<p>Groovy has a concept of GStrings. I can write code like this:</p>
<pre><code>def greeting = 'Hello World'
println """This is my first program ${greeting}"""
</code></pre>
<p>I can access the value of a variable from within the String. </p>
<p>How can I do this in Python?</p>
<p>--
Thanks</p>
| 2
|
2009-04-21T06:41:27Z
| 771,326
|
<p>You can't exactly...</p>
<p>I think the closest you can really get is using standard %-based substitution, e.g:</p>
<pre><code>greeting = "Hello World"
print "This is my first program %s" % greeting
</code></pre>
<p>Having said that, there are some fancy new classes as of Python 2.6 which can do this in different ways: check out <a href="http://docs.python.org/library/string.html" rel="nofollow">the string documentation for 2.6</a>, specifically from section 8.1.2 onwards to find out more.</p>
| 1
|
2009-04-21T06:47:02Z
|
[
"python",
"gstring"
] |
GStrings in Python
| 771,312
|
<p>Groovy has a concept of GStrings. I can write code like this:</p>
<pre><code>def greeting = 'Hello World'
println """This is my first program ${greeting}"""
</code></pre>
<p>I can access the value of a variable from within the String. </p>
<p>How can I do this in Python?</p>
<p>--
Thanks</p>
| 2
|
2009-04-21T06:41:27Z
| 771,343
|
<p>If your trying to do templating you might want to look into Cheetah. It lets you do exactly what your talking about, same syntax and all.</p>
<p><a href="http://www.cheetahtemplate.org/" rel="nofollow">http://www.cheetahtemplate.org/</a></p>
| 1
|
2009-04-21T06:51:06Z
|
[
"python",
"gstring"
] |
GStrings in Python
| 771,312
|
<p>Groovy has a concept of GStrings. I can write code like this:</p>
<pre><code>def greeting = 'Hello World'
println """This is my first program ${greeting}"""
</code></pre>
<p>I can access the value of a variable from within the String. </p>
<p>How can I do this in Python?</p>
<p>--
Thanks</p>
| 2
|
2009-04-21T06:41:27Z
| 771,344
|
<p>In Python 2.6+ you can do:</p>
<pre><code>"My name is {0}".format('Fred')
</code></pre>
<p>Check out <a href="http://www.python.org/dev/peps/pep-3101/" rel="nofollow">PEP 3101</a>.</p>
| 1
|
2009-04-21T06:51:11Z
|
[
"python",
"gstring"
] |
GStrings in Python
| 771,312
|
<p>Groovy has a concept of GStrings. I can write code like this:</p>
<pre><code>def greeting = 'Hello World'
println """This is my first program ${greeting}"""
</code></pre>
<p>I can access the value of a variable from within the String. </p>
<p>How can I do this in Python?</p>
<p>--
Thanks</p>
| 2
|
2009-04-21T06:41:27Z
| 771,371
|
<p>In Python, you have to explicitely pass a dictionary of possible variables, you cannot access arbitrary "outside" variables from within a string. But, you can use the <code>locals()</code> function that returns a dictionary with all variables of the local scope.</p>
<p>For the actual replacement, there are many ways to do it (how unpythonic!):</p>
<pre><code>greeting = "Hello World"
# Use this in versions prior to 2.6:
print("My first programm; %(greeting)s" % locals())
# Since Python 2.6, the recommended example is:
print("My first program; {greeting}".format(**locals()))
# Works in 2.x and 3.x:
from string import Template
print(Template("My first programm; $greeting").substitute(locals()))
</code></pre>
| 5
|
2009-04-21T07:00:49Z
|
[
"python",
"gstring"
] |
Python + PHP + Lighttpd?
| 771,341
|
<p>I've set up a few web servers in my day, but I'm not sure how they work internally. I'm setting up a new environment for myself and I'm interested in configuring my lighttpd server to support both PHP and Python. Is this possible?</p>
| 3
|
2009-04-21T06:49:38Z
| 771,356
|
<p>Yes, this is possible. <a href="http://sam.bluwiki.com/blog/2008/04/django-python-phpoptional-lighttpd-on.php" rel="nofollow">Here</a> you can find a sample configuration.</p>
<pre><code>fastcgi.server = (
".php" => ((
"bin-path" => "/usr/bin/php5-cgi",
"socket" => "/tmp/php.socket"
)),
"django.fcgi" => (
"main" => (
"host" => "127.0.0.1",
"port" => 9090, #set the port numbers to what-eva you want
),
),
"admin.fcgi" => (
"admin" => (
"host" => "127.0.0.1",
"port" => 9091,
)
)
)
</code></pre>
| 3
|
2009-04-21T06:55:45Z
|
[
"php",
"python",
"lighttpd",
"configure"
] |
Python + PHP + Lighttpd?
| 771,341
|
<p>I've set up a few web servers in my day, but I'm not sure how they work internally. I'm setting up a new environment for myself and I'm interested in configuring my lighttpd server to support both PHP and Python. Is this possible?</p>
| 3
|
2009-04-21T06:49:38Z
| 771,528
|
<p>You can also enable Lighty to use .pl, .py and .php as 'cgi' by enabling mod_cgi and setting it up. The default configs are on the Lighty website. However, this will have the benefits and problems of running an independent cgi process. If you are only experiencing light traffic, performance shouldn't be an issue.</p>
| 1
|
2009-04-21T08:01:35Z
|
[
"php",
"python",
"lighttpd",
"configure"
] |
Monitoring a tcp port
| 771,399
|
<p>For fun, I've been toying around with writing a load balancer in python and have been trying to figure the best (correct?) way to test if a port is available and the remote host is still there.</p>
<p>I'm finding that, once connected, it becomes difficult to tell when the remote host goes down. I've turned keep alive on, but can't get it to recognize a downed connection sooner than a minute (I realize polling more often than a minute might be overkill, but lets say I wanted to), even after setting the various TCP_KEEPALIVE options to their lowest.</p>
<p>When I use nonblocking sockets, I've noticed that a recv() will return an error ("resource temporarily unavailable") when it reads from a live socket, but returns "" when reading from a dead one (send and recv of 0 bytes, which might be the cause?). That seems like an odd way to test for it connected, though, and makes it impossible to tell if the connected died but <em>after</em> sending some data.</p>
<p>Aside from connecting/disconnecting for every check, is there something I can do? Can I manually send a tcp keepalive, or can I establish a lower level connection that will let me test the connectivity without sending real data the remote server would potentially process?</p>
| 2
|
2009-04-21T07:11:13Z
| 771,415
|
<p>ping was invented for that purpose</p>
<p>also you might be able to send malformed TCP packets to your destination. For example, in the TCP headers there is a flag for acknowleging end of transmission, its the FIN message. If you send a message with ACK and FIN the remote host should complain with a return packet and you'll be able to evaluate round trip time.</p>
| 0
|
2009-04-21T07:16:34Z
|
[
"python",
"tcp",
"monitoring",
"port"
] |
Monitoring a tcp port
| 771,399
|
<p>For fun, I've been toying around with writing a load balancer in python and have been trying to figure the best (correct?) way to test if a port is available and the remote host is still there.</p>
<p>I'm finding that, once connected, it becomes difficult to tell when the remote host goes down. I've turned keep alive on, but can't get it to recognize a downed connection sooner than a minute (I realize polling more often than a minute might be overkill, but lets say I wanted to), even after setting the various TCP_KEEPALIVE options to their lowest.</p>
<p>When I use nonblocking sockets, I've noticed that a recv() will return an error ("resource temporarily unavailable") when it reads from a live socket, but returns "" when reading from a dead one (send and recv of 0 bytes, which might be the cause?). That seems like an odd way to test for it connected, though, and makes it impossible to tell if the connected died but <em>after</em> sending some data.</p>
<p>Aside from connecting/disconnecting for every check, is there something I can do? Can I manually send a tcp keepalive, or can I establish a lower level connection that will let me test the connectivity without sending real data the remote server would potentially process?</p>
| 2
|
2009-04-21T07:11:13Z
| 771,422
|
<p>I'd recommend not leaving your (single) test socket connected - make a new connection each time you need to poll. Every load balancer / server availability system I've ever seen uses this method instead of a persistent connection.</p>
<p>If the remote server hasn't responded within a reasonable amount of time (e.g. 10s) mark it as "down". Use timers and signals rather than function response codes to handle that timeout.</p>
| 2
|
2009-04-21T07:20:07Z
|
[
"python",
"tcp",
"monitoring",
"port"
] |
Monitoring a tcp port
| 771,399
|
<p>For fun, I've been toying around with writing a load balancer in python and have been trying to figure the best (correct?) way to test if a port is available and the remote host is still there.</p>
<p>I'm finding that, once connected, it becomes difficult to tell when the remote host goes down. I've turned keep alive on, but can't get it to recognize a downed connection sooner than a minute (I realize polling more often than a minute might be overkill, but lets say I wanted to), even after setting the various TCP_KEEPALIVE options to their lowest.</p>
<p>When I use nonblocking sockets, I've noticed that a recv() will return an error ("resource temporarily unavailable") when it reads from a live socket, but returns "" when reading from a dead one (send and recv of 0 bytes, which might be the cause?). That seems like an odd way to test for it connected, though, and makes it impossible to tell if the connected died but <em>after</em> sending some data.</p>
<p>Aside from connecting/disconnecting for every check, is there something I can do? Can I manually send a tcp keepalive, or can I establish a lower level connection that will let me test the connectivity without sending real data the remote server would potentially process?</p>
| 2
|
2009-04-21T07:11:13Z
| 771,438
|
<p>It is theoretically possible to spam a keepalive packet. But to set it to very low intervals, you may need to dig into raw sockets. Also, your host may ignore it if its coming in too fast.</p>
<p>The best way to check if a host is alive in a TCP connection is to send data, and wait for an ACK packet. If the ACK packet arrives, the SEND function will return non-zero. </p>
| 0
|
2009-04-21T07:24:03Z
|
[
"python",
"tcp",
"monitoring",
"port"
] |
Monitoring a tcp port
| 771,399
|
<p>For fun, I've been toying around with writing a load balancer in python and have been trying to figure the best (correct?) way to test if a port is available and the remote host is still there.</p>
<p>I'm finding that, once connected, it becomes difficult to tell when the remote host goes down. I've turned keep alive on, but can't get it to recognize a downed connection sooner than a minute (I realize polling more often than a minute might be overkill, but lets say I wanted to), even after setting the various TCP_KEEPALIVE options to their lowest.</p>
<p>When I use nonblocking sockets, I've noticed that a recv() will return an error ("resource temporarily unavailable") when it reads from a live socket, but returns "" when reading from a dead one (send and recv of 0 bytes, which might be the cause?). That seems like an odd way to test for it connected, though, and makes it impossible to tell if the connected died but <em>after</em> sending some data.</p>
<p>Aside from connecting/disconnecting for every check, is there something I can do? Can I manually send a tcp keepalive, or can I establish a lower level connection that will let me test the connectivity without sending real data the remote server would potentially process?</p>
| 2
|
2009-04-21T07:11:13Z
| 773,207
|
<p>"it becomes difficult to tell when the remote host goes down"</p>
<p>Correct. This is a feature of TCP. The whole point of TCP is to have an enduring connection between ports. Theoretically an application can drop and reconnect to the port through TCP (the socket libraries don't provide a lot of support for this, but it's part of the TCP protocol).</p>
| 1
|
2009-04-21T15:33:33Z
|
[
"python",
"tcp",
"monitoring",
"port"
] |
Monitoring a tcp port
| 771,399
|
<p>For fun, I've been toying around with writing a load balancer in python and have been trying to figure the best (correct?) way to test if a port is available and the remote host is still there.</p>
<p>I'm finding that, once connected, it becomes difficult to tell when the remote host goes down. I've turned keep alive on, but can't get it to recognize a downed connection sooner than a minute (I realize polling more often than a minute might be overkill, but lets say I wanted to), even after setting the various TCP_KEEPALIVE options to their lowest.</p>
<p>When I use nonblocking sockets, I've noticed that a recv() will return an error ("resource temporarily unavailable") when it reads from a live socket, but returns "" when reading from a dead one (send and recv of 0 bytes, which might be the cause?). That seems like an odd way to test for it connected, though, and makes it impossible to tell if the connected died but <em>after</em> sending some data.</p>
<p>Aside from connecting/disconnecting for every check, is there something I can do? Can I manually send a tcp keepalive, or can I establish a lower level connection that will let me test the connectivity without sending real data the remote server would potentially process?</p>
| 2
|
2009-04-21T07:11:13Z
| 35,338,445
|
<p>You can use <a href="http://www.tldp.org/LDP/abs/html/devref1.html" rel="nofollow">Bash pseudo-device files</a> for TCP/UDP connection with a specific I/O port, for example:</p>
<pre><code>printf "" > /dev/tcp/example.com/80 && echo Works
</code></pre>
<p>This would open the connection, but won't send anything. You can test it by:</p>
<pre><code>nc -vl 1234 &
printf "" > /dev/tcp/localhost/1234
</code></pre>
<p>For simple monitoring use cron with above command or using <code>watch</code>:</p>
<pre><code>watch bash -c 'echo > /dev/tcp/localhost/1234 && echo Works || echo FAIL'
</code></pre>
<p>However it's recommended to use specific tools which are designed for that such as Monit, Nagios, etc.</p>
<h3>Monit</h3>
<p>Here is example rule using Monit (<code>monit</code>):</p>
<pre><code># Verify host.
check host example with address example.com
if failed
port 80
protocol http
then alert
</code></pre>
| 0
|
2016-02-11T11:43:34Z
|
[
"python",
"tcp",
"monitoring",
"port"
] |
Call python script from AIR application?
| 771,738
|
<p>How can we invoke a python script using AIR 1.5?</p>
| 1
|
2009-04-21T09:09:18Z
| 771,745
|
<p>You cannot directly invoke system commands or run an executable (the python interpreter) from within an AIR application. If it's possible to share what exactly you want to do, maybe we can suggest alternatives. </p>
<p>If it's really really (that's two reallys) important to run an executable from AIR lookup the CommandProxy demo.</p>
| 1
|
2009-04-21T09:12:14Z
|
[
"python",
"flex3",
"air"
] |
Call python script from AIR application?
| 771,738
|
<p>How can we invoke a python script using AIR 1.5?</p>
| 1
|
2009-04-21T09:09:18Z
| 771,752
|
<p>For example through AMF: <a href="http://pyamf.org/" rel="nofollow">http://pyamf.org/</a></p>
| 0
|
2009-04-21T09:14:42Z
|
[
"python",
"flex3",
"air"
] |
Call python script from AIR application?
| 771,738
|
<p>How can we invoke a python script using AIR 1.5?</p>
| 1
|
2009-04-21T09:09:18Z
| 771,836
|
<p>Hypothetically, Adobe Alchemy technology may allow you to port Python interpreter to Flash.</p>
<p>Though I seriously doubt that's the approach you want to use. Depending on task there should be easier solutions.</p>
| -1
|
2009-04-21T09:38:38Z
|
[
"python",
"flex3",
"air"
] |
Call python script from AIR application?
| 771,738
|
<p>How can we invoke a python script using AIR 1.5?</p>
| 1
|
2009-04-21T09:09:18Z
| 3,895,749
|
<p>Air 2.0 has a native process API.</p>
| 0
|
2010-10-09T04:54:56Z
|
[
"python",
"flex3",
"air"
] |
What does the 'shell' argument in subprocess mean on Windows?
| 771,816
|
<p>The docs for the subprocess module state that 'If <em>shell</em> is True, the specified command will be executed through the shell'. What does this mean in practice, on a Windows OS?</p>
| 1
|
2009-04-21T09:35:09Z
| 771,839
|
<p>It means that the command will be executed using the program specified in the <code>COMSPEC</code> environment variable. Usually <code>cmd.exe</code>.</p>
<p>To be exact, subprocess calls the <a href="http://msdn.microsoft.com/en-us/library/ms682425.aspx" rel="nofollow"><code>CreateProcess</code></a> windows api function, passing <code>"cmd.exe /c " + args</code> as the <code>lpCommandLine</code> argument. </p>
<p>If shell==False, the <code>lpCommandLine</code> argument to CreateProcess is simply <code>args</code>.</p>
| 3
|
2009-04-21T09:39:22Z
|
[
"python",
"subprocess"
] |
What does the 'shell' argument in subprocess mean on Windows?
| 771,816
|
<p>The docs for the subprocess module state that 'If <em>shell</em> is True, the specified command will be executed through the shell'. What does this mean in practice, on a Windows OS?</p>
| 1
|
2009-04-21T09:35:09Z
| 771,852
|
<p>In <a href="http://docs.python.org/library/subprocess.html#using-the-subprocess-module" rel="nofollow">using-the-subprocess-module</a>, there is an explicit paragraph:</p>
<blockquote>
<p>The executable argument specifies the program to execute. It is very seldom needed: Usually, the program to execute is defined by the args argument. If shell=True, the executable argument specifies which shell to use. On Unix, the default shell is /bin/sh. <strong>On Windows, the default shell is specified by the COMSPEC environment variable.</strong></p>
</blockquote>
<p><em>Windows example</em> - the shell (<code>cmd.exe</code>) command <code>date -t</code> will not be recognized without the shell:</p>
<pre><code>>>> p=subprocess.Popen(["date", "/t"], stdout=subprocess.PIPE)
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
File "C:\Python26\lib\subprocess.py", line 595, in __init__
errread, errwrite)
File "C:\Python26\lib\subprocess.py", line 804, in _execute_child
startupinfo)
WindowsError: [Error 2] The system cannot find the file specified
>>>
</code></pre>
<p>Using a shell, all is well:</p>
<pre><code>>>> p=subprocess.Popen(["date", "/t"], shell=True, stdout=subprocess.PIPE)
>>> p.communicate()
('Wed 04/22/2009 \r\n', None)
>>>
</code></pre>
| 0
|
2009-04-21T09:43:28Z
|
[
"python",
"subprocess"
] |
What does the 'shell' argument in subprocess mean on Windows?
| 771,816
|
<p>The docs for the subprocess module state that 'If <em>shell</em> is True, the specified command will be executed through the shell'. What does this mean in practice, on a Windows OS?</p>
| 1
|
2009-04-21T09:35:09Z
| 772,687
|
<p>In addition to what was said in other answers, it is useful in practice if you want to open a file in the default viewer for that file type. For instance, if you want to open an HTML or PDF file, but will not know which browser or viewer is installed on the systems it will be run on, or have no guarantees as to the path to the executable, you can simply pass the file name as the only argument for the args field, then set shell=True. This will have Windows use whatever program is associated with that file type.
One caveat, if the path to your file has spaces, you need to surround it with two ".</p>
<p>eg.</p>
<pre><code>path = "C:\\Documents and Settings\\Bob\\Desktop\\New Folder\\README.txt"
subprocess.call('""' + path + '""', shell = True)
</code></pre>
| 0
|
2009-04-21T13:51:24Z
|
[
"python",
"subprocess"
] |
What does the 'shell' argument in subprocess mean on Windows?
| 771,816
|
<p>The docs for the subprocess module state that 'If <em>shell</em> is True, the specified command will be executed through the shell'. What does this mean in practice, on a Windows OS?</p>
| 1
|
2009-04-21T09:35:09Z
| 772,743
|
<p>When you execute an external process, the command you want may look something like "foo arg1 arg2 arg3". If "foo" is an executable, that is what gets executed and given the arguments. </p>
<p>However, often it is the case that "foo" is actually a script of some sort, or maybe a command that is built-in to the shell and not an actual executable file on disk. In this case the system can't execute "foo" directly because, strictly speaking, these sorts of things aren't executable. They need some sort of "shell" to execute them. On *nix systems this shell is typically (but not necessarily) /bin/sh. On windows it will typically be cmd.exe (or whatever is stored in the COMSPEC environment variable).</p>
<p>This parameter lets you define what shell you wish to use to execute your command, for the relatively rare case when you don't want the default.</p>
| 1
|
2009-04-21T14:04:08Z
|
[
"python",
"subprocess"
] |
Python: how to store a draft email with BCC recipients to Exchange Server via IMAP?
| 771,907
|
<p>I try to store a draft e-mail via IMAP to a folder running on MS Exchange. Everything ok, except that Bcc recipients don't get shown in the draft message stored on the server. Bcc recipients also don't receive the email if I send it with MS Outlook. If I read the message back with Python after I have stored it on the server, I can see the Bcc in the draft.</p>
<p>The following Python code reproduces this behavior:</p>
<pre><code>import imaplib
import time
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
message = MIMEMultipart()
message['Subject'] = 'Test Draft'
message['From'] = 'test@test.net'
message['to'] = 'test@test.com'
message['cc'] = 'testcc@test.com'
message['bcc'] = 'testbcc@test.com'
message.attach(MIMEText('This is a test.\n'))
server= imaplib.IMAP4('the.ser.ver.ip')
server.login('test', 'test')
server.append("Drafts"
,'\Draft'
,imaplib.Time2Internaldate(time.time())
,str(message))
server.logout()
</code></pre>
<p>If I run this code, a draft gets stored into the <code>Draft</code> folder on the Exchange Server. But if I look at the draft with MS Outlook, it does not include the <code>bcc</code> recipient (<code>message['bcc'] = 'testbcc@test.com'</code>). <code>Message</code>, <code>to</code>, <code>from</code>, <code>cc</code> ok, no error.</p>
<p>If I download drafts that already include a bcc from an Exchange folder, I can also see the bcc. Only uploading doesn't work for me.</p>
<p>Any help very much appreciated. Thanks. BTW, MAPI is not an option.</p>
<p><strong>Update</strong>: Thanks. <code>X-Receiver</code> didn't work for me. As for playing around with an IMAP-Folder in Outlook, I got an interesting result. If I access the draft via the IMAP-Folder in Outlook, I see the bcc. But if I access it via the MAPI-Folder, I don't see it. Will play a little bit around with that.</p>
<p><strong>Conclusion</strong>: thanks for the input. Actually, the code works just fine. See below for the answer that I found.</p>
| 5
|
2009-04-21T10:03:09Z
| 772,233
|
<p>It could be that way by design. After all, the whole point of bcc is that the recipients are hidden from each other.</p>
<p>I understand that you are not sending the e-mail, just storing it. But my guess is that Exchange's internal rules kick in when the message is IMAP.appended to the folder, causing the bcc field to be stripped away. </p>
<p>Obviously, when messages are saved to a folder using Outlook the bcc field is <strong>not</strong> stripped away. But I guess outlook communicates with Exchange using some internal mechanizm (MAPI?).</p>
<p>All the above is just guesswork.</p>
<p>Something fun you could try:</p>
<ul>
<li>In an empty Outlook/MAPI profile, create a IMAP account. Set it up to store Drafts and Sent Items on the Exchange server.</li>
<li>See if outlook using IMAP can save bcc of Drafts correctly.</li>
</ul>
<p>I tried the above using the Evolution e-mail client connected to Exchange over IMAP. Using outlook (connected the normal way), I then had a look in Drafts and Sent Items. The bcc field was missing in both places.</p>
<p>I belive this supports my theory.</p>
| 1
|
2009-04-21T12:02:01Z
|
[
"python",
"email",
"exchange-server",
"imap",
"bcc"
] |
Python: how to store a draft email with BCC recipients to Exchange Server via IMAP?
| 771,907
|
<p>I try to store a draft e-mail via IMAP to a folder running on MS Exchange. Everything ok, except that Bcc recipients don't get shown in the draft message stored on the server. Bcc recipients also don't receive the email if I send it with MS Outlook. If I read the message back with Python after I have stored it on the server, I can see the Bcc in the draft.</p>
<p>The following Python code reproduces this behavior:</p>
<pre><code>import imaplib
import time
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
message = MIMEMultipart()
message['Subject'] = 'Test Draft'
message['From'] = 'test@test.net'
message['to'] = 'test@test.com'
message['cc'] = 'testcc@test.com'
message['bcc'] = 'testbcc@test.com'
message.attach(MIMEText('This is a test.\n'))
server= imaplib.IMAP4('the.ser.ver.ip')
server.login('test', 'test')
server.append("Drafts"
,'\Draft'
,imaplib.Time2Internaldate(time.time())
,str(message))
server.logout()
</code></pre>
<p>If I run this code, a draft gets stored into the <code>Draft</code> folder on the Exchange Server. But if I look at the draft with MS Outlook, it does not include the <code>bcc</code> recipient (<code>message['bcc'] = 'testbcc@test.com'</code>). <code>Message</code>, <code>to</code>, <code>from</code>, <code>cc</code> ok, no error.</p>
<p>If I download drafts that already include a bcc from an Exchange folder, I can also see the bcc. Only uploading doesn't work for me.</p>
<p>Any help very much appreciated. Thanks. BTW, MAPI is not an option.</p>
<p><strong>Update</strong>: Thanks. <code>X-Receiver</code> didn't work for me. As for playing around with an IMAP-Folder in Outlook, I got an interesting result. If I access the draft via the IMAP-Folder in Outlook, I see the bcc. But if I access it via the MAPI-Folder, I don't see it. Will play a little bit around with that.</p>
<p><strong>Conclusion</strong>: thanks for the input. Actually, the code works just fine. See below for the answer that I found.</p>
| 5
|
2009-04-21T10:03:09Z
| 772,496
|
<p>Try setting this alternate version of the BCC header:</p>
<pre><code>X-Receiver: someguy@gmail.com
</code></pre>
<p>Exchange in particular will treat this like a BCC when you send it. But I bet it will not strip it when you write via IMAP. You can include more than one BCC recipient by duplicating this line.</p>
<p>This is a complete hack, obviously.</p>
| 1
|
2009-04-21T13:07:21Z
|
[
"python",
"email",
"exchange-server",
"imap",
"bcc"
] |
Python: how to store a draft email with BCC recipients to Exchange Server via IMAP?
| 771,907
|
<p>I try to store a draft e-mail via IMAP to a folder running on MS Exchange. Everything ok, except that Bcc recipients don't get shown in the draft message stored on the server. Bcc recipients also don't receive the email if I send it with MS Outlook. If I read the message back with Python after I have stored it on the server, I can see the Bcc in the draft.</p>
<p>The following Python code reproduces this behavior:</p>
<pre><code>import imaplib
import time
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
message = MIMEMultipart()
message['Subject'] = 'Test Draft'
message['From'] = 'test@test.net'
message['to'] = 'test@test.com'
message['cc'] = 'testcc@test.com'
message['bcc'] = 'testbcc@test.com'
message.attach(MIMEText('This is a test.\n'))
server= imaplib.IMAP4('the.ser.ver.ip')
server.login('test', 'test')
server.append("Drafts"
,'\Draft'
,imaplib.Time2Internaldate(time.time())
,str(message))
server.logout()
</code></pre>
<p>If I run this code, a draft gets stored into the <code>Draft</code> folder on the Exchange Server. But if I look at the draft with MS Outlook, it does not include the <code>bcc</code> recipient (<code>message['bcc'] = 'testbcc@test.com'</code>). <code>Message</code>, <code>to</code>, <code>from</code>, <code>cc</code> ok, no error.</p>
<p>If I download drafts that already include a bcc from an Exchange folder, I can also see the bcc. Only uploading doesn't work for me.</p>
<p>Any help very much appreciated. Thanks. BTW, MAPI is not an option.</p>
<p><strong>Update</strong>: Thanks. <code>X-Receiver</code> didn't work for me. As for playing around with an IMAP-Folder in Outlook, I got an interesting result. If I access the draft via the IMAP-Folder in Outlook, I see the bcc. But if I access it via the MAPI-Folder, I don't see it. Will play a little bit around with that.</p>
<p><strong>Conclusion</strong>: thanks for the input. Actually, the code works just fine. See below for the answer that I found.</p>
| 5
|
2009-04-21T10:03:09Z
| 920,817
|
<p>Actually, the code works just fine. It creates the proper mail with all the right headers including bcc.</p>
<p><strong>How does the mail client display bcc?</strong></p>
<p>The <a href="http://en.wikipedia.org/wiki/E-mail_client" rel="nofollow">mail client</a> (e.g. Python or MS Outlook via IMAP or MAPI in my case) decides whether and how to display bcc-headers. Outlook for example doesn't display bcc headers from an IMAP folder. This is a feature to hide bcc recipients from each other where they have not been stripped away from the mail before (it is not clear from the standard whether one bcc recipient is allowed to see all other bcc recipients or not, see <a href="http://en.wikipedia.org/wiki/Blind_carbon_copy#Visibility" rel="nofollow">Wikipedia</a>).</p>
<p><strong>Who handles bcc upon sending an email?</strong></p>
<p>Suppose now that we have drafted a message in a mail client and stored it in an IMAP or MAPI folder. The server providing the IMAP / MAPI folders leaves the draft message unchanged. What happens to the bcc-headers upon sending the mail is implementation dependent, and might depend both on the mail client and the <a href="http://en.wikipedia.org/wiki/Mail_transfer_agent" rel="nofollow">mail transfer agent</a> (e.g. MS Exchange Server in my case). In a nutshell, people do not agree whether the mail client or the mail transfer agent is reponsible for removing bcc headers. It seems however to be the case that a majority of developers is of the opinion that it is the mail client's business with the mail transfer agent not touching the mail (e.g. MS Exchange, MS SMTP, Exim, OpenWave). In this case, the mail transfer agent sends the email to the recipient as defined in the <code>RCPT TO:</code> of the <a href="http://en.wikipedia.org/wiki/SMTP" rel="nofollow">SMTP</a> communication, and leaves the email unchanged otherwise. Some other mail transfer agents strip bcc headers from emails however (e.g. sendmail, Lotus Notes). A very thorough discussion can be found on the Exim mailing list starting <a href="http://lists.exim.org/lurker/message/20040722.043422.7a079b9f.hu.html#exim-dev" rel="nofollow">here</a>.</p>
<p>In the case of MS Outlook and MS Exchange, MS Outlook never sends bcc (but sends individual emails for each bcc recipient) and MS Exchange does not touch the email headers, but sends the full email (possibly including bcc recipients) to the recipients defined in <code>RCPT TO:</code>.</p>
<p><strong>Conclusion</strong></p>
<p>I did not understand that there is no guaranteed behavior for bcc, and that usually the client handles bcc. I will rewrite my Python code to loop over bcc recipients and generate one email for each bcc recipient.</p>
| 5
|
2009-05-28T13:22:51Z
|
[
"python",
"email",
"exchange-server",
"imap",
"bcc"
] |
pyqt4 and pyserial
| 771,988
|
<p>I want to do an app constantly watching the serial port and changing the user interface according to the input received from the port. I've managed to read lines from the port with pyserial under Linux, but I'm not sure how to do this in a regular fashion: create a separate thread and check for input on a timer event? How do i make sure I don't miss anything? (implementing some kind of handshake/protocol seems like an overkill for this...) And most importantly: How do I do it with the facilities of qt4?</p>
<p><strong>Edit:</strong> This is what I'm doing now (I want to do this periodically with the rest of the app running and not waiting)</p>
<pre><code>class MessageBox(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
ser = serial.Serial('/dev/ttyS0', 9600, bytesize=serial.EIGHTBITS,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
timeout=None,
xonxoff=0,
rtscts=0,
interCharTimeout=None)
self.label = QtGui.QLabel(ser.readline(), self)
self.label.move(15, 10)
ser.close()
self.setGeometry(300, 300, 250, 150)
self.setWindowTitle('Authentication')
self.color = QtGui.QColor(0, 0, 0)
self.square = QtGui.QWidget(self)
self.square.setGeometry(120, 20, 100, 100)
self.square.setStyleSheet("QWidget { background-color: %s }" % self.color.name())
</code></pre>
| 4
|
2009-04-21T10:37:15Z
| 772,091
|
<p>You won't miss any bytes, any pending input is buffered.</p>
<p>You have several options:</p>
<ol>
<li><p>use a thread that polls the serial port with PySerial/inWaiting() </p></li>
<li><p>Use a timer in the main thread that polls the serial port with PySerial/inWaiting.</p></li>
<li><p>find the handle of the port and pass it to QSocketNotifier. This works only on linux but in that case, QSocketNotifier will watch the file associated with your serial port and send a signal when there's something available.</p></li>
</ol>
<p>Method 2 and 3 are better because you don't need a thread.</p>
| 4
|
2009-04-21T11:12:42Z
|
[
"python",
"linux",
"qt",
"serial-port",
"pyserial"
] |
How to add a second bouncing ball to the window?
| 771,992
|
<p>I have coded an animation (in python) for a beach ball to bounce around a screen. I now wish to add a second ball to the window, and when the two collide for them to bounce off each other. </p>
<p>So far, my attempts at this have been unsuccessful. Any ideas how to do this? The code I have so far is below.</p>
<pre><code>import pygame
import sys
if __name__ =='__main__':
ball_image = 'Beachball.jpg'
bounce_sound = 'Thump.wav'
width = 800
height = 600
background_colour = 0,0,0
caption= 'Bouncing Ball animation'
velocity = [1,1]
pygame.init ()
frame = pygame.display.set_mode ((width, height))
pygame.display.set_caption (caption)
ball= pygame.image.load (ball_image). convert()
ball_boundary = ball.get_rect (center=(300,300))
sound = pygame.mixer.Sound (bounce_sound)
while True:
for event in pygame.event.get():
print event
if event.type == pygame.QUIT: sys.exit(0)
if ball_boundary.left < 0 or ball_boundary.right > width:
sound.play()
velocity[0] = -1 * velocity[0]
if ball_boundary.top < 0 or ball_boundary.bottom > height:
sound.play()
velocity[1] = -1 * velocity[1]
ball_boundary = ball_boundary.move (velocity)
frame.fill (background_colour)
frame.blit (ball, ball_boundary)
pygame.display.flip()
</code></pre>
| 1
|
2009-04-21T10:38:19Z
| 772,015
|
<p>You should probably create a class to represent your beachball. Then you'd instance as many as you like, and put the instances in a Python list.</p>
<p>You'd then go through that list on each frame, updating and rendering each.</p>
<p>You would need to include a method to test for collision against another ball (this is simple for circles). If a collision is detected, the balls involved should simulate a bounce away from each other.</p>
| 3
|
2009-04-21T10:46:51Z
|
[
"python",
"animation",
"pygame"
] |
How to add a second bouncing ball to the window?
| 771,992
|
<p>I have coded an animation (in python) for a beach ball to bounce around a screen. I now wish to add a second ball to the window, and when the two collide for them to bounce off each other. </p>
<p>So far, my attempts at this have been unsuccessful. Any ideas how to do this? The code I have so far is below.</p>
<pre><code>import pygame
import sys
if __name__ =='__main__':
ball_image = 'Beachball.jpg'
bounce_sound = 'Thump.wav'
width = 800
height = 600
background_colour = 0,0,0
caption= 'Bouncing Ball animation'
velocity = [1,1]
pygame.init ()
frame = pygame.display.set_mode ((width, height))
pygame.display.set_caption (caption)
ball= pygame.image.load (ball_image). convert()
ball_boundary = ball.get_rect (center=(300,300))
sound = pygame.mixer.Sound (bounce_sound)
while True:
for event in pygame.event.get():
print event
if event.type == pygame.QUIT: sys.exit(0)
if ball_boundary.left < 0 or ball_boundary.right > width:
sound.play()
velocity[0] = -1 * velocity[0]
if ball_boundary.top < 0 or ball_boundary.bottom > height:
sound.play()
velocity[1] = -1 * velocity[1]
ball_boundary = ball_boundary.move (velocity)
frame.fill (background_colour)
frame.blit (ball, ball_boundary)
pygame.display.flip()
</code></pre>
| 1
|
2009-04-21T10:38:19Z
| 772,180
|
<p>Here's a very basic restructure of your code. It could still be tidied up a lot, but it should show you how you can use instances of the class.</p>
<pre><code>import pygame
import random
import sys
class Ball:
def __init__(self,X,Y):
self.velocity = [1,1]
self.ball_image = pygame.image.load ('Beachball.jpg'). convert()
self.ball_boundary = self.ball_image.get_rect (center=(X,Y))
self.sound = pygame.mixer.Sound ('Thump.wav')
if __name__ =='__main__':
width = 800
height = 600
background_colour = 0,0,0
pygame.init()
frame = pygame.display.set_mode((width, height))
pygame.display.set_caption("Bouncing Ball animation")
num_balls = 1000
ball_list = []
for i in range(num_balls):
ball_list.append( Ball(random.randint(0, width),random.randint(0, height)) )
while True:
for event in pygame.event.get():
print event
if event.type == pygame.QUIT:
sys.exit(0)
frame.fill (background_colour)
for ball in ball_list:
if ball.ball_boundary.left < 0 or ball.ball_boundary.right > width:
ball.sound.play()
ball.velocity[0] = -1 * ball.velocity[0]
if ball.ball_boundary.top < 0 or ball.ball_boundary.bottom > height:
ball.sound.play()
ball.velocity[1] = -1 * ball.velocity[1]
ball.ball_boundary = ball.ball_boundary.move (ball.velocity)
frame.blit (ball.ball_image, ball.ball_boundary)
pygame.display.flip()
</code></pre>
| 7
|
2009-04-21T11:42:49Z
|
[
"python",
"animation",
"pygame"
] |
Running python code from standard Cocoa application
| 772,112
|
<p>I have an XCode project built as a Cocoa single document application (it's not a Python-Cocoa application, that is not what I want).</p>
<p>All the documentation I found assumes I want to create a Cocoa application with code written in Python and this is not the case - I want a standard Cocoa application that calls a method out of a Python class.</p>
<p>Can I use PyObjC to run python code from a file without replacing the Cocoa standard main.c with a main.py file?</p>
<p>Later edit: I am aware of Python.framework but as far as I can tell I can only send parameters to PyRun_SimpleFile through the environment - I'd like to use the bridge directly to exchange data with the python code.</p>
| 8
|
2009-04-21T11:18:44Z
| 772,220
|
<p>A google search for <a href="http://www.google.com/search?q=embed%2Bpython%2Bobjective%2BC">embed python objective C</a>, returns a few links that might be of interest, in particular:</p>
<ul>
<li><a href="http://blog.alienoverlord.com/?p=14">http://blog.alienoverlord.com/?p=14</a></li>
<li><a href="http://blog.tlensing.org/2008/11/04/embedding-python-in-a-cocoa-application/">http://blog.tlensing.org/2008/11/04/embedding-python-in-a-cocoa-application/</a></li>
</ul>
| 7
|
2009-04-21T11:57:55Z
|
[
"python",
"cocoa",
"osx",
"pyobjc"
] |
What does the Python Ellipsis object do?
| 772,124
|
<p>While idly surfing the namespace I noticed an odd looking object called "<strong>Ellipsis</strong>", it does not seem to be or do anything special, but it's a globally available builtin. </p>
<p>After a search I found that it is used in some obscure variant of the slicing syntax by Numpy and Scipy... but almost nothing else. </p>
<p>Was this object added to the language specifically to support Numpy + Scipy? Does Ellipsis have any generic meaning or use at all?</p>
<pre><code>D:\workspace\numpy>python
Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> Ellipsis
Ellipsis
</code></pre>
| 196
|
2009-04-21T11:21:12Z
| 772,134
|
<p>You can use Ellipsis yourself, in custom slicing situations like numpy has done, but it has no usage in any builtin class.</p>
<p>I don't know if it was added specifically for use in numpy, but I certainly haven't seen it used elsewhere.</p>
<p>See also: <a href="http://stackoverflow.com/questions/118370/how-do-you-use-the-ellipsis-slicing-syntax-in-python">http://stackoverflow.com/questions/118370/how-do-you-use-the-ellipsis-slicing-syntax-in-python</a></p>
| 8
|
2009-04-21T11:24:33Z
|
[
"python",
"ellipsis"
] |
What does the Python Ellipsis object do?
| 772,124
|
<p>While idly surfing the namespace I noticed an odd looking object called "<strong>Ellipsis</strong>", it does not seem to be or do anything special, but it's a globally available builtin. </p>
<p>After a search I found that it is used in some obscure variant of the slicing syntax by Numpy and Scipy... but almost nothing else. </p>
<p>Was this object added to the language specifically to support Numpy + Scipy? Does Ellipsis have any generic meaning or use at all?</p>
<pre><code>D:\workspace\numpy>python
Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> Ellipsis
Ellipsis
</code></pre>
| 196
|
2009-04-21T11:21:12Z
| 772,148
|
<p>From the <a href="http://www.python.org/doc/2.5.2/lib/bltin-ellipsis-object.html">Python documentation</a>:</p>
<blockquote>
<p>This object is used by extended slice
notation (see the <em><a href="http://www.python.org/doc/2.5.2/ref/ref.html">Python Reference
Manual</a></em>). It supports no special
operations. There is exactly one
ellipsis object, named <code>Ellipsis</code> (a
built-in name).</p>
</blockquote>
| 27
|
2009-04-21T11:30:30Z
|
[
"python",
"ellipsis"
] |
What does the Python Ellipsis object do?
| 772,124
|
<p>While idly surfing the namespace I noticed an odd looking object called "<strong>Ellipsis</strong>", it does not seem to be or do anything special, but it's a globally available builtin. </p>
<p>After a search I found that it is used in some obscure variant of the slicing syntax by Numpy and Scipy... but almost nothing else. </p>
<p>Was this object added to the language specifically to support Numpy + Scipy? Does Ellipsis have any generic meaning or use at all?</p>
<pre><code>D:\workspace\numpy>python
Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> Ellipsis
Ellipsis
</code></pre>
| 196
|
2009-04-21T11:21:12Z
| 773,472
|
<p>This came up in another <a href="http://stackoverflow.com/questions/752602/slicing-in-python-expressions-documentation">question</a> recently. I'll elaborate on my <a href="http://stackoverflow.com/questions/752602/slicing-in-python-expressions-documentation/753260#753260">answer</a> from there:</p>
<p><a href="http://docs.python.org/dev/library/constants.html#Ellipsis">Ellipsis</a> is an object that can appear in slice notation. For example:</p>
<pre><code>myList[1:2, ..., 0]
</code></pre>
<p>Its interpretation is purely up to whatever implements the <code>__getitem__</code> function and sees <code>Ellipsis</code> objects there, but its main (and intended) use is in the <a href="http://numpy.scipy.org/">numeric python</a> extension, which adds a multidimensional array type. Since there are more than one dimensions, slicing becomes more complex than just a start and stop index; it is useful to be able to slice in multiple dimensions as well. E.g., given a 4x4 array, the top left area would be defined by the slice <code>[:2,:2]</code>:</p>
<pre><code>>>> a
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12],
[13, 14, 15, 16]])
>>> a[:2,:2] # top left
array([[1, 2],
[5, 6]])
</code></pre>
<p>Extending this further, Ellipsis is used here to indicate a placeholder for the rest of the array dimensions not specified. Think of it as indicating the full slice <code>[:]</code> for all the dimensions in the gap it is placed, so for a 3d array, <code>a[...,0]</code> is the same as <code>a[:,:,0]</code> and for 4d, <code>a[:,:,:,0]</code>, similarly, <code>a[0,...,0]</code> is <code>a[0,:,:,0]</code> (with however many colons in the middle make up the full number of dimensions in the array).</p>
<p>Interestingly, in python3, the Ellipsis literal (<code>...</code>) is usable outside the slice syntax, so you can actually write: </p>
<pre><code>>>> ...
Ellipsis
</code></pre>
<p>Other than the various numeric types, no, I don't think it's used. As far as I'm aware, it was added purely for numpy use and has no core support other than providing the object and corresponding syntax. The object being there didn't require this, but the literal "..." support for slices did.</p>
| 242
|
2009-04-21T16:26:07Z
|
[
"python",
"ellipsis"
] |
What does the Python Ellipsis object do?
| 772,124
|
<p>While idly surfing the namespace I noticed an odd looking object called "<strong>Ellipsis</strong>", it does not seem to be or do anything special, but it's a globally available builtin. </p>
<p>After a search I found that it is used in some obscure variant of the slicing syntax by Numpy and Scipy... but almost nothing else. </p>
<p>Was this object added to the language specifically to support Numpy + Scipy? Does Ellipsis have any generic meaning or use at all?</p>
<pre><code>D:\workspace\numpy>python
Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> Ellipsis
Ellipsis
</code></pre>
| 196
|
2009-04-21T11:21:12Z
| 6,189,281
|
<p>In Python 3, you can use the Ellipsis literal <code>...</code> as a ânopâ placeholder for code:</p>
<pre><code>def will_do_something():
...
</code></pre>
<p>This is <strong>not</strong> magic; any expression can be used instead of <code>...</code>, e.g.:</p>
<pre><code>def will_do_something():
1
</code></pre>
<p>(Can't use the word âsanctionedâ, but I can say that this use was <a href="http://mail.python.org/pipermail/python-3000/2008-January/011793.html"><em>not outrightly rejected</em></a> by Guido.)</p>
| 73
|
2011-05-31T14:39:41Z
|
[
"python",
"ellipsis"
] |
What does the Python Ellipsis object do?
| 772,124
|
<p>While idly surfing the namespace I noticed an odd looking object called "<strong>Ellipsis</strong>", it does not seem to be or do anything special, but it's a globally available builtin. </p>
<p>After a search I found that it is used in some obscure variant of the slicing syntax by Numpy and Scipy... but almost nothing else. </p>
<p>Was this object added to the language specifically to support Numpy + Scipy? Does Ellipsis have any generic meaning or use at all?</p>
<pre><code>D:\workspace\numpy>python
Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> Ellipsis
Ellipsis
</code></pre>
| 196
|
2009-04-21T11:21:12Z
| 6,189,379
|
<p>You can also use the Ellipsis when specifying expected <a href="http://docs.python.org/library/doctest.html#doctest.ELLIPSIS">doctest</a> output:</p>
<pre><code>class MyClass(object):
"""Example of a doctest Ellipsis
>>> thing = MyClass()
>>> # Match <class '__main__.MyClass'> and <class '%(module).MyClass'>
>>> type(thing) # doctest:+ELLIPSIS
<class '....MyClass'>
"""
pass
</code></pre>
| 33
|
2011-05-31T14:47:58Z
|
[
"python",
"ellipsis"
] |
What does the Python Ellipsis object do?
| 772,124
|
<p>While idly surfing the namespace I noticed an odd looking object called "<strong>Ellipsis</strong>", it does not seem to be or do anything special, but it's a globally available builtin. </p>
<p>After a search I found that it is used in some obscure variant of the slicing syntax by Numpy and Scipy... but almost nothing else. </p>
<p>Was this object added to the language specifically to support Numpy + Scipy? Does Ellipsis have any generic meaning or use at all?</p>
<pre><code>D:\workspace\numpy>python
Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> Ellipsis
Ellipsis
</code></pre>
| 196
|
2009-04-21T11:21:12Z
| 17,763,893
|
<p>Its intended use shouldn't be only for these 3rd party modules. It isn't mentioned properly in the Python documentation (or maybe I just couldn't find that) but the <strong>ellipsis <code>...</code> is actually used in CPython</strong> in at least one place. </p>
<p>It is used for representing infinite data structures in Python. I came upon this notation while playing around with lists.</p>
<p>See <a href="http://stackoverflow.com/questions/17160162/what-is-in-python-2-7">this question</a> for more info.</p>
| 0
|
2013-07-20T15:42:41Z
|
[
"python",
"ellipsis"
] |
What does the Python Ellipsis object do?
| 772,124
|
<p>While idly surfing the namespace I noticed an odd looking object called "<strong>Ellipsis</strong>", it does not seem to be or do anything special, but it's a globally available builtin. </p>
<p>After a search I found that it is used in some obscure variant of the slicing syntax by Numpy and Scipy... but almost nothing else. </p>
<p>Was this object added to the language specifically to support Numpy + Scipy? Does Ellipsis have any generic meaning or use at all?</p>
<pre><code>D:\workspace\numpy>python
Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> Ellipsis
Ellipsis
</code></pre>
| 196
|
2009-04-21T11:21:12Z
| 33,087,462
|
<blockquote>
<p>What does the Python Ellipsis object do?</p>
</blockquote>
<p>Serves as a singleton class magic value that gets passed to <code>__getitem__</code> when you use the "magic-looking" <code>...</code> syntax.</p>
<p>The class can then do whatever it wants with it.</p>
<p>Example:</p>
<pre><code>class C(object):
def __getitem__(self, k):
return k
# Single argument is passed directly.
assert C()[0] == 0
# Multiple indices generate a tuple.
assert C()[0, 1] == (0, 1)
# Slice notation generates a slice object.
assert C()[1:2:3] == slice(1, 2, 3)
# Ellipsis notation generates an Ellipsis class object.
assert C()[...] == Ellipsis
</code></pre>
<p>The Python built-in <code>list</code> class chooses to give it the semantic of a range, and any sane usage of it should too of course.</p>
<p>Personally, I'd just stay away from it in my APIs, and create a separate, more explicit method instead.</p>
| 2
|
2015-10-12T18:03:20Z
|
[
"python",
"ellipsis"
] |
What does the Python Ellipsis object do?
| 772,124
|
<p>While idly surfing the namespace I noticed an odd looking object called "<strong>Ellipsis</strong>", it does not seem to be or do anything special, but it's a globally available builtin. </p>
<p>After a search I found that it is used in some obscure variant of the slicing syntax by Numpy and Scipy... but almost nothing else. </p>
<p>Was this object added to the language specifically to support Numpy + Scipy? Does Ellipsis have any generic meaning or use at all?</p>
<pre><code>D:\workspace\numpy>python
Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> Ellipsis
Ellipsis
</code></pre>
| 196
|
2009-04-21T11:21:12Z
| 37,499,388
|
<p>As of Python 3.5 and <a href="https://www.python.org/dev/peps/pep-0484/#callable">PEP484</a>, the literal ellipsis is used to denote certain types to a static type checker when using the <a href="https://docs.python.org/3/library/typing.html">typing</a> module.</p>
<p>Example 1:</p>
<blockquote>
<p>Arbitrary-length homogeneous tuples can be expressed using one type and ellipsis, for example <code>Tuple[int, ...]</code> </p>
</blockquote>
<p>Example 2:</p>
<blockquote>
<p>It is possible to declare the return type of a callable without specifying the call signature by substituting a literal ellipsis (three dots) for the list of arguments:</p>
</blockquote>
<pre><code>def partial(func: Callable[..., str], *args) -> Callable[..., str]:
# Body
</code></pre>
| 5
|
2016-05-28T13:08:47Z
|
[
"python",
"ellipsis"
] |
Django payment proccessing
| 772,240
|
<p>Can anyone suggest any good payment processing libraries for python/django?</p>
| 22
|
2009-04-21T12:05:31Z
| 772,311
|
<p>Perhaps you can find some usefull code hints/modules looking at Satchmo:
<a href="http://www.satchmoproject.com/" rel="nofollow">Satchmo Homepage</a></p>
| 2
|
2009-04-21T12:26:33Z
|
[
"python",
"django"
] |
Django payment proccessing
| 772,240
|
<p>Can anyone suggest any good payment processing libraries for python/django?</p>
| 22
|
2009-04-21T12:05:31Z
| 772,320
|
<p>The most developed Django solution is <a href="http://www.satchmoproject.com/docs/svn/">Satchmo</a> with support for Authorize.Net, TrustCommerce, CyberSource, PayPal, Google Checkout, and Protx.</p>
<p>The new kid on the Django block is <a href="http://code.google.com/p/django-lfs/">django-lfs</a> which looks like only support for PayPal at the moment, and even that may not be complete.</p>
<p>For general Python the main player is <a href="http://code.google.com/p/getpaid/">getpaid</a></p>
| 18
|
2009-04-21T12:28:12Z
|
[
"python",
"django"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.