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
sequence
How to generate dynamic (parametrized) unit tests in python?
32,899
<p>I have some kind of test data and want to create an unit test for each item. My first idea was to do it like this:</p> <pre><code>import unittest l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]] class TestSequence(unittest.TestCase): def testsample(self): for name, a,b in l: print "test", name self.assertEqual(a,b) if __name__ == '__main__': unittest.main() </code></pre> <p>The downside of this is that it handles all data in one test. I would like to generate one test for each item on the fly. Any suggestions?</p>
111
2008-08-28T17:49:02Z
31,161,347
<p>I use metaclasses and decorators for generate tests. You can check my implementation <a href="https://github.com/erm0l0v/python_wrap_cases" rel="nofollow">python_wrap_cases</a>. This library doesn't require any test frameworks.</p> <p>Your example:</p> <pre><code>import unittest from python_wrap_cases import wrap_case @wrap_case class TestSequence(unittest.TestCase): @wrap_case("foo", "a", "a") @wrap_case("bar", "a", "b") @wrap_case("lee", "b", "b") def testsample(self, name, a, b): print "test", name self.assertEqual(a, b) </code></pre> <p>Console output:</p> <pre><code>testsample_u'bar'_u'a'_u'b' (tests.example.test_stackoverflow.TestSequence) ... test bar FAIL testsample_u'foo'_u'a'_u'a' (tests.example.test_stackoverflow.TestSequence) ... test foo ok testsample_u'lee'_u'b'_u'b' (tests.example.test_stackoverflow.TestSequence) ... test lee ok </code></pre> <p>Also you may use <em>generators</em>. For example this code generate all possible combinations of tests with arguments <code>a__list</code> and <code>b__list</code></p> <pre><code>import unittest from python_wrap_cases import wrap_case @wrap_case class TestSequence(unittest.TestCase): @wrap_case(a__list=["a", "b"], b__list=["a", "b"]) def testsample(self, a, b): self.assertEqual(a, b) </code></pre> <p>Console output:</p> <pre><code>testsample_a(u'a')_b(u'a') (tests.example.test_stackoverflow.TestSequence) ... ok testsample_a(u'a')_b(u'b') (tests.example.test_stackoverflow.TestSequence) ... FAIL testsample_a(u'b')_b(u'a') (tests.example.test_stackoverflow.TestSequence) ... FAIL testsample_a(u'b')_b(u'b') (tests.example.test_stackoverflow.TestSequence) ... ok </code></pre>
2
2015-07-01T12:28:27Z
[ "python", "unit-testing", "parameterized-unit-test" ]
How to generate dynamic (parametrized) unit tests in python?
32,899
<p>I have some kind of test data and want to create an unit test for each item. My first idea was to do it like this:</p> <pre><code>import unittest l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]] class TestSequence(unittest.TestCase): def testsample(self): for name, a,b in l: print "test", name self.assertEqual(a,b) if __name__ == '__main__': unittest.main() </code></pre> <p>The downside of this is that it handles all data in one test. I would like to generate one test for each item on the fly. Any suggestions?</p>
111
2008-08-28T17:49:02Z
33,884,166
<p>There's also Hypothesis which adds fuzz or property based testing: <a href="https://pypi.python.org/pypi/hypothesis" rel="nofollow">https://pypi.python.org/pypi/hypothesis</a></p> <p>This is a very powerful testing method.</p>
1
2015-11-24T02:00:00Z
[ "python", "unit-testing", "parameterized-unit-test" ]
How to generate dynamic (parametrized) unit tests in python?
32,899
<p>I have some kind of test data and want to create an unit test for each item. My first idea was to do it like this:</p> <pre><code>import unittest l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]] class TestSequence(unittest.TestCase): def testsample(self): for name, a,b in l: print "test", name self.assertEqual(a,b) if __name__ == '__main__': unittest.main() </code></pre> <p>The downside of this is that it handles all data in one test. I would like to generate one test for each item on the fly. Any suggestions?</p>
111
2008-08-28T17:49:02Z
34,382,688
<p>You can use <code>TestSuite</code> and custom <code>TestCase</code> classes. </p> <pre><code>import unittest class CustomTest(unittest.TestCase): def __init__(self, name, a, b): super().__init__() self.name = name self.a = a self.b = b def runTest(self): print("test", name) self.assertEqual(a, b) if __name__ == '__main__': suite = unittest.TestSuite() suite.addTest(CustomTest("Foo", 1337, 1337)) suite.addTest(CustomTest("Bar", 0xDEAD, 0xC0DE)) unittest.TextTestRunner().run(suite) </code></pre>
1
2015-12-20T15:41:54Z
[ "python", "unit-testing", "parameterized-unit-test" ]
How to generate dynamic (parametrized) unit tests in python?
32,899
<p>I have some kind of test data and want to create an unit test for each item. My first idea was to do it like this:</p> <pre><code>import unittest l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]] class TestSequence(unittest.TestCase): def testsample(self): for name, a,b in l: print "test", name self.assertEqual(a,b) if __name__ == '__main__': unittest.main() </code></pre> <p>The downside of this is that it handles all data in one test. I would like to generate one test for each item on the fly. Any suggestions?</p>
111
2008-08-28T17:49:02Z
36,788,233
<p>I'd been having trouble with a very particular style of parameterized tests. All our Selenium tests can run locally, but they also should be able to be run remotely against several platforms on SauceLabs. Basically, I wanted to take a large amount of already-written test cases and parameterize them with the fewest changes to code possible. Furthermore, I needed to be able to pass the parameters into the setUp method, something which I haven't seen any solutions for elsewhere.</p> <p>Here's what I've come up with:</p> <pre><code>import inspect import types test_platforms = [ {'browserName': "internet explorer", 'platform': "Windows 7", 'version': "10.0"}, {'browserName': "internet explorer", 'platform': "Windows 7", 'version': "11.0"}, {'browserName': "firefox", 'platform': "Linux", 'version': "43.0"}, ] def sauce_labs(): def wrapper(cls): return test_on_platforms(cls) return wrapper def test_on_platforms(base_class): for name, function in inspect.getmembers(base_class, inspect.isfunction): if name.startswith('test_'): for platform in test_platforms: new_name = '_'.join(list([name, ''.join(platform['browserName'].title().split()), platform['version']])) new_function = types.FunctionType(function.__code__, function.__globals__, new_name, function.__defaults__, function.__closure__) setattr(new_function, 'platform', platform) setattr(base_class, new_name, new_function) delattr(base_class, name) return base_class </code></pre> <p>With this, all I had to do was add a simple decorator @sauce_labs() to each regular old TestCase, and now when running them, they're wrapped up and rewritten, so that all the test methods are parameterized and renamed. LoginTests.test_login(self) runs as LoginTests.test_login_internet_explorer_10.0(self), LoginTests.test_login_internet_explorer_11.0(self), and LoginTests.test_login_firefox_43.0(self), and each one has the parameter self.platform to decide what browser/platform to run against, even in LoginTests.setUp, which is crucial for my task since that's where the connection to SauceLabs is initialized.</p> <p>Anyway, I hope this might be of help to someone looking to do a similar "global" parameterization of their tests!</p>
0
2016-04-22T08:02:46Z
[ "python", "unit-testing", "parameterized-unit-test" ]
How to generate dynamic (parametrized) unit tests in python?
32,899
<p>I have some kind of test data and want to create an unit test for each item. My first idea was to do it like this:</p> <pre><code>import unittest l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]] class TestSequence(unittest.TestCase): def testsample(self): for name, a,b in l: print "test", name self.assertEqual(a,b) if __name__ == '__main__': unittest.main() </code></pre> <p>The downside of this is that it handles all data in one test. I would like to generate one test for each item on the fly. Any suggestions?</p>
111
2008-08-28T17:49:02Z
37,470,261
<p>Besides using setattr, we can use load_tests since python 3.2. Please refer to blog post <a href="http://blog.livreuro.com/en/coding/python/how-to-generate-discoverable-unit-tests-in-python-dynamically/" rel="nofollow">blog.livreuro.com/en/coding/python/how-to-generate-discoverable-unit-tests-in-python-dynamically/</a></p> <pre><code>class Test(unittest.TestCase): pass def _test(self, file_name): open(file_name, 'r') as f: self.assertEqual('test result',f.read()) def _generate_test(file_name): def test(self): _test(self, file_name) return test def _generate_tests(): for file in files: file_name = os.path.splitext(os.path.basename(file))[0] setattr(Test, 'test_%s' % file_name, _generate_test(file)) test_cases = (Test,) def load_tests(loader, tests, pattern): _generate_tests() suite = TestSuite() for test_class in test_cases: tests = loader.loadTestsFromTestCase(test_class) suite.addTests(tests) return suite if __name__ == '__main__': _generate_tests() unittest.main() </code></pre>
-1
2016-05-26T20:20:39Z
[ "python", "unit-testing", "parameterized-unit-test" ]
How to generate dynamic (parametrized) unit tests in python?
32,899
<p>I have some kind of test data and want to create an unit test for each item. My first idea was to do it like this:</p> <pre><code>import unittest l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]] class TestSequence(unittest.TestCase): def testsample(self): for name, a,b in l: print "test", name self.assertEqual(a,b) if __name__ == '__main__': unittest.main() </code></pre> <p>The downside of this is that it handles all data in one test. I would like to generate one test for each item on the fly. Any suggestions?</p>
111
2008-08-28T17:49:02Z
38,726,022
<p>Following is my solution. I find this useful when: 1. Should work for unittest.Testcase and unittest discover 2. Have a set of tests to be run for different parameter settings. 3. Very simple no dependency on other packages import unittest</p> <pre><code> class BaseClass(unittest.TestCase): def setUp(self): self.param = 2 self.base = 2 def test_me(self): self.assertGreaterEqual(5, self.param+self.base) def test_me_too(self): self.assertLessEqual(3, self.param+self.base) class Child_One(BaseClass): def setUp(self): BaseClass.setUp(self) self.param = 4 class Child_Two(BaseClass): def setUp(self): BaseClass.setUp(self) self.param = 1 </code></pre>
-1
2016-08-02T16:35:17Z
[ "python", "unit-testing", "parameterized-unit-test" ]
How to generate dynamic (parametrized) unit tests in python?
32,899
<p>I have some kind of test data and want to create an unit test for each item. My first idea was to do it like this:</p> <pre><code>import unittest l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]] class TestSequence(unittest.TestCase): def testsample(self): for name, a,b in l: print "test", name self.assertEqual(a,b) if __name__ == '__main__': unittest.main() </code></pre> <p>The downside of this is that it handles all data in one test. I would like to generate one test for each item on the fly. Any suggestions?</p>
111
2008-08-28T17:49:02Z
39,350,898
<p>This solution works with <code>unittest</code> and <code>nose</code>:</p> <pre><code>#!/usr/bin/env python import unittest def make_function(description, a, b): def ghost(self): self.assertEqual(a, b, description) print description ghost.__name__ = 'test_{0}'.format(description) return ghost class TestsContainer(unittest.TestCase): pass testsmap = { 'foo': [1, 1], 'bar': [1, 2], 'baz': [5, 5]} def generator(): for name, params in testsmap.iteritems(): test_func = make_function(name, params[0], params[1]) setattr(TestsContainer, 'test_{0}'.format(name), test_func) generator() if __name__ == '__main__': unittest.main() </code></pre>
0
2016-09-06T13:57:36Z
[ "python", "unit-testing", "parameterized-unit-test" ]
ssh hangs when command invoked directly, but exits cleanly when run interactive
33,475
<p>I need to launch a server on the remote machine and retrieve the port number that the server process is lsitening on. When invoked, the server will listen on a random port and output the port number on stderr.</p> <p>I want to automate the process of logging on to the remote machine, launching the process, and retrieving the port number. I wrote a Python script called "<code>invokejob.py</code>" that lives on the remote machine to act as a wrapper that invokes the job and then returns the port number, it looks like this:</p> <pre><code>import re, subprocess executable = ... # Name of executable regex = ... # Regex to extract the port number from the output p = subprocess.Popen(executable, bufsize=1, # line buffered stderr=subprocess.PIPE ) s = p.stderr.readline() port = re.match(regex).groups()[0] print port </code></pre> <p>If I log in interactively, this script works:</p> <pre><code>$ ssh remotehost.example.com Last login: Thu Aug 28 17:31:18 2008 from localhost $ ./invokejob.py 63409 $ exit logout Connection to remotehost.example.com closed. </code></pre> <p>(Note: successful logout, it did not hang).</p> <p>However, if I try to invoke it from the command-line, it just hangs:</p> <pre><code>$ ssh remotehost.example.com invokejob.py </code></pre> <p>Does anybody know why it hangs in the second case, and what I can do to avoid this? </p> <p>Note that I need to retrieve the output of the program, so I can't just use the ssh "-f" flag or redirect standard output.</p>
1
2008-08-28T21:48:09Z
33,486
<blockquote> <pre><code>s = p.stderr.readline() </code></pre> </blockquote> <p>I suspect it's the above line. When you invoke a command directly through ssh, you don't get your full pty (assuming Linux), and thus no stderr to read from.</p> <p>When you log in interactively, stdin, stdout, and stderr are set up for you, and so your script works.</p>
3
2008-08-28T21:53:10Z
[ "python", "ssh" ]
ssh hangs when command invoked directly, but exits cleanly when run interactive
33,475
<p>I need to launch a server on the remote machine and retrieve the port number that the server process is lsitening on. When invoked, the server will listen on a random port and output the port number on stderr.</p> <p>I want to automate the process of logging on to the remote machine, launching the process, and retrieving the port number. I wrote a Python script called "<code>invokejob.py</code>" that lives on the remote machine to act as a wrapper that invokes the job and then returns the port number, it looks like this:</p> <pre><code>import re, subprocess executable = ... # Name of executable regex = ... # Regex to extract the port number from the output p = subprocess.Popen(executable, bufsize=1, # line buffered stderr=subprocess.PIPE ) s = p.stderr.readline() port = re.match(regex).groups()[0] print port </code></pre> <p>If I log in interactively, this script works:</p> <pre><code>$ ssh remotehost.example.com Last login: Thu Aug 28 17:31:18 2008 from localhost $ ./invokejob.py 63409 $ exit logout Connection to remotehost.example.com closed. </code></pre> <p>(Note: successful logout, it did not hang).</p> <p>However, if I try to invoke it from the command-line, it just hangs:</p> <pre><code>$ ssh remotehost.example.com invokejob.py </code></pre> <p>Does anybody know why it hangs in the second case, and what I can do to avoid this? </p> <p>Note that I need to retrieve the output of the program, so I can't just use the ssh "-f" flag or redirect standard output.</p>
1
2008-08-28T21:48:09Z
33,673
<p>what if you do the following:</p> <h2><code>ssh &lt;remote host&gt; '&lt;your command&gt; ;&lt;your regexp using awk or something&gt;'</code></h2> <p>For example</p> <h2><code>ssh &lt;remote host&gt; '&lt;your program&gt;; ps aux | awk \'/root/ {print $2}\''</code></h2> <p>This will connect to , execute and then print each PSID for any user root or any process with root in its description.</p> <p>I have used this method for running all kinds of commands on remote machines. The catch is to wrap the command(s) you wish to execute in single quotation marks (') and to separate each command with a semi-colon (;).</p>
0
2008-08-28T23:50:19Z
[ "python", "ssh" ]
ssh hangs when command invoked directly, but exits cleanly when run interactive
33,475
<p>I need to launch a server on the remote machine and retrieve the port number that the server process is lsitening on. When invoked, the server will listen on a random port and output the port number on stderr.</p> <p>I want to automate the process of logging on to the remote machine, launching the process, and retrieving the port number. I wrote a Python script called "<code>invokejob.py</code>" that lives on the remote machine to act as a wrapper that invokes the job and then returns the port number, it looks like this:</p> <pre><code>import re, subprocess executable = ... # Name of executable regex = ... # Regex to extract the port number from the output p = subprocess.Popen(executable, bufsize=1, # line buffered stderr=subprocess.PIPE ) s = p.stderr.readline() port = re.match(regex).groups()[0] print port </code></pre> <p>If I log in interactively, this script works:</p> <pre><code>$ ssh remotehost.example.com Last login: Thu Aug 28 17:31:18 2008 from localhost $ ./invokejob.py 63409 $ exit logout Connection to remotehost.example.com closed. </code></pre> <p>(Note: successful logout, it did not hang).</p> <p>However, if I try to invoke it from the command-line, it just hangs:</p> <pre><code>$ ssh remotehost.example.com invokejob.py </code></pre> <p>Does anybody know why it hangs in the second case, and what I can do to avoid this? </p> <p>Note that I need to retrieve the output of the program, so I can't just use the ssh "-f" flag or redirect standard output.</p>
1
2008-08-28T21:48:09Z
33,873
<p>@Ben Collins</p> <p>I think you're right about stderr being an issue. I am pretty sure it's blocking on the readline() call. </p> <p>In the end, I gave up and decided to use the pxssh module from <a href="http://pexpect.sourceforge.net" rel="nofollow">pexpect</a> to automate my interaction with an ssh session.</p> <p>@Misha M</p> <p>Unfortunately, the semi-colon trick doesn't work here: it blocks on executing my program. </p>
0
2008-08-29T02:42:07Z
[ "python", "ssh" ]
Extending base classes in Python
33,534
<p>I'm trying to extend some "base" classes in Python:</p> <pre><code>class xlist (list): def len(self): return len(self) def add(self, *args): self.extend(args) return None class xint (int): def add(self, value): self += value return self x = xlist([1,2,3]) print x.len() ## &gt;&gt;&gt; 3 ok print x ## &gt;&gt;&gt; [1,2,3] ok x.add (4, 5, 6) print x ## &gt;&gt;&gt; [1,2,3,4,5,6] ok x = xint(10) print x ## &gt;&gt;&gt; 10 ok x.add (2) print x ## &gt;&gt;&gt; 10 # Not ok (#1) print type(x) ## &gt;&gt;&gt; &lt;class '__main__.xint'&gt; ok x += 5 print type(x) ## &gt;&gt;&gt; &lt;type 'int'&gt; # Not ok (#2) </code></pre> <p>It works fine in the <em>list</em> case because the <em>append</em> method modifies the object "in place", without returning it. But in the <em>int</em> case, the <em>add</em> method doesn't modify the value of the external <em>x</em> variable. I suppose that's fine in the sense that <em>self</em> is a local variable in the <em>add</em> method of the class, but this is preventing me from modifying the initial value assigned to the instance of the class.</p> <p>Is it possible to extend a class this way or should I define a class property with the base type and map all the needed methods to this property?</p>
10
2008-08-28T22:18:02Z
33,556
<p>Ints are immutable and you can't modify them in place, so you should go with option #2 (because option #1 is impossible without some trickery).</p>
0
2008-08-28T22:28:36Z
[ "python" ]
Extending base classes in Python
33,534
<p>I'm trying to extend some "base" classes in Python:</p> <pre><code>class xlist (list): def len(self): return len(self) def add(self, *args): self.extend(args) return None class xint (int): def add(self, value): self += value return self x = xlist([1,2,3]) print x.len() ## &gt;&gt;&gt; 3 ok print x ## &gt;&gt;&gt; [1,2,3] ok x.add (4, 5, 6) print x ## &gt;&gt;&gt; [1,2,3,4,5,6] ok x = xint(10) print x ## &gt;&gt;&gt; 10 ok x.add (2) print x ## &gt;&gt;&gt; 10 # Not ok (#1) print type(x) ## &gt;&gt;&gt; &lt;class '__main__.xint'&gt; ok x += 5 print type(x) ## &gt;&gt;&gt; &lt;type 'int'&gt; # Not ok (#2) </code></pre> <p>It works fine in the <em>list</em> case because the <em>append</em> method modifies the object "in place", without returning it. But in the <em>int</em> case, the <em>add</em> method doesn't modify the value of the external <em>x</em> variable. I suppose that's fine in the sense that <em>self</em> is a local variable in the <em>add</em> method of the class, but this is preventing me from modifying the initial value assigned to the instance of the class.</p> <p>Is it possible to extend a class this way or should I define a class property with the base type and map all the needed methods to this property?</p>
10
2008-08-28T22:18:02Z
33,563
<p><strong>int</strong> is a value type, so each time you do an assignment, (e.g. both instances of <strong>+=</strong> above), it doesn't modify the object you have on the heap, but replaces the reference with one of the result of the right hand side of the assignment (i.e. an int)</p> <p><strong>list</strong> isn't a value type, so it isn't bound by the same rules.</p> <p>this page has more details on the differences: <a href="http://docs.python.org/ref/objects.html">http://docs.python.org/ref/objects.html</a></p> <p>IMO, yes, you should define a new class that keeps an int as an instance variable</p>
5
2008-08-28T22:32:40Z
[ "python" ]
Extending base classes in Python
33,534
<p>I'm trying to extend some "base" classes in Python:</p> <pre><code>class xlist (list): def len(self): return len(self) def add(self, *args): self.extend(args) return None class xint (int): def add(self, value): self += value return self x = xlist([1,2,3]) print x.len() ## &gt;&gt;&gt; 3 ok print x ## &gt;&gt;&gt; [1,2,3] ok x.add (4, 5, 6) print x ## &gt;&gt;&gt; [1,2,3,4,5,6] ok x = xint(10) print x ## &gt;&gt;&gt; 10 ok x.add (2) print x ## &gt;&gt;&gt; 10 # Not ok (#1) print type(x) ## &gt;&gt;&gt; &lt;class '__main__.xint'&gt; ok x += 5 print type(x) ## &gt;&gt;&gt; &lt;type 'int'&gt; # Not ok (#2) </code></pre> <p>It works fine in the <em>list</em> case because the <em>append</em> method modifies the object "in place", without returning it. But in the <em>int</em> case, the <em>add</em> method doesn't modify the value of the external <em>x</em> variable. I suppose that's fine in the sense that <em>self</em> is a local variable in the <em>add</em> method of the class, but this is preventing me from modifying the initial value assigned to the instance of the class.</p> <p>Is it possible to extend a class this way or should I define a class property with the base type and map all the needed methods to this property?</p>
10
2008-08-28T22:18:02Z
33,663
<p>Your two <code>xint</code> examples don't work for two different reasons.</p> <p>The first doesn't work because <code>self += value</code> is equivalent to <code>self = self + value</code> which just reassigns the local variable <code>self</code> to a different object (an integer) but doesn't change the original object. You can't really get this </p> <pre><code>&gt;&gt;&gt; x = xint(10) &gt;&gt;&gt; x.add(2) </code></pre> <p>to work with a subclass of <code>int</code> since integers are <a href="http://docs.python.org/ref/objects.html">immutable</a>.</p> <p>To get the second one to work you can define an <a href="http://docs.python.org/ref/numeric-types.html"><code>__add__</code> method</a>, like so:</p> <pre><code>class xint(int): def __add__(self, value): return xint(int.__add__(self, value)) &gt;&gt;&gt; x = xint(10) &gt;&gt;&gt; type(x) &lt;class '__main__.xint'&gt; &gt;&gt;&gt; x += 3 &gt;&gt;&gt; x 13 &gt;&gt;&gt; type(x) &lt;class '__main__.xint'&gt; </code></pre>
22
2008-08-28T23:41:55Z
[ "python" ]
Extending base classes in Python
33,534
<p>I'm trying to extend some "base" classes in Python:</p> <pre><code>class xlist (list): def len(self): return len(self) def add(self, *args): self.extend(args) return None class xint (int): def add(self, value): self += value return self x = xlist([1,2,3]) print x.len() ## &gt;&gt;&gt; 3 ok print x ## &gt;&gt;&gt; [1,2,3] ok x.add (4, 5, 6) print x ## &gt;&gt;&gt; [1,2,3,4,5,6] ok x = xint(10) print x ## &gt;&gt;&gt; 10 ok x.add (2) print x ## &gt;&gt;&gt; 10 # Not ok (#1) print type(x) ## &gt;&gt;&gt; &lt;class '__main__.xint'&gt; ok x += 5 print type(x) ## &gt;&gt;&gt; &lt;type 'int'&gt; # Not ok (#2) </code></pre> <p>It works fine in the <em>list</em> case because the <em>append</em> method modifies the object "in place", without returning it. But in the <em>int</em> case, the <em>add</em> method doesn't modify the value of the external <em>x</em> variable. I suppose that's fine in the sense that <em>self</em> is a local variable in the <em>add</em> method of the class, but this is preventing me from modifying the initial value assigned to the instance of the class.</p> <p>Is it possible to extend a class this way or should I define a class property with the base type and map all the needed methods to this property?</p>
10
2008-08-28T22:18:02Z
6,809,498
<p>i expanded you xlist class just a bit, made it so you could find all index points of a number making it so you can extend with multiple lists at once making it initialize and making it so you can iterate through it</p> <pre><code>class xlist: def __init__(self,alist): if type(alist)==type(' '): self.alist = [int(i) for i in alist.split(' ')] else: self.alist = alist def __iter__(self): i = 0 while i&lt;len(self.alist): yield self.alist[i] i+=1 def len(self): return len(self.alist) def add(self, *args): if type(args[0])==type([1]): if len(args)&gt;1: tmp = [] [tmp.extend(i) for i in args] args = tmp else:args = args[0] if type(args)==type(''):args = [int(i) for i in args.split(' ')] (self.alist).extend(args) return None def index(self,val): gen = (i for i,x in enumerate(self.alist) if x == val) return list(gen) </code></pre>
1
2011-07-24T20:30:07Z
[ "python" ]
Find out how much memory is being used by an object in Python
33,978
<p>How would you go about finding out how much memory is being used by an object? I know it is possible to find out how much is used by a block of code, but not by an instantiated object (anytime during its life), which is what I want. </p>
117
2008-08-29T04:59:31Z
34,011
<p>I haven't any personal experience with either of the following, but a simple search for a "Python [memory] profiler" yield:</p> <ul> <li><p>PySizer, "a memory profiler for Python," found at <a href="http://pysizer.8325.org/" rel="nofollow">http://pysizer.8325.org/</a>. However the page seems to indicate that the project hasn't been updated for a while, and refers to...</p></li> <li><p>Heapy, "support[ing] debugging and optimization regarding memory related issues in Python programs," found at <a href="http://guppy-pe.sourceforge.net/#Heapy" rel="nofollow">http://guppy-pe.sourceforge.net/#Heapy</a>.</p></li> </ul> <p>Hope that helps.</p>
3
2008-08-29T05:33:49Z
[ "python", "performance", "memory-profiling" ]
Find out how much memory is being used by an object in Python
33,978
<p>How would you go about finding out how much memory is being used by an object? I know it is possible to find out how much is used by a block of code, but not by an instantiated object (anytime during its life), which is what I want. </p>
117
2008-08-29T04:59:31Z
35,645
<p><strong>There's no easy way to find out the memory size of a python object</strong>. One of the problems you may find is that Python objects - like lists and dicts - may have references to other python objects (in this case, what would your size be? The size containing the size of each object or not?). There are some pointers overhead and internal structures related to object types and garbage collection. Finally, some python objects have non-obvious behaviors. For instance, lists reserve space for more objects than they have, most of the time; dicts are even more complicated since they can operate in different ways (they have a different implementation for small number of keys and sometimes they over allocate entries).</p> <p>There is a <a href="http://code.activestate.com/recipes/544288/">big chunk of code</a> (and an <a href="http://code.activestate.com/recipes/546530/">updated big chunk of code</a>) out there to try to best approximate the size of a python object in memory. There's also some <a href="https://mail.python.org/pipermail/python-list/2008-January/483475.html">simpler approximations</a>. But they will always be approximations.</p> <p>You may also want to check some <a href="http://mail.python.org/pipermail/python-list/2002-March/135223.html">old description about PyObject</a> (the internal C struct that represents virtually all python objects).</p>
67
2008-08-30T03:25:43Z
[ "python", "performance", "memory-profiling" ]
Find out how much memory is being used by an object in Python
33,978
<p>How would you go about finding out how much memory is being used by an object? I know it is possible to find out how much is used by a block of code, but not by an instantiated object (anytime during its life), which is what I want. </p>
117
2008-08-29T04:59:31Z
12,924,399
<p>Another approach is to use pickle. See <a href="http://stackoverflow.com/a/565382/420867">this answer</a> to a duplicate of this question.</p>
14
2012-10-16T22:25:06Z
[ "python", "performance", "memory-profiling" ]
Find out how much memory is being used by an object in Python
33,978
<p>How would you go about finding out how much memory is being used by an object? I know it is possible to find out how much is used by a block of code, but not by an instantiated object (anytime during its life), which is what I want. </p>
117
2008-08-29T04:59:31Z
19,865,746
<p>Try this:</p> <pre><code>sys.getsizeof(object) </code></pre> <p><a href="https://docs.python.org/3/library/sys.html#sys.getsizeof" rel="nofollow">getsizeof()</a> calls the object’s <code>__sizeof__</code> method and adds an additional garbage collector overhead <strong>if</strong> the object is managed by the garbage collector.</p>
24
2013-11-08T18:11:11Z
[ "python", "performance", "memory-profiling" ]
Find out how much memory is being used by an object in Python
33,978
<p>How would you go about finding out how much memory is being used by an object? I know it is possible to find out how much is used by a block of code, but not by an instantiated object (anytime during its life), which is what I want. </p>
117
2008-08-29T04:59:31Z
20,906,366
<p>This must be used with care because an override on the objects __sizeof__ might be misleading.</p> <p>Using the bregman.suite, some tests with sys.getsizeof output a copy of an array object (data) in an object instance as being bigger than the object itself (mfcc).</p> <pre><code>&gt;&gt;&gt; mfcc = MelFrequencyCepstrum(filepath, params) &gt;&gt;&gt; data = mfcc.X[:] &gt;&gt;&gt; sys.getsizeof(mfcc) 64 &gt;&gt;&gt; sys.getsizeof(mfcc.X) &gt;&gt;&gt;80 &gt;&gt;&gt; sys.getsizeof(data) 80 &gt;&gt;&gt; mfcc &lt;bregman.features.MelFrequencyCepstrum object at 0x104ad3e90&gt; </code></pre>
1
2014-01-03T14:54:15Z
[ "python", "performance", "memory-profiling" ]
Find out how much memory is being used by an object in Python
33,978
<p>How would you go about finding out how much memory is being used by an object? I know it is possible to find out how much is used by a block of code, but not by an instantiated object (anytime during its life), which is what I want. </p>
117
2008-08-29T04:59:31Z
24,495,011
<p>For big objects you may use a somewhat crude but effective method: check how much memory your Python process occupies in the system, then delete the object and compare.</p> <p>This method has many drawbacks but it will give you a very fast estimate for very big objects.</p>
-2
2014-06-30T16:44:04Z
[ "python", "performance", "memory-profiling" ]
Are Python threads buggy?
34,020
<p>A reliable coder friend told me that Python's current multi-threading implementation is seriously buggy - enough to avoid using altogether. What can said about this rumor?</p>
17
2008-08-29T05:43:16Z
34,024
<p>I've used it in several applications and have never had nor heard of threading being anything other than 100% reliable, as long as you know its limits. You can't spawn 1000 threads at the same time and expect your program to run properly on Windows, however you can easily write a worker pool and just feed it 1000 operations, and keep everything nice and under control.</p>
-2
2008-08-29T05:50:47Z
[ "python", "multithreading" ]
Are Python threads buggy?
34,020
<p>A reliable coder friend told me that Python's current multi-threading implementation is seriously buggy - enough to avoid using altogether. What can said about this rumor?</p>
17
2008-08-29T05:43:16Z
34,031
<p>As far as I know there are no real bugs, but the performance when threading in cPython is really bad (compared to most other threading implementations, but usually good enough if all most of the threads do is block) due to the <a href="http://docs.python.org/api/threads.html" rel="nofollow">GIL</a> (Global Interpreter Lock), so really it is implementation specific rather than language specific. Jython, for example, does not suffer from this due to using the Java thread model.</p> <p>See <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=214235" rel="nofollow">this</a> post on why it is not really feasible to remove the GIL from the cPython implementation, and <a href="http://www.pyzine.com/Issue001/Section_Articles/article_ThreadingGlobalInterpreter.html" rel="nofollow">this</a> for some practical elaboration and workarounds.</p> <p>Do a quick google for <a href="http://www.google.com/search?q=python+gil" rel="nofollow">"Python GIL"</a> for more information.</p>
3
2008-08-29T05:58:34Z
[ "python", "multithreading" ]
Are Python threads buggy?
34,020
<p>A reliable coder friend told me that Python's current multi-threading implementation is seriously buggy - enough to avoid using altogether. What can said about this rumor?</p>
17
2008-08-29T05:43:16Z
34,060
<p>Python threads are good for <strong>concurrent I/O programming</strong>. Threads are swapped out of the CPU as soon as they block waiting for input from file, network, etc. This allows other Python threads to use the CPU while others wait. This would allow you to write a multi-threaded web server or web crawler, for example.</p> <p>However, Python threads are serialized by the <a href="http://en.wikipedia.org/wiki/Global_Interpreter_Lock">GIL</a> when they enter interpreter core. This means that if two threads are crunching numbers, only one can run at any given moment. It also means that you can't take advantage of multi-core or multi-processor architectures.</p> <p>There are solutions like running multiple Python interpreters concurrently, using a C based threading library. This is not for the faint of heart and the benefits might not be worth the trouble. Let's hope for an all Python solution in a future release.</p>
43
2008-08-29T06:33:54Z
[ "python", "multithreading" ]
Are Python threads buggy?
34,020
<p>A reliable coder friend told me that Python's current multi-threading implementation is seriously buggy - enough to avoid using altogether. What can said about this rumor?</p>
17
2008-08-29T05:43:16Z
34,078
<p>The GIL (Global Interpreter Lock) might be a problem, but the API is quite OK. Try out the excellent <code>processing</code> module, which implements the Threading API for separate processes. I am using that right now (albeit on OS X, have yet to do some testing on Windows) and am really impressed. The Queue class is really saving my bacon in terms of managing complexity!</p> <p><strong>EDIT</strong>: it seemes the processing module is being included in the standard library as of version 2.6 (<code>import multiprocessing</code>). Joy!</p>
7
2008-08-29T06:55:14Z
[ "python", "multithreading" ]
Are Python threads buggy?
34,020
<p>A reliable coder friend told me that Python's current multi-threading implementation is seriously buggy - enough to avoid using altogether. What can said about this rumor?</p>
17
2008-08-29T05:43:16Z
34,782
<p>The standard implementation of Python (generally known as CPython as it is written in C) uses OS threads, but since there is the <a href="http://en.wikipedia.org/wiki/Global_Interpreter_Lock" rel="nofollow">Global Interpreter Lock</a>, only one thread at a time is allowed to run Python code. But within those limitations, the threading libraries are robust and widely used.</p> <p>If you want to be able to use multiple CPU cores, there are a few options. One is to use multiple python interpreters concurrently, as mentioned by others. Another option is to use a different implementation of Python that does not use a GIL. The two main options are <a href="http://en.wikipedia.org/wiki/Jython" rel="nofollow">Jython</a> and <a href="http://en.wikipedia.org/wiki/IronPython" rel="nofollow">IronPython</a>.</p> <p>Jython is written in Java, and is now fairly mature, though some incompatibilities remain. For example, the web framework <a href="http://zyasoft.com/pythoneering/2008/01/django-on-jython-minding-gap.html" rel="nofollow">Django does not run perfectly yet</a>, but is getting closer all the time. Jython is <a href="http://mail.python.org/pipermail/python-list/2001-December/116555.html" rel="nofollow">great for thread safety</a>, comes out <a href="http://blogs.warwick.ac.uk/dwatkins/entry/benchmarking_parallel_python_1_2/" rel="nofollow">better in benchmarks</a> and has a <a href="http://cgwalters.livejournal.com/17956.html" rel="nofollow">cheeky message for those wanting the GIL</a>.</p> <p>IronPython uses the .NET framework and is written in C#. Compatibility is reaching the stage where <a href="http://www.infoq.com/news/2008/03/django-and-ironpython" rel="nofollow">Django can run on IronPython</a> (at least as a demo) and there are <a href="http://www.voidspace.org.uk/ironpython/threading.shtml" rel="nofollow">guides to using threads in IronPython</a>.</p>
13
2008-08-29T17:17:18Z
[ "python", "multithreading" ]
Are Python threads buggy?
34,020
<p>A reliable coder friend told me that Python's current multi-threading implementation is seriously buggy - enough to avoid using altogether. What can said about this rumor?</p>
17
2008-08-29T05:43:16Z
576,667
<p>If you want to code in python and get great threading support, you might want to check out IronPython or Jython. Since the python code in IronPython and Jython run on the .NET CLR and Java VM respectively, they enjoy the great threading support built into those libraries. In addition to that, IronPython doesn't have the GIL, an issue that prevents CPython threads from taking full advantage of multi-core architectures.</p>
1
2009-02-23T06:15:07Z
[ "python", "multithreading" ]
How to specify an authenticated proxy for a python http connection?
34,079
<p>What's the best way to specify a proxy with username and password for an http connection in python?</p>
44
2008-08-29T06:55:54Z
34,116
<p>This works for me: </p> <pre><code>import urllib2 proxy = urllib2.ProxyHandler({'http': 'http:// username:password@proxyurl:proxyport'}) auth = urllib2.HTTPBasicAuthHandler() opener = urllib2.build_opener(proxy, auth, urllib2.HTTPHandler) urllib2.install_opener(opener) conn = urllib2.urlopen('http://python.org') return_str = conn.read() </code></pre>
53
2008-08-29T07:30:35Z
[ "python", "http", "proxy" ]
How to specify an authenticated proxy for a python http connection?
34,079
<p>What's the best way to specify a proxy with username and password for an http connection in python?</p>
44
2008-08-29T06:55:54Z
35,443
<p>The best way of going through a proxy that requires authentication is using <a href="http://docs.python.org/lib/module-urllib2.html">urllib2</a> to build a custom url opener, then using that to make all the requests you want to go through the proxy. Note in particular, you probably don't want to embed the proxy password in the url or the python source code (unless it's just a quick hack).</p> <pre><code>import urllib2 def get_proxy_opener(proxyurl, proxyuser, proxypass, proxyscheme="http"): password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() password_mgr.add_password(None, proxyurl, proxyuser, proxypass) proxy_handler = urllib2.ProxyHandler({proxyscheme: proxyurl}) proxy_auth_handler = urllib2.ProxyBasicAuthHandler(password_mgr) return urllib2.build_opener(proxy_handler, proxy_auth_handler) if __name__ == "__main__": import sys if len(sys.argv) &gt; 4: url_opener = get_proxy_opener(*sys.argv[1:4]) for url in sys.argv[4:]: print url_opener.open(url).headers else: print "Usage:", sys.argv[0], "proxy user pass fetchurls..." </code></pre> <p>In a more complex program, you can seperate these components out as appropriate (for instance, only using one password manager for the lifetime of the application). The python documentation has <a href="http://docs.python.org/lib/urllib2-examples.html">more examples on how to do complex things with urllib2</a> that you might also find useful.</p>
8
2008-08-29T22:52:47Z
[ "python", "http", "proxy" ]
How to specify an authenticated proxy for a python http connection?
34,079
<p>What's the best way to specify a proxy with username and password for an http connection in python?</p>
44
2008-08-29T06:55:54Z
142,324
<p>Or if you want to install it, so that it is always used with urllib2.urlopen (so you don't need to keep a reference to the opener around):</p> <pre><code>import urllib2 url = 'www.proxyurl.com' username = 'user' password = 'pass' password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() # None, with the "WithDefaultRealm" password manager means # that the user/pass will be used for any realm (where # there isn't a more specific match). password_mgr.add_password(None, url, username, password) auth_handler = urllib2.HTTPBasicAuthHandler(password_mgr) opener = urllib2.build_opener(auth_handler) urllib2.install_opener(opener) print urllib2.urlopen("http://www.example.com/folder/page.html").read() </code></pre>
3
2008-09-26T22:17:59Z
[ "python", "http", "proxy" ]
How to specify an authenticated proxy for a python http connection?
34,079
<p>What's the best way to specify a proxy with username and password for an http connection in python?</p>
44
2008-08-29T06:55:54Z
3,942,980
<p>Setting an environment var named <strong>http_proxy</strong> like this: <strong>http://username:password@proxy_url:port</strong></p>
11
2010-10-15T14:06:56Z
[ "python", "http", "proxy" ]
How to specify an authenticated proxy for a python http connection?
34,079
<p>What's the best way to specify a proxy with username and password for an http connection in python?</p>
44
2008-08-29T06:55:54Z
36,216,636
<p>Here is the method use urllib </p> <pre><code>import urllib.request # set up authentication info authinfo = urllib.request.HTTPBasicAuthHandler() proxy_support = urllib.request.ProxyHandler({"http" : "http://ahad-haam:3128"}) # build a new opener that adds authentication and caching FTP handlers opener = urllib.request.build_opener(proxy_support, authinfo, urllib.request.CacheFTPHandler) # install it urllib.request.install_opener(opener) f = urllib.request.urlopen('http://www.python.org/') """ </code></pre>
0
2016-03-25T08:37:45Z
[ "python", "http", "proxy" ]
Django ImageField core=False in newforms admin
34,209
<p>In the transition to newforms admin I'm having difficulty figuring out how specify core=False for ImageFields.</p> <p>I get the following error:</p> <pre><code>TypeError: __init__() got an unexpected keyword argument 'core' </code></pre> <p>[Edit] However, by just removing the core argument I get a "This field is required." error in the admin interface on attempted submission. How does one accomplish what core=False is meant to do using newforms admin?</p>
1
2008-08-29T09:03:27Z
34,391
<p>This is simple. I started getting this problems a few revisions ago. Basically, just remove the "core=True" parameter in the ImageField in the models, and then follow the instructions <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#inlinemodeladmin-objects" rel="nofollow">here</a> to convert to what the newforms admin uses.</p>
2
2008-08-29T11:39:27Z
[ "python", "django", "django-models" ]
Django ImageField core=False in newforms admin
34,209
<p>In the transition to newforms admin I'm having difficulty figuring out how specify core=False for ImageFields.</p> <p>I get the following error:</p> <pre><code>TypeError: __init__() got an unexpected keyword argument 'core' </code></pre> <p>[Edit] However, by just removing the core argument I get a "This field is required." error in the admin interface on attempted submission. How does one accomplish what core=False is meant to do using newforms admin?</p>
1
2008-08-29T09:03:27Z
35,089
<p>The <code>core</code> attribute isn't used anymore.</p> <p>From <a href="http://oebfare.com/blog/2008/jul/20/newforms-admin-migration-and-screencast/" rel="nofollow">Brian Rosner's Blog</a>:</p> <blockquote> <p>You can safely just remove any and all <code>core</code> arguments. They are no longer used. <em>newforms-admin</em> now provides a nice delete checkbox for exisiting instances in inlines.</p> </blockquote>
3
2008-08-29T19:20:47Z
[ "python", "django", "django-models" ]
Django ImageField core=False in newforms admin
34,209
<p>In the transition to newforms admin I'm having difficulty figuring out how specify core=False for ImageFields.</p> <p>I get the following error:</p> <pre><code>TypeError: __init__() got an unexpected keyword argument 'core' </code></pre> <p>[Edit] However, by just removing the core argument I get a "This field is required." error in the admin interface on attempted submission. How does one accomplish what core=False is meant to do using newforms admin?</p>
1
2008-08-29T09:03:27Z
35,633
<p>To get rid of "This field is required," you need to make it not required, by using blank=True (and possibly null=True as well, if it's not a CharField).</p>
3
2008-08-30T03:04:44Z
[ "python", "django", "django-models" ]
Python descriptor protocol analog in other languages?
34,243
<p>Is there something like the Python descriptor protocol implemented in other languages? It seems like a nice way to increase modularity/encapsulation without bloating your containing class' implementation, but I've never heard of a similar thing in any other languages. Is it likely absent from other languages because of the lookup overhead?</p>
8
2008-08-29T09:24:08Z
34,266
<p>I've not heard of a direct equivalent either. You could probably achieve the same effect with macros, especially in a language like Lisp which has extremely powerful macros.</p> <p>I wouldn't be at all surprised if other languages start to incorporate something similar because it is so powerful.</p>
4
2008-08-29T09:39:47Z
[ "python", "language-features", "encapsulation" ]
Python descriptor protocol analog in other languages?
34,243
<p>Is there something like the Python descriptor protocol implemented in other languages? It seems like a nice way to increase modularity/encapsulation without bloating your containing class' implementation, but I've never heard of a similar thing in any other languages. Is it likely absent from other languages because of the lookup overhead?</p>
8
2008-08-29T09:24:08Z
48,974
<p>Ruby and C# both easily let you create accessors by specifying getter/setter methods for an attribute, much like in Python. However, this isn't designed to naturally let you write the code for these methods in another class the way that Python allows. In practice, I'm not sure how much this matters, since every time I've seen an attribute defined through the descriptor protocol its been implemented in the same class.</p> <p>EDIT: Darn my dyslexia (by which I mean careless reading). For some reason I've always read "descriptor" as "decorator" and vice versa, even when I'm the one typing both of them. I'll leave my post intact since it has valid information, albeit information which has absolutely nothing to do with the question.</p> <p>The term "decorator" itself is actually the name of a design pattern described in the famous "Design Patterns" book. The Wikipedia article contains many examples in different programming languages of decorator usage: <a href="http://en.wikipedia.org/wiki/Decorator_pattern" rel="nofollow">http://en.wikipedia.org/wiki/Decorator_pattern</a></p> <p>However, the decorators in that article object-oriented; they have classes implementing a predefined interface which lets another existing class behave differently somehow, etc. Python decorators act in a functional way by replacing a function at runtime with another function, allowing you to effectively modify/replace that function, insert code, etc.</p> <p>This is known in the Java world as Aspect-Oriented programming, and the AspectJ Java compiler lets you do these kinds of things and compile your AspectJ code (which is a superset of Java) into Java bytecode.</p> <p>I'm not familiar enough with C# or Ruby to know what their version of decorators would be.</p>
0
2008-09-08T01:31:32Z
[ "python", "language-features", "encapsulation" ]
How do I make Windows aware of a service I have written in Python?
34,328
<p>In <a href="http://stackoverflow.com/questions/32404/can-i-run-a-python-script-as-a-service-in-windows-how" rel="nofollow" title="Python scripts as Windows service">another question</a> I posted yesterday, I got very good advice on how a Python script could be run as a service in Windows. What I'm left wondering is: How is Windows aware of the services that can be managed in the native tools ("services" window in "administrative tools"). I. e. what is the Windows equivalent of putting a start/stop script in /etc/init.d under Linux?</p>
10
2008-08-29T10:18:21Z
34,330
<p>Here is code to install a python-script as a service, written in python :)</p> <p><a href="http://code.activestate.com/recipes/551780/">http://code.activestate.com/recipes/551780/</a></p> <p>This post could also help you out:</p> <p><a href="http://essiene.blogspot.com/2005/04/python-windows-services.html">http://essiene.blogspot.com/2005/04/python-windows-services.html</a></p>
8
2008-08-29T10:20:39Z
[ "python", "windows", "cross-platform" ]
How do I make Windows aware of a service I have written in Python?
34,328
<p>In <a href="http://stackoverflow.com/questions/32404/can-i-run-a-python-script-as-a-service-in-windows-how" rel="nofollow" title="Python scripts as Windows service">another question</a> I posted yesterday, I got very good advice on how a Python script could be run as a service in Windows. What I'm left wondering is: How is Windows aware of the services that can be managed in the native tools ("services" window in "administrative tools"). I. e. what is the Windows equivalent of putting a start/stop script in /etc/init.d under Linux?</p>
10
2008-08-29T10:18:21Z
34,418
<p>As with most "aware" things in Windows, the answer is "Registry".</p> <p>Take a look at this Microsoft Knowledge Base article: <a href="http://support.microsoft.com/kb/103000" rel="nofollow">http://support.microsoft.com/kb/103000</a></p> <p>Search for "A Win32 program that can be started by the Service Controller and that obeys the service control protocol." This is the kind of service you're interested in.</p> <p>The service registration (contents of KEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services \myservice) carries information about the service, including things like its executable location, what to do when it fails (halt the OS?), what services must be started before this one, what user it runs as.</p> <p>As to service control protocol, main() of your program is supposed to invoke a Windows API call, setting up callbacks for start, stop, pause for your service. What you do in those callbacks is all up to you.</p>
3
2008-08-29T15:00:52Z
[ "python", "windows", "cross-platform" ]
How do I make Windows aware of a service I have written in Python?
34,328
<p>In <a href="http://stackoverflow.com/questions/32404/can-i-run-a-python-script-as-a-service-in-windows-how" rel="nofollow" title="Python scripts as Windows service">another question</a> I posted yesterday, I got very good advice on how a Python script could be run as a service in Windows. What I'm left wondering is: How is Windows aware of the services that can be managed in the native tools ("services" window in "administrative tools"). I. e. what is the Windows equivalent of putting a start/stop script in /etc/init.d under Linux?</p>
10
2008-08-29T10:18:21Z
34,421
<p>You can use srvany.exe from Windows NT Resource Kit to create a user defined service that will show up in the admin tools...</p> <p><a href="http://support.microsoft.com/kb/137890" rel="nofollow">http://support.microsoft.com/kb/137890</a></p> <p>I am using this method to run tracd (a python script / server) for trac. </p> <p>Here are some very clear instructions: <a href="http://www.tacktech.com/display.cfm?ttid=197" rel="nofollow">http://www.tacktech.com/display.cfm?ttid=197</a></p> <p>It does require some registry editing (very minimal and easy) but will allow you to make any command line / script a windows service. </p>
0
2008-08-29T15:01:50Z
[ "python", "windows", "cross-platform" ]
How do I make Windows aware of a service I have written in Python?
34,328
<p>In <a href="http://stackoverflow.com/questions/32404/can-i-run-a-python-script-as-a-service-in-windows-how" rel="nofollow" title="Python scripts as Windows service">another question</a> I posted yesterday, I got very good advice on how a Python script could be run as a service in Windows. What I'm left wondering is: How is Windows aware of the services that can be managed in the native tools ("services" window in "administrative tools"). I. e. what is the Windows equivalent of putting a start/stop script in /etc/init.d under Linux?</p>
10
2008-08-29T10:18:21Z
259,438
<p>Don't muck with the registry directly. User the SC command-line tool. Namely, SC CREATE</p> <pre> DESCRIPTION: SC is a command line program used for communicating with the NT Service Controller and services. USAGE: sc [command] [service name] ... The option has the form "\\ServerName" Further help on commands can be obtained by typing: "sc [command]" Commands: query-----------Queries the status for a service, or enumerates the status for types of services. queryex---------Queries the extended status for a service, or enumerates the status for types of services. start-----------Starts a service. pause-----------Sends a PAUSE control request to a service. interrogate-----Sends an INTERROGATE control request to a service. continue--------Sends a CONTINUE control request to a service. stop------------Sends a STOP request to a service. config----------Changes the configuration of a service (persistant). description-----Changes the description of a service. failure---------Changes the actions taken by a service upon failure. qc--------------Queries the configuration information for a service. qdescription----Queries the description for a service. qfailure--------Queries the actions taken by a service upon failure. delete----------Deletes a service (from the registry). create----------Creates a service. (adds it to the registry). control---------Sends a control to a service. sdshow----------Displays a service's security descriptor. sdset-----------Sets a service's security descriptor. GetDisplayName--Gets the DisplayName for a service. GetKeyName------Gets the ServiceKeyName for a service. EnumDepend------Enumerates Service Dependencies. The following commands don't require a service name: sc boot------------(ok | bad) Indicates whether the last boot should be saved as the last-known-good boot configuration Lock------------Locks the Service Database QueryLock-------Queries the LockStatus for the SCManager Database EXAMPLE: sc start MyService </pre>
5
2008-11-03T18:03:16Z
[ "python", "windows", "cross-platform" ]
Finding what methods an object has
34,439
<p>Given a Python object of any kind, is there an easy way to get a list of all methods that this object has?<br> Or,</p> <p>if this is not possible, is there at least an easy way to check if it has a particular method other than simply checking if an error occurs when the method is called?</p>
159
2008-08-29T15:05:17Z
34,452
<p>It appears you can use this code, replacing 'object' with the object you're interested in:-</p> <pre><code>[method for method in dir(object) if callable(getattr(object, method))] </code></pre> <p>I discovered it at <a href="http://www.diveintopython.net/power_of_introspection/index.html">this site</a>, hopefully that should provide some further detail!</p>
188
2008-08-29T15:09:05Z
[ "python", "introspection" ]
Finding what methods an object has
34,439
<p>Given a Python object of any kind, is there an easy way to get a list of all methods that this object has?<br> Or,</p> <p>if this is not possible, is there at least an easy way to check if it has a particular method other than simply checking if an error occurs when the method is called?</p>
159
2008-08-29T15:05:17Z
34,467
<p>You can use the built in <code>dir()</code> function to get a list of all the attributes a module has. Try this at the command line to see how it works.</p> <pre><code>&gt;&gt;&gt; import moduleName &gt;&gt;&gt; dir(moduleName) </code></pre> <p>Also, you can use the <code>hasattr(module_name, "attr_name")</code> function to find out if a module has a specific attribute.</p> <p>See the <a href="http://www.ibm.com/developerworks/library/l-pyint.html">Guide to Python introspection</a> for more information.</p>
78
2008-08-29T15:36:55Z
[ "python", "introspection" ]
Finding what methods an object has
34,439
<p>Given a Python object of any kind, is there an easy way to get a list of all methods that this object has?<br> Or,</p> <p>if this is not possible, is there at least an easy way to check if it has a particular method other than simply checking if an error occurs when the method is called?</p>
159
2008-08-29T15:05:17Z
34,472
<p>To check if it has a particular method:</p> <pre><code>hasattr(object,"method") </code></pre>
20
2008-08-29T15:40:05Z
[ "python", "introspection" ]
Finding what methods an object has
34,439
<p>Given a Python object of any kind, is there an easy way to get a list of all methods that this object has?<br> Or,</p> <p>if this is not possible, is there at least an easy way to check if it has a particular method other than simply checking if an error occurs when the method is called?</p>
159
2008-08-29T15:05:17Z
34,481
<p>On top of the more direct answers, I'd be remiss if I didn't mention <a href="http://ipython.scipy.org/">iPython</a>. Hit 'tab' to see the available methods, with autocompletion.</p> <p>And once you've found a method, try:</p> <pre><code>help(object.method) </code></pre> <p>to see the pydocs, method signature, etc.</p> <p>Ahh... <a href="http://en.wikipedia.org/wiki/REPL">REPL</a>.</p>
11
2008-08-29T15:47:04Z
[ "python", "introspection" ]
Finding what methods an object has
34,439
<p>Given a Python object of any kind, is there an easy way to get a list of all methods that this object has?<br> Or,</p> <p>if this is not possible, is there at least an easy way to check if it has a particular method other than simply checking if an error occurs when the method is called?</p>
159
2008-08-29T15:05:17Z
15,640,132
<blockquote> <p>...is there at least an easy way to check if it has a particular method other than simply checking if an error occurs when the method is called</p> </blockquote> <p>While "<a href="http://docs.python.org/2/glossary.html#term-eafp" rel="nofollow">Easier to ask for forgiveness than permission</a>" is certainly the Pythonic way, what you are looking for maybe:</p> <pre><code>d={'foo':'bar', 'spam':'eggs'} if 'get' in dir(d): d.get('foo') # OUT: 'bar' </code></pre>
1
2013-03-26T14:51:55Z
[ "python", "introspection" ]
Finding what methods an object has
34,439
<p>Given a Python object of any kind, is there an easy way to get a list of all methods that this object has?<br> Or,</p> <p>if this is not possible, is there at least an easy way to check if it has a particular method other than simply checking if an error occurs when the method is called?</p>
159
2008-08-29T15:05:17Z
20,100,900
<p>The simplest method is to use dir(objectname). It will display all the methods available for that object. Cool trick.</p>
21
2013-11-20T16:06:27Z
[ "python", "introspection" ]
Finding what methods an object has
34,439
<p>Given a Python object of any kind, is there an easy way to get a list of all methods that this object has?<br> Or,</p> <p>if this is not possible, is there at least an easy way to check if it has a particular method other than simply checking if an error occurs when the method is called?</p>
159
2008-08-29T15:05:17Z
27,380,776
<p>The problem with all methods indicated here is that you CAN'T be sure that a method doesn't exist.</p> <p>In Python you can intercept the dot calling thru <code>__getattr__</code> and <code>__getattribute__</code>, making it possible to create method "at runtime"</p> <p>Exemple:</p> <pre><code>class MoreMethod(object): def some_method(self, x): return x def __getattr__(self, *args): return lambda x: x*2 </code></pre> <p>If you execute it, you can call method non existing in the object dictionary...</p> <pre><code>&gt;&gt;&gt; o = MoreMethod() &gt;&gt;&gt; o.some_method(5) 5 &gt;&gt;&gt; dir(o) ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattr__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'some_method'] &gt;&gt;&gt; o.i_dont_care_of_the_name(5) 10 </code></pre> <p>And it's why you use the <a href="https://docs.python.org/2/glossary.html#term-eafp" rel="nofollow">Easier to ask for forgiveness than permission</a> paradigms in Python.</p>
4
2014-12-09T14:02:06Z
[ "python", "introspection" ]
Finding what methods an object has
34,439
<p>Given a Python object of any kind, is there an easy way to get a list of all methods that this object has?<br> Or,</p> <p>if this is not possible, is there at least an easy way to check if it has a particular method other than simply checking if an error occurs when the method is called?</p>
159
2008-08-29T15:05:17Z
28,220,562
<p>If you specifically want <strong>methods</strong>, you should use <a href="https://docs.python.org/2/library/inspect.html#inspect.ismethod" rel="nofollow">inspect.ismethod</a>.</p> <p>For method names:</p> <pre><code>import inspect method_names = [attr for attr in dir(self) if inspect.ismethod(getattr(self, attr))] </code></pre> <p>For the methods themselves:</p> <pre><code>import inspect methods = [member for member in [getattr(self, attr) for attr in dir(self)] if inspect.ismethod(member)] </code></pre>
4
2015-01-29T17:10:18Z
[ "python", "introspection" ]
Finding what methods an object has
34,439
<p>Given a Python object of any kind, is there an easy way to get a list of all methods that this object has?<br> Or,</p> <p>if this is not possible, is there at least an easy way to check if it has a particular method other than simply checking if an error occurs when the method is called?</p>
159
2008-08-29T15:05:17Z
29,851,741
<p>One can create a <code>getAttrs</code> function that will return an object's callable property names</p> <pre><code>def getAttrs(object): return filter(lambda m: callable(getattr(object, m)), dir(object)) print getAttrs('Foo bar'.split(' ')) </code></pre> <p>That'd return</p> <pre><code>['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] </code></pre>
1
2015-04-24T15:37:28Z
[ "python", "introspection" ]
Finding what methods an object has
34,439
<p>Given a Python object of any kind, is there an easy way to get a list of all methods that this object has?<br> Or,</p> <p>if this is not possible, is there at least an easy way to check if it has a particular method other than simply checking if an error occurs when the method is called?</p>
159
2008-08-29T15:05:17Z
32,608,298
<p>There is no reliable way to list all object's methods. <code>dir(object)</code> is usually useful, but in some cases it may not list all methods. According to <a href="https://docs.python.org/2/library/functions.html#dir" rel="nofollow"><code>dir()</code> documentation</a>: <em>"With an argument, <strong>attempt</strong> to return a list of valid attributes for that object."</em></p> <p>Checking that method exists can be done by <code>callable(getattr(object, method))</code> as already mentioned there.</p>
2
2015-09-16T12:13:18Z
[ "python", "introspection" ]
Finding what methods an object has
34,439
<p>Given a Python object of any kind, is there an easy way to get a list of all methods that this object has?<br> Or,</p> <p>if this is not possible, is there at least an easy way to check if it has a particular method other than simply checking if an error occurs when the method is called?</p>
159
2008-08-29T15:05:17Z
37,464,502
<p>I believe that what you want is a something like this: a list of attributes/methods of your object. dir() built-in can do this job for you IMHO :).</p> <pre><code>$ python Python 2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; a = "I am a string" &gt;&gt;&gt; dir(a) ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] </code></pre> <p><b> +PLUS </b><br> As I was checking your issue, I have decided to make a script in order to better format the output of dir(). Here goes:</p> <p><b>list_objects_methods.py</b></p> <pre><code>#!/usr/bin/python OBJ = "I am a string." COUNT = 0 for method in dir(OBJ): print "| {0: &lt;20}".format(method), COUNT += 1 if COUNT == 4: COUNT = 0 print </code></pre> <p>Hope that I have contributed :). Regards!</p>
1
2016-05-26T14:58:48Z
[ "python", "introspection" ]
Scaffolding in pylons
34,916
<p>Is there anything similar to rails' scaffolding fo pylons? I've been poking around google, but fofund only this thing caled dbsprockets, which is fine, although probably way to much for my needs. What i really need is a basic CRUD thas is based on the SQLAlchemy model.</p>
8
2008-08-29T18:12:30Z
35,110
<p>I hear you, I've followed the Pylons mailing list for a while looking for something similar. There have been some attempts in the past (see <a href="http://adminpylon.devjavu.com/" rel="nofollow">AdminPylon</a> and <a href="http://code.google.com/p/restin/" rel="nofollow">Restin</a>) but none have really kept up with SQLAlchemy's rapidly developing orm api.</p> <p>Since DBSprockets is likely to be incorporated into TurboGears it will likely be maintained. I'd bite the bullet and go with that.</p>
4
2008-08-29T19:30:29Z
[ "python", "pylons" ]
Scaffolding in pylons
34,916
<p>Is there anything similar to rails' scaffolding fo pylons? I've been poking around google, but fofund only this thing caled dbsprockets, which is fine, although probably way to much for my needs. What i really need is a basic CRUD thas is based on the SQLAlchemy model.</p>
8
2008-08-29T18:12:30Z
1,056,092
<p>The question is super old, but hell: <a href="http://code.google.com/p/formalchemy/" rel="nofollow">http://code.google.com/p/formalchemy/</a></p> <p>Gives you basic crud out of the box, customizable to do even relatively complex things easily, and gives you a drop-in Pylons admin app too (written and customizable with the same api, no magic).</p>
6
2009-06-29T00:02:20Z
[ "python", "pylons" ]
Scaffolding in pylons
34,916
<p>Is there anything similar to rails' scaffolding fo pylons? I've been poking around google, but fofund only this thing caled dbsprockets, which is fine, although probably way to much for my needs. What i really need is a basic CRUD thas is based on the SQLAlchemy model.</p>
8
2008-08-29T18:12:30Z
1,869,967
<p>Just updating an old question. DBSprockets has been replaced by <a href="http://sprox.org/" rel="nofollow">sprox</a> which learns a lot of lessons from it and is pretty cool.</p> <p>It isn't quite the throwaway 'scaffolding' that Rails provides, it is more like an agile form generation tool that is highly extensible.</p>
0
2009-12-08T21:28:30Z
[ "python", "pylons" ]
Validate (X)HTML in Python
35,538
<p>What's the best way to go about validating that a document follows some version of HTML (prefereably that I can specify)? I'd like to be able to know where the failures occur, as in a web-based validator, except in a native Python app.</p>
21
2008-08-30T01:15:32Z
35,543
<p>XHTML is easy, use <a href="http://lxml.de/validation.html" rel="nofollow">lxml</a>.</p> <p>HTML is harder, since there's traditionally not been as much interest in validation among the HTML crowd (run StackOverflow itself through a validator, yikes). The easiest solution would be to execute external applications such as <a href="http://www.jclark.com/sp/" rel="nofollow">nsgmls</a> or <a href="http://openjade.sourceforge.net/" rel="nofollow">OpenJade</a>, and then parse their output.</p>
7
2008-08-30T01:20:52Z
[ "python", "html", "validation", "xhtml" ]
Validate (X)HTML in Python
35,538
<p>What's the best way to go about validating that a document follows some version of HTML (prefereably that I can specify)? I'd like to be able to know where the failures occur, as in a web-based validator, except in a native Python app.</p>
21
2008-08-30T01:15:32Z
35,562
<p>I think that <a href="http://tidy.sourceforge.net/" rel="nofollow">HTML tidy</a> will do what you want. There is a Python binding for it.</p>
3
2008-08-30T01:48:07Z
[ "python", "html", "validation", "xhtml" ]
Validate (X)HTML in Python
35,538
<p>What's the best way to go about validating that a document follows some version of HTML (prefereably that I can specify)? I'd like to be able to know where the failures occur, as in a web-based validator, except in a native Python app.</p>
21
2008-08-30T01:15:32Z
35,572
<p>Try tidylib. You can get some really basic bindings as part of the elementtidy module (builds elementtrees from HTML documents). <a href="http://effbot.org/downloads/#elementtidy">http://effbot.org/downloads/#elementtidy</a></p> <pre><code>&gt;&gt;&gt; import _elementtidy &gt;&gt;&gt; xhtml, log = _elementtidy.fixup("&lt;html&gt;&lt;/html&gt;") &gt;&gt;&gt; print log line 1 column 1 - Warning: missing &lt;!DOCTYPE&gt; declaration line 1 column 7 - Warning: discarding unexpected &lt;/html&gt; line 1 column 14 - Warning: inserting missing 'title' element </code></pre> <p>Parsing the log should give you pretty much everything you need.</p>
5
2008-08-30T01:55:50Z
[ "python", "html", "validation", "xhtml" ]
Validate (X)HTML in Python
35,538
<p>What's the best way to go about validating that a document follows some version of HTML (prefereably that I can specify)? I'd like to be able to know where the failures occur, as in a web-based validator, except in a native Python app.</p>
21
2008-08-30T01:15:32Z
646,877
<p>Starting with html5, you can try to use <a href="http://code.google.com/p/html5lib/">html5lib</a>. </p> <p>You can also decide to install the HTML validator locally and create a client to request the validation. </p> <p>Here I had made a program to validate a list of urls in a txt file. I was just checking the HEAD to get the validation status, but if you do a GET you would get the full results. Look at the API of the validator, there are plenty of options for it.</p> <pre><code>import httplib2 import time h = httplib2.Http(".cache") f = open("urllistfile.txt", "r") urllist = f.readlines() f.close() for url in urllist: # wait 10 seconds before the next request - be nice with the validator time.sleep(10) resp= {} url = url.strip() urlrequest = "http://qa-dev.w3.org/wmvs/HEAD/check?doctype=HTML5&amp;uri="+url try: resp, content = h.request(urlrequest, "HEAD") if resp['x-w3c-validator-status'] == "Abort": print url, "FAIL" else: print url, resp['x-w3c-validator-status'], resp['x-w3c-validator-errors'], resp['x-w3c-validator-warnings'] except: pass </code></pre>
11
2009-03-14T22:42:12Z
[ "python", "html", "validation", "xhtml" ]
Validate (X)HTML in Python
35,538
<p>What's the best way to go about validating that a document follows some version of HTML (prefereably that I can specify)? I'd like to be able to know where the failures occur, as in a web-based validator, except in a native Python app.</p>
21
2008-08-30T01:15:32Z
1,279,293
<p><a href="http://countergram.com/software/pytidylib">http://countergram.com/software/pytidylib</a> is a nice python binding for HTML Tidy. Their example:</p> <pre><code>from tidylib import tidy_document document, errors = tidy_document('''&lt;p&gt;f&amp;otilde;o &lt;img src="bar.jpg"&gt;''', options={'numeric-entities':1}) print document print errors </code></pre>
18
2009-08-14T18:04:38Z
[ "python", "html", "validation", "xhtml" ]
Validate (X)HTML in Python
35,538
<p>What's the best way to go about validating that a document follows some version of HTML (prefereably that I can specify)? I'd like to be able to know where the failures occur, as in a web-based validator, except in a native Python app.</p>
21
2008-08-30T01:15:32Z
10,519,634
<p>I think the most elegant way it to invoke the W3C Validation Service at</p> <pre><code>http://validator.w3.org/ </code></pre> <p>programmatically. Few people know that you do not have to screen-scrape the results in order to get the results, because the service returns non-standard HTTP header paramaters </p> <pre><code>X-W3C-Validator-Recursion: 1 X-W3C-Validator-Status: Invalid (or Valid) X-W3C-Validator-Errors: 6 X-W3C-Validator-Warnings: 0 </code></pre> <p>for indicating the validity and the number of errors and warnings.</p> <p>For instance, the command line </p> <pre><code>curl -I "http://validator.w3.org/check?uri=http%3A%2F%2Fwww.stalsoft.com" </code></pre> <p>returns</p> <pre><code>HTTP/1.1 200 OK Date: Wed, 09 May 2012 15:23:58 GMT Server: Apache/2.2.9 (Debian) mod_python/3.3.1 Python/2.5.2 Content-Language: en X-W3C-Validator-Recursion: 1 X-W3C-Validator-Status: Invalid X-W3C-Validator-Errors: 6 X-W3C-Validator-Warnings: 0 Content-Type: text/html; charset=UTF-8 Vary: Accept-Encoding Connection: close </code></pre> <p>Thus, you can elegantly invoke the W3C Validation Service and extract the results from the HTTP header:</p> <pre class="lang-python prettyprint-override"><code># Programmatic XHTML Validations in Python # Martin Hepp and Alex Stolz # mhepp@computer.org / alex.stolz@ebusiness-unibw.org import urllib import urllib2 URL = "http://validator.w3.org/check?uri=%s" SITE_URL = "http://www.heppnetz.de" # pattern for HEAD request taken from # http://stackoverflow.com/questions/4421170/python-head-request-with-urllib2 request = urllib2.Request(URL % urllib.quote(SITE_URL)) request.get_method = lambda : 'HEAD' response = urllib2.urlopen(request) valid = response.info().getheader('X-W3C-Validator-Status') if valid == "Valid": valid = True else: valid = False errors = int(response.info().getheader('X-W3C-Validator-Errors')) warnings = int(response.info().getheader('X-W3C-Validator-Warnings')) print "Valid markup: %s (Errors: %i, Warnings: %i) " % (valid, errors, warnings) </code></pre>
14
2012-05-09T15:53:46Z
[ "python", "html", "validation", "xhtml" ]
Validate (X)HTML in Python
35,538
<p>What's the best way to go about validating that a document follows some version of HTML (prefereably that I can specify)? I'd like to be able to know where the failures occur, as in a web-based validator, except in a native Python app.</p>
21
2008-08-30T01:15:32Z
39,336,630
<p>In my case the python W3C/HTML validation packages did not work <code>pip search w3c</code> (as of sept 2016).</p> <p>I solved this with</p> <pre><code>$ pip install requests $ python Python 2.7.12 (default, Jun 29 2016, 12:46:54) [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; r = requests.post('https://validator.w3.org/nu/', ... data=file('index.html', 'rb').read(), ... params={'out': 'json'}, ... headers={'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36', ... 'Content-Type': 'text/html; charset=UTF-8'}) &gt;&gt;&gt; r.text &gt;&gt;&gt; u'{"messages":[{"type":"info", ... &gt;&gt;&gt; r.json() &gt;&gt;&gt; {u'messages': [{u'lastColumn': 59, ... </code></pre> <p>More documentation here <a href="http://docs.python-requests.org/en/master/user/quickstart/#binary-response-content" rel="nofollow">python requests</a>, <a href="https://github.com/validator/validator/wiki/Service:-Input:-POST-body" rel="nofollow">W3C Validator API</a></p>
0
2016-09-05T19:30:06Z
[ "python", "html", "validation", "xhtml" ]
Why does Python's iter() on a mapping return iterkeys() instead of iteritems()?
35,569
<p>It seems like if you want to get the keys of a mapping, you ask for them; otherwise, give me the <em>whole</em> mapping (constituted by a set of key-value pairs). Is there a historical reason for this?</p>
6
2008-08-30T01:51:05Z
35,582
<p>Check out <a href="http://mail.python.org/pipermail/python-3000/2007-September/010209.html" rel="nofollow">this thread</a> for a discussion on the reasons behind this behavior (including that Guido likes it, and it's <a href="http://mail.python.org/pipermail/python-3000/2007-September/010222.html" rel="nofollow">not likely to change</a>).</p>
8
2008-08-30T02:01:57Z
[ "python", "mapping", "iteration" ]
Ruby "is" equivalent
35,634
<p>Is there a Ruby equivalent for Python's "is"? It tests whether two objects are identical (i.e. have the same memory location).</p>
6
2008-08-30T03:04:54Z
35,635
<p>Use <code>a.equal? b</code></p> <p><a href="http://www.ruby-doc.org/core/classes/Object.html">http://www.ruby-doc.org/core/classes/Object.html</a></p> <blockquote> <p>Unlike ==, the equal? method should never be overridden by subclasses: it is used to determine object identity (that is, a.equal?(b) iff a is the same object as b). </p> </blockquote>
12
2008-08-30T03:06:02Z
[ "python", "ruby" ]
Ruby "is" equivalent
35,634
<p>Is there a Ruby equivalent for Python's "is"? It tests whether two objects are identical (i.e. have the same memory location).</p>
6
2008-08-30T03:04:54Z
39,062
<p>You could also use <code>__id__</code>. This gives you the objects internal ID number, which is always unique. To check if to objects are the same, try</p> <blockquote> <p><code>a.__id__ = b.__id__</code></p> </blockquote> <p>This is how Ruby's standard library does it as far as I can tell (see <code>group_by</code> and others).</p>
2
2008-09-02T09:02:34Z
[ "python", "ruby" ]
Is Python good for big software projects (not web based)?
35,753
<p>Right now I'm developing mostly in C/C++, but I wrote some small utilities in Python to automatize some tasks and I really love it as language (especially the productivity). </p> <p>Except for the performances (a problem that could be sometimes solved thanks to the ease of interfacing Python with C modules), do you think it is proper for production use in the development of stand-alone complex applications (think for example to a word processor or a graphic tool)?</p> <p>What IDE would you suggest? The IDLE provided with Python is not enough even for small projects in my opinion.</p>
25
2008-08-30T07:08:22Z
35,757
<p>In my opinion python is more than ready for developing complex applications. I see pythons strength more on the server side than writing graphical clients. But have a look at <a href="http://www.resolversystems.com/" rel="nofollow">http://www.resolversystems.com/</a>. They develop a whole spreadsheet in python using the .net ironpython port.</p> <p>If you are familiar with eclipse have a look at <a href="http://pydev.sourceforge.net/" rel="nofollow">pydev</a> which provides auto-completion and debugging support for python with all the other eclipse goodies like svn support. The guy developing it has just been bought by <a href="http://aptana.com/blog/pcolton/pydev_news" rel="nofollow">aptana</a>, so this will be solid choice for the future.</p> <p>@Marcin</p> <blockquote> <p>Cons: as a dynamic language, has way worse IDE support (proper syntax completion requires static typing, whether explicit in Java or inferred in SML),</p> </blockquote> <p>You are right, that static analysis may not provide full syntax completion for dynamic languages, but I thing pydev gets the job done very well. Further more I have a different development style when programming python. I have always an ipython session open and with one F5 I do not only get the perfect completion from ipython, but object introspection and manipulation as well.</p> <blockquote> <p>But if you want to write second Google or Yahoo, you will be much better with C# or Java.</p> </blockquote> <p><a href="http://www.jaiku.com/blog/2008/08/18/from-the-dev-corner-an-under-the-hood-preview-of-our-new-engine/" rel="nofollow">Google just rewrote jaiku</a> to work on top of App Engine, all in python. And as far as I know they use a lot of python inside google too.</p>
16
2008-08-30T07:19:40Z
[ "python", "ide" ]
Is Python good for big software projects (not web based)?
35,753
<p>Right now I'm developing mostly in C/C++, but I wrote some small utilities in Python to automatize some tasks and I really love it as language (especially the productivity). </p> <p>Except for the performances (a problem that could be sometimes solved thanks to the ease of interfacing Python with C modules), do you think it is proper for production use in the development of stand-alone complex applications (think for example to a word processor or a graphic tool)?</p> <p>What IDE would you suggest? The IDLE provided with Python is not enough even for small projects in my opinion.</p>
25
2008-08-30T07:08:22Z
35,759
<p>I really like python, it's usually my language of choice these days for small (non-gui) stuff that I do on my own.</p> <p>However, for some larger Python projects I've tackled, I'm finding that it's not quite the same as programming in say, C++. I was working on a language parser, and needed to represent an AST in Python. This is certainly within the scope of what Python can do, but I had a bit of trouble with some refactoring. I was changing the representation of my AST and changing methods and classes around a lot, and I found I missed the strong typing that would be available to me in a C++ solution. Python's duck typing was almost <em>too</em> flexible and I found myself adding a lot of <code>assert</code> code to try to check my types as the program ran. And then I couldn't really be sure that everything was properly typed unless I had 100% code coverage testing (which I didn't at the time).</p> <p>Actually, that's another thing that I miss sometimes. It's possible to write syntactically correct code in Python that simply won't run. The compiler is incapable of telling you about it until it actually executes the code, so in infrequently-used code paths such as error handlers you can easily have unseen bugs lurking around. Even code that's as simple as printing an error message with a % format string can fail at runtime because of mismatched types.</p> <p>I haven't used Python for any GUI stuff so I can't comment on that aspect.</p>
11
2008-08-30T07:22:03Z
[ "python", "ide" ]
Is Python good for big software projects (not web based)?
35,753
<p>Right now I'm developing mostly in C/C++, but I wrote some small utilities in Python to automatize some tasks and I really love it as language (especially the productivity). </p> <p>Except for the performances (a problem that could be sometimes solved thanks to the ease of interfacing Python with C modules), do you think it is proper for production use in the development of stand-alone complex applications (think for example to a word processor or a graphic tool)?</p> <p>What IDE would you suggest? The IDLE provided with Python is not enough even for small projects in my opinion.</p>
25
2008-08-30T07:08:22Z
35,776
<p>Python is considered (among Python programmers :) to be a great language for rapid prototyping. There's not a lot of extraneous syntax getting in the way of your thought processes, so most of the work you do tends to go into the code. (There's far less idioms required to be involved in writing good Python code than in writing good C++.)</p> <p>Given this, most Python (CPython) programmers ascribe to the "premature optimization is the root of all evil" philosophy. By writing high-level (and significantly slower) Python code, one can optimize the bottlenecks out using C/C++ bindings when your application is nearing completion. At this point it becomes more clear what your processor-intensive algorithms are through proper profiling. This way, you write most of the code in a very readable and maintainable manner while allowing for speedups down the road. You'll see several Python library modules written in C for this very reason.</p> <p>Most graphics libraries in Python (i.e. wxPython) are just Python wrappers around C++ libraries anyway, so you're pretty much writing to a C++ backend.</p> <p>To address your IDE question, <a href="http://pythonide.blogspot.com/">SPE</a> (Stani's Python Editor) is a good IDE that I've used and <a href="http://www.eclipse.org/">Eclipse</a> with <a href="http://pydev.sourceforge.net/">PyDev</a> gets the job done as well. Both are OSS, so they're free to try!</p> <p>[Edit] @Marcin: Have you had experience writing > 30k LOC in Python? It's also funny that you should mention Google's scalability concerns, since they're Python's biggest supporters! Also a small organization called NASA also uses Python frequently ;) see <a href="http://www.python.org/about/success/usa/">"One coder and 17,000 Lines of Code Later"</a>.</p>
8
2008-08-30T08:21:18Z
[ "python", "ide" ]
Is Python good for big software projects (not web based)?
35,753
<p>Right now I'm developing mostly in C/C++, but I wrote some small utilities in Python to automatize some tasks and I really love it as language (especially the productivity). </p> <p>Except for the performances (a problem that could be sometimes solved thanks to the ease of interfacing Python with C modules), do you think it is proper for production use in the development of stand-alone complex applications (think for example to a word processor or a graphic tool)?</p> <p>What IDE would you suggest? The IDLE provided with Python is not enough even for small projects in my opinion.</p>
25
2008-08-30T07:08:22Z
35,777
<p>You'll find mostly two answers to that &ndash; the religous one (Yes! Of course! It's the best language ever!) and the other religious one (you gotta be kidding me! Python? No... it's not mature enough). I will maybe skip the last religion (Python?! Use Ruby!). The truth, as always, is far from obvious. </p> <p><strong>Pros</strong>: it's easy, readable, batteries included, has lots of good libraries for pretty much everything. It's expressive and dynamic typing makes it more concise in many cases.</p> <p><strong>Cons</strong>: as a dynamic language, has way worse IDE support (proper syntax completion <strong>requires</strong> static typing, whether explicit in Java or inferred in SML), its object system is far from perfect (interfaces, anyone?) and it is easy to end up with messy code that has methods returning either int or boolean or object or some sort under unknown circumstances.</p> <p>My take &ndash; I love Python for scripting, automation, tiny webapps and other simple well defined tasks. In my opinion it is by far <strong>the best</strong> dynamic language on the planet. That said, I would <strong>never</strong> use it <strong>any</strong> dynamically typed language to develop an application of substantial size.</p> <p>Say &ndash; it would be fine to use it for Stack Overflow, which has three developers and I guess no more than 30k lines of code. For bigger things &ndash; first your development would be super fast, and then once team and codebase grow things are slowing down more than they would with Java or C#. You need to offset lack of compilation time checks by writing more unittests, refactorings get harder cause you never know what your refacoring broke until you run all tests or even the whole big app, etc.</p> <p>Now &ndash; decide on how big your team is going to be and how big the app is supposed to be once it is done. If you have 5 or less people and the target size is roughly Stack Overflow, go ahead, write in Python. You will finish in no time and be happy with good codebase. But if you want to write second Google or Yahoo, you will be much better with C# or Java.</p> <p>Side-note on C/C++ you have mentioned: if you are not writing performance critical software (say massive parallel raytracer that will run for three months rendering a film) or a very mission critical system (say Mars lander that will fly three years straight and has only one chance to land right or you lose $400mln) do not use it. For web apps, most desktop apps, most apps in general it is not a good choice. You will die debugging pointers and memory allocation in complex business logic.</p>
19
2008-08-30T08:21:24Z
[ "python", "ide" ]
Is Python good for big software projects (not web based)?
35,753
<p>Right now I'm developing mostly in C/C++, but I wrote some small utilities in Python to automatize some tasks and I really love it as language (especially the productivity). </p> <p>Except for the performances (a problem that could be sometimes solved thanks to the ease of interfacing Python with C modules), do you think it is proper for production use in the development of stand-alone complex applications (think for example to a word processor or a graphic tool)?</p> <p>What IDE would you suggest? The IDLE provided with Python is not enough even for small projects in my opinion.</p>
25
2008-08-30T07:08:22Z
35,838
<p>I know I'm probably stating the obvious, but don't forget that the quality of the development team and their familiarity with the technology will have a major impact on your ability to deliver. </p> <p>If you have a strong team, then it's probably not an issue if they're familiar. But if you have people who are more 9 to 5'rs who aren't familiar with the technology, they will need more support and you'd need to make a call if the productivity gains are worth whatever the cost of that support is.</p>
0
2008-08-30T09:49:27Z
[ "python", "ide" ]
Is Python good for big software projects (not web based)?
35,753
<p>Right now I'm developing mostly in C/C++, but I wrote some small utilities in Python to automatize some tasks and I really love it as language (especially the productivity). </p> <p>Except for the performances (a problem that could be sometimes solved thanks to the ease of interfacing Python with C modules), do you think it is proper for production use in the development of stand-alone complex applications (think for example to a word processor or a graphic tool)?</p> <p>What IDE would you suggest? The IDLE provided with Python is not enough even for small projects in my opinion.</p>
25
2008-08-30T07:08:22Z
35,841
<p>Refactoring is inevitable on larger codebases and the lack of static typing makes this much harder in python than in statically typed languages.</p>
2
2008-08-30T09:53:02Z
[ "python", "ide" ]
Is Python good for big software projects (not web based)?
35,753
<p>Right now I'm developing mostly in C/C++, but I wrote some small utilities in Python to automatize some tasks and I really love it as language (especially the productivity). </p> <p>Except for the performances (a problem that could be sometimes solved thanks to the ease of interfacing Python with C modules), do you think it is proper for production use in the development of stand-alone complex applications (think for example to a word processor or a graphic tool)?</p> <p>What IDE would you suggest? The IDLE provided with Python is not enough even for small projects in my opinion.</p>
25
2008-08-30T07:08:22Z
36,238
<p>One way to judge what python is used for is to look at what products use python at the moment. This <a href="http://en.wikipedia.org/wiki/Python_software" rel="nofollow">wikipedia page</a> has a long list including various web frameworks, content management systems, version control systems, desktop apps and IDEs.</p> <p>As it says <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29#Usage" rel="nofollow">here</a> - "Some of the largest projects that use Python are the Zope application server, YouTube, and the original BitTorrent client. Large organizations that make use of Python include Google, Yahoo!, CERN and NASA. ITA uses Python for some of its components."</p> <p>So in short, yes, it is "proper for production use in the development of stand-alone complex applications". So are many other languages, with various pros and cons. Which is the best language for your particular use case is too subjective to answer, so I won't try, but often the answer will be "the one your developers know best".</p>
4
2008-08-30T18:42:19Z
[ "python", "ide" ]
Is Python good for big software projects (not web based)?
35,753
<p>Right now I'm developing mostly in C/C++, but I wrote some small utilities in Python to automatize some tasks and I really love it as language (especially the productivity). </p> <p>Except for the performances (a problem that could be sometimes solved thanks to the ease of interfacing Python with C modules), do you think it is proper for production use in the development of stand-alone complex applications (think for example to a word processor or a graphic tool)?</p> <p>What IDE would you suggest? The IDLE provided with Python is not enough even for small projects in my opinion.</p>
25
2008-08-30T07:08:22Z
259,591
<p>We've used IronPython to build our flagship spreadsheet application (40kloc production code - and it's Python, which IMO means loc per feature is low) at <a href="http://www.resolversystems.com/">Resolver Systems</a>, so I'd definitely say it's ready for production use of complex apps.</p> <p>There are two ways in which this might not be a useful answer to you :-)</p> <ol> <li>We're using IronPython, not the more usual CPython. This gives us the huge advantage of being able to use .NET class libraries. I may be setting myself up for flaming here, but I would say that I've never really seen a CPython application that looked "professional" - so having access to the WinForms widget set was a huge win for us. IronPython also gives us the advantage of being able to easily drop into C# if we need a performance boost. (Though to be honest we have <em>never</em> needed to do that. All of our performance problems to date have been because we chose dumb algorithms rather than because the language was slow.) Using C# from IP is much easier than writing a C Extension for CPython. </li> <li>We're an Extreme Programming shop, so we write tests before we write code. I would not write production code in a dynamic language without writing the tests first; the lack of a compile step needs to be covered by something, and as other people have pointed out, refactoring without it can be tough. (Greg Hewgill's answer suggests he's had the same problem. On the other hand, I don't think I would write - or especially refactor - production code in <em>any</em> language these days without writing the tests first - but YMMV.)</li> </ol> <p>Re: the IDE - we've been pretty much fine with each person using their favourite text editor; if you prefer something a bit more heavyweight then <a href="http://www.wingware.com/products">WingIDE</a> is pretty well-regarded.</p>
28
2008-11-03T19:05:14Z
[ "python", "ide" ]
Is Python good for big software projects (not web based)?
35,753
<p>Right now I'm developing mostly in C/C++, but I wrote some small utilities in Python to automatize some tasks and I really love it as language (especially the productivity). </p> <p>Except for the performances (a problem that could be sometimes solved thanks to the ease of interfacing Python with C modules), do you think it is proper for production use in the development of stand-alone complex applications (think for example to a word processor or a graphic tool)?</p> <p>What IDE would you suggest? The IDLE provided with Python is not enough even for small projects in my opinion.</p>
25
2008-08-30T07:08:22Z
263,761
<p>Nothing to add to the other answers, <em>besides</em> that if you choose python you <strong>must</strong> use something like <a href="http://pypi.python.org/pypi/pylint" rel="nofollow">pylint</a> which nobody mentioned so far.</p>
4
2008-11-04T22:44:46Z
[ "python", "ide" ]
Is Python good for big software projects (not web based)?
35,753
<p>Right now I'm developing mostly in C/C++, but I wrote some small utilities in Python to automatize some tasks and I really love it as language (especially the productivity). </p> <p>Except for the performances (a problem that could be sometimes solved thanks to the ease of interfacing Python with C modules), do you think it is proper for production use in the development of stand-alone complex applications (think for example to a word processor or a graphic tool)?</p> <p>What IDE would you suggest? The IDLE provided with Python is not enough even for small projects in my opinion.</p>
25
2008-08-30T07:08:22Z
277,490
<p>I had only one python experience, my trash-cli project.</p> <p>I know that probably some or all problems depends of my inexperience with python.</p> <p>I found frustrating these things: </p> <ol> <li>the difficult of finding a good IDE for free</li> <li>the limited support to automatic refactoring</li> </ol> <p>Moreover:</p> <ol> <li>the need of introduce two level of grouping packages and modules confuses me.</li> <li>it seems to me that there is not a widely adopted code naming convention</li> <li>it seems to me that there are some standard library APIs docs that are incomplete</li> <li>the fact that some standard libraries are not fully object oriented annoys me</li> </ol> <p>Although some python coders tell me that they does not have these problems, or they say these are not problems.</p>
-1
2008-11-10T10:03:07Z
[ "python", "ide" ]
Is Python good for big software projects (not web based)?
35,753
<p>Right now I'm developing mostly in C/C++, but I wrote some small utilities in Python to automatize some tasks and I really love it as language (especially the productivity). </p> <p>Except for the performances (a problem that could be sometimes solved thanks to the ease of interfacing Python with C modules), do you think it is proper for production use in the development of stand-alone complex applications (think for example to a word processor or a graphic tool)?</p> <p>What IDE would you suggest? The IDLE provided with Python is not enough even for small projects in my opinion.</p>
25
2008-08-30T07:08:22Z
286,449
<blockquote> <p>And as far as I know they use a lot of python inside google too.</p> </blockquote> <p>Well i'd hope so, the maker of python still works at google if i'm not mistaken? </p> <p>As for the use of Python, i think it's a great language for stand-alone apps. It's heavily used in a lot of Linux programs, and there are a few nice widget sets out there to aid in the development of GUI's. </p>
1
2008-11-13T07:36:28Z
[ "python", "ide" ]
Is Python good for big software projects (not web based)?
35,753
<p>Right now I'm developing mostly in C/C++, but I wrote some small utilities in Python to automatize some tasks and I really love it as language (especially the productivity). </p> <p>Except for the performances (a problem that could be sometimes solved thanks to the ease of interfacing Python with C modules), do you think it is proper for production use in the development of stand-alone complex applications (think for example to a word processor or a graphic tool)?</p> <p>What IDE would you suggest? The IDLE provided with Python is not enough even for small projects in my opinion.</p>
25
2008-08-30T07:08:22Z
286,491
<p>Python is a delight to use. I use it routinely and also write a lot of code for work in C#. There are two drawbacks to writing UI code in Python. one is that there is not a single ui framework that is accepted by the majority of the community. when you write in c# the .NET runtime and class libraries are all meant to work together. With Python every UI library has at's own semantics which are often at odds with the pythonic mindset in which you are trying to write your program. I am not blaming the library writers. I've tried several libraries (wxwidgets, PythonWin[Wrapper around MFC], Tkinter), When doing so I often felt that I was writing code in a language other than Python (despite the fact that it was python) because the libraries aren't exactly pythonic they are a port from another language be it c, c++, tk.</p> <p>So for me I will write UI code in .NET (for me C#) because of the IDE &amp; the consistency of the libraries. But when I can I will write business logic in python because it is more clear and more fun.</p>
1
2008-11-13T08:12:21Z
[ "python", "ide" ]
Is Python good for big software projects (not web based)?
35,753
<p>Right now I'm developing mostly in C/C++, but I wrote some small utilities in Python to automatize some tasks and I really love it as language (especially the productivity). </p> <p>Except for the performances (a problem that could be sometimes solved thanks to the ease of interfacing Python with C modules), do you think it is proper for production use in the development of stand-alone complex applications (think for example to a word processor or a graphic tool)?</p> <p>What IDE would you suggest? The IDLE provided with Python is not enough even for small projects in my opinion.</p>
25
2008-08-30T07:08:22Z
3,445,481
<p>Try Django or Pylons, write a simple app with both of them and then decide which one suits you best. There are others (like Turbogears or Werkzeug) but those are the most used.</p>
0
2010-08-10T01:51:26Z
[ "python", "ide" ]
Why is my instance variable not in __dict__?
35,805
<p>If I create a class <code>A</code> as follows:</p> <pre><code>class A: def __init__(self): self.name = 'A' </code></pre> <p>Inspecting the <code>__dict__</code> member looks like <code>{'name': 'A'}</code></p> <p>If however I create a class <code>B</code>:</p> <pre><code>class B: name = 'B' </code></pre> <p><code>__dict__</code> is empty.</p> <p>What is the difference between the two, and why doesn't <code>name</code> show up in <code>B</code>'s <code>__dict__</code>?</p>
27
2008-08-30T09:12:41Z
35,823
<p><code>B.name</code> is a class attribute, not an instance attribute. It shows up in <code>B.__dict__</code>, but not in <code>b = B(); b.__dict__</code>.</p> <p>The distinction is obscured somewhat because when you access an attribute on an instance, the class dict is a fallback. So in the above example, <code>b.name</code> will give you the value of <code>B.name</code>.</p>
38
2008-08-30T09:33:00Z
[ "python" ]
Why is my instance variable not in __dict__?
35,805
<p>If I create a class <code>A</code> as follows:</p> <pre><code>class A: def __init__(self): self.name = 'A' </code></pre> <p>Inspecting the <code>__dict__</code> member looks like <code>{'name': 'A'}</code></p> <p>If however I create a class <code>B</code>:</p> <pre><code>class B: name = 'B' </code></pre> <p><code>__dict__</code> is empty.</p> <p>What is the difference between the two, and why doesn't <code>name</code> show up in <code>B</code>'s <code>__dict__</code>?</p>
27
2008-08-30T09:12:41Z
39,755
<pre><code>class A: def _ _init_ _(self): self.name = 'A' a = A() </code></pre> <p>Creates an attribute on the object instance a of type A and it can therefore be found in: <code>a.__dict__</code></p> <pre><code>class B: name = 'B' b = B() </code></pre> <p>Creates an attribute on the class B and the attribute can be found in <code>B.__dict__</code> alternatively if you have an instance b of type B you can see the class level attributes in <code>b.__class__.__dict__</code></p>
11
2008-09-02T15:12:12Z
[ "python" ]
How to escape os.system() calls in Python?
35,817
<p>When using os.system() it's often necessary to escape filenames and other arguments passed as parameters to commands. How can I do this? Preferably something that would work on multiple operating systems/shells but in particular for bash.</p> <p>I'm currently doing the following, but am sure there must be a library function for this, or at least a more elegant/robust/efficient option:</p> <pre><code>def sh_escape(s): return s.replace("(","\\(").replace(")","\\)").replace(" ","\\ ") os.system("cat %s | grep something | sort &gt; %s" % (sh_escape(in_filename), sh_escape(out_filename))) </code></pre> <p><em>Edit:</em> I've accepted the simple answer of using quotes, don't know why I didn't think of that; I guess because I came from Windows where ' and " behave a little differently.</p> <p>Regarding security, I understand the concern, but, in this case, I'm interested in a quick and easy solution which os.system() provides, and the source of the strings is either not user-generated or at least entered by a trusted user (me).</p>
72
2008-08-30T09:27:24Z
35,831
<p>I believe that os.system just invokes whatever command shell is configured for the user, so I don't think you can do it in a platform independent way. My command shell could be anything from bash, emacs, ruby, or even quake3. Some of these programs aren't expecting the kind of arguments you are passing to them and even if they did there is no guarantee they do their escaping the same way.</p>
3
2008-08-30T09:43:50Z
[ "python", "shell", "escaping" ]
How to escape os.system() calls in Python?
35,817
<p>When using os.system() it's often necessary to escape filenames and other arguments passed as parameters to commands. How can I do this? Preferably something that would work on multiple operating systems/shells but in particular for bash.</p> <p>I'm currently doing the following, but am sure there must be a library function for this, or at least a more elegant/robust/efficient option:</p> <pre><code>def sh_escape(s): return s.replace("(","\\(").replace(")","\\)").replace(" ","\\ ") os.system("cat %s | grep something | sort &gt; %s" % (sh_escape(in_filename), sh_escape(out_filename))) </code></pre> <p><em>Edit:</em> I've accepted the simple answer of using quotes, don't know why I didn't think of that; I guess because I came from Windows where ' and " behave a little differently.</p> <p>Regarding security, I understand the concern, but, in this case, I'm interested in a quick and easy solution which os.system() provides, and the source of the strings is either not user-generated or at least entered by a trusted user (me).</p>
72
2008-08-30T09:27:24Z
35,857
<p>This is what I use:</p> <pre><code>def shellquote(s): return "'" + s.replace("'", "'\\''") + "'" </code></pre> <p>The shell will always accept a quoted filename and remove the surrounding quotes before passing it to the program in question. Notably, this avoids problems with filenames that contain spaces or any other kind of nasty shell metacharacter.</p> <p><strong>Update</strong>: If you are using Python 3.3 or later, use <a href="http://docs.python.org/dev/library/shlex.html#shlex.quote">shlex.quote</a> instead of rolling your own.</p>
44
2008-08-30T10:13:11Z
[ "python", "shell", "escaping" ]
How to escape os.system() calls in Python?
35,817
<p>When using os.system() it's often necessary to escape filenames and other arguments passed as parameters to commands. How can I do this? Preferably something that would work on multiple operating systems/shells but in particular for bash.</p> <p>I'm currently doing the following, but am sure there must be a library function for this, or at least a more elegant/robust/efficient option:</p> <pre><code>def sh_escape(s): return s.replace("(","\\(").replace(")","\\)").replace(" ","\\ ") os.system("cat %s | grep something | sort &gt; %s" % (sh_escape(in_filename), sh_escape(out_filename))) </code></pre> <p><em>Edit:</em> I've accepted the simple answer of using quotes, don't know why I didn't think of that; I guess because I came from Windows where ' and " behave a little differently.</p> <p>Regarding security, I understand the concern, but, in this case, I'm interested in a quick and easy solution which os.system() provides, and the source of the strings is either not user-generated or at least entered by a trusted user (me).</p>
72
2008-08-30T09:27:24Z
35,858
<p>Perhaps you have a specific reason for using <code>os.system()</code>. But if not you should probably be using the <a href="http://docs.python.org/lib/module-subprocess.html"><code>subprocess</code> module</a>. You can specify the pipes directly and avoid using the shell.</p> <p>The following is from <a href="http://www.python.org/dev/peps/pep-0324/">PEP324</a>:</p> <blockquote> <pre><code>Replacing shell pipe line ------------------------- output=`dmesg | grep hda` ==&gt; p1 = Popen(["dmesg"], stdout=PIPE) p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) output = p2.communicate()[0] </code></pre> </blockquote>
49
2008-08-30T10:15:02Z
[ "python", "shell", "escaping" ]
How to escape os.system() calls in Python?
35,817
<p>When using os.system() it's often necessary to escape filenames and other arguments passed as parameters to commands. How can I do this? Preferably something that would work on multiple operating systems/shells but in particular for bash.</p> <p>I'm currently doing the following, but am sure there must be a library function for this, or at least a more elegant/robust/efficient option:</p> <pre><code>def sh_escape(s): return s.replace("(","\\(").replace(")","\\)").replace(" ","\\ ") os.system("cat %s | grep something | sort &gt; %s" % (sh_escape(in_filename), sh_escape(out_filename))) </code></pre> <p><em>Edit:</em> I've accepted the simple answer of using quotes, don't know why I didn't think of that; I guess because I came from Windows where ' and " behave a little differently.</p> <p>Regarding security, I understand the concern, but, in this case, I'm interested in a quick and easy solution which os.system() provides, and the source of the strings is either not user-generated or at least entered by a trusted user (me).</p>
72
2008-08-30T09:27:24Z
35,900
<p>If you do use the system command, I would try and whitelist what goes into the os.system() call.. For example..</p> <pre><code>clean_user_input re.sub("[^a-zA-Z]", "", user_input) os.system("ls %s" % (clean_user_input)) </code></pre> <p>The subprocess module is a better option, and I would recommend trying to avoid using anything like os.system/subprocess wherever possible.</p>
-2
2008-08-30T11:43:44Z
[ "python", "shell", "escaping" ]
How to escape os.system() calls in Python?
35,817
<p>When using os.system() it's often necessary to escape filenames and other arguments passed as parameters to commands. How can I do this? Preferably something that would work on multiple operating systems/shells but in particular for bash.</p> <p>I'm currently doing the following, but am sure there must be a library function for this, or at least a more elegant/robust/efficient option:</p> <pre><code>def sh_escape(s): return s.replace("(","\\(").replace(")","\\)").replace(" ","\\ ") os.system("cat %s | grep something | sort &gt; %s" % (sh_escape(in_filename), sh_escape(out_filename))) </code></pre> <p><em>Edit:</em> I've accepted the simple answer of using quotes, don't know why I didn't think of that; I guess because I came from Windows where ' and " behave a little differently.</p> <p>Regarding security, I understand the concern, but, in this case, I'm interested in a quick and easy solution which os.system() provides, and the source of the strings is either not user-generated or at least entered by a trusted user (me).</p>
72
2008-08-30T09:27:24Z
847,800
<p><a href="https://docs.python.org/3/library/shlex.html#shlex.quote"><code>shlex.quote()</code></a> does what you want since python 3.</p> <p>(Use <a href="https://docs.python.org/2/library/pipes.html#pipes.quote"><code>pipes.quote</code></a> to support both python 2 and python 3)</p>
101
2009-05-11T12:06:40Z
[ "python", "shell", "escaping" ]
How to escape os.system() calls in Python?
35,817
<p>When using os.system() it's often necessary to escape filenames and other arguments passed as parameters to commands. How can I do this? Preferably something that would work on multiple operating systems/shells but in particular for bash.</p> <p>I'm currently doing the following, but am sure there must be a library function for this, or at least a more elegant/robust/efficient option:</p> <pre><code>def sh_escape(s): return s.replace("(","\\(").replace(")","\\)").replace(" ","\\ ") os.system("cat %s | grep something | sort &gt; %s" % (sh_escape(in_filename), sh_escape(out_filename))) </code></pre> <p><em>Edit:</em> I've accepted the simple answer of using quotes, don't know why I didn't think of that; I guess because I came from Windows where ' and " behave a little differently.</p> <p>Regarding security, I understand the concern, but, in this case, I'm interested in a quick and easy solution which os.system() provides, and the source of the strings is either not user-generated or at least entered by a trusted user (me).</p>
72
2008-08-30T09:27:24Z
1,884,718
<p>Note that pipes.quote is actually broken in Python 2.5 and Python 3.1 and not safe to use--It doesn't handle zero-length arguments.</p> <pre><code>&gt;&gt;&gt; from pipes import quote &gt;&gt;&gt; args = ['arg1', '', 'arg3'] &gt;&gt;&gt; print 'mycommand %s' % (' '.join(quote(arg) for arg in args)) mycommand arg1 arg3 </code></pre> <p>See <a href="http://bugs.python.org/issue7476" rel="nofollow">Python issue 7476</a>; it has been fixed in Python 2.6 and 3.2 and newer.</p>
4
2009-12-10T23:03:55Z
[ "python", "shell", "escaping" ]
How to escape os.system() calls in Python?
35,817
<p>When using os.system() it's often necessary to escape filenames and other arguments passed as parameters to commands. How can I do this? Preferably something that would work on multiple operating systems/shells but in particular for bash.</p> <p>I'm currently doing the following, but am sure there must be a library function for this, or at least a more elegant/robust/efficient option:</p> <pre><code>def sh_escape(s): return s.replace("(","\\(").replace(")","\\)").replace(" ","\\ ") os.system("cat %s | grep something | sort &gt; %s" % (sh_escape(in_filename), sh_escape(out_filename))) </code></pre> <p><em>Edit:</em> I've accepted the simple answer of using quotes, don't know why I didn't think of that; I guess because I came from Windows where ' and " behave a little differently.</p> <p>Regarding security, I understand the concern, but, in this case, I'm interested in a quick and easy solution which os.system() provides, and the source of the strings is either not user-generated or at least entered by a trusted user (me).</p>
72
2008-08-30T09:27:24Z
3,851,646
<p>The function I use is:</p> <pre><code>def quote_argument(argument): return '"%s"' % ( argument .replace('\\', '\\\\') .replace('"', '\\"') .replace('$', '\\$') .replace('`', '\\`') ) </code></pre> <p>that is: I always enclose the argument in double quotes, and then backslash-quote the only characters special inside double quotes.</p>
1
2010-10-03T21:21:44Z
[ "python", "shell", "escaping" ]
How to escape os.system() calls in Python?
35,817
<p>When using os.system() it's often necessary to escape filenames and other arguments passed as parameters to commands. How can I do this? Preferably something that would work on multiple operating systems/shells but in particular for bash.</p> <p>I'm currently doing the following, but am sure there must be a library function for this, or at least a more elegant/robust/efficient option:</p> <pre><code>def sh_escape(s): return s.replace("(","\\(").replace(")","\\)").replace(" ","\\ ") os.system("cat %s | grep something | sort &gt; %s" % (sh_escape(in_filename), sh_escape(out_filename))) </code></pre> <p><em>Edit:</em> I've accepted the simple answer of using quotes, don't know why I didn't think of that; I guess because I came from Windows where ' and " behave a little differently.</p> <p>Regarding security, I understand the concern, but, in this case, I'm interested in a quick and easy solution which os.system() provides, and the source of the strings is either not user-generated or at least entered by a trusted user (me).</p>
72
2008-08-30T09:27:24Z
10,750,633
<p>Maybe <code>subprocess.list2cmdline</code> is a better shot?</p>
7
2012-05-25T07:54:41Z
[ "python", "shell", "escaping" ]
How to escape os.system() calls in Python?
35,817
<p>When using os.system() it's often necessary to escape filenames and other arguments passed as parameters to commands. How can I do this? Preferably something that would work on multiple operating systems/shells but in particular for bash.</p> <p>I'm currently doing the following, but am sure there must be a library function for this, or at least a more elegant/robust/efficient option:</p> <pre><code>def sh_escape(s): return s.replace("(","\\(").replace(")","\\)").replace(" ","\\ ") os.system("cat %s | grep something | sort &gt; %s" % (sh_escape(in_filename), sh_escape(out_filename))) </code></pre> <p><em>Edit:</em> I've accepted the simple answer of using quotes, don't know why I didn't think of that; I guess because I came from Windows where ' and " behave a little differently.</p> <p>Regarding security, I understand the concern, but, in this case, I'm interested in a quick and easy solution which os.system() provides, and the source of the strings is either not user-generated or at least entered by a trusted user (me).</p>
72
2008-08-30T09:27:24Z
16,210,253
<p>The real answer is: Don't use <code>os.system()</code> in the first place. Use <a href="http://docs.python.org/2/library/subprocess.html#subprocess.call" rel="nofollow"><code>subprocess.call</code></a> instead and supply the unescaped arguments.</p>
-2
2013-04-25T08:44:50Z
[ "python", "shell", "escaping" ]
How to escape os.system() calls in Python?
35,817
<p>When using os.system() it's often necessary to escape filenames and other arguments passed as parameters to commands. How can I do this? Preferably something that would work on multiple operating systems/shells but in particular for bash.</p> <p>I'm currently doing the following, but am sure there must be a library function for this, or at least a more elegant/robust/efficient option:</p> <pre><code>def sh_escape(s): return s.replace("(","\\(").replace(")","\\)").replace(" ","\\ ") os.system("cat %s | grep something | sort &gt; %s" % (sh_escape(in_filename), sh_escape(out_filename))) </code></pre> <p><em>Edit:</em> I've accepted the simple answer of using quotes, don't know why I didn't think of that; I guess because I came from Windows where ' and " behave a little differently.</p> <p>Regarding security, I understand the concern, but, in this case, I'm interested in a quick and easy solution which os.system() provides, and the source of the strings is either not user-generated or at least entered by a trusted user (me).</p>
72
2008-08-30T09:27:24Z
29,597,408
<p><strong>Notice</strong>: This is an answer for Python 2.7.x.</p> <p>According to the <a href="https://hg.python.org/cpython/file/2.7/Lib/pipes.py#l262" rel="nofollow">source</a>, <code>pipes.quote()</code> is a way to "<em>Reliably quote a string as a single argument for <strong>/bin/sh</em></strong>". (Although it is <a href="https://docs.python.org/2/library/pipes.html#pipes.quote" rel="nofollow">deprecated since version 2.7</a> and finally exposed publicly in Python 3.3 as the <code>shelx.quote()</code> function.)</p> <p>On <a href="https://hg.python.org/cpython/file/2.7/Lib/subprocess.py#l577" rel="nofollow">the other hand</a>, <code>subprocess.list2cmdline()</code> is a way to "<em>Translate a sequence of arguments into a command line string, using the same rules as the <strong>MS C runtime</em></strong>".</p> <p>Here we are, the platform independent way of quoting strings for command lines.</p> <pre><code>import sys mswindows = (sys.platform == "win32") if mswindows: from subprocess import list2cmdline quote_args = list2cmdline else: # POSIX from pipes import quote def quote_args(seq): return ' '.join(quote(arg) for arg in seq) </code></pre> <p>Usage:</p> <pre><code># Quote a single argument print quote_args(['my argument']) # Quote multiple arguments my_args = ['This', 'is', 'my arguments'] print quote_args(my_args) </code></pre>
2
2015-04-13T03:26:35Z
[ "python", "shell", "escaping" ]
Django templates and variable attributes
35,948
<p>I'm using Google App Engine and Django templates.<br> I have a table that I want to display the objects look something like:<br></p> <pre><code>Object Result: Items = [item1,item2] Users = [{name='username',item1=3,item2=4},..] </code></pre> <p>The Django template is:</p> <pre><code>&lt;table&gt; &lt;tr align="center"&gt; &lt;th&gt;user&lt;/th&gt; {% for item in result.items %} &lt;th&gt;{{item}}&lt;/th&gt; {% endfor %} &lt;/tr&gt; {% for user in result.users %} &lt;tr align="center"&gt; &lt;td&gt;{{user.name}}&lt;/td&gt; {% for item in result.items %} &lt;td&gt;{{ user.item }}&lt;/td&gt; {% endfor %} &lt;/tr&gt; {% endfor %} &lt;/table&gt; </code></pre> <p>Now the <a href="http://www.djangoproject.com/documentation/0.96/templates/#variables" rel="nofollow">Django documention</a> states that when it sees a <strong>.</strong> in variables<br> It tries several things to get the data, one of which is dictionary lookup which is exactly what I want but doesn't seem to happen...</p>
30
2008-08-30T13:20:02Z
35,978
<p>I'm assuming that the part the doesn't work is <code>{{ user.item }}</code>.</p> <p>Django will be trying a dictionary lookup, but using the string <code>"item"</code> and not the value of the <code>item</code> loop variable. Django did the same thing when it resolved <code>{{ user.name }}</code> to the <code>name</code> attribute of the <code>user</code> object, rather than looking for a variable called <code>name</code>.</p> <p>I think you will need to do some preprocessing of the data in your view before you render it in your template.</p>
9
2008-08-30T14:16:54Z
[ "python", "django", "google-app-engine" ]
Django templates and variable attributes
35,948
<p>I'm using Google App Engine and Django templates.<br> I have a table that I want to display the objects look something like:<br></p> <pre><code>Object Result: Items = [item1,item2] Users = [{name='username',item1=3,item2=4},..] </code></pre> <p>The Django template is:</p> <pre><code>&lt;table&gt; &lt;tr align="center"&gt; &lt;th&gt;user&lt;/th&gt; {% for item in result.items %} &lt;th&gt;{{item}}&lt;/th&gt; {% endfor %} &lt;/tr&gt; {% for user in result.users %} &lt;tr align="center"&gt; &lt;td&gt;{{user.name}}&lt;/td&gt; {% for item in result.items %} &lt;td&gt;{{ user.item }}&lt;/td&gt; {% endfor %} &lt;/tr&gt; {% endfor %} &lt;/table&gt; </code></pre> <p>Now the <a href="http://www.djangoproject.com/documentation/0.96/templates/#variables" rel="nofollow">Django documention</a> states that when it sees a <strong>.</strong> in variables<br> It tries several things to get the data, one of which is dictionary lookup which is exactly what I want but doesn't seem to happen...</p>
30
2008-08-30T13:20:02Z
37,190
<p>shouldn't this:</p> <pre><code>{{ user.item }} </code></pre> <p>be this?</p> <pre><code>{{ item }} </code></pre> <p>there is no user object in the context within that loop....?</p>
0
2008-08-31T22:29:14Z
[ "python", "django", "google-app-engine" ]
Django templates and variable attributes
35,948
<p>I'm using Google App Engine and Django templates.<br> I have a table that I want to display the objects look something like:<br></p> <pre><code>Object Result: Items = [item1,item2] Users = [{name='username',item1=3,item2=4},..] </code></pre> <p>The Django template is:</p> <pre><code>&lt;table&gt; &lt;tr align="center"&gt; &lt;th&gt;user&lt;/th&gt; {% for item in result.items %} &lt;th&gt;{{item}}&lt;/th&gt; {% endfor %} &lt;/tr&gt; {% for user in result.users %} &lt;tr align="center"&gt; &lt;td&gt;{{user.name}}&lt;/td&gt; {% for item in result.items %} &lt;td&gt;{{ user.item }}&lt;/td&gt; {% endfor %} &lt;/tr&gt; {% endfor %} &lt;/table&gt; </code></pre> <p>Now the <a href="http://www.djangoproject.com/documentation/0.96/templates/#variables" rel="nofollow">Django documention</a> states that when it sees a <strong>.</strong> in variables<br> It tries several things to get the data, one of which is dictionary lookup which is exactly what I want but doesn't seem to happen...</p>
30
2008-08-30T13:20:02Z
50,425
<p>I found a "nicer"/"better" solution for getting variables inside Its not the nicest way, but it works.</p> <p>You install a custom filter into django which gets the key of your dict as a parameter</p> <p>To make it work in google app-engine you need to add a file to your main directory, I called mine *django_hack.py* which contains this little piece of code</p> <pre><code>from google.appengine.ext import webapp register = webapp.template.create_template_register() def hash(h,key): if key in h: return h[key] else: return None register.filter(hash) </code></pre> <p>Now that we have this file, all we need to do is tell the app-engine to use it... we do that by adding this little line to your main file</p> <pre><code>webapp.template.register_template_library('django_hack') </code></pre> <p>and in your template view add this template instead of the usual code</p> <pre><code>{{ user|hash:item }} </code></pre> <p>And its should work perfectly =)</p>
30
2008-09-08T19:01:24Z
[ "python", "django", "google-app-engine" ]
Django templates and variable attributes
35,948
<p>I'm using Google App Engine and Django templates.<br> I have a table that I want to display the objects look something like:<br></p> <pre><code>Object Result: Items = [item1,item2] Users = [{name='username',item1=3,item2=4},..] </code></pre> <p>The Django template is:</p> <pre><code>&lt;table&gt; &lt;tr align="center"&gt; &lt;th&gt;user&lt;/th&gt; {% for item in result.items %} &lt;th&gt;{{item}}&lt;/th&gt; {% endfor %} &lt;/tr&gt; {% for user in result.users %} &lt;tr align="center"&gt; &lt;td&gt;{{user.name}}&lt;/td&gt; {% for item in result.items %} &lt;td&gt;{{ user.item }}&lt;/td&gt; {% endfor %} &lt;/tr&gt; {% endfor %} &lt;/table&gt; </code></pre> <p>Now the <a href="http://www.djangoproject.com/documentation/0.96/templates/#variables" rel="nofollow">Django documention</a> states that when it sees a <strong>.</strong> in variables<br> It tries several things to get the data, one of which is dictionary lookup which is exactly what I want but doesn't seem to happen...</p>
30
2008-08-30T13:20:02Z
1,278,623
<p>@Dave Webb (i haven't been rated high enough to comment yet)</p> <p>The dot lookups can be summarized like this: when the template system encounters a dot in a variable name, it tries the following lookups, in this order:</p> <pre><code>* Dictionary lookup (e.e., foo["bar"]) * Attribute lookup (e.g., foo.bar) * Method call (e.g., foo.bar()) * List-index lookup (e.g., foo[bar]) </code></pre> <p>The system uses the first lookup type that works. It’s short-circuit logic.</p>
3
2009-08-14T15:45:39Z
[ "python", "django", "google-app-engine" ]
Django templates and variable attributes
35,948
<p>I'm using Google App Engine and Django templates.<br> I have a table that I want to display the objects look something like:<br></p> <pre><code>Object Result: Items = [item1,item2] Users = [{name='username',item1=3,item2=4},..] </code></pre> <p>The Django template is:</p> <pre><code>&lt;table&gt; &lt;tr align="center"&gt; &lt;th&gt;user&lt;/th&gt; {% for item in result.items %} &lt;th&gt;{{item}}&lt;/th&gt; {% endfor %} &lt;/tr&gt; {% for user in result.users %} &lt;tr align="center"&gt; &lt;td&gt;{{user.name}}&lt;/td&gt; {% for item in result.items %} &lt;td&gt;{{ user.item }}&lt;/td&gt; {% endfor %} &lt;/tr&gt; {% endfor %} &lt;/table&gt; </code></pre> <p>Now the <a href="http://www.djangoproject.com/documentation/0.96/templates/#variables" rel="nofollow">Django documention</a> states that when it sees a <strong>.</strong> in variables<br> It tries several things to get the data, one of which is dictionary lookup which is exactly what I want but doesn't seem to happen...</p>
30
2008-08-30T13:20:02Z
3,125,956
<p>As a replacement for k,v in user.items on Google App Engine using django templates where user = {'a':1, 'b', 2, 'c', 3}</p> <pre><code>{% for pair in user.items %} {% for keyval in pair %} {{ keyval }}{% endfor %}&lt;br&gt; {% endfor %} </code></pre> <p>a 1<br> b 2<br> c 3<br></p> <p>pair = (key, value) for each dictionary item.</p>
1
2010-06-27T00:34:47Z
[ "python", "django", "google-app-engine" ]
Django templates and variable attributes
35,948
<p>I'm using Google App Engine and Django templates.<br> I have a table that I want to display the objects look something like:<br></p> <pre><code>Object Result: Items = [item1,item2] Users = [{name='username',item1=3,item2=4},..] </code></pre> <p>The Django template is:</p> <pre><code>&lt;table&gt; &lt;tr align="center"&gt; &lt;th&gt;user&lt;/th&gt; {% for item in result.items %} &lt;th&gt;{{item}}&lt;/th&gt; {% endfor %} &lt;/tr&gt; {% for user in result.users %} &lt;tr align="center"&gt; &lt;td&gt;{{user.name}}&lt;/td&gt; {% for item in result.items %} &lt;td&gt;{{ user.item }}&lt;/td&gt; {% endfor %} &lt;/tr&gt; {% endfor %} &lt;/table&gt; </code></pre> <p>Now the <a href="http://www.djangoproject.com/documentation/0.96/templates/#variables" rel="nofollow">Django documention</a> states that when it sees a <strong>.</strong> in variables<br> It tries several things to get the data, one of which is dictionary lookup which is exactly what I want but doesn't seem to happen...</p>
30
2008-08-30T13:20:02Z
3,466,349
<p>Or you can use the default django system which is used to resolve attributes in tempaltes like this : </p> <pre><code>from django.template import Variable, VariableDoesNotExist @register.filter def hash(object, attr): pseudo_context = { 'object' : object } try: value = Variable('object.%s' % attr).resolve(pseudo_context) except VariableDoesNotExist: value = None return value </code></pre> <p>That just works</p> <p>in your template :</p> <pre><code>{{ user|hash:item }} </code></pre>
7
2010-08-12T09:36:35Z
[ "python", "django", "google-app-engine" ]
C-like structures in Python
35,988
<p>Is there a way to conveniently define a C-like structure in Python? I'm tired of writing stuff like:</p> <pre><code>class MyStruct(): def __init__(self, field1, field2, field3): self.field1 = field1 self.field2 = field2 self.field3 = field3 </code></pre>
210
2008-08-30T14:33:25Z
35,990
<p>How about a dictionary?</p> <p>Something like this:</p> <pre><code>myStruct = {'field1': 'some val', 'field2': 'some val'} </code></pre> <p>Then you can use this to manipulate values:</p> <pre><code>print myStruct['field1'] myStruct['field2'] = 'some other values' </code></pre> <p>And the values don't have to be strings. They can be pretty much any other object.</p>
47
2008-08-30T14:35:29Z
[ "python", "struct" ]
C-like structures in Python
35,988
<p>Is there a way to conveniently define a C-like structure in Python? I'm tired of writing stuff like:</p> <pre><code>class MyStruct(): def __init__(self, field1, field2, field3): self.field1 = field1 self.field2 = field2 self.field3 = field3 </code></pre>
210
2008-08-30T14:33:25Z
35,993
<p>You can use a tuple for a lot of things where you would use a struct in C (something like x,y coordinates or RGB colors for example).</p> <p>For everything else you can use dictionary, or a utility class like <a href="http://code.activestate.com/recipes/52308/">this one</a>:</p> <pre><code>&gt;&gt;&gt; class Bunch: ... def __init__(self, **kwds): ... self.__dict__.update(kwds) ... &gt;&gt;&gt; mystruct = Bunch(field1=value1, field2=value2) </code></pre> <p>I think the "definitive" discussion is <a href="http://books.google.com/books?id=Q0s6Vgb98CQC&amp;lpg=PT212&amp;dq=Python%20Cookbook%20%22Collecting%20a%20Bunch%20of%20Named%20Items%22&amp;hl=en&amp;pg=PT213#v=onepage&amp;q&amp;f=false">here</a>, in the published version of the Python Cookbook.</p>
70
2008-08-30T14:38:38Z
[ "python", "struct" ]
C-like structures in Python
35,988
<p>Is there a way to conveniently define a C-like structure in Python? I'm tired of writing stuff like:</p> <pre><code>class MyStruct(): def __init__(self, field1, field2, field3): self.field1 = field1 self.field2 = field2 self.field3 = field3 </code></pre>
210
2008-08-30T14:33:25Z
36,033
<p>Use a <a href="https://docs.python.org/2/library/collections.html#collections.namedtuple">named tuple</a>, which was added to the <a href="http://docs.python.org/library/collections.html">collections module</a> in the standard library in Python 2.6. It's also possible to use Raymond Hettinger's <a href="http://code.activestate.com/recipes/500261/">named tuple</a> recipe if you need to support Python 2.4.</p> <p>It's nice for your basic example, but also covers a bunch of edge cases you might run into later as well. Your fragment above would be written as:</p> <pre><code>from collections import namedtuple MyStruct = namedtuple("MyStruct", "field1 field2 field3") </code></pre> <p>The newly created type can be used like this:</p> <pre><code>m = MyStruct("foo", "bar", "baz") </code></pre> <p>Or you can use named arguments:</p> <pre><code>m = MyStruct(field1 = "foo", field2 = "bar", field3 = "baz") </code></pre>
202
2008-08-30T15:18:59Z
[ "python", "struct" ]
C-like structures in Python
35,988
<p>Is there a way to conveniently define a C-like structure in Python? I'm tired of writing stuff like:</p> <pre><code>class MyStruct(): def __init__(self, field1, field2, field3): self.field1 = field1 self.field2 = field2 self.field3 = field3 </code></pre>
210
2008-08-30T14:33:25Z
36,034
<blockquote> <p>dF: that's pretty cool... I didn't know that I could access the fields in a class using dict.</p> <p>Mark: the situations that I wish I had this are precisely when I want a tuple but nothing as "heavy" as a dictionary.</p> </blockquote> <p>You can access the fields of a class using a dictionary because the fields of a class, its methods and all its properties are stored internally using dicts (at least in CPython).</p> <p>...Which leads us to your second comment. Believing that Python dicts are "heavy" is an extremely non-pythonistic concept. And reading such comments kills my Python Zen. That's not good.</p> <p>You see, when you declare a class you are actually creating a pretty complex wrapper around a dictionary - so, if anything, you are adding more overhead than by using a simple dictionary. An overhead which, by the way, is meaningless in any case. If you are working on performance critical applications, use C or something.</p>
17
2008-08-30T15:20:15Z
[ "python", "struct" ]
C-like structures in Python
35,988
<p>Is there a way to conveniently define a C-like structure in Python? I'm tired of writing stuff like:</p> <pre><code>class MyStruct(): def __init__(self, field1, field2, field3): self.field1 = field1 self.field2 = field2 self.field3 = field3 </code></pre>
210
2008-08-30T14:33:25Z
36,061
<p>You can also pass the init parameters to the instance variables by position</p> <pre><code># Abstract struct class class Struct: def __init__ (self, *argv, **argd): if len(argd): # Update by dictionary self.__dict__.update (argd) else: # Update by position attrs = filter (lambda x: x[0:2] != "__", dir(self)) for n in range(len(argv)): setattr(self, attrs[n], argv[n]) # Specific class class Point3dStruct (Struct): x = 0 y = 0 z = 0 pt1 = Point3dStruct() pt1.x = 10 print pt1.x print "-"*10 pt2 = Point3dStruct(5, 6) print pt2.x, pt2.y print "-"*10 pt3 = Point3dStruct (x=1, y=2, z=3) print pt3.x, pt3.y, pt3.z print "-"*10 </code></pre>
13
2008-08-30T15:53:10Z
[ "python", "struct" ]