title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
list |
|---|---|---|---|---|---|---|---|---|---|
How to include external Python code to use in other files?
| 714,881
|
<p>If you have a collection of methods in a file, is there a way to include those files in another file, but call them without any prefix (i.e. file prefix)?</p>
<p>So if I have:</p>
<pre><code>[Math.py]
def Calculate ( num )
</code></pre>
<p>How do I call it like this:</p>
<pre><code>[Tool.py]
using Math.py
for i in range ( 5 ) :
Calculate ( i )
</code></pre>
| 86
|
2009-04-03T17:21:58Z
| 714,890
|
<p>You will need to import the other file as a module like this:</p>
<pre><code>import Math
</code></pre>
<p>If you don't want to prefix your <code>Calculate</code> function with the module name then do this:</p>
<pre><code>from Math import Calculate
</code></pre>
<p>If you want to import all members of a module then do this:</p>
<pre><code>from Math import *
</code></pre>
<p><strong>Edit:</strong> <a href="http://www.diveintopython.net/object_oriented_framework/importing_modules.html">Here is a good chapter</a> from <a href="http://www.diveintopython.net/">Dive Into Python</a> that goes a bit more in depth on this topic.</p>
| 129
|
2009-04-03T17:24:28Z
|
[
"python"
] |
How to include external Python code to use in other files?
| 714,881
|
<p>If you have a collection of methods in a file, is there a way to include those files in another file, but call them without any prefix (i.e. file prefix)?</p>
<p>So if I have:</p>
<pre><code>[Math.py]
def Calculate ( num )
</code></pre>
<p>How do I call it like this:</p>
<pre><code>[Tool.py]
using Math.py
for i in range ( 5 ) :
Calculate ( i )
</code></pre>
| 86
|
2009-04-03T17:21:58Z
| 16,604,453
|
<p>Just write the "include" command : </p>
<pre><code>import os
def include(filename):
if os.path.exists(filename):
execfile(filename)
include('myfile.py')
</code></pre>
<p>@Deleet :</p>
<p>@bfieck remark is correct, for python 2 and 3 compatibility, you need either :</p>
<p>Python 2 and 3: alternative 1</p>
<pre><code>from past.builtins import execfile
execfile('myfile.py')
</code></pre>
<p>Python 2 and 3: alternative 2</p>
<pre><code>exec(compile(open('myfile.py').read()))
</code></pre>
| 32
|
2013-05-17T08:15:42Z
|
[
"python"
] |
How to include external Python code to use in other files?
| 714,881
|
<p>If you have a collection of methods in a file, is there a way to include those files in another file, but call them without any prefix (i.e. file prefix)?</p>
<p>So if I have:</p>
<pre><code>[Math.py]
def Calculate ( num )
</code></pre>
<p>How do I call it like this:</p>
<pre><code>[Tool.py]
using Math.py
for i in range ( 5 ) :
Calculate ( i )
</code></pre>
| 86
|
2009-04-03T17:21:58Z
| 19,918,123
|
<p>I've found the python inspect module to be very useful</p>
<p>For example with teststuff.py</p>
<pre><code>import inspect
def dostuff():
return __name__
DOSTUFF_SOURCE = inspect.getsource(dostuff)
if __name__ == "__main__":
dostuff()
</code></pre>
<p>And from the another script or the python console</p>
<pre><code>import teststuff
exec(DOSTUFF_SOURCE)
dostuff()
</code></pre>
<p>And now <strong>dostuff</strong> should be in the local scope and <strong>dostuff()</strong> will return the console or scripts <strong>_<em>name</em>_</strong> whereas executing test.dostuff() will return the python modules name.</p>
| 0
|
2013-11-11T23:34:50Z
|
[
"python"
] |
WeakValueDictionary for holding any type
| 715,125
|
<p>Is there any way to work around the limitations of WeakValueDictionary to allow it to hold weak references to built-in types like dict or list? Can something be done at the C level in an extension module? I really need a weakref container that can hold (nearly) any type of object.</p>
| 1
|
2009-04-03T18:34:46Z
| 715,212
|
<p>According to the <a href="http://docs.python.org/library/weakref.html" rel="nofollow">Python documentation</a> you can create weak references to subclasses of <code>dict</code> and <code>list</code>... it's not a perfect solution, but if you're able to create a custom subclass of <code>dict</code> and use that instead of a native <code>dict</code>, it should be good enough. (I've never actually done this myself)</p>
| 1
|
2009-04-03T19:01:08Z
|
[
"python"
] |
python dict update diff
| 715,234
|
<p>Does python have any sort of built in functionality of notifying what dictionary elements changed upon dict update? For example I am looking for some functionality like this:</p>
<pre><code>>>> a = {'a':'hamburger', 'b':'fries', 'c':'coke'}
>>> b = {'b':'fries', 'c':'pepsi', 'd':'ice cream'}
>>> a.diff(b)
{'c':'pepsi', 'd':'ice cream'}
>>> a.update(b)
>>> a
{'a':'hamburger', 'b':'fries', 'c':'pepsi', 'd':'ice cream'}
</code></pre>
<p>I am looking to get a dictionary of the changed values as shown in the result of a.diff(b) </p>
| 5
|
2009-04-03T19:04:34Z
| 715,267
|
<p>Not built in, but you could iterate on the keys of the dict and do comparisons. Could be slow though.</p>
<p>Better solution is probably to build a more complex datastructure and use a dictionary as the underlying representation.</p>
| 0
|
2009-04-03T19:13:30Z
|
[
"python",
"diff",
"dictionary"
] |
python dict update diff
| 715,234
|
<p>Does python have any sort of built in functionality of notifying what dictionary elements changed upon dict update? For example I am looking for some functionality like this:</p>
<pre><code>>>> a = {'a':'hamburger', 'b':'fries', 'c':'coke'}
>>> b = {'b':'fries', 'c':'pepsi', 'd':'ice cream'}
>>> a.diff(b)
{'c':'pepsi', 'd':'ice cream'}
>>> a.update(b)
>>> a
{'a':'hamburger', 'b':'fries', 'c':'pepsi', 'd':'ice cream'}
</code></pre>
<p>I am looking to get a dictionary of the changed values as shown in the result of a.diff(b) </p>
| 5
|
2009-04-03T19:04:34Z
| 715,268
|
<p>No, it doesn't. But it's not hard to write a dictionary diff function:</p>
<pre><code>def diff(a, b):
diff = {}
for key in b.keys():
if (not a.has_key(key)) or (a.has_key(key) and a[key] != b[key]):
diff[key] = b[key]
return diff
</code></pre>
| 2
|
2009-04-03T19:13:35Z
|
[
"python",
"diff",
"dictionary"
] |
python dict update diff
| 715,234
|
<p>Does python have any sort of built in functionality of notifying what dictionary elements changed upon dict update? For example I am looking for some functionality like this:</p>
<pre><code>>>> a = {'a':'hamburger', 'b':'fries', 'c':'coke'}
>>> b = {'b':'fries', 'c':'pepsi', 'd':'ice cream'}
>>> a.diff(b)
{'c':'pepsi', 'd':'ice cream'}
>>> a.update(b)
>>> a
{'a':'hamburger', 'b':'fries', 'c':'pepsi', 'd':'ice cream'}
</code></pre>
<p>I am looking to get a dictionary of the changed values as shown in the result of a.diff(b) </p>
| 5
|
2009-04-03T19:04:34Z
| 715,314
|
<p>No, but you can subclass dict to provide notification on change. </p>
<pre><code>class ObservableDict( dict ):
def __init__( self, *args, **kw ):
self.observers= []
super( ObservableDict, self ).__init__( *args, **kw )
def observe( self, observer ):
self.observers.append( observer )
def __setitem__( self, key, value ):
for o in self.observers:
o.notify( self, key, self[key], value )
super( ObservableDict, self ).__setitem__( key, value )
def update( self, anotherDict ):
for k in anotherDict:
self[k]= anotherDict[k]
class Watcher( object ):
def notify( self, observable, key, old, new ):
print "Change to ", observable, "at", key
w= Watcher()
a= ObservableDict( {'a':'hamburger', 'b':'fries', 'c':'coke'} )
a.observe( w )
b = {'b':'fries', 'c':'pepsi'}
a.update( b )
</code></pre>
<p>Note that the superclass Watcher defined here doesn't check to see if there was a "real" change or not; it simply notes that there was a change.</p>
| 10
|
2009-04-03T19:23:17Z
|
[
"python",
"diff",
"dictionary"
] |
python dict update diff
| 715,234
|
<p>Does python have any sort of built in functionality of notifying what dictionary elements changed upon dict update? For example I am looking for some functionality like this:</p>
<pre><code>>>> a = {'a':'hamburger', 'b':'fries', 'c':'coke'}
>>> b = {'b':'fries', 'c':'pepsi', 'd':'ice cream'}
>>> a.diff(b)
{'c':'pepsi', 'd':'ice cream'}
>>> a.update(b)
>>> a
{'a':'hamburger', 'b':'fries', 'c':'pepsi', 'd':'ice cream'}
</code></pre>
<p>I am looking to get a dictionary of the changed values as shown in the result of a.diff(b) </p>
| 5
|
2009-04-03T19:04:34Z
| 715,364
|
<pre><code>def diff_update(dict_to_update, updater):
changes=dict((k,updater[k]) for k in filter(lambda k:(k not in dict_to_update or updater[k] != dict_to_update[k]), updater.iterkeys()))
dict_to_update.update(updater)
return changes
a = {'a':'hamburger', 'b':'fries', 'c':'coke'}
b = {'b':'fries', 'c':'pepsi'}
>>> print diff_update(a, b)
{'c': 'pepsi'}
>>> print a
{'a': 'hamburger', 'c': 'pepsi', 'b': 'fries'}
</code></pre>
| 1
|
2009-04-03T19:33:08Z
|
[
"python",
"diff",
"dictionary"
] |
python dict update diff
| 715,234
|
<p>Does python have any sort of built in functionality of notifying what dictionary elements changed upon dict update? For example I am looking for some functionality like this:</p>
<pre><code>>>> a = {'a':'hamburger', 'b':'fries', 'c':'coke'}
>>> b = {'b':'fries', 'c':'pepsi', 'd':'ice cream'}
>>> a.diff(b)
{'c':'pepsi', 'd':'ice cream'}
>>> a.update(b)
>>> a
{'a':'hamburger', 'b':'fries', 'c':'pepsi', 'd':'ice cream'}
</code></pre>
<p>I am looking to get a dictionary of the changed values as shown in the result of a.diff(b) </p>
| 5
|
2009-04-03T19:04:34Z
| 715,366
|
<p>A simple diffing function is easy to write. Depending on how often you need it, it may be faster than the more elegant ObservableDict by S.Lott.</p>
<pre><code>def dict_diff(a, b):
"""Return differences from dictionaries a to b.
Return a tuple of three dicts: (removed, added, changed).
'removed' has all keys and values removed from a. 'added' has
all keys and values that were added to b. 'changed' has all
keys and their values in b that are different from the corresponding
key in a.
"""
removed = dict()
added = dict()
changed = dict()
for key, value in a.iteritems():
if key not in b:
removed[key] = value
elif b[key] != value:
changed[key] = b[key]
for key, value in b.iteritems():
if key not in a:
added[key] = value
return removed, added, changed
if __name__ == "__main__":
print dict_diff({'foo': 1, 'bar': 2, 'yo': 4 },
{'foo': 0, 'foobar': 3, 'yo': 4 })
</code></pre>
| 2
|
2009-04-03T19:33:22Z
|
[
"python",
"diff",
"dictionary"
] |
python dict update diff
| 715,234
|
<p>Does python have any sort of built in functionality of notifying what dictionary elements changed upon dict update? For example I am looking for some functionality like this:</p>
<pre><code>>>> a = {'a':'hamburger', 'b':'fries', 'c':'coke'}
>>> b = {'b':'fries', 'c':'pepsi', 'd':'ice cream'}
>>> a.diff(b)
{'c':'pepsi', 'd':'ice cream'}
>>> a.update(b)
>>> a
{'a':'hamburger', 'b':'fries', 'c':'pepsi', 'd':'ice cream'}
</code></pre>
<p>I am looking to get a dictionary of the changed values as shown in the result of a.diff(b) </p>
| 5
|
2009-04-03T19:04:34Z
| 2,904,335
|
<h2>one year later</h2>
<p>I like the following solution:</p>
<pre><code>>>> def dictdiff(d1, d2):
return dict(set(d2.iteritems()) - set(d1.iteritems()))
...
>>> a = {'a':'hamburger', 'b':'fries', 'c':'coke'}
>>> b = {'b':'fries', 'c':'pepsi', 'd':'ice cream'}
>>> dictdiff(a, b)
{'c': 'pepsi', 'd': 'ice cream'}
</code></pre>
| 7
|
2010-05-25T12:02:03Z
|
[
"python",
"diff",
"dictionary"
] |
How do I iterate over all lines of files passed on the command line?
| 715,277
|
<p>I usually do this in Perl:</p>
<p>whatever.pl</p>
<pre><code>while(<>) {
#do whatever;
}
</code></pre>
<p>then <code>cat foo.txt | whatever.pl</code></p>
<p>Now, I want to do this in Python. I tried <code>sys.stdin</code> but I have no idea how to do as I have done in Perl. How can I read the input?</p>
| 16
|
2009-04-03T19:15:37Z
| 715,282
|
<p>Try this:</p>
<pre><code>import fileinput
for line in fileinput.input():
process(line)
</code></pre>
| 35
|
2009-04-03T19:17:06Z
|
[
"python",
"stdin"
] |
How do I iterate over all lines of files passed on the command line?
| 715,277
|
<p>I usually do this in Perl:</p>
<p>whatever.pl</p>
<pre><code>while(<>) {
#do whatever;
}
</code></pre>
<p>then <code>cat foo.txt | whatever.pl</code></p>
<p>Now, I want to do this in Python. I tried <code>sys.stdin</code> but I have no idea how to do as I have done in Perl. How can I read the input?</p>
| 16
|
2009-04-03T19:15:37Z
| 715,300
|
<pre><code>import sys
def main():
for line in sys.stdin:
print line
if __name__=='__main__':
sys.exit(main())
</code></pre>
| 10
|
2009-04-03T19:19:50Z
|
[
"python",
"stdin"
] |
How do I iterate over all lines of files passed on the command line?
| 715,277
|
<p>I usually do this in Perl:</p>
<p>whatever.pl</p>
<pre><code>while(<>) {
#do whatever;
}
</code></pre>
<p>then <code>cat foo.txt | whatever.pl</code></p>
<p>Now, I want to do this in Python. I tried <code>sys.stdin</code> but I have no idea how to do as I have done in Perl. How can I read the input?</p>
| 16
|
2009-04-03T19:15:37Z
| 715,301
|
<p>Something like this:</p>
<pre><code>import sys
for line in sys.stdin:
# whatever
</code></pre>
| 5
|
2009-04-03T19:20:25Z
|
[
"python",
"stdin"
] |
How do I iterate over all lines of files passed on the command line?
| 715,277
|
<p>I usually do this in Perl:</p>
<p>whatever.pl</p>
<pre><code>while(<>) {
#do whatever;
}
</code></pre>
<p>then <code>cat foo.txt | whatever.pl</code></p>
<p>Now, I want to do this in Python. I tried <code>sys.stdin</code> but I have no idea how to do as I have done in Perl. How can I read the input?</p>
| 16
|
2009-04-03T19:15:37Z
| 715,305
|
<pre><code>import sys
for line in sys.stdin:
# do stuff w/line
</code></pre>
| 3
|
2009-04-03T19:20:46Z
|
[
"python",
"stdin"
] |
How do I iterate over all lines of files passed on the command line?
| 715,277
|
<p>I usually do this in Perl:</p>
<p>whatever.pl</p>
<pre><code>while(<>) {
#do whatever;
}
</code></pre>
<p>then <code>cat foo.txt | whatever.pl</code></p>
<p>Now, I want to do this in Python. I tried <code>sys.stdin</code> but I have no idea how to do as I have done in Perl. How can I read the input?</p>
| 16
|
2009-04-03T19:15:37Z
| 715,327
|
<p>You may find a <a href="http://en.wikipedia.org/wiki/Rosetta%5Fstone" rel="nofollow">Rosetta Stone</a> helpful. I tend to use <a href="http://www.lurklurk.org/rosetta.html" rel="nofollow">http://www.lurklurk.org/rosetta.html</a>.</p>
| 2
|
2009-04-03T19:25:45Z
|
[
"python",
"stdin"
] |
How can I print entity numbers in my xml document instead of entity names using python's lxml?
| 715,304
|
<p>I'm using lxml and python to generate xml documents (just using etree.tostring(root) ) but at the moment the resulting xml displays html entities as with named entities ( &lt ; ) rather than their numeric values ( &#60 ; ). How exactly do I go about changing this so that the result uses the numeric values instead of the names?</p>
<p>Thanks</p>
| 4
|
2009-04-03T19:20:45Z
| 715,859
|
<p>Ultimately, it looks like the python code will call <a href="http://www.opensource.apple.com/darwinsource/WWDC2003/libxml2-3/libxml2/doc/html/libxml-tree.html#XMLNODEDUMPOUTPUT" rel="nofollow">xmlNodeDumpOutput</a> in the libxml2 library.</p>
<p>Unfortunately, it doesn't look like there is any way to configure this to control how such entities are represented. Looking at entities.c in xmlEncodeEntitiesReentrant, the < > and & characters are hardcoded to always use the appropriate XML entity, so there seems no way to force it to use numeric values.</p>
<p>If you need this, you'll probably have to perform another pass on the string, and manually perform "<code>outputString.replace("&lt;","&#60;")</code>" for those characters.</p>
| 2
|
2009-04-03T21:50:14Z
|
[
"python",
"xml",
"lxml"
] |
Converting from a string to boolean in Python?
| 715,417
|
<p>Does anyone know how to do convert from a string to a boolean in Python? I found <a href="http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/">this link</a>. But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc.</p>
<p>EDIT: The reason I asked this is because I learned int("string"), from here. I tried bool ("string") but always got True.</p>
| 258
|
2009-04-03T19:44:20Z
| 715,455
|
<p>Really, you just compare the string to whatever you expect to accept as representing true, so you can do this:</p>
<pre><code>s == 'True'
</code></pre>
<p>Or to checks against a whole bunch of values:</p>
<pre><code>s in ['true', '1', 't', 'y', 'yes', 'yeah', 'yup', 'certainly', 'uh-huh']
</code></pre>
<p>Be cautious when using the following:</p>
<pre><code>>>> bool("foo")
True
>>> bool("")
False
</code></pre>
<p>Empty strings evaluate to <code>False</code>, but everything else evaluates to <code>True</code>. So this should not be used for any kind of parsing purposes.</p>
| 361
|
2009-04-03T19:52:56Z
|
[
"python",
"string"
] |
Converting from a string to boolean in Python?
| 715,417
|
<p>Does anyone know how to do convert from a string to a boolean in Python? I found <a href="http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/">this link</a>. But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc.</p>
<p>EDIT: The reason I asked this is because I learned int("string"), from here. I tried bool ("string") but always got True.</p>
| 258
|
2009-04-03T19:44:20Z
| 715,458
|
<p>you could always do something like </p>
<pre><code>myString = "false"
val = (myString == "true")
</code></pre>
<p>the bit in parens would evaluate to False. This is just another way to do it without having to do an actual function call.</p>
| 6
|
2009-04-03T19:53:23Z
|
[
"python",
"string"
] |
Converting from a string to boolean in Python?
| 715,417
|
<p>Does anyone know how to do convert from a string to a boolean in Python? I found <a href="http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/">this link</a>. But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc.</p>
<p>EDIT: The reason I asked this is because I learned int("string"), from here. I tried bool ("string") but always got True.</p>
| 258
|
2009-04-03T19:44:20Z
| 715,468
|
<pre><code>def str2bool(v):
return v.lower() in ("yes", "true", "t", "1")
</code></pre>
<p>Then call it like so:</p>
<pre><code>str2bool("yes")
</code></pre>
<p><code>> True</code></p>
<pre><code>str2bool("no")
</code></pre>
<p><code>> False</code></p>
<pre><code>str2bool("stuff")
</code></pre>
<p><code>> False</code></p>
<pre><code>str2bool("1")
</code></pre>
<p><code>> True</code></p>
<pre><code>str2bool("0")
</code></pre>
<p><code>> False</code></p>
<hr>
<p><strong>Handling true and false explicitly:</strong></p>
<p>You could also make your function explicitly check against a True list of words and a False list of words. Then if it is in neither list, you could throw an exception. </p>
| 152
|
2009-04-03T19:56:44Z
|
[
"python",
"string"
] |
Converting from a string to boolean in Python?
| 715,417
|
<p>Does anyone know how to do convert from a string to a boolean in Python? I found <a href="http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/">this link</a>. But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc.</p>
<p>EDIT: The reason I asked this is because I learned int("string"), from here. I tried bool ("string") but always got True.</p>
| 258
|
2009-04-03T19:44:20Z
| 922,374
|
<p>Starting with Python 2.6, there is now <code>ast.literal_eval</code>:</p>
<pre>
>>> import ast
>>> help(ast.literal_eval)
Help on function literal_eval in module ast:
literal_eval(node_or_string)
Safely evaluate an expression node or a string containing a Python
expression. The string or node provided may only consist of the following
Python literal structures: strings, numbers, tuples, lists, dicts, booleans,
and None.
</pre>
<p>Which seems to work, as long as you're <strong>sure</strong> your strings are going to be either <code>"True"</code> or <code>"False"</code>:</p>
<pre>
>>> ast.literal_eval("True")
True
>>> ast.literal_eval("False")
False
>>> ast.literal_eval("F")
Traceback (most recent call last):
File "", line 1, in
File "/opt/Python-2.6.1/lib/python2.6/ast.py", line 68, in literal_eval
return _convert(node_or_string)
File "/opt/Python-2.6.1/lib/python2.6/ast.py", line 67, in _convert
raise ValueError('malformed string')
ValueError: malformed string
>>> ast.literal_eval("'False'")
'False'
</pre>
<p>I wouldn't normally recommend this, but it is completely built-in and could be the right thing depending on your requirements.</p>
| 77
|
2009-05-28T18:06:39Z
|
[
"python",
"string"
] |
Converting from a string to boolean in Python?
| 715,417
|
<p>Does anyone know how to do convert from a string to a boolean in Python? I found <a href="http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/">this link</a>. But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc.</p>
<p>EDIT: The reason I asked this is because I learned int("string"), from here. I tried bool ("string") but always got True.</p>
| 258
|
2009-04-03T19:44:20Z
| 1,114,606
|
<p>The usual rule for casting to a bool is that a few special literals (<code>False</code>, <code>0</code>, <code>0.0</code>, <code>()</code>, <code>[]</code>, <code>{}</code>) are false and then everything else is true, so I recommend the following:</p>
<pre><code>def boolify(val):
if (isinstance(val, basestring) and bool(val)):
return not val in ('False', '0', '0.0')
else:
return bool(val)
</code></pre>
| 3
|
2009-07-11T20:45:35Z
|
[
"python",
"string"
] |
Converting from a string to boolean in Python?
| 715,417
|
<p>Does anyone know how to do convert from a string to a boolean in Python? I found <a href="http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/">this link</a>. But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc.</p>
<p>EDIT: The reason I asked this is because I learned int("string"), from here. I tried bool ("string") but always got True.</p>
| 258
|
2009-04-03T19:44:20Z
| 1,114,688
|
<p>here's a hairy, built in way to get many of the same answers. Note that although python considers <code>""</code> to be false and all other strings to be true, TCL has a very different idea about things. </p>
<pre><code>>>> import Tkinter
>>> tk = Tkinter.Tk()
>>> var = Tkinter.BooleanVar(tk)
>>> var.set("false")
>>> var.get()
False
>>> var.set("1")
>>> var.get()
True
>>> var.set("[exec 'rm -r /']")
>>> var.get()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.5/lib-tk/Tkinter.py", line 324, in get
return self._tk.getboolean(self._tk.globalgetvar(self._name))
_tkinter.TclError: 0expected boolean value but got "[exec 'rm -r /']"
>>>
</code></pre>
<p>A good thing about this is that it is fairly forgiving about the values you can use. It's lazy about turning strings into values, and it's hygenic about what it accepts and rejects(notice that if the above statement were given at a tcl prompt, it would erase the users hard disk). </p>
<p>the bad thing is that it requires that Tkinter be available, which is usually, but not universally true, and more significantly, requires that a Tk instance be created, which is comparatively heavy. </p>
<p>What is considered true or false depends on the behavior of the <code>Tcl_GetBoolean</code>, which considers <strong><code>0</code></strong>, <strong><code>false</code></strong>, <strong><code>no</code></strong> and <strong><code>off</code></strong> to be false and <strong><code>1</code></strong>, <strong><code>true</code></strong>, <strong><code>yes</code></strong> and <strong><code>on</code></strong> to be true, case insensitive. Any other string, including the empty string, cause an exception.</p>
| 0
|
2009-07-11T21:31:45Z
|
[
"python",
"string"
] |
Converting from a string to boolean in Python?
| 715,417
|
<p>Does anyone know how to do convert from a string to a boolean in Python? I found <a href="http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/">this link</a>. But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc.</p>
<p>EDIT: The reason I asked this is because I learned int("string"), from here. I tried bool ("string") but always got True.</p>
| 258
|
2009-04-03T19:44:20Z
| 2,073,768
|
<p>You probably already have a solution but for others who are looking for a method to convert a value to a boolean value using "standard" false values including None, [], {}, and "" in addition to false, no , and 0.</p>
<pre><code>def toBoolean( val ):
"""
Get the boolean value of the provided input.
If the value is a boolean return the value.
Otherwise check to see if the value is in
["false", "f", "no", "n", "none", "0", "[]", "{}", "" ]
and returns True if value is not in the list
"""
if val is True or val is False:
return val
falseItems = ["false", "f", "no", "n", "none", "0", "[]", "{}", "" ]
return not str( val ).strip().lower() in falseItems
</code></pre>
| 4
|
2010-01-15T18:13:01Z
|
[
"python",
"string"
] |
Converting from a string to boolean in Python?
| 715,417
|
<p>Does anyone know how to do convert from a string to a boolean in Python? I found <a href="http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/">this link</a>. But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc.</p>
<p>EDIT: The reason I asked this is because I learned int("string"), from here. I tried bool ("string") but always got True.</p>
| 258
|
2009-04-03T19:44:20Z
| 2,736,717
|
<pre><code>def str2bool(str):
if isinstance(str, basestring) and str.lower() in ['0','false','no']:
return False
else:
return bool(str)
</code></pre>
<p>idea: check if you want the string to be evaluated to False; otherwise bool() returns True for any non-empty string.</p>
| 0
|
2010-04-29T11:01:15Z
|
[
"python",
"string"
] |
Converting from a string to boolean in Python?
| 715,417
|
<p>Does anyone know how to do convert from a string to a boolean in Python? I found <a href="http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/">this link</a>. But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc.</p>
<p>EDIT: The reason I asked this is because I learned int("string"), from here. I tried bool ("string") but always got True.</p>
| 258
|
2009-04-03T19:44:20Z
| 9,051,825
|
<p>Here's something I threw together to evaluate the truthiness of a string:</p>
<pre><code>def as_bool(val):
if val:
try:
if not int(val): val=False
except: pass
try:
if val.lower()=="false": val=False
except: pass
return bool(val)
</code></pre>
<p>more-or-less same results as using <code>eval</code> but safer.</p>
| 0
|
2012-01-29T08:09:54Z
|
[
"python",
"string"
] |
Converting from a string to boolean in Python?
| 715,417
|
<p>Does anyone know how to do convert from a string to a boolean in Python? I found <a href="http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/">this link</a>. But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc.</p>
<p>EDIT: The reason I asked this is because I learned int("string"), from here. I tried bool ("string") but always got True.</p>
| 258
|
2009-04-03T19:44:20Z
| 9,333,816
|
<p>Here's is my version. It checks against both positive and negative values lists, raising an exception for unknown values. And it does not receive a string, but any type should do.</p>
<pre><code>def to_bool(value):
"""
Converts 'something' to boolean. Raises exception for invalid formats
Possible True values: 1, True, "1", "TRue", "yes", "y", "t"
Possible False values: 0, False, None, [], {}, "", "0", "faLse", "no", "n", "f", 0.0, ...
"""
if str(value).lower() in ("yes", "y", "true", "t", "1"): return True
if str(value).lower() in ("no", "n", "false", "f", "0", "0.0", "", "none", "[]", "{}"): return False
raise Exception('Invalid value for boolean conversion: ' + str(value))
</code></pre>
<p>Sample runs:</p>
<pre><code>>>> to_bool(True)
True
>>> to_bool("tRUe")
True
>>> to_bool("1")
True
>>> to_bool(1)
True
>>> to_bool(2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 9, in to_bool
Exception: Invalid value for boolean conversion: 2
>>> to_bool([])
False
>>> to_bool({})
False
>>> to_bool(None)
False
>>> to_bool("Wasssaaaaa")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 9, in to_bool
Exception: Invalid value for boolean conversion: Wasssaaaaa
>>>
</code></pre>
| 11
|
2012-02-17T18:57:43Z
|
[
"python",
"string"
] |
Converting from a string to boolean in Python?
| 715,417
|
<p>Does anyone know how to do convert from a string to a boolean in Python? I found <a href="http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/">this link</a>. But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc.</p>
<p>EDIT: The reason I asked this is because I learned int("string"), from here. I tried bool ("string") but always got True.</p>
| 258
|
2009-04-03T19:44:20Z
| 9,742,086
|
<p>A dict (really, a defaultdict) gives you a pretty easy way to do this trick:</p>
<pre><code>from collections import defaultdict
bool_mapping = defaultdict(bool) # Will give you False for non-found values
for val in ['True', 'yes', ...]:
bool_mapping[val] = True
print(bool_mapping['True']) # True
print(bool_mapping['kitten']) # False
</code></pre>
<p>It's really easy to tailor this method to the exact conversion behavior you want -- you can fill it with allowed Truthy and Falsy values and let it raise an exception (or return None) when a value isn't found, or default to True, or default to False, or whatever you want.</p>
| 5
|
2012-03-16T17:47:14Z
|
[
"python",
"string"
] |
Converting from a string to boolean in Python?
| 715,417
|
<p>Does anyone know how to do convert from a string to a boolean in Python? I found <a href="http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/">this link</a>. But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc.</p>
<p>EDIT: The reason I asked this is because I learned int("string"), from here. I tried bool ("string") but always got True.</p>
| 258
|
2009-04-03T19:44:20Z
| 10,587,945
|
<p>This is the version I wrote. Combines several of the other solutions into one.</p>
<pre><code>def to_bool(value):
"""
Converts 'something' to boolean. Raises exception if it gets a string it doesn't handle.
Case is ignored for strings. These string values are handled:
True: 'True', "1", "TRue", "yes", "y", "t"
False: "", "0", "faLse", "no", "n", "f"
Non-string values are passed to bool.
"""
if type(value) == type(''):
if value.lower() in ("yes", "y", "true", "t", "1"):
return True
if value.lower() in ("no", "n", "false", "f", "0", ""):
return False
raise Exception('Invalid value for boolean conversion: ' + value)
return bool(value)
</code></pre>
<p>If it gets a string it expects specific values, otherwise raises an Exception. If it doesn't get a string, just lets the bool constructor figure it out. Tested these cases:</p>
<pre><code>test_cases = [
('true', True),
('t', True),
('yes', True),
('y', True),
('1', True),
('false', False),
('f', False),
('no', False),
('n', False),
('0', False),
('', False),
(1, True),
(0, False),
(1.0, True),
(0.0, False),
([], False),
({}, False),
((), False),
([1], True),
({1:2}, True),
((1,), True),
(None, False),
(object(), True),
]
</code></pre>
| 3
|
2012-05-14T17:07:45Z
|
[
"python",
"string"
] |
Converting from a string to boolean in Python?
| 715,417
|
<p>Does anyone know how to do convert from a string to a boolean in Python? I found <a href="http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/">this link</a>. But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc.</p>
<p>EDIT: The reason I asked this is because I learned int("string"), from here. I tried bool ("string") but always got True.</p>
| 258
|
2009-04-03T19:44:20Z
| 11,759,968
|
<p>I like to use the ternary operator for this, since it's a bit more succinct for something that feels like it shouldn't be more than 1 line.</p>
<pre><code>True if myString=="True" else False
</code></pre>
| 2
|
2012-08-01T13:07:39Z
|
[
"python",
"string"
] |
Converting from a string to boolean in Python?
| 715,417
|
<p>Does anyone know how to do convert from a string to a boolean in Python? I found <a href="http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/">this link</a>. But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc.</p>
<p>EDIT: The reason I asked this is because I learned int("string"), from here. I tried bool ("string") but always got True.</p>
| 258
|
2009-04-03T19:44:20Z
| 13,562,496
|
<p>I don't agree with any solution here, as they are too permissive. This is not normally what you want when parsing a string.</p>
<p>So here the solution I'm using:</p>
<pre><code>def to_bool(bool_str):
"""Parse the string and return the boolean value encoded or raise an exception"""
if isinstance(bool_str, basestring) and bool_str:
if bool_str.lower() in ['true', 't', '1']: return True
elif bool_str.lower() in ['false', 'f', '0']: return False
#if here we couldn't parse it
raise ValueError("%s is no recognized as a boolean value" % bool_str)
</code></pre>
<p>And the results:</p>
<pre><code>>>> [to_bool(v) for v in ['true','t','1','F','FALSE','0']]
[True, True, True, False, False, False]
>>> to_bool("")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 8, in to_bool
ValueError: '' is no recognized as a boolean value
</code></pre>
<p>Just to be clear because it looks as if my answer offended somebody somehow:</p>
<p>The point is that you don't want to test for only one value and assume the other. I don't think you always want to map Absolutely everything to the non parsed value. That produces error prone code.</p>
<p>So, if you know what you want code it in.</p>
| 6
|
2012-11-26T10:04:22Z
|
[
"python",
"string"
] |
Converting from a string to boolean in Python?
| 715,417
|
<p>Does anyone know how to do convert from a string to a boolean in Python? I found <a href="http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/">this link</a>. But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc.</p>
<p>EDIT: The reason I asked this is because I learned int("string"), from here. I tried bool ("string") but always got True.</p>
| 258
|
2009-04-03T19:44:20Z
| 13,706,457
|
<p>The JSON parser is also useful for in general converting strings to reasonable python types.</p>
<pre><code>>>> import json
>>> json.loads("false")
False
>>> json.loads("true")
True
</code></pre>
| 35
|
2012-12-04T15:38:14Z
|
[
"python",
"string"
] |
Converting from a string to boolean in Python?
| 715,417
|
<p>Does anyone know how to do convert from a string to a boolean in Python? I found <a href="http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/">this link</a>. But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc.</p>
<p>EDIT: The reason I asked this is because I learned int("string"), from here. I tried bool ("string") but always got True.</p>
| 258
|
2009-04-03T19:44:20Z
| 14,946,382
|
<p>A cool, simple trick (based on what @Alan Marchiori posted), but using yaml:</p>
<pre><code>import yaml
parsed = yaml.load("true")
print bool(parsed)
</code></pre>
<p>If this is too wide, it can be refined by testing the type result. If the yaml-returned type is a str, then it can't be cast to any other type (that I can think of anyway), so you could handle that separately, or just let it be true.</p>
<p>I won't make any guesses at speed, but since I am working with yaml data under Qt gui anyway, this has a nice symmetry.</p>
| 2
|
2013-02-18T22:21:51Z
|
[
"python",
"string"
] |
Converting from a string to boolean in Python?
| 715,417
|
<p>Does anyone know how to do convert from a string to a boolean in Python? I found <a href="http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/">this link</a>. But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc.</p>
<p>EDIT: The reason I asked this is because I learned int("string"), from here. I tried bool ("string") but always got True.</p>
| 258
|
2009-04-03T19:44:20Z
| 18,156,046
|
<p>I realize this is an old post, but some of the solutions require quite a bit of code, here's what I ended up using:</p>
<pre><code>def str2bool(value):
return {"True": True, "true": True}.get(value, False)
</code></pre>
| 2
|
2013-08-09T21:37:50Z
|
[
"python",
"string"
] |
Converting from a string to boolean in Python?
| 715,417
|
<p>Does anyone know how to do convert from a string to a boolean in Python? I found <a href="http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/">this link</a>. But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc.</p>
<p>EDIT: The reason I asked this is because I learned int("string"), from here. I tried bool ("string") but always got True.</p>
| 258
|
2009-04-03T19:44:20Z
| 18,472,142
|
<p>Just use:</p>
<pre><code>distutils.util.strtobool(some_string)
</code></pre>
<p><a href="http://docs.python.org/2/distutils/apiref.html?highlight=distutils.util#distutils.util.strtobool">http://docs.python.org/2/distutils/apiref.html?highlight=distutils.util#distutils.util.strtobool</a></p>
<blockquote>
<p>True values are y, yes, t, true, on and 1; false values are n, no, f, false, off and 0. Raises ValueError if val is anything else.</p>
</blockquote>
| 81
|
2013-08-27T17:42:22Z
|
[
"python",
"string"
] |
Converting from a string to boolean in Python?
| 715,417
|
<p>Does anyone know how to do convert from a string to a boolean in Python? I found <a href="http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/">this link</a>. But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc.</p>
<p>EDIT: The reason I asked this is because I learned int("string"), from here. I tried bool ("string") but always got True.</p>
| 258
|
2009-04-03T19:44:20Z
| 19,015,368
|
<p>This version keeps the semantics of constructors like int(value) and provides an easy way to define acceptable string values.</p>
<pre><code>def to_bool(value):
valid = {'true': True, 't': True, '1': True,
'false': False, 'f': False, '0': False,
}
if isinstance(value, bool):
return value
if not isinstance(value, basestring):
raise ValueError('invalid literal for boolean. Not a string.')
lower_value = value.lower()
if lower_value in valid:
return valid[lower_value]
else:
raise ValueError('invalid literal for boolean: "%s"' % value)
# Test cases
assert to_bool('true'), '"true" is True'
assert to_bool('True'), '"True" is True'
assert to_bool('TRue'), '"TRue" is True'
assert to_bool('TRUE'), '"TRUE" is True'
assert to_bool('T'), '"T" is True'
assert to_bool('t'), '"t" is True'
assert to_bool('1'), '"1" is True'
assert to_bool(True), 'True is True'
assert to_bool(u'true'), 'unicode "true" is True'
assert to_bool('false') is False, '"false" is False'
assert to_bool('False') is False, '"False" is False'
assert to_bool('FAlse') is False, '"FAlse" is False'
assert to_bool('FALSE') is False, '"FALSE" is False'
assert to_bool('F') is False, '"F" is False'
assert to_bool('f') is False, '"f" is False'
assert to_bool('0') is False, '"0" is False'
assert to_bool(False) is False, 'False is False'
assert to_bool(u'false') is False, 'unicode "false" is False'
# Expect ValueError to be raised for invalid parameter...
try:
to_bool('')
to_bool(12)
to_bool([])
to_bool('yes')
to_bool('FOObar')
except ValueError, e:
pass
</code></pre>
| 9
|
2013-09-25T21:16:55Z
|
[
"python",
"string"
] |
Converting from a string to boolean in Python?
| 715,417
|
<p>Does anyone know how to do convert from a string to a boolean in Python? I found <a href="http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/">this link</a>. But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc.</p>
<p>EDIT: The reason I asked this is because I learned int("string"), from here. I tried bool ("string") but always got True.</p>
| 258
|
2009-04-03T19:44:20Z
| 25,242,187
|
<p>You can simply use the built-in function <a href="https://docs.python.org/2/library/functions.html#eval">eval()</a>:</p>
<pre><code>a='True'
if a is True:
print 'a is True, a type is', type(a)
else:
print "a isn't True, a type is", type(a)
b = eval(a)
if b is True:
print 'b is True, b type is', type(b)
else:
print "b isn't True, b type is", type(b)
</code></pre>
<p>and the output:</p>
<pre><code>a isn't True, a type is <type 'str'>
b is True, b type is <type 'bool'>
</code></pre>
| 8
|
2014-08-11T11:27:49Z
|
[
"python",
"string"
] |
Converting from a string to boolean in Python?
| 715,417
|
<p>Does anyone know how to do convert from a string to a boolean in Python? I found <a href="http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/">this link</a>. But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc.</p>
<p>EDIT: The reason I asked this is because I learned int("string"), from here. I tried bool ("string") but always got True.</p>
| 258
|
2009-04-03T19:44:20Z
| 36,185,083
|
<p>If you know that your input will be either "True" or "False" then why not use:</p>
<pre><code>def bool_convert(s):
return s == "True" if s else False
</code></pre>
| 0
|
2016-03-23T17:39:39Z
|
[
"python",
"string"
] |
How can I talk to UniProt over HTTP in Python?
| 715,538
|
<p>I'm trying to get some results from UniProt, which is a protein database (details are not important). I'm trying to use some script that translates from one kind of ID to another. I was able to do this manually on the browser, but could not do it in Python. </p>
<p>In <a href="http://www.uniprot.org/faq/28" rel="nofollow">http://www.uniprot.org/faq/28</a> there are some sample scripts. I tried the Perl one and it seems to work, so the problem is my Python attempts. The (working) script is:</p>
<pre><code>## tool_example.pl ##
use strict;
use warnings;
use LWP::UserAgent;
my $base = 'http://www.uniprot.org';
my $tool = 'mapping';
my $params = {
from => 'ACC', to => 'P_REFSEQ_AC', format => 'tab',
query => 'P13368 P20806 Q9UM73 P97793 Q17192'
};
my $agent = LWP::UserAgent->new;
push @{$agent->requests_redirectable}, 'POST';
print STDERR "Submitting...\n";
my $response = $agent->post("$base/$tool/", $params);
while (my $wait = $response->header('Retry-After')) {
print STDERR "Waiting ($wait)...\n";
sleep $wait;
print STDERR "Checking...\n";
$response = $agent->get($response->base);
}
$response->is_success ?
print $response->content :
die 'Failed, got ' . $response->status_line .
' for ' . $response->request->uri . "\n";
</code></pre>
<p>My questions are:</p>
<p>1) How would you do that in Python?</p>
<p>2) Will I be able to massively "scale" that (i.e., use a lot of entries in the query field)?</p>
| 4
|
2009-04-03T20:11:22Z
| 715,610
|
<p><strong>question #1:</strong></p>
<p>This can be done using python's urllibs:</p>
<pre><code>import urllib, urllib2
import time
import sys
query = ' '.join(sys.argv)
# encode params as a list of 2-tuples
params = ( ('from','ACC'), ('to', 'P_REFSEQ_AC'), ('format','tab'), ('query', query))
# url encode them
data = urllib.urlencode(params)
url = 'http://www.uniprot.org/mapping/'
# fetch the data
try:
foo = urllib2.urlopen(url, data)
except urllib2.HttpError, e:
if e.code == 503:
# blah blah get the value of the header...
wait_time = int(e.hdrs.get('Retry-after', 0))
print 'Sleeping %i seconds...' % (wait_time,)
time.sleep(wait_time)
foo = urllib2.urlopen(url, data)
# foo is a file-like object, do with it what you will.
foo.read()
</code></pre>
| 6
|
2009-04-03T20:28:44Z
|
[
"python",
"http",
"user-agent",
"bioinformatics"
] |
How can I talk to UniProt over HTTP in Python?
| 715,538
|
<p>I'm trying to get some results from UniProt, which is a protein database (details are not important). I'm trying to use some script that translates from one kind of ID to another. I was able to do this manually on the browser, but could not do it in Python. </p>
<p>In <a href="http://www.uniprot.org/faq/28" rel="nofollow">http://www.uniprot.org/faq/28</a> there are some sample scripts. I tried the Perl one and it seems to work, so the problem is my Python attempts. The (working) script is:</p>
<pre><code>## tool_example.pl ##
use strict;
use warnings;
use LWP::UserAgent;
my $base = 'http://www.uniprot.org';
my $tool = 'mapping';
my $params = {
from => 'ACC', to => 'P_REFSEQ_AC', format => 'tab',
query => 'P13368 P20806 Q9UM73 P97793 Q17192'
};
my $agent = LWP::UserAgent->new;
push @{$agent->requests_redirectable}, 'POST';
print STDERR "Submitting...\n";
my $response = $agent->post("$base/$tool/", $params);
while (my $wait = $response->header('Retry-After')) {
print STDERR "Waiting ($wait)...\n";
sleep $wait;
print STDERR "Checking...\n";
$response = $agent->get($response->base);
}
$response->is_success ?
print $response->content :
die 'Failed, got ' . $response->status_line .
' for ' . $response->request->uri . "\n";
</code></pre>
<p>My questions are:</p>
<p>1) How would you do that in Python?</p>
<p>2) Will I be able to massively "scale" that (i.e., use a lot of entries in the query field)?</p>
| 4
|
2009-04-03T20:11:22Z
| 715,683
|
<p>Let's assume that you are using Python 2.5.
We can use <a href="http://docs.python.org/library/httplib.html?highlight=httplib#module-httplib" rel="nofollow">httplib</a> to directly call the web site:</p>
<pre><code>import httplib, urllib
querystring = {}
#Build the query string here from the following keys (query, format, columns, compress, limit, offset)
querystring["query"] = ""
querystring["format"] = "" # one of html | tab | fasta | gff | txt | xml | rdf | rss | list
querystring["columns"] = "" # the columns you want comma seperated
querystring["compress"] = "" # yes or no
## These may be optional
querystring["limit"] = "" # I guess if you only want a few rows
querystring["offset"] = "" # bring on paging
##From the examples - query=organism:9606+AND+antigen&format=xml&compress=no
##Delete the following and replace with your query
querystring = {}
querystring["query"] = "organism:9606 AND antigen"
querystring["format"] = "xml" #make it human readable
querystring["compress"] = "no" #I don't want to have to unzip
conn = httplib.HTTPConnection("www.uniprot.org")
conn.request("GET", "/uniprot/?"+ urllib.urlencode(querystring))
r1 = conn.getresponse()
if r1.status == 200:
data1 = r1.read()
print data1 #or do something with it
</code></pre>
<p>You could then make a function around creating the query string and you should be away.</p>
| 1
|
2009-04-03T20:49:38Z
|
[
"python",
"http",
"user-agent",
"bioinformatics"
] |
How can I talk to UniProt over HTTP in Python?
| 715,538
|
<p>I'm trying to get some results from UniProt, which is a protein database (details are not important). I'm trying to use some script that translates from one kind of ID to another. I was able to do this manually on the browser, but could not do it in Python. </p>
<p>In <a href="http://www.uniprot.org/faq/28" rel="nofollow">http://www.uniprot.org/faq/28</a> there are some sample scripts. I tried the Perl one and it seems to work, so the problem is my Python attempts. The (working) script is:</p>
<pre><code>## tool_example.pl ##
use strict;
use warnings;
use LWP::UserAgent;
my $base = 'http://www.uniprot.org';
my $tool = 'mapping';
my $params = {
from => 'ACC', to => 'P_REFSEQ_AC', format => 'tab',
query => 'P13368 P20806 Q9UM73 P97793 Q17192'
};
my $agent = LWP::UserAgent->new;
push @{$agent->requests_redirectable}, 'POST';
print STDERR "Submitting...\n";
my $response = $agent->post("$base/$tool/", $params);
while (my $wait = $response->header('Retry-After')) {
print STDERR "Waiting ($wait)...\n";
sleep $wait;
print STDERR "Checking...\n";
$response = $agent->get($response->base);
}
$response->is_success ?
print $response->content :
die 'Failed, got ' . $response->status_line .
' for ' . $response->request->uri . "\n";
</code></pre>
<p>My questions are:</p>
<p>1) How would you do that in Python?</p>
<p>2) Will I be able to massively "scale" that (i.e., use a lot of entries in the query field)?</p>
| 4
|
2009-04-03T20:11:22Z
| 1,393,345
|
<p>You're probably better off using the Protein Identifier Cross Reference service from the EBI to convert one set of IDs to another. It has a very good REST interface.</p>
<p><a href="http://www.ebi.ac.uk/Tools/picr/" rel="nofollow">http://www.ebi.ac.uk/Tools/picr/</a></p>
<p>I should also mention that UniProt has very good webservices available. Though if you are tied to using simple http requests for some reason then its probably not useful.</p>
| 1
|
2009-09-08T11:00:26Z
|
[
"python",
"http",
"user-agent",
"bioinformatics"
] |
How can I talk to UniProt over HTTP in Python?
| 715,538
|
<p>I'm trying to get some results from UniProt, which is a protein database (details are not important). I'm trying to use some script that translates from one kind of ID to another. I was able to do this manually on the browser, but could not do it in Python. </p>
<p>In <a href="http://www.uniprot.org/faq/28" rel="nofollow">http://www.uniprot.org/faq/28</a> there are some sample scripts. I tried the Perl one and it seems to work, so the problem is my Python attempts. The (working) script is:</p>
<pre><code>## tool_example.pl ##
use strict;
use warnings;
use LWP::UserAgent;
my $base = 'http://www.uniprot.org';
my $tool = 'mapping';
my $params = {
from => 'ACC', to => 'P_REFSEQ_AC', format => 'tab',
query => 'P13368 P20806 Q9UM73 P97793 Q17192'
};
my $agent = LWP::UserAgent->new;
push @{$agent->requests_redirectable}, 'POST';
print STDERR "Submitting...\n";
my $response = $agent->post("$base/$tool/", $params);
while (my $wait = $response->header('Retry-After')) {
print STDERR "Waiting ($wait)...\n";
sleep $wait;
print STDERR "Checking...\n";
$response = $agent->get($response->base);
}
$response->is_success ?
print $response->content :
die 'Failed, got ' . $response->status_line .
' for ' . $response->request->uri . "\n";
</code></pre>
<p>My questions are:</p>
<p>1) How would you do that in Python?</p>
<p>2) Will I be able to massively "scale" that (i.e., use a lot of entries in the query field)?</p>
| 4
|
2009-04-03T20:11:22Z
| 22,295,870
|
<p>There is a python package in pip which does exactly what you want</p>
<pre><code>pip install uniprot-mapper
</code></pre>
| 0
|
2014-03-10T09:04:08Z
|
[
"python",
"http",
"user-agent",
"bioinformatics"
] |
How can I talk to UniProt over HTTP in Python?
| 715,538
|
<p>I'm trying to get some results from UniProt, which is a protein database (details are not important). I'm trying to use some script that translates from one kind of ID to another. I was able to do this manually on the browser, but could not do it in Python. </p>
<p>In <a href="http://www.uniprot.org/faq/28" rel="nofollow">http://www.uniprot.org/faq/28</a> there are some sample scripts. I tried the Perl one and it seems to work, so the problem is my Python attempts. The (working) script is:</p>
<pre><code>## tool_example.pl ##
use strict;
use warnings;
use LWP::UserAgent;
my $base = 'http://www.uniprot.org';
my $tool = 'mapping';
my $params = {
from => 'ACC', to => 'P_REFSEQ_AC', format => 'tab',
query => 'P13368 P20806 Q9UM73 P97793 Q17192'
};
my $agent = LWP::UserAgent->new;
push @{$agent->requests_redirectable}, 'POST';
print STDERR "Submitting...\n";
my $response = $agent->post("$base/$tool/", $params);
while (my $wait = $response->header('Retry-After')) {
print STDERR "Waiting ($wait)...\n";
sleep $wait;
print STDERR "Checking...\n";
$response = $agent->get($response->base);
}
$response->is_success ?
print $response->content :
die 'Failed, got ' . $response->status_line .
' for ' . $response->request->uri . "\n";
</code></pre>
<p>My questions are:</p>
<p>1) How would you do that in Python?</p>
<p>2) Will I be able to massively "scale" that (i.e., use a lot of entries in the query field)?</p>
| 4
|
2009-04-03T20:11:22Z
| 38,795,612
|
<p>check this out <code>bioservices</code>. they interface a lot of databases through Python.
<a href="https://pythonhosted.org/bioservices/_modules/bioservices/uniprot.html" rel="nofollow">https://pythonhosted.org/bioservices/_modules/bioservices/uniprot.html</a></p>
<pre><code>conda install bioservices --yes
</code></pre>
| 0
|
2016-08-05T18:22:05Z
|
[
"python",
"http",
"user-agent",
"bioinformatics"
] |
Best way to encode tuples with json
| 715,550
|
<p>In python I have a dictionary that maps tuples to a list of tuples. e.g. </p>
<p><code>{(1,2): [(2,3),(1,7)]}</code></p>
<p>I want to be able to encode this data use it with javascript, so I looked into json but it appears keys must be strings so my tuple does not work as a key.</p>
<p>Is the best way to handle this is encode it as "1,2" and then parse it into something I want on the javascript? Or is there a more clever way to handle this.</p>
| 21
|
2009-04-03T20:14:25Z
| 715,569
|
<p>Could it simply be a two dimensional array? Then you may use integers as keys</p>
| 0
|
2009-04-03T20:17:25Z
|
[
"python",
"json"
] |
Best way to encode tuples with json
| 715,550
|
<p>In python I have a dictionary that maps tuples to a list of tuples. e.g. </p>
<p><code>{(1,2): [(2,3),(1,7)]}</code></p>
<p>I want to be able to encode this data use it with javascript, so I looked into json but it appears keys must be strings so my tuple does not work as a key.</p>
<p>Is the best way to handle this is encode it as "1,2" and then parse it into something I want on the javascript? Or is there a more clever way to handle this.</p>
| 21
|
2009-04-03T20:14:25Z
| 715,581
|
<p>My recommendation would be:</p>
<pre><code>{ "1": [
{ "2": [[2,3],[1,7]] }
]
}
</code></pre>
<p>It's still parsing, but depending on how you use it, it may be easier in this form.</p>
| 2
|
2009-04-03T20:20:06Z
|
[
"python",
"json"
] |
Best way to encode tuples with json
| 715,550
|
<p>In python I have a dictionary that maps tuples to a list of tuples. e.g. </p>
<p><code>{(1,2): [(2,3),(1,7)]}</code></p>
<p>I want to be able to encode this data use it with javascript, so I looked into json but it appears keys must be strings so my tuple does not work as a key.</p>
<p>Is the best way to handle this is encode it as "1,2" and then parse it into something I want on the javascript? Or is there a more clever way to handle this.</p>
| 21
|
2009-04-03T20:14:25Z
| 715,584
|
<p>You can't use an array as a key in JSON. The best you can do is encode it. Sorry, but there's really no other sane way to do it.</p>
| 1
|
2009-04-03T20:20:25Z
|
[
"python",
"json"
] |
Best way to encode tuples with json
| 715,550
|
<p>In python I have a dictionary that maps tuples to a list of tuples. e.g. </p>
<p><code>{(1,2): [(2,3),(1,7)]}</code></p>
<p>I want to be able to encode this data use it with javascript, so I looked into json but it appears keys must be strings so my tuple does not work as a key.</p>
<p>Is the best way to handle this is encode it as "1,2" and then parse it into something I want on the javascript? Or is there a more clever way to handle this.</p>
| 21
|
2009-04-03T20:14:25Z
| 715,601
|
<p>You might consider saying</p>
<pre><code>{"[1,2]": [(2,3),(1,7)]}
</code></pre>
<p>and then when you need to get the value out, you can just parse the keys themselves as JSON objects, which all modern browsers can do with the built-in <code>JSON.parse</code> method (I'm using <code>jQuery.each</code> to iterate here but you could use anything):</p>
<pre><code>var myjson = JSON.parse('{"[1,2]": [[2,3],[1,7]]}');
$.each(myjson, function(keystr,val){
var key = JSON.parse(keystr);
// do something with key and val
});
</code></pre>
<p>On the other hand, you might want to just structure your object differently, e.g.</p>
<pre><code>{1: {2: [(2,3),(1,7)]}}
</code></pre>
<p>so that instead of saying</p>
<pre><code>myjson[1,2] // doesn't work
</code></pre>
<p>which is invalid Javascript syntax, you could say</p>
<pre><code>myjson[1][2] // returns [[2,3],[1,7]]
</code></pre>
| 16
|
2009-04-03T20:25:57Z
|
[
"python",
"json"
] |
Best way to encode tuples with json
| 715,550
|
<p>In python I have a dictionary that maps tuples to a list of tuples. e.g. </p>
<p><code>{(1,2): [(2,3),(1,7)]}</code></p>
<p>I want to be able to encode this data use it with javascript, so I looked into json but it appears keys must be strings so my tuple does not work as a key.</p>
<p>Is the best way to handle this is encode it as "1,2" and then parse it into something I want on the javascript? Or is there a more clever way to handle this.</p>
| 21
|
2009-04-03T20:14:25Z
| 715,614
|
<p>If your key tuples are truly integer pairs, then the easiest and probably most straightforward approach would be as you suggest.... encode them to a string. You can do this in a one-liner:</p>
<pre><code>>>> simplejson.dumps(dict([("%d,%d" % k, v) for k, v in d.items()]))
'{"1,2": [[2, 3], [1, 7]]}'
</code></pre>
<p>This would get you a javascript data structure whose keys you could then split to get the points back again:</p>
<pre><code>'1,2'.split(',')
</code></pre>
| 6
|
2009-04-03T20:29:27Z
|
[
"python",
"json"
] |
Launching a .py python script from within a cgi script
| 715,791
|
<p>I'm trying to launch a .py script from within a cgi script while running a local cgi server.
The cgi script simply receives some data from Google Earth and passes it to the .py script which is currently being called using execfile('script.py') placed at the end of the cgi script.</p>
<p>The script runs to completion, however script.py contains some print statements that I need to be able to monitor while the process runs. Any errors in the .py print to the localhost console window and the print statements seem to be buffered.</p>
<p>Is there a way to send the output from the .py to another python console window while the localhost console is running?</p>
<p>It seems like the subprocess module should do what I need but I've only been able to send the output to a variable or a logfile. This is fine except that I need to see the print statements in real-time.</p>
<p>Thanks in advance</p>
| 0
|
2009-04-03T21:26:00Z
| 715,825
|
<p>You say you're launching a python script from a CGI script, but you don't specify what language the CGI script is written in. Because CGI is simply an interface, it's not clear what language the CGI script is written in. I'm going to assume python, since that makes the most sense. </p>
<p>What would work best would be to write your messages out to a log file. In your "script.py" file, instead of using print, you should open a log file for appending, like so: </p>
<pre><code>logfile = file("/var/log/my-app-log.txt", "a")
</code></pre>
<p>Then, wherever you have a print statement like this:</p>
<pre><code>print("Starting to do step 2...")
</code></pre>
<p>Change it to a logfile.write() statement like this:</p>
<pre><code>logfile.write("starting to do step 2...\n")
</code></pre>
<p>Note that you will need to add newlines separately as file.write() does not add one for you. </p>
<p>Then, you can watch what's going on in your script with a command like tail:</p>
<pre><code>tail -f /var/log/my-app-log.txt
</code></pre>
<p>This will show data as it gets appended to your log file. </p>
| 1
|
2009-04-03T21:36:57Z
|
[
"python",
"cgi",
"scripting"
] |
Launching a .py python script from within a cgi script
| 715,791
|
<p>I'm trying to launch a .py script from within a cgi script while running a local cgi server.
The cgi script simply receives some data from Google Earth and passes it to the .py script which is currently being called using execfile('script.py') placed at the end of the cgi script.</p>
<p>The script runs to completion, however script.py contains some print statements that I need to be able to monitor while the process runs. Any errors in the .py print to the localhost console window and the print statements seem to be buffered.</p>
<p>Is there a way to send the output from the .py to another python console window while the localhost console is running?</p>
<p>It seems like the subprocess module should do what I need but I've only been able to send the output to a variable or a logfile. This is fine except that I need to see the print statements in real-time.</p>
<p>Thanks in advance</p>
| 0
|
2009-04-03T21:26:00Z
| 715,834
|
<p>Use <a href="http://docs.python.org/library/popen2.html" rel="nofollow">popen2</a> or <a href="http://docs.python.org/library/subprocess.html" rel="nofollow">subprocess</a> to launch a console while redirecting your output stream to that console.</p>
| 0
|
2009-04-03T21:41:12Z
|
[
"python",
"cgi",
"scripting"
] |
Populating form field based on query/slug factor
| 715,889
|
<p>I've seen some similar questions, but nothing that quite pointed me in the direction I was hoping for. I have a situation where I have a standard django form built off of a model. This form has a drop down box where you select an item you want to post a comment on. Now I'd like people to be able to browse by items, and click a link to comment on that particular item. What I'd like is for when a user clicks that link they'll be presented with the same old form, however, the dropbox will be defaulted to the item they wanted to comment on. </p>
<p>Is there a sane way to do this with the existing form?
Should I create a separate form entirely for this need?</p>
<p>As a note, this isn't a true comment system, and isn't intended to be. One idea I had was to construct urls like:</p>
<pre><code>comment/?q=item1
</code></pre>
<p>Catching the 'item1' section, and then over riding the save function to force that into the form, while hiding the company in the form. From a UI standpoint, I'm not ecstatic with that idea though. Any thoughts or ideas?</p>
| 0
|
2009-04-03T21:58:47Z
| 716,031
|
<p>If I'm reading your question right, this is a fairly common use-case and well support by django forms. You can use the same form for both scenarios you describe.</p>
<p>Let's say the item to be commented has the primary key 5. You would build a link for the user to click with a URL that looks like this:</p>
<pre><code><a href="/comment/5/">Comment on me</a>
</code></pre>
<p>(This would work just as well with a slug field, though see the comment below about how the identifier must match the ID in the field's choices: /comment/my_item_1/)</p>
<p>Your view would pick up the parameter, and pass it on to the form in the <code>initial</code> parameter:</p>
<pre><code>def show_comment_form(request, item_id):
form = MyCommentForm(initial={'item_drop_down':item_id})
</code></pre>
<p>The form will be displayed with the drop-down pre-selected. For this example to work, of course, the <code>item_id</code> parameter must match whatever the choice identifier is for the item field (if it's built automatically off a model field, as it sounds, that will probably be the primary key of the available items' class).</p>
<p>By this I mean that, if the choices were to look like:</p>
<pre><code>choices = ( (1, 'Item 1'),
(2, 'Item 2') )
</code></pre>
<p>Then the <code>item_id</code> should be 1 or 2 as that's what will be in the resulting <code><select></code> options (ie: <code><option value="1">Item 1</option></code>). Automatically created ModelForm classes will take care of this for you, otherwise just be vigilant.</p>
<p>You can find more information here in the django docs: <a href="http://docs.djangoproject.com/en/dev/ref/forms/api/#dynamic-initial-values" rel="nofollow">Dynamic Initial Values</a></p>
| 1
|
2009-04-03T23:02:06Z
|
[
"python",
"django-forms"
] |
A wxPython timeline widget
| 715,950
|
<p>I am looking for a certain wxPython widget to use in my program. I hope that something like this exists and that you might know where to find. I will try to describe the functionality I'm looking for:</p>
<p>Imagine something like the widget that Audacity uses to display an audio track. It's a horizontal timeline, with a ruler. It is possible to zoom in and out, and to scroll, and the ruler updates to reflect where / how deep you are on the timeline.
Only a finite segment of the timeline is "occupied", i.e., actually contains data. The rest is empty.
It is possible to select with the mouse any time point on the timeline, and, of course, it is possible to let it "play": to traverse the timeline from left to right in a specified speed.</p>
<p>If you know something that's at least close to what I describe, I'd be interested.</p>
<p><hr /></p>
<p>If you want to know what the job of this widget is: It's for a program for running simulations. The program calculates the simulation in the background, extending the "occupied" part of the timeline. It is possible to select different points in the timeline to observe the state of the system in a certain timepoint, and of course it is possible to play the simulation.</p>
<p>Thanks!</p>
| 1
|
2009-04-03T22:24:24Z
| 716,196
|
<p>A quick web search doesn't yield anything but others hoping for the same thing. My guess is you won't find any nice wx widgets for timelines. The closest you're likely to get is a <a href="http://zetcode.com/wxpython/widgets/#slider" rel="nofollow">wxSlider</a>. This is far from ideal, but it'll get you up and running. You can also look at creating a <a href="http://www.zetcode.com/wxpython/customwidgets/" rel="nofollow">custom widget</a> -- that'd definitely do what you want, but it will be a lot of work. Sorry I don't have anything better, but I figured some answer is better than nothing. </p>
| 1
|
2009-04-04T00:46:01Z
|
[
"python",
"controls",
"wxpython",
"widget",
"timeline"
] |
A wxPython timeline widget
| 715,950
|
<p>I am looking for a certain wxPython widget to use in my program. I hope that something like this exists and that you might know where to find. I will try to describe the functionality I'm looking for:</p>
<p>Imagine something like the widget that Audacity uses to display an audio track. It's a horizontal timeline, with a ruler. It is possible to zoom in and out, and to scroll, and the ruler updates to reflect where / how deep you are on the timeline.
Only a finite segment of the timeline is "occupied", i.e., actually contains data. The rest is empty.
It is possible to select with the mouse any time point on the timeline, and, of course, it is possible to let it "play": to traverse the timeline from left to right in a specified speed.</p>
<p>If you know something that's at least close to what I describe, I'd be interested.</p>
<p><hr /></p>
<p>If you want to know what the job of this widget is: It's for a program for running simulations. The program calculates the simulation in the background, extending the "occupied" part of the timeline. It is possible to select different points in the timeline to observe the state of the system in a certain timepoint, and of course it is possible to play the simulation.</p>
<p>Thanks!</p>
| 1
|
2009-04-03T22:24:24Z
| 819,462
|
<p>I have been working on a timeline widget for use in Task Coach (<a href="http://www.taskcoach.org" rel="nofollow">http://www.taskcoach.org</a>). I haven't released it separately yet, but it is fully isolated from the rest of the Task Coach source code so you should be able to rip it out quite easily. See <a href="http://taskcoach.svn.sourceforge.net/viewvc/taskcoach/trunk/taskcoach/taskcoachlib/thirdparty/timeline/" rel="nofollow">http://taskcoach.svn.sourceforge.net/viewvc/taskcoach/trunk/taskcoach/taskcoachlib/thirdparty/timeline/</a></p>
| 1
|
2009-05-04T09:35:26Z
|
[
"python",
"controls",
"wxpython",
"widget",
"timeline"
] |
OptionParser - supporting any option at the end of the command line
| 716,006
|
<p>I'm writing a small program that's supposed to execute a command on a remote server (let's say a reasonably dumb wrapper around <code>ssh [hostname] [command]</code>).</p>
<p>I want to execute it as such:</p>
<pre>./floep [command] </pre>
<p>However, I need to pass certain command lines from time to time:</p>
<pre>./floep -v [command]</pre>
<p>so I decided to use optparse.OptionParser for this. Problem is, I sometimes the command also has argument, which works fine if I do:</p>
<pre>./floep -v "uname -a"</pre>
<p>But I also want it to work when I use:</p>
<pre>./floep -v uname -a</pre>
<p>The idea is, as soon as I come across the first non-option argument, everything after that should be part of my command.</p>
<p>This, however, gives me:</p>
<pre>Usage: floep [options]
floep: error: no such option: -a</pre>
<p>Does OptionParser support this syntax? If so: how?
If not: what's the best way to fix this?</p>
| 5
|
2009-04-03T22:52:46Z
| 716,032
|
<p>You can use a bash script like this:</p>
<pre><code>#!/bin/bash
while [ "-" == "${1:0:1}" ] ; do
if [ "-v" == "${1}" ] ; then
# do something
echo "-v"
elif [ "-s" == "${1}" ] ; then
# do something
echo "-s"
fi
shift
done
${@}
</code></pre>
<p>The ${@} gives you the rest of the command line that was not consumed by the shift calls.
To use ssh you simply change the line from
${@}
to
ssh ${user}@${host} ${@}</p>
<p>test.sh echo bla<br />
bla </p>
<p>test.sh -v echo bla<br />
-v<br />
bla </p>
<p>test.sh -v -s echo bla<br />
-v<br />
-s<br />
bla </p>
| -1
|
2009-04-03T23:03:02Z
|
[
"python",
"optparse"
] |
OptionParser - supporting any option at the end of the command line
| 716,006
|
<p>I'm writing a small program that's supposed to execute a command on a remote server (let's say a reasonably dumb wrapper around <code>ssh [hostname] [command]</code>).</p>
<p>I want to execute it as such:</p>
<pre>./floep [command] </pre>
<p>However, I need to pass certain command lines from time to time:</p>
<pre>./floep -v [command]</pre>
<p>so I decided to use optparse.OptionParser for this. Problem is, I sometimes the command also has argument, which works fine if I do:</p>
<pre>./floep -v "uname -a"</pre>
<p>But I also want it to work when I use:</p>
<pre>./floep -v uname -a</pre>
<p>The idea is, as soon as I come across the first non-option argument, everything after that should be part of my command.</p>
<p>This, however, gives me:</p>
<pre>Usage: floep [options]
floep: error: no such option: -a</pre>
<p>Does OptionParser support this syntax? If so: how?
If not: what's the best way to fix this?</p>
| 5
|
2009-04-03T22:52:46Z
| 716,081
|
<p>OptionParser instances can actually be manipulated during the parsing operation for complex cases. In this case, however, I believe the scenario you describe is supported out-of-the-box (which would be good news if true! how often does that happen??). See this section in the docs: <a href="http://docs.python.org/library/optparse.html#querying-and-manipulating-your-option-parser" rel="nofollow">Querying and manipulating your option parser</a>.</p>
<p>To quote the link above:</p>
<blockquote>
<p>disable_interspersed_args()</p>
<p>Set parsing to stop on the first non-option. Use this if you have a
command processor which runs another command which has options of its
own and you want to make sure these options donât get confused. For example,
each command might have a different set of options.</p>
</blockquote>
| 1
|
2009-04-03T23:29:02Z
|
[
"python",
"optparse"
] |
OptionParser - supporting any option at the end of the command line
| 716,006
|
<p>I'm writing a small program that's supposed to execute a command on a remote server (let's say a reasonably dumb wrapper around <code>ssh [hostname] [command]</code>).</p>
<p>I want to execute it as such:</p>
<pre>./floep [command] </pre>
<p>However, I need to pass certain command lines from time to time:</p>
<pre>./floep -v [command]</pre>
<p>so I decided to use optparse.OptionParser for this. Problem is, I sometimes the command also has argument, which works fine if I do:</p>
<pre>./floep -v "uname -a"</pre>
<p>But I also want it to work when I use:</p>
<pre>./floep -v uname -a</pre>
<p>The idea is, as soon as I come across the first non-option argument, everything after that should be part of my command.</p>
<p>This, however, gives me:</p>
<pre>Usage: floep [options]
floep: error: no such option: -a</pre>
<p>Does OptionParser support this syntax? If so: how?
If not: what's the best way to fix this?</p>
| 5
|
2009-04-03T22:52:46Z
| 716,090
|
<p>Try using <a href="http://docs.python.org/library/optparse.html#other-methods"><code>disable_interspersed_args()</code></a></p>
<pre><code>#!/usr/bin/env python
from optparse import OptionParser
parser = OptionParser()
parser.disable_interspersed_args()
parser.add_option("-v", action="store_true", dest="verbose")
(options, args) = parser.parse_args()
print "Options: %s args: %s" % (options, args)
</code></pre>
<p>When run:</p>
<pre>
$ ./options.py foo -v bar
Options: {'verbose': None} args: ['foo', '-v', 'bar']
$ ./options.py -v foo bar
Options: {'verbose': True} args: ['foo', 'bar']
$ ./options.py foo -a bar
Options: {'verbose': None} args: ['foo', '-a', 'bar']
</pre>
| 13
|
2009-04-03T23:33:45Z
|
[
"python",
"optparse"
] |
OptionParser - supporting any option at the end of the command line
| 716,006
|
<p>I'm writing a small program that's supposed to execute a command on a remote server (let's say a reasonably dumb wrapper around <code>ssh [hostname] [command]</code>).</p>
<p>I want to execute it as such:</p>
<pre>./floep [command] </pre>
<p>However, I need to pass certain command lines from time to time:</p>
<pre>./floep -v [command]</pre>
<p>so I decided to use optparse.OptionParser for this. Problem is, I sometimes the command also has argument, which works fine if I do:</p>
<pre>./floep -v "uname -a"</pre>
<p>But I also want it to work when I use:</p>
<pre>./floep -v uname -a</pre>
<p>The idea is, as soon as I come across the first non-option argument, everything after that should be part of my command.</p>
<p>This, however, gives me:</p>
<pre>Usage: floep [options]
floep: error: no such option: -a</pre>
<p>Does OptionParser support this syntax? If so: how?
If not: what's the best way to fix this?</p>
| 5
|
2009-04-03T22:52:46Z
| 716,108
|
<pre><code>from optparse import OptionParser
import subprocess
import os
import sys
parser = OptionParser()
parser.add_option("-q", "--quiet",
action="store_true", dest="quiet", default=False,
help="don't print output")
parser.add_option("-s", "--signal",
action="store_true", dest="signal", default=False,
help="signal end of program and return code")
parser.disable_interspersed_args()
(options, command) = parser.parse_args()
if not command:
parser.print_help()
sys.exit(1)
if options.quiet:
ret = subprocess.call(command, stdout=open(os.devnull, 'w'),
stderr=subprocess.STDOUT)
else:
ret = subprocess.call(command)
if options.signal:
print "END OF PROGRAM!!! Code: %d" % ret
</code></pre>
| 1
|
2009-04-03T23:43:06Z
|
[
"python",
"optparse"
] |
Why can't environmental variables set in python persist?
| 716,011
|
<p>I was hoping to write a python script to create some appropriate environmental variables by running the script in whatever directory I'll be executing some simulation code, and I've read that I can't write a script to make these env vars persist in the mac os terminal. So two things:</p>
<p>Is this true?</p>
<p>and</p>
<p>It seems like it would be a useful things to do; why isn't it possible in general?</p>
| 25
|
2009-04-03T22:55:29Z
| 716,018
|
<p>It's not generally possible. The new process created for python cannot affect its parent process' environment. Neither can the parent affect the child, but the parent gets to setup the child's environment as part of new process creation.</p>
<p>Perhaps you can set them in <code>.bashrc</code>, <code>.profile</code> or the equivalent "runs on login" or "runs on every new terminal session" script in MacOS.</p>
<p>You can also have python start the simulation program with the desired environment. (use the <code>env</code> parameter to subprocess.Popen (<a href="http://docs.python.org/library/subprocess.html" rel="nofollow">http://docs.python.org/library/subprocess.html</a>) )</p>
<pre><code>import subprocess, os
os.chdir('/home/you/desired/directory')
subprocess.Popen(['desired_program_cmd', 'args', ...], env=dict(SOMEVAR='a_value') )
</code></pre>
<p>Or you could have python write out a shell script like this to a file with a <code>.sh</code> extension: </p>
<pre><code>export SOMEVAR=a_value
cd /home/you/desired/directory
./desired_program_cmd
</code></pre>
<p>and then <code>chmod +x</code> it and run it from anywhere.</p>
| 1
|
2009-04-03T22:59:09Z
|
[
"python",
"persistence",
"environment-variables"
] |
Why can't environmental variables set in python persist?
| 716,011
|
<p>I was hoping to write a python script to create some appropriate environmental variables by running the script in whatever directory I'll be executing some simulation code, and I've read that I can't write a script to make these env vars persist in the mac os terminal. So two things:</p>
<p>Is this true?</p>
<p>and</p>
<p>It seems like it would be a useful things to do; why isn't it possible in general?</p>
| 25
|
2009-04-03T22:55:29Z
| 716,026
|
<p>If you set environment variables within a python script (or any other script or program), it won't affect the parent shell.</p>
<p>Edit clarification:
So the answer to your question is yes, it is true.
You can however export from within a shell script and source it by using the dot invocation</p>
<p>in fooexport.sh</p>
<pre><code>export FOO="bar"
</code></pre>
<p>at the command prompt</p>
<pre><code>$ . ./fooexport.sh
$ echo $FOO
bar
</code></pre>
| 2
|
2009-04-03T23:00:56Z
|
[
"python",
"persistence",
"environment-variables"
] |
Why can't environmental variables set in python persist?
| 716,011
|
<p>I was hoping to write a python script to create some appropriate environmental variables by running the script in whatever directory I'll be executing some simulation code, and I've read that I can't write a script to make these env vars persist in the mac os terminal. So two things:</p>
<p>Is this true?</p>
<p>and</p>
<p>It seems like it would be a useful things to do; why isn't it possible in general?</p>
| 25
|
2009-04-03T22:55:29Z
| 716,046
|
<p>You can't do it from python, but some clever bash tricks can do something similar. The basic reasoning is this: environment variables exist in a per-process memory space. When a new process is created with fork() it inherits its parent's environment variables. When you set an environment variable in your shell (e.g. bash) like this: </p>
<pre><code>export VAR="foo"
</code></pre>
<p>What you're doing is telling bash to set the variable VAR in its process space to "foo". When you run a program, bash uses fork() and then exec() to run the program, so anything you run from bash inherits the bash environment variables. </p>
<p>Now, suppose you want to create a bash command that sets some environment variable DATA with content from a file in your current directory called ".data". First, you need to have a command to get the data out of the file: </p>
<pre><code>cat .data
</code></pre>
<p>That prints the data. Now, we want to create a bash command to set that data in an environment variable: </p>
<pre><code>export DATA=`cat .data`
</code></pre>
<p>That command takes the contents of .data and puts it in the environment variable DATA. Now, if you put that inside an alias command, you have a bash command that sets your environment variable:</p>
<pre><code>alias set-data="export DATA=`cat .data`"
</code></pre>
<p>You can put that alias command inside the .bashrc or .bash_profile files in your home directory to have that command available in any new bash shell you start. </p>
| 26
|
2009-04-03T23:08:47Z
|
[
"python",
"persistence",
"environment-variables"
] |
Why can't environmental variables set in python persist?
| 716,011
|
<p>I was hoping to write a python script to create some appropriate environmental variables by running the script in whatever directory I'll be executing some simulation code, and I've read that I can't write a script to make these env vars persist in the mac os terminal. So two things:</p>
<p>Is this true?</p>
<p>and</p>
<p>It seems like it would be a useful things to do; why isn't it possible in general?</p>
| 25
|
2009-04-03T22:55:29Z
| 716,069
|
<p>What I like to do is use /usr/bin/env in a shell script to "wrap" my command line when I find myself in similar situations:</p>
<pre><code>#!/bin/bash
/usr/bin/env NAME1="VALUE1" NAME2="VALUE2" ${*}
</code></pre>
<p>So let's call this script "myappenv". I put it in my $HOME/bin directory which I have in my $PATH.</p>
<p>Now I can invoke any command using that environment by simply prepending "myappenv" as such:</p>
<pre><code>myappenv dosometask -xyz
</code></pre>
<p>Other posted solutions work too, but this is my personal preference. One advantage is that the environment is transient, so if I'm working in the shell only the command I invoke is affected by the altered environment.</p>
<p><strong>Modified version based on new comments</strong></p>
<pre><code>#!/bin/bash
/usr/bin/env G4WORKDIR=$PWD ${*}
</code></pre>
<p>You could wrap this all up in an alias too. I prefer the wrapper script approach since I tend to have other environment prep in there too, which makes it easier for me to maintain.</p>
| 2
|
2009-04-03T23:22:30Z
|
[
"python",
"persistence",
"environment-variables"
] |
Why can't environmental variables set in python persist?
| 716,011
|
<p>I was hoping to write a python script to create some appropriate environmental variables by running the script in whatever directory I'll be executing some simulation code, and I've read that I can't write a script to make these env vars persist in the mac os terminal. So two things:</p>
<p>Is this true?</p>
<p>and</p>
<p>It seems like it would be a useful things to do; why isn't it possible in general?</p>
| 25
|
2009-04-03T22:55:29Z
| 716,188
|
<p>One workaround is to output <code>export</code> commands, and have the parent shell evaluate this..</p>
<p><code>thescript.py</code>:</p>
<pre><code>import pipes
import random
r = random.randint(1,100)
print("export BLAHBLAH=%s" % (pipes.quote(str(r))))
</code></pre>
<p>..and the bash alias (the same can be done in most shells.. even tcsh!):</p>
<pre><code>alias setblahblahenv="eval $(python thescript.py)"
</code></pre>
<p>Usage:</p>
<pre><code>$ echo $BLAHBLAH
$ setblahblahenv
$ echo $BLAHBLAH
72
</code></pre>
<p>You can output any arbitrary shell code, including multiple commands like:</p>
<pre><code>export BLAHBLAH=23 SECONDENVVAR='something else' && echo 'everything worked'
</code></pre>
<p>Just remember to be careful about escaping any dynamically created output (the <code>pipes.quote</code> module is good for this)</p>
| 16
|
2009-04-04T00:38:24Z
|
[
"python",
"persistence",
"environment-variables"
] |
Why can't environmental variables set in python persist?
| 716,011
|
<p>I was hoping to write a python script to create some appropriate environmental variables by running the script in whatever directory I'll be executing some simulation code, and I've read that I can't write a script to make these env vars persist in the mac os terminal. So two things:</p>
<p>Is this true?</p>
<p>and</p>
<p>It seems like it would be a useful things to do; why isn't it possible in general?</p>
| 25
|
2009-04-03T22:55:29Z
| 32,547,868
|
<p>As answered by Benson, but the best hack-around is to create a simple bash function to preserve arguments:</p>
<pre><code>upsert-env-var (){ eval $(python upsert_env_var.py $*); }
</code></pre>
<p>Your can do whatever you want in your python script with the arguments. To simply add a variable use something like:</p>
<pre><code>var = sys.argv[1]
val = sys.argv[2]
if os.environ.get(var, None):
print "export %s=%s:%s" % (var, val, os.environ[var])
else:
print "export %s=%s" % (var, val)
</code></pre>
<p>Usage:</p>
<pre><code>upsert-env-var VAR VAL
</code></pre>
| 0
|
2015-09-13T08:39:56Z
|
[
"python",
"persistence",
"environment-variables"
] |
Matrices in Python
| 716,259
|
<p>Yesterday I had the need for a matrix type in Python.</p>
<p>Apparently, a trivial answer to this need would be to use <code>numpy.matrix()</code>, but the additional issue I have is that I would like a matrix to store arbitrary values with mixed types, similarly to a list. <code>numpy.matrix</code> does not perform this. An example is</p>
<pre><code>>>> numpy.matrix([[1,2,3],[4,"5",6]])
matrix([['1', '2', '3'],
['4', '5', '6']],
dtype='|S4')
>>> numpy.matrix([[1,2,3],[4,5,6]])
matrix([[1, 2, 3],
[4, 5, 6]])
</code></pre>
<p>As you can see, the <code>numpy.matrix</code> must be homogeneous in content. If a string value is present in my initialization, every value gets implicitly stored as a string. This is also confirmed by accessing the single values</p>
<pre><code>>>> numpy.matrix([[1,2,3],[4,"5",6]])[1,1]
'5'
>>> numpy.matrix([[1,2,3],[4,"5",6]])[1,2]
'6'
</code></pre>
<p>Now, the Python list type can instead accept mixed types. You can have a list containing an integer and a string, both conserving their type. What I would need is something similar to a list, but operating in a matrix-like behavior. </p>
<p>Therefore, I had to implement my own type. I had two choices for the internal implementation: list containing lists, and dictionaries. Both solutions have shortcomings: </p>
<ul>
<li>list of lists require careful synchronization of the various lists' sizes. Swapping two rows is easy. Swapping two columns is less easy. Removing a row is easy as well.</li>
<li>dictionaries (with a tuple as a key) are slightly better, but you have to define the limits of your key (for example, you cannot insert element 5,5 if your matrix is 3x3), and they are more complex to use to insert, remove, or swap columns or rows.</li>
</ul>
<p>Edit: clarification. The concrete reason on why I need this functionality is because I am reading CSV files. Once I collect the values from a CSV file (values that can be string, integers, floats) I would like to perform swapping, removal, insertion and other operations alike. For this reason I need a "matrix list".</p>
<p>My curiosities are: </p>
<ul>
<li>do you know if a Python data type providing this service already exists (maybe in a "non-battery included" library out there)?</li>
<li>why is this data type not provided in the standard library? Too restricted interest maybe?</li>
<li>How would you have solved this need? Dictionary, list, or another smarter solution?</li>
</ul>
| 4
|
2009-04-04T01:21:36Z
| 716,277
|
<p>I'm curious why you want this functionality; as I understand it, the reason for having matrices (in numpy), is primarily for doing linear math (matrix transformations and so on).</p>
<p>I'm not sure what the mathematical definition would be for the product of a decimal and a String.</p>
<p>Internally, you'll probably want to look at sparse matrix implementations (<a href="http://www.inf.ethz.ch/personal/arbenz/pycon03_contrib.pdf">http://www.inf.ethz.ch/personal/arbenz/pycon03_contrib.pdf</a>). There are lots of ways to do this (hash, list, linked list), and each has its own advantages and drawbacks. If your matrix isn't going to have a lot of nulls or zeroes, then you can ditch the sparse implementations.</p>
| 5
|
2009-04-04T01:27:36Z
|
[
"python",
"matrix"
] |
Matrices in Python
| 716,259
|
<p>Yesterday I had the need for a matrix type in Python.</p>
<p>Apparently, a trivial answer to this need would be to use <code>numpy.matrix()</code>, but the additional issue I have is that I would like a matrix to store arbitrary values with mixed types, similarly to a list. <code>numpy.matrix</code> does not perform this. An example is</p>
<pre><code>>>> numpy.matrix([[1,2,3],[4,"5",6]])
matrix([['1', '2', '3'],
['4', '5', '6']],
dtype='|S4')
>>> numpy.matrix([[1,2,3],[4,5,6]])
matrix([[1, 2, 3],
[4, 5, 6]])
</code></pre>
<p>As you can see, the <code>numpy.matrix</code> must be homogeneous in content. If a string value is present in my initialization, every value gets implicitly stored as a string. This is also confirmed by accessing the single values</p>
<pre><code>>>> numpy.matrix([[1,2,3],[4,"5",6]])[1,1]
'5'
>>> numpy.matrix([[1,2,3],[4,"5",6]])[1,2]
'6'
</code></pre>
<p>Now, the Python list type can instead accept mixed types. You can have a list containing an integer and a string, both conserving their type. What I would need is something similar to a list, but operating in a matrix-like behavior. </p>
<p>Therefore, I had to implement my own type. I had two choices for the internal implementation: list containing lists, and dictionaries. Both solutions have shortcomings: </p>
<ul>
<li>list of lists require careful synchronization of the various lists' sizes. Swapping two rows is easy. Swapping two columns is less easy. Removing a row is easy as well.</li>
<li>dictionaries (with a tuple as a key) are slightly better, but you have to define the limits of your key (for example, you cannot insert element 5,5 if your matrix is 3x3), and they are more complex to use to insert, remove, or swap columns or rows.</li>
</ul>
<p>Edit: clarification. The concrete reason on why I need this functionality is because I am reading CSV files. Once I collect the values from a CSV file (values that can be string, integers, floats) I would like to perform swapping, removal, insertion and other operations alike. For this reason I need a "matrix list".</p>
<p>My curiosities are: </p>
<ul>
<li>do you know if a Python data type providing this service already exists (maybe in a "non-battery included" library out there)?</li>
<li>why is this data type not provided in the standard library? Too restricted interest maybe?</li>
<li>How would you have solved this need? Dictionary, list, or another smarter solution?</li>
</ul>
| 4
|
2009-04-04T01:21:36Z
| 716,292
|
<p>You can have inhomogeneous types if your <code>dtype</code> is <code>object</code>:</p>
<pre><code>In [1]: m = numpy.matrix([[1, 2, 3], [4, '5', 6]], dtype=numpy.object)
In [2]: m
Out[2]:
matrix([[1, 2, 3],
[4, 5, 6]], dtype=object)
In [3]: m[1, 1]
Out[3]: '5'
In [4]: m[1, 2]
Out[4]: 6
</code></pre>
<p>I have no idea what good this does you other than fancy indexing, because, as Don pointed out, you can't do math with this matrix.</p>
| 10
|
2009-04-04T01:38:21Z
|
[
"python",
"matrix"
] |
Matrices in Python
| 716,259
|
<p>Yesterday I had the need for a matrix type in Python.</p>
<p>Apparently, a trivial answer to this need would be to use <code>numpy.matrix()</code>, but the additional issue I have is that I would like a matrix to store arbitrary values with mixed types, similarly to a list. <code>numpy.matrix</code> does not perform this. An example is</p>
<pre><code>>>> numpy.matrix([[1,2,3],[4,"5",6]])
matrix([['1', '2', '3'],
['4', '5', '6']],
dtype='|S4')
>>> numpy.matrix([[1,2,3],[4,5,6]])
matrix([[1, 2, 3],
[4, 5, 6]])
</code></pre>
<p>As you can see, the <code>numpy.matrix</code> must be homogeneous in content. If a string value is present in my initialization, every value gets implicitly stored as a string. This is also confirmed by accessing the single values</p>
<pre><code>>>> numpy.matrix([[1,2,3],[4,"5",6]])[1,1]
'5'
>>> numpy.matrix([[1,2,3],[4,"5",6]])[1,2]
'6'
</code></pre>
<p>Now, the Python list type can instead accept mixed types. You can have a list containing an integer and a string, both conserving their type. What I would need is something similar to a list, but operating in a matrix-like behavior. </p>
<p>Therefore, I had to implement my own type. I had two choices for the internal implementation: list containing lists, and dictionaries. Both solutions have shortcomings: </p>
<ul>
<li>list of lists require careful synchronization of the various lists' sizes. Swapping two rows is easy. Swapping two columns is less easy. Removing a row is easy as well.</li>
<li>dictionaries (with a tuple as a key) are slightly better, but you have to define the limits of your key (for example, you cannot insert element 5,5 if your matrix is 3x3), and they are more complex to use to insert, remove, or swap columns or rows.</li>
</ul>
<p>Edit: clarification. The concrete reason on why I need this functionality is because I am reading CSV files. Once I collect the values from a CSV file (values that can be string, integers, floats) I would like to perform swapping, removal, insertion and other operations alike. For this reason I need a "matrix list".</p>
<p>My curiosities are: </p>
<ul>
<li>do you know if a Python data type providing this service already exists (maybe in a "non-battery included" library out there)?</li>
<li>why is this data type not provided in the standard library? Too restricted interest maybe?</li>
<li>How would you have solved this need? Dictionary, list, or another smarter solution?</li>
</ul>
| 4
|
2009-04-04T01:21:36Z
| 716,389
|
<p>Have you looked at the numpy.recarray capabilities?</p>
<p>For instance here:
http://docs.scipy.org/doc/numpy/reference/generated/numpy.recarray.html</p>
<p>It's designed to allow arrays with mixed datatypes.</p>
<p>I don't know if an array will suit your purposes, or if you really need a matrix - I haven't worked with the numpy matrices. But if an array is good enough, recarray might work.</p>
| 3
|
2009-04-04T02:37:53Z
|
[
"python",
"matrix"
] |
Matrices in Python
| 716,259
|
<p>Yesterday I had the need for a matrix type in Python.</p>
<p>Apparently, a trivial answer to this need would be to use <code>numpy.matrix()</code>, but the additional issue I have is that I would like a matrix to store arbitrary values with mixed types, similarly to a list. <code>numpy.matrix</code> does not perform this. An example is</p>
<pre><code>>>> numpy.matrix([[1,2,3],[4,"5",6]])
matrix([['1', '2', '3'],
['4', '5', '6']],
dtype='|S4')
>>> numpy.matrix([[1,2,3],[4,5,6]])
matrix([[1, 2, 3],
[4, 5, 6]])
</code></pre>
<p>As you can see, the <code>numpy.matrix</code> must be homogeneous in content. If a string value is present in my initialization, every value gets implicitly stored as a string. This is also confirmed by accessing the single values</p>
<pre><code>>>> numpy.matrix([[1,2,3],[4,"5",6]])[1,1]
'5'
>>> numpy.matrix([[1,2,3],[4,"5",6]])[1,2]
'6'
</code></pre>
<p>Now, the Python list type can instead accept mixed types. You can have a list containing an integer and a string, both conserving their type. What I would need is something similar to a list, but operating in a matrix-like behavior. </p>
<p>Therefore, I had to implement my own type. I had two choices for the internal implementation: list containing lists, and dictionaries. Both solutions have shortcomings: </p>
<ul>
<li>list of lists require careful synchronization of the various lists' sizes. Swapping two rows is easy. Swapping two columns is less easy. Removing a row is easy as well.</li>
<li>dictionaries (with a tuple as a key) are slightly better, but you have to define the limits of your key (for example, you cannot insert element 5,5 if your matrix is 3x3), and they are more complex to use to insert, remove, or swap columns or rows.</li>
</ul>
<p>Edit: clarification. The concrete reason on why I need this functionality is because I am reading CSV files. Once I collect the values from a CSV file (values that can be string, integers, floats) I would like to perform swapping, removal, insertion and other operations alike. For this reason I need a "matrix list".</p>
<p>My curiosities are: </p>
<ul>
<li>do you know if a Python data type providing this service already exists (maybe in a "non-battery included" library out there)?</li>
<li>why is this data type not provided in the standard library? Too restricted interest maybe?</li>
<li>How would you have solved this need? Dictionary, list, or another smarter solution?</li>
</ul>
| 4
|
2009-04-04T01:21:36Z
| 716,931
|
<p>Have you considered the csv module for working with csv files?</p>
<p><a href="http://docs.python.org/library/csv.html" rel="nofollow">Python docs for csv module</a></p>
| 0
|
2009-04-04T11:32:13Z
|
[
"python",
"matrix"
] |
Matrices in Python
| 716,259
|
<p>Yesterday I had the need for a matrix type in Python.</p>
<p>Apparently, a trivial answer to this need would be to use <code>numpy.matrix()</code>, but the additional issue I have is that I would like a matrix to store arbitrary values with mixed types, similarly to a list. <code>numpy.matrix</code> does not perform this. An example is</p>
<pre><code>>>> numpy.matrix([[1,2,3],[4,"5",6]])
matrix([['1', '2', '3'],
['4', '5', '6']],
dtype='|S4')
>>> numpy.matrix([[1,2,3],[4,5,6]])
matrix([[1, 2, 3],
[4, 5, 6]])
</code></pre>
<p>As you can see, the <code>numpy.matrix</code> must be homogeneous in content. If a string value is present in my initialization, every value gets implicitly stored as a string. This is also confirmed by accessing the single values</p>
<pre><code>>>> numpy.matrix([[1,2,3],[4,"5",6]])[1,1]
'5'
>>> numpy.matrix([[1,2,3],[4,"5",6]])[1,2]
'6'
</code></pre>
<p>Now, the Python list type can instead accept mixed types. You can have a list containing an integer and a string, both conserving their type. What I would need is something similar to a list, but operating in a matrix-like behavior. </p>
<p>Therefore, I had to implement my own type. I had two choices for the internal implementation: list containing lists, and dictionaries. Both solutions have shortcomings: </p>
<ul>
<li>list of lists require careful synchronization of the various lists' sizes. Swapping two rows is easy. Swapping two columns is less easy. Removing a row is easy as well.</li>
<li>dictionaries (with a tuple as a key) are slightly better, but you have to define the limits of your key (for example, you cannot insert element 5,5 if your matrix is 3x3), and they are more complex to use to insert, remove, or swap columns or rows.</li>
</ul>
<p>Edit: clarification. The concrete reason on why I need this functionality is because I am reading CSV files. Once I collect the values from a CSV file (values that can be string, integers, floats) I would like to perform swapping, removal, insertion and other operations alike. For this reason I need a "matrix list".</p>
<p>My curiosities are: </p>
<ul>
<li>do you know if a Python data type providing this service already exists (maybe in a "non-battery included" library out there)?</li>
<li>why is this data type not provided in the standard library? Too restricted interest maybe?</li>
<li>How would you have solved this need? Dictionary, list, or another smarter solution?</li>
</ul>
| 4
|
2009-04-04T01:21:36Z
| 5,371,300
|
<p>Check out sympy -- it does quite a good job at polymorphism
in its matrices and you you have operations on sympy.matrices.Matrix
objects like col_swap, col_insert, col_del, etc...</p>
<pre>
In [2]: import sympy as s
In [6]: import numpy as np
In [11]: npM = np.array([[1,2,3.0], [4,4,"abc"]], dtype=object)
In [12]: npM
Out[12]:
[[1 2 3.0]
[4 4 abc]]
In [14]: type( npM[0][0] )
Out[14]:
In [15]: type( npM[0][2] )
Out[15]:
In [16]: type( npM[1][2] )
Out[16]:
In [17]: M = s.matrices.Matrix(npM)
In [18]: M
Out[18]:
â¡1 2 3.0â¤
⢠â¥
â£4 4 abcâ¦
In [27]: type( M[0,2] )
Out[27]:
In [28]: type( M[1,2] )
Out[28]:
In [29]: sym= M[1,2]
In [32]: print sym.name
abc
In [34]: sym.n
Out[34]:
In [40]: sym.n(subs={'abc':45} )
Out[40]: 45.0000000000000
</pre>
| 1
|
2011-03-20T20:28:20Z
|
[
"python",
"matrix"
] |
Matrices in Python
| 716,259
|
<p>Yesterday I had the need for a matrix type in Python.</p>
<p>Apparently, a trivial answer to this need would be to use <code>numpy.matrix()</code>, but the additional issue I have is that I would like a matrix to store arbitrary values with mixed types, similarly to a list. <code>numpy.matrix</code> does not perform this. An example is</p>
<pre><code>>>> numpy.matrix([[1,2,3],[4,"5",6]])
matrix([['1', '2', '3'],
['4', '5', '6']],
dtype='|S4')
>>> numpy.matrix([[1,2,3],[4,5,6]])
matrix([[1, 2, 3],
[4, 5, 6]])
</code></pre>
<p>As you can see, the <code>numpy.matrix</code> must be homogeneous in content. If a string value is present in my initialization, every value gets implicitly stored as a string. This is also confirmed by accessing the single values</p>
<pre><code>>>> numpy.matrix([[1,2,3],[4,"5",6]])[1,1]
'5'
>>> numpy.matrix([[1,2,3],[4,"5",6]])[1,2]
'6'
</code></pre>
<p>Now, the Python list type can instead accept mixed types. You can have a list containing an integer and a string, both conserving their type. What I would need is something similar to a list, but operating in a matrix-like behavior. </p>
<p>Therefore, I had to implement my own type. I had two choices for the internal implementation: list containing lists, and dictionaries. Both solutions have shortcomings: </p>
<ul>
<li>list of lists require careful synchronization of the various lists' sizes. Swapping two rows is easy. Swapping two columns is less easy. Removing a row is easy as well.</li>
<li>dictionaries (with a tuple as a key) are slightly better, but you have to define the limits of your key (for example, you cannot insert element 5,5 if your matrix is 3x3), and they are more complex to use to insert, remove, or swap columns or rows.</li>
</ul>
<p>Edit: clarification. The concrete reason on why I need this functionality is because I am reading CSV files. Once I collect the values from a CSV file (values that can be string, integers, floats) I would like to perform swapping, removal, insertion and other operations alike. For this reason I need a "matrix list".</p>
<p>My curiosities are: </p>
<ul>
<li>do you know if a Python data type providing this service already exists (maybe in a "non-battery included" library out there)?</li>
<li>why is this data type not provided in the standard library? Too restricted interest maybe?</li>
<li>How would you have solved this need? Dictionary, list, or another smarter solution?</li>
</ul>
| 4
|
2009-04-04T01:21:36Z
| 19,811,361
|
<p>Maybe it's a late answer,
but,
why not use <a href="http://pandas.pydata.org/" rel="nofollow">pandas</a>?</p>
| 1
|
2013-11-06T11:49:11Z
|
[
"python",
"matrix"
] |
My first python program: can you tell me what I'm doing wrong?
| 716,278
|
<p>I hope this question is considered appropriate for stackoverflow. If not, I'll remove the question right away.</p>
<p>I've just wrote my very first python program. The idea is that you can issue a command, and it's gets sent to several servers in parallel.</p>
<p>This is just for personal educational purposes. The program works! I really want to get better at python and therefore I'd like to ask the following questions:</p>
<ol>
<li>My style looks messy compared to PHP (what I'm used to). Do you have any suggestions around style improvements.</li>
<li>Am I using the correct libraries? Am I using them correctly?</li>
<li>Am I using the correct datatypes? Am I using them correctly?</li>
</ol>
<p>I have a good programming background, but it took me quite a while to develope a decent style for PHP (PEAR-coding standards, knowing what tools to use and when).</p>
<p>The source (one file, 92 lines of code)</p>
<p><a href="http://code.google.com/p/floep/source/browse/trunk/floep" rel="nofollow">http://code.google.com/p/floep/source/browse/trunk/floep</a></p>
| 6
|
2009-04-04T01:27:46Z
| 716,309
|
<p>Usually is preferred that what follows after the end of sentence <code>:</code> is in a separate line (also don't add a space before it)</p>
<pre><code>if options.verbose:
print ""
</code></pre>
<p>instead of</p>
<pre><code>if options.verbose : print ""
</code></pre>
<p>You don't need to check the len of a list if you are going to iterate over it</p>
<pre><code>if len(threadlist) > 0 :
for server in threadlist :
...
</code></pre>
<p>is redundant, a more 'readable' is (python is smart enough to not iterate over an empty list):</p>
<pre><code>for server in threadlist:
...
</code></pre>
<p>Also a more 'pythonistic' is to use list's comprehensions (but certainly is a debatable opinion)</p>
<pre><code>server = []
for i in grouplist : servers+=getServers(i)
</code></pre>
<p>can be shortened to</p>
<pre><code>server = [getServers(i) for i in grouplist]
</code></pre>
| 10
|
2009-04-04T01:46:23Z
|
[
"python"
] |
My first python program: can you tell me what I'm doing wrong?
| 716,278
|
<p>I hope this question is considered appropriate for stackoverflow. If not, I'll remove the question right away.</p>
<p>I've just wrote my very first python program. The idea is that you can issue a command, and it's gets sent to several servers in parallel.</p>
<p>This is just for personal educational purposes. The program works! I really want to get better at python and therefore I'd like to ask the following questions:</p>
<ol>
<li>My style looks messy compared to PHP (what I'm used to). Do you have any suggestions around style improvements.</li>
<li>Am I using the correct libraries? Am I using them correctly?</li>
<li>Am I using the correct datatypes? Am I using them correctly?</li>
</ol>
<p>I have a good programming background, but it took me quite a while to develope a decent style for PHP (PEAR-coding standards, knowing what tools to use and when).</p>
<p>The source (one file, 92 lines of code)</p>
<p><a href="http://code.google.com/p/floep/source/browse/trunk/floep" rel="nofollow">http://code.google.com/p/floep/source/browse/trunk/floep</a></p>
| 6
|
2009-04-04T01:27:46Z
| 716,367
|
<p>String exceptions are deprecated in Python, so this line:</p>
<pre><code>if not config.has_section(sectionname):
raise 'Server or group ' + sectionname + ' not found in ' + configfile
</code></pre>
<p>should be reworked into something like this:</p>
<pre><code>if not config.has_section(sectionname):
raise ConfigNotFoundError(
"Server or group" + sectionname + "not found in" + configfile)
class ConfigNotFoundError(Exception):
pass
</code></pre>
<p>[Edited to reflect the suggestion of dangph in the comments]</p>
<p>It's more lines of code, but it's better for future upgrades.</p>
<p>For readability's sake, something like this:</p>
<pre><code>parser.add_option('-q','--quiet',action="store_false", help="Display only server output", dest="verbose", default=True)
</code></pre>
<p>Can be rewritten like this:</p>
<pre><code>parser.add_option('-q',
'--quiet',
action="store_false",
help="Display only server output",
dest="verbose",
default=True)
</code></pre>
<p>You might prefer another method of splitting the method call up, but the idea is that long lines can be hard to read.</p>
<p>You should also read <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP 8</a> to get a sense of Python style.</p>
| 5
|
2009-04-04T02:22:43Z
|
[
"python"
] |
My first python program: can you tell me what I'm doing wrong?
| 716,278
|
<p>I hope this question is considered appropriate for stackoverflow. If not, I'll remove the question right away.</p>
<p>I've just wrote my very first python program. The idea is that you can issue a command, and it's gets sent to several servers in parallel.</p>
<p>This is just for personal educational purposes. The program works! I really want to get better at python and therefore I'd like to ask the following questions:</p>
<ol>
<li>My style looks messy compared to PHP (what I'm used to). Do you have any suggestions around style improvements.</li>
<li>Am I using the correct libraries? Am I using them correctly?</li>
<li>Am I using the correct datatypes? Am I using them correctly?</li>
</ol>
<p>I have a good programming background, but it took me quite a while to develope a decent style for PHP (PEAR-coding standards, knowing what tools to use and when).</p>
<p>The source (one file, 92 lines of code)</p>
<p><a href="http://code.google.com/p/floep/source/browse/trunk/floep" rel="nofollow">http://code.google.com/p/floep/source/browse/trunk/floep</a></p>
| 6
|
2009-04-04T01:27:46Z
| 716,388
|
<p>Before unloading any criticism, first let me say congratulations on getting your first Python program working. Moving from one language to another can be a chore, constantly fumbling around with syntax issues and hunting through unfamiliar libraries.</p>
<p>The most quoted style guideline is <a href="http://www.python.org/dev/peps/pep-0008/">PEP-8</a>, but that's only a guide, and at least some part of it is ignored...no, I mean deemed not applicable to some specific situation with all due respect to the guideline authors and contributors :-).</p>
<p>I can't compare it to PHP, but compared to other Python applications it is pretty clear that you are following style conventions from other languages. I didn't always agree with many things that other developers said you <b>must</b> do, but over time I recognized why using conventions helps communicate what the application is doing and will help other developers help you.</p>
<p><hr>
Raise exceptions, not strings.</p>
<pre>raise 'Server or group ' + sectionname + ' not found in ' + configfile</pre>
becomes
<pre>raise RuntimeError('Server or group ' + sectionname + ' not found in ' + configfile)</pre>
<hr>
No space before the ':' at the end of an 'if' or 'for', and don't put multiple statements on the same line, and be consistent about putting spaces around operators. Use variable names for objects and stick with <code>i</code> and <code>j</code> for loop index variables (like our masterful FORTRAN forefathers):
<pre>for i in grouplist : servers+=getServers(i)</pre>
becomes:
<pre>for section in grouplist:
servers += getServers(section)</pre>
<hr>
Containers can be tested for contents without getting their length:
<pre>while len(threadlist) > 0 :</pre>
becomes
<pre>while threadlist:</pre>
and
<pre>if command.strip() == "" :</pre>
becomes
<pre>if command.strip():</pre>
<hr>
Splitting a tuple is usually not put in parenthesis on the left hand side of a statement, and the command logic is a bit convoluted. If there are no args then the " ".join(...) is going to be an empty string:
<pre>
(options,args) = parser.parse_args()
if options.verbose : print "floep 0.1"
command = " ".join(args)
if command.strip() == "" : parser.error('no command given')
</pre>
<p>becomes</p>
<pre>
options, args = parser.parse_args()
if options.verbose:
print "floep 0.1"
if not args:
parser.error('no command given')
command = " ".join(args)
</pre>
<p><hr>
A python for loop has an unusual 'else' clause which is executed if the loop goes through all of the elements without a 'break':</p>
<pre>
for server in threadlist :
foundOne = False
if not server.isAlive() :
...snip...
foundOne = True
if not foundOne :
time.sleep(0.010)
</pre>
<p>becomes</p>
<pre>
for server in threadlist:
if not server.isAlive():
...snip...
break
else:
time.sleep(0.010)
</pre>
<p><hr>
Getting a list of lines and then joining them back together is a bit long winded:</p>
<pre>
result = proc.readlines()
strresult = ''
for line in result : strresult+=line
self.result = strresult
</pre>
<p>becomes</p>
<pre>
self.result = proc.read()
</pre>
<p><hr>
Your library use is good, check out the subprocess module, it's a little more up-to-date.</p>
<p>Your datatypes are fine.</p>
<p>And you'll get lots of other anwsers :-)</p>
| 7
|
2009-04-04T02:37:51Z
|
[
"python"
] |
My first python program: can you tell me what I'm doing wrong?
| 716,278
|
<p>I hope this question is considered appropriate for stackoverflow. If not, I'll remove the question right away.</p>
<p>I've just wrote my very first python program. The idea is that you can issue a command, and it's gets sent to several servers in parallel.</p>
<p>This is just for personal educational purposes. The program works! I really want to get better at python and therefore I'd like to ask the following questions:</p>
<ol>
<li>My style looks messy compared to PHP (what I'm used to). Do you have any suggestions around style improvements.</li>
<li>Am I using the correct libraries? Am I using them correctly?</li>
<li>Am I using the correct datatypes? Am I using them correctly?</li>
</ol>
<p>I have a good programming background, but it took me quite a while to develope a decent style for PHP (PEAR-coding standards, knowing what tools to use and when).</p>
<p>The source (one file, 92 lines of code)</p>
<p><a href="http://code.google.com/p/floep/source/browse/trunk/floep" rel="nofollow">http://code.google.com/p/floep/source/browse/trunk/floep</a></p>
| 6
|
2009-04-04T01:27:46Z
| 716,954
|
<p>Often, for reuse purposes, we do the following, starting at about line 48 in your program</p>
<pre><code>def main():
config = ConfigParser.RawConfigParser()
etc.
if __name__ == "__main__":
main()
</code></pre>
<p>This is just a starting point. </p>
<p>Once you've done this, you realize that main() is really two parts: parsing the command-line interface and doing the work. You then want to refactor things to look like this.</p>
<pre><code>def serverWork(group,...):
servers = getServers(group)
etc.
def main():
config = ConfigParser.RawConfigParser()
if command.strip() == "":
parser.error('no command given')
else:
serverWork( options.group, options.etc., ... )
</code></pre>
<p>Now, you have elevated the real work to a function within this module. Your serverWork function can now be reused easily by other programs or scripts.</p>
| 3
|
2009-04-04T11:58:15Z
|
[
"python"
] |
Why is my PyObjc Cocoa view class forgetting its fields?
| 716,386
|
<p>I was trying to hack up a tool to visualize shaders for my game and I figured I would try using python and cocoa. I have ran into a brick wall of sorts though. Maybe its my somewhat poor understand of objective c but I can not seem to get this code for a view I was trying to write working:</p>
<pre><code>from objc import YES, NO, IBAction, IBOutlet
from Foundation import *
from AppKit import *
import gv
class SceneView(NSOpenGLView):
def __init__(self):
NSOpenGLView.__init__(self)
self.renderer = None
def doinit(self):
self.renderer = gv.CoreRenderer()
def initWithFrame_(self, frame):
self = super(SceneView, self).initWithFrame_(frame)
if self:
self.doinit()
print self.__dict__
return self
def drawRect_(self, rect):
clearColor = [0.0,0.0,0.0,0.0]
print self.__dict__
self.renderer.clear(CF_Target|CF_ZBuffer,clearColor)
</code></pre>
<p>It outputs this when executed:</p>
<pre><code>{'renderer': <gv.CoreRenderer; proxy of <Swig Object of type 'GV::CoreRenderer *' at 0x202c7d0> >}
{}
2009-04-03 19:13:30.941 geom-view-edit[50154:10b] An exception has occured:
Traceback (most recent call last):
File "/System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/PyObjCTools/AppHelper.py", line 235, in runEventLoop
File "/mnt/gilead/amcharg/projects/geom-view-edit/build/Debug/geom-view-edit.app/Contents/Resources/SceneView.py", line 37, in drawRect_
self.renderer.clear(CF_Target|CF_ZBuffer,clearColor)
AttributeError: 'SceneView' object has no attribute 'renderer'
</code></pre>
<p>It seems to be losing my renderer variable which is not that surprising considering how funky the initWithFrame_ code is but this was something xcode seemed to write which I suppose makes sense since objective C has the init separate from alloc idiom. It is still strange seeing it python however.</p>
<p>Is there anyways to salvage this or should I take it out behind the code shed shoot it and use QT or wxPython? I considered using objective-c but I want to test out these nifty swig bindings I just compiled =)</p>
| 1
|
2009-04-04T02:33:10Z
| 716,917
|
<p>Depending on what's happening elsewhere in your app, your instance might actually be getting copied. </p>
<p>In this case, implement the <code>copyWithZone</code> method to ensure that the new copy gets the renderer as well. (Caveat, while I am a Python developer, and an Objective-C cocoa developer, I haven't used PyObjC myself, so I can't say for certain if you should be implementing <code>copyWithZone</code> or <code>__copy__</code>).</p>
<p>In fact, shoving a <code>copyWithZone</code> method into the class with a print will allow you to tell if the method is being called and if that's the reason renderer appears to have vanished.</p>
<p><hr /></p>
<p><strong>Edit</strong>: Base on your feedback, I've pasted your code into a blank xcode python project (just substituting something else for gv.CoreRenderer, since I don't have that), and it works fine with some minor modifications. How are you instantiating your SceneView?</p>
<p>In my case I:</p>
<ul>
<li>Created a blank xcode project using the Cocoa-Python template</li>
<li>Created a new file called <code>SceneView.py</code>. I pasted in your code.</li>
<li>Opened the <code>MainMenu.xib</code> file, and dragged an NSOpenGLView box onto the window.</li>
<li>With the NSOpenGLView box selected, I went to the attributes inspector and changed the class of the box to <code>SceneView</code></li>
<li>Back in xcode, I added <code>import SceneView</code> in the imports in <code>main.py</code> so that the class would be available when the xib file is loaded</li>
<li>I implemented an <code>awakeFromNib</code> method in <code>SceneView.py</code> to handle setting up <code>self.renderer</code>. Note that <code>__init__</code>, and <code>initWithFrame</code> are not called for nib objects during your program execution... they are considered "serialized" into the nib file, and therefore already instantiated. I'm glossing over some details, but this is why awakeFromNib exists.</li>
<li>Everything worked on run. The <code>__dict__</code> had appropriate values in the <code>drawRect_</code> call, and such.</li>
</ul>
<p>Here's the awakeFromNib function:</p>
<pre><code>def awakeFromNib(self):
print "Awake from nib"
self.renderer = gv.CoreRenderer()
</code></pre>
<p>So, I'm guessing there are just some crossed wires somewhere in how your object is being instantiated and/or added to the view. Are you using Interface Builder for your object, or are you manually creating it and adding it to a view later? I'm curious to see that you are getting loggin outputs from initWithFrame, which is why I'm asking how you are creating the SceneView.</p>
| 3
|
2009-04-04T11:14:01Z
|
[
"python",
"xcode",
"osx",
"pyobjc"
] |
Why is my PyObjc Cocoa view class forgetting its fields?
| 716,386
|
<p>I was trying to hack up a tool to visualize shaders for my game and I figured I would try using python and cocoa. I have ran into a brick wall of sorts though. Maybe its my somewhat poor understand of objective c but I can not seem to get this code for a view I was trying to write working:</p>
<pre><code>from objc import YES, NO, IBAction, IBOutlet
from Foundation import *
from AppKit import *
import gv
class SceneView(NSOpenGLView):
def __init__(self):
NSOpenGLView.__init__(self)
self.renderer = None
def doinit(self):
self.renderer = gv.CoreRenderer()
def initWithFrame_(self, frame):
self = super(SceneView, self).initWithFrame_(frame)
if self:
self.doinit()
print self.__dict__
return self
def drawRect_(self, rect):
clearColor = [0.0,0.0,0.0,0.0]
print self.__dict__
self.renderer.clear(CF_Target|CF_ZBuffer,clearColor)
</code></pre>
<p>It outputs this when executed:</p>
<pre><code>{'renderer': <gv.CoreRenderer; proxy of <Swig Object of type 'GV::CoreRenderer *' at 0x202c7d0> >}
{}
2009-04-03 19:13:30.941 geom-view-edit[50154:10b] An exception has occured:
Traceback (most recent call last):
File "/System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/PyObjCTools/AppHelper.py", line 235, in runEventLoop
File "/mnt/gilead/amcharg/projects/geom-view-edit/build/Debug/geom-view-edit.app/Contents/Resources/SceneView.py", line 37, in drawRect_
self.renderer.clear(CF_Target|CF_ZBuffer,clearColor)
AttributeError: 'SceneView' object has no attribute 'renderer'
</code></pre>
<p>It seems to be losing my renderer variable which is not that surprising considering how funky the initWithFrame_ code is but this was something xcode seemed to write which I suppose makes sense since objective C has the init separate from alloc idiom. It is still strange seeing it python however.</p>
<p>Is there anyways to salvage this or should I take it out behind the code shed shoot it and use QT or wxPython? I considered using objective-c but I want to test out these nifty swig bindings I just compiled =)</p>
| 1
|
2009-04-04T02:33:10Z
| 717,655
|
<p>Even if they weren't serialized, the __init__-constructor of python isn't supported by the ObjectiveC-bridge. So one needs to overload e.g. initWithFrame: for self-created Views.</p>
| 2
|
2009-04-04T19:28:33Z
|
[
"python",
"xcode",
"osx",
"pyobjc"
] |
Packaging Ruby or Python applications for distribution?
| 716,524
|
<p>Are there any good options <em>other</em> than the JVM for packaging Python or Ruby applications for distribution to end-users? Specifically, I'm looking for ways to be able to write and test a web-based application written in either Ruby or Python, complete with a back-end database, that I can then wrap up in a convenient set of platform-independent packages (of some type) for deployment on Windows, Linux, OS X, and FreeBSD?</p>
<p><b>Edit:</b> What I mean by a 'web-based application' is a webapp that end-users can run on servers at their companies, providing a web service internally to their end-users. There are a lot of ways to do this on the JVM via JPython or JRuby, but I'm curious if there's a non-JVM route with alternate VMs or interpreters.</p>
| 4
|
2009-04-04T04:52:53Z
| 716,538
|
<p>For Python, there's <a href="http://docs.python.org/library/distutils.html" rel="nofollow">distutils</a>, and Ars Technica had a <a href="http://arstechnica.com/open-source/guides/2009/03/how-to-deploying-pyqt-applications-on-windows-and-mac-os-x.ars" rel="nofollow">pretty good article</a> on packaging cross-platform PyQt applications a while back. This will get you set up so you can at least bundle things up into packages that can be deployed on multiple platforms, which is reasonable for free stuff.</p>
<p>I'm not sure this is really a better way to distribute things than using the JVM if you're trying to distribute proprietary code.</p>
| 4
|
2009-04-04T05:08:36Z
|
[
"python",
"ruby",
"deployment"
] |
Packaging Ruby or Python applications for distribution?
| 716,524
|
<p>Are there any good options <em>other</em> than the JVM for packaging Python or Ruby applications for distribution to end-users? Specifically, I'm looking for ways to be able to write and test a web-based application written in either Ruby or Python, complete with a back-end database, that I can then wrap up in a convenient set of platform-independent packages (of some type) for deployment on Windows, Linux, OS X, and FreeBSD?</p>
<p><b>Edit:</b> What I mean by a 'web-based application' is a webapp that end-users can run on servers at their companies, providing a web service internally to their end-users. There are a lot of ways to do this on the JVM via JPython or JRuby, but I'm curious if there's a non-JVM route with alternate VMs or interpreters.</p>
| 4
|
2009-04-04T04:52:53Z
| 717,159
|
<p>I'm not sure I understand you here. You want to create a web-based application that you want to ship to end-users? I'm not sure how to interpret that:</p>
<ul>
<li>You want to create an app with a custom GUI that uses a network connection to grab data and stores some information locally in a database?</li>
<li>You want to create a RoR/Django-type app that users can install on a webserver, and then access their own instance through the browser?</li>
</ul>
<p>I can't speak to python, but you could use <a href="http://wiki.github.com/why/shoes" rel="nofollow">Shoes</a> to create and package a custom GUI for Ruby (cross-platform). For packaging a webserver-based/browser-GUI app, I think the Ruby on Rails community has built some tools for that - possibly <a href="http://www.capify.org" rel="nofollow">Capistrano</a> - but then again, I don't do a lot of RoR development.</p>
| 2
|
2009-04-04T14:10:28Z
|
[
"python",
"ruby",
"deployment"
] |
Packaging Ruby or Python applications for distribution?
| 716,524
|
<p>Are there any good options <em>other</em> than the JVM for packaging Python or Ruby applications for distribution to end-users? Specifically, I'm looking for ways to be able to write and test a web-based application written in either Ruby or Python, complete with a back-end database, that I can then wrap up in a convenient set of platform-independent packages (of some type) for deployment on Windows, Linux, OS X, and FreeBSD?</p>
<p><b>Edit:</b> What I mean by a 'web-based application' is a webapp that end-users can run on servers at their companies, providing a web service internally to their end-users. There are a lot of ways to do this on the JVM via JPython or JRuby, but I'm curious if there's a non-JVM route with alternate VMs or interpreters.</p>
| 4
|
2009-04-04T04:52:53Z
| 718,216
|
<p>You can't strictly do this (creating a single installer/executable) in a general cross-platform way, because different platforms use different executable formats. The JVM thing is relying on having a platform-specific JVM already installed on the destination computer; if there is <em>not</em> one installed, then your JAR won't run unless you install a JVM in a platform-specific way. Perhaps more importantly, any third-party Python packages that rely on binary extensions will not play well with Jython unless specifically released in a Jython version, which is unusual. (I presume that a similar situation holds for Ruby packages, though I have no direct knowledge there, nor even how common it is for Ruby packages to use binary extensions....) You'd be able to use the whole range of Java libraries, but very little in the way of Python/Ruby libraries. It's also worth noting that the JVM versions of languages tend to lag behind the standard version, offering fewer language features and less-frequent bugfixes.</p>
<p>If your code is pure Python, then it's already cross-platform as long as the destination machine already has Python installed, just as Java is... but at least in Windows, it's rather less safe to assume that Python is installed than to assume that Java is installed. The third-party elements (database, etc) are likely to be platform-specific binaries, too. User expectations about what's a reasonable installation process vary considerably across platforms, too -- if your app uses third-party libraries or tools, you'd better include all of them for Windows users, but *nix users tend to be more tolerant of downloading dependencies. (However, expectations for that to be handled automatically by a package manager are growing...)</p>
<p>Really, if this is a large-ish application stack and you want to be able to have a drop-in bundle that can be deployed on almost any server, the easiest route would probably be to distribute it as a complete VMWare virtual machine -- the player software is free (for at least Windows and *nix, but I presume for Mac as well), and it allows you to create a dedicated Linux/BSD system that's already fully configured specifically for your application. (I say Linux/BSD because then you don't need to worry about OS licensing fees...)</p>
<p>(If it's a smaller application that you want to allow to run on a client's existing webserver, then I suspect that cross-OS compatibility will be less of a concern than cross-webserver compatibility -- while Apache <em>does</em> have a Windows version, the vast majority of Windows webservers run IIS, and having a single package distribution (or even single version of your application) that plays well with both of those webservers is likely to be impractical.)</p>
| 1
|
2009-04-05T02:22:44Z
|
[
"python",
"ruby",
"deployment"
] |
Packaging Ruby or Python applications for distribution?
| 716,524
|
<p>Are there any good options <em>other</em> than the JVM for packaging Python or Ruby applications for distribution to end-users? Specifically, I'm looking for ways to be able to write and test a web-based application written in either Ruby or Python, complete with a back-end database, that I can then wrap up in a convenient set of platform-independent packages (of some type) for deployment on Windows, Linux, OS X, and FreeBSD?</p>
<p><b>Edit:</b> What I mean by a 'web-based application' is a webapp that end-users can run on servers at their companies, providing a web service internally to their end-users. There are a lot of ways to do this on the JVM via JPython or JRuby, but I'm curious if there's a non-JVM route with alternate VMs or interpreters.</p>
| 4
|
2009-04-04T04:52:53Z
| 7,002,189
|
<p>You can either distribute the app as a virtual machine or create an installer that includes all dependencies, like the GitHub guys did for their on-premise version.</p>
| 1
|
2011-08-09T20:00:27Z
|
[
"python",
"ruby",
"deployment"
] |
Locating (file/line) the invocation of a constructor in python
| 716,795
|
<p>I'm implementing a event system: Various pieces of code will post events to a central place where they will be distributed to all listeners. The main problem with this approach: When an exception happens during event processing, I can't tell anymore who posted the event.</p>
<p>So my question is: Is there an efficient way to figure out who called the constructor and remember that in Python 2.5?</p>
<p>More info: The simple way would be to use the traceback module to get a copy of the stack in the constructor and remember that. Alas, I only need this information rarely, so I'm wondering if there was a way to cache this or whether I could just remember the topmost stack frame and work my way back in the rare case that I actually need this data.</p>
| 1
|
2009-04-04T08:58:33Z
| 716,803
|
<p>It may be worthwhile to attach a hash of the stack trace to the constructor of your event and to store the actual contents in memcache with the hash as the key.</p>
| 0
|
2009-04-04T09:06:57Z
|
[
"python",
"exception",
"event-handling",
"stack-trace"
] |
Locating (file/line) the invocation of a constructor in python
| 716,795
|
<p>I'm implementing a event system: Various pieces of code will post events to a central place where they will be distributed to all listeners. The main problem with this approach: When an exception happens during event processing, I can't tell anymore who posted the event.</p>
<p>So my question is: Is there an efficient way to figure out who called the constructor and remember that in Python 2.5?</p>
<p>More info: The simple way would be to use the traceback module to get a copy of the stack in the constructor and remember that. Alas, I only need this information rarely, so I'm wondering if there was a way to cache this or whether I could just remember the topmost stack frame and work my way back in the rare case that I actually need this data.</p>
| 1
|
2009-04-04T08:58:33Z
| 716,829
|
<pre><code>import sys
def get_caller(ext=False):
""" Get the caller of the caller of this function. If the optional ext parameter is given, returns the line's text as well. """
f=sys._getframe(2)
s=(f.f_code.co_filename, f.f_lineno)
del f
if ext:
import linecache
s=(s[0], s[1], linecache.getline(s[0], s[1]))
return s
def post_event(e):
caller=get_caller(True)
print "Event %r posted from %r"%(e, caller)
## Testing the functions.
def q():
post_event("baz")
post_event("foo")
print "Hello!"
q()
</code></pre>
<p>results in </p>
<pre><code>Event 'foo' posted from ('getcaller.py', 20, 'post_event("foo")\n')
Hello!
Event 'baz' posted from ('getcaller.py', 17, '\tpost_event("baz")\n')
</code></pre>
| 1
|
2009-04-04T09:41:55Z
|
[
"python",
"exception",
"event-handling",
"stack-trace"
] |
Locating (file/line) the invocation of a constructor in python
| 716,795
|
<p>I'm implementing a event system: Various pieces of code will post events to a central place where they will be distributed to all listeners. The main problem with this approach: When an exception happens during event processing, I can't tell anymore who posted the event.</p>
<p>So my question is: Is there an efficient way to figure out who called the constructor and remember that in Python 2.5?</p>
<p>More info: The simple way would be to use the traceback module to get a copy of the stack in the constructor and remember that. Alas, I only need this information rarely, so I'm wondering if there was a way to cache this or whether I could just remember the topmost stack frame and work my way back in the rare case that I actually need this data.</p>
| 1
|
2009-04-04T08:58:33Z
| 716,855
|
<p>You could simply store a reference to the caller's frame object, but this is probably a bad idea. This keeps the frames alive, and also holds references to all the local variables used, so it may impact performance if they happen to be using large chunks of memory, and could have even worse effects if they're relying (incorrectly) on finalization to destroy resources like locks and filehandles when they go out of scope.</p>
<p>That means you'd need to hold a string representation of the stacktrace instead, which is not ideal for your purposes (need to actually do some processing to get it, even though it's rarely needed). Unfortunately, there doesn't seem to be much way around this, though you could consider disabling it until you set some configuration option. That way you'd get better performance for the common case, but could still enable the setting when trying to diagnose failures.</p>
<p>If your calling function alone (or some small number of parent callers) is enough to distinguish the route (ie. the trace is always the same when called via func1(), and there's no func2 -> func1() vs func3() -> func1() to distinguish between ), you could maintain a hash based on filename and line number of the calling frame (or the last two calling frames etc). However this probably doesn't match your situation, and where it doesn't, you'd end up with bogus stack traces.</p>
<p>Note that if you do want the caller's frame, using <a href="http://docs.python.org/library/inspect.html#inspect.currentframe" rel="nofollow"><code>inspect.currentframe(depth)</code></a> is probably a better way to get it.</p>
| 1
|
2009-04-04T10:15:51Z
|
[
"python",
"exception",
"event-handling",
"stack-trace"
] |
Locating (file/line) the invocation of a constructor in python
| 716,795
|
<p>I'm implementing a event system: Various pieces of code will post events to a central place where they will be distributed to all listeners. The main problem with this approach: When an exception happens during event processing, I can't tell anymore who posted the event.</p>
<p>So my question is: Is there an efficient way to figure out who called the constructor and remember that in Python 2.5?</p>
<p>More info: The simple way would be to use the traceback module to get a copy of the stack in the constructor and remember that. Alas, I only need this information rarely, so I'm wondering if there was a way to cache this or whether I could just remember the topmost stack frame and work my way back in the rare case that I actually need this data.</p>
| 1
|
2009-04-04T08:58:33Z
| 718,230
|
<p>I'd think that the <i>simplest</i> method would be to add an ID field to the event(s) in question, and to have each event source (by whatever definition of 'event source' is appropriate here) provide a unique identifier when it posts the event. You do get slightly more overhead, but probably not enough to be problematic, and I'd suspect that you'll find other ways that knowing an event's source would be helpful. </p>
| 1
|
2009-04-05T02:37:33Z
|
[
"python",
"exception",
"event-handling",
"stack-trace"
] |
How do I enable SMS notifications in my web apps?
| 716,946
|
<p>I have a web application and I would like to enable real time SMS notifications to the users of the applications. </p>
<p>Note: I currently cannot use the Twitter API because I live in West Africa, and Twitter doesn't send SMS to my country.</p>
<p>Also email2sms is not an option because the mobile operators don't allow that in my country.</p>
| 1
|
2009-04-04T11:47:00Z
| 716,953
|
<p>I don't have any knowledge in this area. But I think you'll have to talk to the mobile operators, and see if they have any API for sending SMS messages.
You'll probably have to pay them, or have some scheme for customers to pay them. Alternatively there might be some 3rd party that implements this functionality.</p>
| 0
|
2009-04-04T11:58:09Z
|
[
"python",
"sms",
"notifications"
] |
How do I enable SMS notifications in my web apps?
| 716,946
|
<p>I have a web application and I would like to enable real time SMS notifications to the users of the applications. </p>
<p>Note: I currently cannot use the Twitter API because I live in West Africa, and Twitter doesn't send SMS to my country.</p>
<p>Also email2sms is not an option because the mobile operators don't allow that in my country.</p>
| 1
|
2009-04-04T11:47:00Z
| 716,956
|
<p>What about using a proper sms gateway. These guys got APIs for several languages:</p>
<p><a href="http://www.clickatell.com/developers/php.php" rel="nofollow">http://www.clickatell.com/developers/php.php</a></p>
<p>There is an unofficial Python API too </p>
<p><a href="http://www.arnebrodowski.de/projects/clickatell/" rel="nofollow">http://www.arnebrodowski.de/projects/clickatell/</a></p>
| 3
|
2009-04-04T12:01:38Z
|
[
"python",
"sms",
"notifications"
] |
How do I enable SMS notifications in my web apps?
| 716,946
|
<p>I have a web application and I would like to enable real time SMS notifications to the users of the applications. </p>
<p>Note: I currently cannot use the Twitter API because I live in West Africa, and Twitter doesn't send SMS to my country.</p>
<p>Also email2sms is not an option because the mobile operators don't allow that in my country.</p>
| 1
|
2009-04-04T11:47:00Z
| 716,962
|
<p>There are a couple of options.</p>
<ul>
<li>Get some kind of SMS modem or connectivity and use your own cell phone using <a href="http://smslib.org/" rel="nofollow">smslib</a>. I am sorry I don't provide python interfaces but my experience is Java. The downside is that you will pay the full consumer rate. And you will have to put a cell phone on your data center.</li>
<li>Connect to <a href="http://en.wikipedia.org/wiki/Short%5Fmessage%5Fpeer-to-peer%5Fprotocol" rel="nofollow">SMPP</a> gateway. You will have to talk to the mobile operator in order to make this work. There is a library called <a href="http://code.google.com/p/jsmpp/" rel="nofollow">jsmpp here</a>. Again, I am sorry it is not python.</li>
<li>If it is too much of a hassle you could use an intermediary, which provides HTTP-SMS gateways, like <a href="http://www.ericsson.com/solutions/ipx/" rel="nofollow">this one</a>. That's easy because you don't need to use SMPP and your system administrators wont bark at you for putting cell phones in the datacenter.</li>
</ul>
| 4
|
2009-04-04T12:05:42Z
|
[
"python",
"sms",
"notifications"
] |
How do I enable SMS notifications in my web apps?
| 716,946
|
<p>I have a web application and I would like to enable real time SMS notifications to the users of the applications. </p>
<p>Note: I currently cannot use the Twitter API because I live in West Africa, and Twitter doesn't send SMS to my country.</p>
<p>Also email2sms is not an option because the mobile operators don't allow that in my country.</p>
| 1
|
2009-04-04T11:47:00Z
| 1,071,496
|
<p>Another SMS gateway with a Python interface is TextMagic. Their Python API is available from the Google Code project <a href="https://github.com/dfstrauss/textmagic-sms-api-python" rel="nofollow">textmagic-sms-api-python</a>. They have libraries available for other languages as well; all wrapping a simple HTTPS API.</p>
<p>Code samples from the project website:</p>
<p>How to send an SMS:</p>
<pre><code>import textmagic.client
client = textmagic.client.TextMagicClient('your_username', 'your_api_password')
result = client.send("Hello, World!", "1234567890")
message_id = result['message_id'].keys()[0]
</code></pre>
<p>And retrieve its delivery status:</p>
<pre><code>response = client.message_status(message_id)
status = response[message_id]['status']
</code></pre>
<p>(Full disclosure: I am the author of the Python wrapper library)</p>
| 3
|
2009-07-01T21:30:54Z
|
[
"python",
"sms",
"notifications"
] |
How do I enable SMS notifications in my web apps?
| 716,946
|
<p>I have a web application and I would like to enable real time SMS notifications to the users of the applications. </p>
<p>Note: I currently cannot use the Twitter API because I live in West Africa, and Twitter doesn't send SMS to my country.</p>
<p>Also email2sms is not an option because the mobile operators don't allow that in my country.</p>
| 1
|
2009-04-04T11:47:00Z
| 5,414,483
|
<p>The easiest way to accomplish this is by using a third party API. Some I know that work well are:</p>
<ul>
<li>restSms.me</li>
<li>Twilio.com</li>
<li>Clicatell.com</li>
</ul>
<p>I have used all of them and they easiest/cheapest one to implement was restSms.me</p>
<p>Hope that helps.</p>
| 2
|
2011-03-24T03:38:58Z
|
[
"python",
"sms",
"notifications"
] |
How do I enable SMS notifications in my web apps?
| 716,946
|
<p>I have a web application and I would like to enable real time SMS notifications to the users of the applications. </p>
<p>Note: I currently cannot use the Twitter API because I live in West Africa, and Twitter doesn't send SMS to my country.</p>
<p>Also email2sms is not an option because the mobile operators don't allow that in my country.</p>
| 1
|
2009-04-04T11:47:00Z
| 35,903,945
|
<p>Warning: extremely elegant solution ahead! (Android app)</p>
<p>If you want to send SMS to any number in as simple of a manner as sending an e-mail:</p>
<pre><code>mail('configuredEMail@configuredDomain', '0981122334', 'SMS message'); // PHP
</code></pre>
<p>or even:</p>
<pre><code>echo 'SMS message' | mail -s '0981234567' configuredEMail@configuredDomain.com
</code></pre>
<p>or even from a GUI mail client, then read on.</p>
<p>To skip explanations google Evorion SMS Gateway.</p>
<p>What does it do? It forwards e-mail to SMS with a built-in battery saver.
In order to send an SMS you simply send an email to 'configuredEMail@configuredDomain.com' with Subject 'phoneNumberToForwardTo'.</p>
<p>Code contributions welcome.</p>
| 0
|
2016-03-09T22:27:46Z
|
[
"python",
"sms",
"notifications"
] |
How do I enable SMS notifications in my web apps?
| 716,946
|
<p>I have a web application and I would like to enable real time SMS notifications to the users of the applications. </p>
<p>Note: I currently cannot use the Twitter API because I live in West Africa, and Twitter doesn't send SMS to my country.</p>
<p>Also email2sms is not an option because the mobile operators don't allow that in my country.</p>
| 1
|
2009-04-04T11:47:00Z
| 36,032,986
|
<p>If your country is in <a href="https://www.twilio.com/international" rel="nofollow">this list</a>, Twilio is an extremely easy API to use :)</p>
| 0
|
2016-03-16T10:28:38Z
|
[
"python",
"sms",
"notifications"
] |
Python's subprocess.Popen returns the same stdout even though it shouldn't
| 717,120
|
<p>I'm having a very strange issue with Python's subprocess.Popen. I'm using it to call several times an external exe and keep the output in a list. </p>
<p>Every time you call this external exe, it will return <strong>a different string</strong>. However, if I call it several times using Popen, it will always <strong>return the SAME string</strong>. =:-O </p>
<p>It looks like Popen is returning always the same value from stdout, without recalling the exe. Maybe doing some sort of caching without actually calling again the exe.</p>
<p>This is my code:</p>
<pre><code>def get_key():
from subprocess import Popen, PIPE
args = [C_KEY_MAKER, '/26', USER_NAME, ENCRYPTION_TEMPLATE, '0', ]
process = Popen(args, stdout=PIPE)
output = process.communicate()[0].strip()
return output
if __name__ == '__main__':
print get_key() # Returns a certain string
print get_key() # Should return another string, but returns the same!
</code></pre>
<p>What on Earth am I doing wrong?!</p>
| 1
|
2009-04-04T13:49:46Z
| 717,143
|
<p>Nothing. That works fine, on my own tests (aside from your indentation error at the bottom). The problem is either in your exe. or elsewhere.</p>
<p>To clarify, I created a python program tfile.py</p>
<pre><code>cat > tfile.py
#!/usr/bin/env python
import random
print random.random()
</code></pre>
<p>And then altered tthe program to get rid of the indentation problem at the bottom, and to call tfile.py . It did give two different results.</p>
| 1
|
2009-04-04T13:59:45Z
|
[
"python",
"subprocess",
"stdout",
"popen"
] |
Python's subprocess.Popen returns the same stdout even though it shouldn't
| 717,120
|
<p>I'm having a very strange issue with Python's subprocess.Popen. I'm using it to call several times an external exe and keep the output in a list. </p>
<p>Every time you call this external exe, it will return <strong>a different string</strong>. However, if I call it several times using Popen, it will always <strong>return the SAME string</strong>. =:-O </p>
<p>It looks like Popen is returning always the same value from stdout, without recalling the exe. Maybe doing some sort of caching without actually calling again the exe.</p>
<p>This is my code:</p>
<pre><code>def get_key():
from subprocess import Popen, PIPE
args = [C_KEY_MAKER, '/26', USER_NAME, ENCRYPTION_TEMPLATE, '0', ]
process = Popen(args, stdout=PIPE)
output = process.communicate()[0].strip()
return output
if __name__ == '__main__':
print get_key() # Returns a certain string
print get_key() # Should return another string, but returns the same!
</code></pre>
<p>What on Earth am I doing wrong?!</p>
| 1
|
2009-04-04T13:49:46Z
| 717,160
|
<p>Your code is not executable as is so it's hard to help you out much. Consider fixing indentation and syntax and making it self-contained, so that we can give it a try.</p>
<p>On Linux, it seems to work fine according to Devin Jeanpierre.</p>
| 0
|
2009-04-04T14:10:51Z
|
[
"python",
"subprocess",
"stdout",
"popen"
] |
Python's subprocess.Popen returns the same stdout even though it shouldn't
| 717,120
|
<p>I'm having a very strange issue with Python's subprocess.Popen. I'm using it to call several times an external exe and keep the output in a list. </p>
<p>Every time you call this external exe, it will return <strong>a different string</strong>. However, if I call it several times using Popen, it will always <strong>return the SAME string</strong>. =:-O </p>
<p>It looks like Popen is returning always the same value from stdout, without recalling the exe. Maybe doing some sort of caching without actually calling again the exe.</p>
<p>This is my code:</p>
<pre><code>def get_key():
from subprocess import Popen, PIPE
args = [C_KEY_MAKER, '/26', USER_NAME, ENCRYPTION_TEMPLATE, '0', ]
process = Popen(args, stdout=PIPE)
output = process.communicate()[0].strip()
return output
if __name__ == '__main__':
print get_key() # Returns a certain string
print get_key() # Should return another string, but returns the same!
</code></pre>
<p>What on Earth am I doing wrong?!</p>
| 1
|
2009-04-04T13:49:46Z
| 718,047
|
<p>I don't know what is going wrong with your example, I cannot replicate this behaviour, however try a more by-the-book approach:</p>
<pre><code>def get_key():
from subprocess import Popen, PIPE
args = [C_KEY_MAKER, '/26', USER_NAME, ENCRYPTION_TEMPLATE, '0', ]
output = Popen(args, stdout=PIPE).stdout
data = output.read().strip()
output.close()
return data
</code></pre>
| 1
|
2009-04-04T23:38:53Z
|
[
"python",
"subprocess",
"stdout",
"popen"
] |
Python's subprocess.Popen returns the same stdout even though it shouldn't
| 717,120
|
<p>I'm having a very strange issue with Python's subprocess.Popen. I'm using it to call several times an external exe and keep the output in a list. </p>
<p>Every time you call this external exe, it will return <strong>a different string</strong>. However, if I call it several times using Popen, it will always <strong>return the SAME string</strong>. =:-O </p>
<p>It looks like Popen is returning always the same value from stdout, without recalling the exe. Maybe doing some sort of caching without actually calling again the exe.</p>
<p>This is my code:</p>
<pre><code>def get_key():
from subprocess import Popen, PIPE
args = [C_KEY_MAKER, '/26', USER_NAME, ENCRYPTION_TEMPLATE, '0', ]
process = Popen(args, stdout=PIPE)
output = process.communicate()[0].strip()
return output
if __name__ == '__main__':
print get_key() # Returns a certain string
print get_key() # Should return another string, but returns the same!
</code></pre>
<p>What on Earth am I doing wrong?!</p>
| 1
|
2009-04-04T13:49:46Z
| 1,124,714
|
<p>It is possible (if <code>C_KEY_MAKER</code>'s random behaviour is based on the current time in seconds, or similar) that when you run it twice on the command line, the time has changed in between runs and so you get a different output, but when python runs it, it runs it twice in such quick succession that the time hasn't changed and so it returns the same value twice in a row.</p>
| 3
|
2009-07-14T11:08:41Z
|
[
"python",
"subprocess",
"stdout",
"popen"
] |
Queue.Queue vs. collections.deque
| 717,148
|
<p>I need a queue which multiple threads can put stuff into, and multiple threads may read from.</p>
<p>Python has at least two queue classes, Queue.Queue and collections.deque, with the former seemingly using the latter internally. Both claim to be thread-safe in the documentation.</p>
<p>However, the Queue docs also state:</p>
<blockquote>
<p>collections.deque is an alternative
implementation of unbounded queues
with fast atomic append() and
popleft() operations that do not
require locking.</p>
</blockquote>
<p>Which I guess I don't quite unterstand: Does this mean deque isn't fully thread-safe after all?</p>
<p>If it is, I may not fully understand the difference between the two classes. I can see that Queue adds blocking functionality. On the other hand, it loses some deque features like support for the in-operator.</p>
<p>Accessing the internal deque object directly, is</p>
<blockquote>
<p>x in Queue().deque</p>
</blockquote>
<p>thread-safe?</p>
<p>Also, why does Queue employ a mutex for it's operations when deque is thread-safe already?</p>
| 85
|
2009-04-04T14:03:09Z
| 717,199
|
<p><code>deque</code> is thread-safe. "operations that do not require locking" means that you don't have to do the locking yourself, the <code>deque</code> takes care of it.</p>
<p>Taking a look at the <code>Queue</code> source, the internal deque is called <code>self.queue</code> and uses a mutex for accessors and mutations, so <code>Queue().queue</code> is <em>not</em> thread-safe to use.</p>
<p>If you're looking for an "in" operator, then a deque or queue is possibly not the most appropriate data structure for your problem.</p>
| 3
|
2009-04-04T14:42:23Z
|
[
"python",
"thread-safety",
"queue"
] |
Queue.Queue vs. collections.deque
| 717,148
|
<p>I need a queue which multiple threads can put stuff into, and multiple threads may read from.</p>
<p>Python has at least two queue classes, Queue.Queue and collections.deque, with the former seemingly using the latter internally. Both claim to be thread-safe in the documentation.</p>
<p>However, the Queue docs also state:</p>
<blockquote>
<p>collections.deque is an alternative
implementation of unbounded queues
with fast atomic append() and
popleft() operations that do not
require locking.</p>
</blockquote>
<p>Which I guess I don't quite unterstand: Does this mean deque isn't fully thread-safe after all?</p>
<p>If it is, I may not fully understand the difference between the two classes. I can see that Queue adds blocking functionality. On the other hand, it loses some deque features like support for the in-operator.</p>
<p>Accessing the internal deque object directly, is</p>
<blockquote>
<p>x in Queue().deque</p>
</blockquote>
<p>thread-safe?</p>
<p>Also, why does Queue employ a mutex for it's operations when deque is thread-safe already?</p>
| 85
|
2009-04-04T14:03:09Z
| 717,261
|
<p><code>Queue.Queue</code> and <code>collections.deque</code> serve different purposes. Queue.Queue is intended for allowing different threads to communicate using queued messages/data, whereas <code>collections.deque</code> is simply intended as a datastructure. That's why <code>Queue.Queue</code> has methods like <code>put_nowait()</code>, <code>get_nowait()</code>, and <code>join()</code>, whereas <code>collections.deque</code> doesn't. <code>Queue.Queue</code> isn't intended to be used as a collection, which is why it lacks the likes of the <code>in</code> operator.</p>
<p>It boils down to this: if you have multiple threads and you want them to be able to communicate without the need for locks, you're looking for <code>Queue.Queue</code>; if you just want a queue or a double-ended queue as a datastructure, use <code>collections.deque</code>.</p>
<p>Finally, accessing and manipulating the internal deque of a <code>Queue.Queue</code> is playing with fire - you really don't want to be doing that.</p>
| 142
|
2009-04-04T15:26:29Z
|
[
"python",
"thread-safety",
"queue"
] |
Queue.Queue vs. collections.deque
| 717,148
|
<p>I need a queue which multiple threads can put stuff into, and multiple threads may read from.</p>
<p>Python has at least two queue classes, Queue.Queue and collections.deque, with the former seemingly using the latter internally. Both claim to be thread-safe in the documentation.</p>
<p>However, the Queue docs also state:</p>
<blockquote>
<p>collections.deque is an alternative
implementation of unbounded queues
with fast atomic append() and
popleft() operations that do not
require locking.</p>
</blockquote>
<p>Which I guess I don't quite unterstand: Does this mean deque isn't fully thread-safe after all?</p>
<p>If it is, I may not fully understand the difference between the two classes. I can see that Queue adds blocking functionality. On the other hand, it loses some deque features like support for the in-operator.</p>
<p>Accessing the internal deque object directly, is</p>
<blockquote>
<p>x in Queue().deque</p>
</blockquote>
<p>thread-safe?</p>
<p>Also, why does Queue employ a mutex for it's operations when deque is thread-safe already?</p>
| 85
|
2009-04-04T14:03:09Z
| 20,330,499
|
<p>If all you're looking for is <strong>a thread-safe way to transfer objects between threads</strong>, then both would work (both for FIFO and LIFO). For FIFO:</p>
<ul>
<li><a href="http://docs.python.org/2/library/queue.html#"><code>Queue.put()</code> and <code>Queue.get()</code> are thread-safe</a></li>
<li><a href="http://docs.python.org/2/library/collections.html#deque-objects"><code>deque.append()</code> and <code>deque.popleft()</code> are thread-safe</a></li>
</ul>
<p>Note:</p>
<ul>
<li>Other operations on <code>deque</code> might not be thread safe, I'm not sure.</li>
<li><code>deque</code> does not block on <code>pop()</code> or <code>popleft()</code> so you can't base your consumer thread flow on blocking till a new item arrives.</li>
</ul>
<p>However, it seems that <strong>deque has a significant efficiency advantage</strong>. Here are some benchmark results in seconds using CPython 2.7.3 for inserting and removing 100k items</p>
<pre><code>deque 0.0747888759791
Queue 1.60079066852
</code></pre>
<p>Here's the benchmark code:</p>
<pre><code>import time
import Queue
import collections
q = collections.deque()
t0 = time.clock()
for i in xrange(100000):
q.append(1)
for i in xrange(100000):
q.popleft()
print 'deque', time.clock() - t0
q = Queue.Queue(200000)
t0 = time.clock()
for i in xrange(100000):
q.put(1)
for i in xrange(100000):
q.get()
print 'Queue', time.clock() - t0
</code></pre>
| 18
|
2013-12-02T14:20:14Z
|
[
"python",
"thread-safety",
"queue"
] |
Queue.Queue vs. collections.deque
| 717,148
|
<p>I need a queue which multiple threads can put stuff into, and multiple threads may read from.</p>
<p>Python has at least two queue classes, Queue.Queue and collections.deque, with the former seemingly using the latter internally. Both claim to be thread-safe in the documentation.</p>
<p>However, the Queue docs also state:</p>
<blockquote>
<p>collections.deque is an alternative
implementation of unbounded queues
with fast atomic append() and
popleft() operations that do not
require locking.</p>
</blockquote>
<p>Which I guess I don't quite unterstand: Does this mean deque isn't fully thread-safe after all?</p>
<p>If it is, I may not fully understand the difference between the two classes. I can see that Queue adds blocking functionality. On the other hand, it loses some deque features like support for the in-operator.</p>
<p>Accessing the internal deque object directly, is</p>
<blockquote>
<p>x in Queue().deque</p>
</blockquote>
<p>thread-safe?</p>
<p>Also, why does Queue employ a mutex for it's operations when deque is thread-safe already?</p>
| 85
|
2009-04-04T14:03:09Z
| 31,672,446
|
<p>(seems I don't have reputation to comment...)
You need to be careful which methods of the deque you use from different threads.</p>
<p>deque.get() appears to be threadsafe, but I have found that doing</p>
<pre><code>for item in a_deque:
process(item)
</code></pre>
<p>can fail if another thread is adding items at the same time.
I got an RuntimeException that complained "deque mutated during iteration".</p>
<p>Check <a href="https://hg.python.org/cpython/file/3.5/Modules/_collectionsmodule.c" rel="nofollow">collectionsmodule.c</a> to see which operations are affected by this</p>
| 0
|
2015-07-28T09:31:09Z
|
[
"python",
"thread-safety",
"queue"
] |
Queue.Queue vs. collections.deque
| 717,148
|
<p>I need a queue which multiple threads can put stuff into, and multiple threads may read from.</p>
<p>Python has at least two queue classes, Queue.Queue and collections.deque, with the former seemingly using the latter internally. Both claim to be thread-safe in the documentation.</p>
<p>However, the Queue docs also state:</p>
<blockquote>
<p>collections.deque is an alternative
implementation of unbounded queues
with fast atomic append() and
popleft() operations that do not
require locking.</p>
</blockquote>
<p>Which I guess I don't quite unterstand: Does this mean deque isn't fully thread-safe after all?</p>
<p>If it is, I may not fully understand the difference between the two classes. I can see that Queue adds blocking functionality. On the other hand, it loses some deque features like support for the in-operator.</p>
<p>Accessing the internal deque object directly, is</p>
<blockquote>
<p>x in Queue().deque</p>
</blockquote>
<p>thread-safe?</p>
<p>Also, why does Queue employ a mutex for it's operations when deque is thread-safe already?</p>
| 85
|
2009-04-04T14:03:09Z
| 34,239,413
|
<p>For information there is a Python ticket referenced for deque thread-safety (<a href="https://bugs.python.org/issue15329" rel="nofollow">https://bugs.python.org/issue15329</a>).
Title "clarify which deque methods are thread-safe"</p>
<p>Bottom line here: <a href="https://bugs.python.org/issue15329#msg199368" rel="nofollow">https://bugs.python.org/issue15329#msg199368</a></p>
<blockquote>
<p>The deque's append(), appendleft(), pop(), popleft(), and len(d)
operations are thread-safe in CPython. The append methods have a
DECREF at the end (for cases where maxlen has been set), but this
happens after all of the structure updates have been made and the
invariants have been restored, so it is okay to treat these operations
as atomic.</p>
</blockquote>
<p>Anyway, if you are not 100% sure and you prefer reliability over performance, just put a like Lock ;)</p>
| 1
|
2015-12-12T11:41:50Z
|
[
"python",
"thread-safety",
"queue"
] |
If monkey patching is permitted in both Ruby and Python, why is it more controversial in Ruby?
| 717,506
|
<p>In many discussions I have heard about Ruby in which people have expressed their reservations about the language, the issue of monkey patching comes up as one of their primary concerns. </p>
<p>However, I rarely hear the same arguments made in the context of Python although it is also permitted in the Python language. </p>
<p>Why this distinction? </p>
<p>Does Python include different types of safeguards to minimize the risks of this feature?</p>
| 12
|
2009-04-04T17:54:50Z
| 717,527
|
<p>The languages might permit it, but neither community condones the practice. Monkeypatching isn't condoned in either language, but you hear about it more often in Ruby because the form of open class it uses makes it very, very easy to monkeypatch a class and because of this, <a href="http://avdi.org/devblog/2008/02/23/why-monkeypatching-is-destroying-ruby/" rel="nofollow">it's more acceptable in the Ruby community, but still frowned upon</a>. Monkeypatching simply isn't as prevalent or as easy in Python, which is why you won't hear the same arguments against it in that community. Python does nothing that Ruby doesn't do to prevent the practice.</p>
<p>The reason you hear/read about it more often in Ruby is that this in Ruby:</p>
<pre class="lang-ruby prettyprint-override"><code>class MyClass
def foo
puts "foo"
end
end
</code></pre>
<pre class="lang-ruby prettyprint-override"><code>class MyClass
def bar
puts "bar"
end
end
</code></pre>
<p>will give you a class that contains two methods, <code>foo</code> and <code>bar</code>, whereas this in Python:</p>
<pre class="lang-python prettyprint-override"><code>class MyClass:
def foo(self):
print "foo"
</code></pre>
<pre class="lang-python prettyprint-override"><code>class MyClass:
def bar(self):
print "bar"
</code></pre>
<p>will leave you with a class that only contains the method <code>bar</code>, as redefinition of a class clobbers the previous definition completely. To monkeypatch in Python, you actually have to write this:</p>
<pre class="lang-python prettyprint-override"><code>class MyClass:
def foo(self):
print "foo"
</code></pre>
<pre class="lang-python prettyprint-override"><code>def bar(self):
print "bar"
MyClass.bar = bar
</code></pre>
<p>which is harder than the Ruby version. That alone makes Ruby code much easier to monkeypatch than Python code.</p>
| 13
|
2009-04-04T18:03:18Z
|
[
"python",
"ruby",
"language-features",
"monkeypatching"
] |
If monkey patching is permitted in both Ruby and Python, why is it more controversial in Ruby?
| 717,506
|
<p>In many discussions I have heard about Ruby in which people have expressed their reservations about the language, the issue of monkey patching comes up as one of their primary concerns. </p>
<p>However, I rarely hear the same arguments made in the context of Python although it is also permitted in the Python language. </p>
<p>Why this distinction? </p>
<p>Does Python include different types of safeguards to minimize the risks of this feature?</p>
| 12
|
2009-04-04T17:54:50Z
| 717,553
|
<p>"Does Python include different types of safeguards to minimize the risks of this feature?" </p>
<p>Yes. The community refuses to do it. The safeguard is entirely social.</p>
| 13
|
2009-04-04T18:17:20Z
|
[
"python",
"ruby",
"language-features",
"monkeypatching"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.