title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
How to do a meaningful code-coverage analysis of my unit-tests?
1,006,189
<p>I manage the testing for a very large financial pricing system. Recently our HQ have insisted that we verify that every single part of our project has a meaningful test in place. At the very least they want a system which guarantees that when we change something we can spot unintentional changes to other sub-systems. Preferably they want something which validates the correctness of every component in our system.</p> <p>That's obviously going to be quite a lot of work! It could take years, but for this kind of project it's worth it. </p> <p>I need to find out which parts of our code are not covered by any of our unit-tests. If I knew which parts of my system were untested then I could set about developing new tests which would eventually approach towards my goal of complete test-coverage. </p> <p>So how can I go about running this kind of analysis. What tools are available to me?</p> <p>I use Python 2.4 on Windows 32bit XP</p> <p>UPDATE0:</p> <p>Just to clarify: We have a very comprehensive unit-test suite (plus a seperate and very comprehensive regtest suite which is outside the scope of this exercise). We also have a very stable continuous integration platform (built with Hudson) which is designed to split-up and run standard python unit-tests across our test facility: Approx 20 PCs built to the company spec.</p> <p>The object of this exercise is to plug any gaps in our python unittest suite (only) suite so that every component has some degree of unittest coverage. Other developers will be taking responsibility for non Python components of the project (which are also outside of scope).</p> <p>"<strong>Component</strong>" is intentionally vague: Sometime it will be a class, other time an entire module or assembly of modules. It might even refer to a single financial concept (e.g. a single type of financial option or a financial model used by many types of option). This cake can be cut in many ways. </p> <p>"<strong>Meaningful</strong>" tests (to me) are ones which validate that the function does what the developer originally intended. We do not want to simply reproduce the regtests in pure python. Often the developer's intent is not immediatly obvious, hence the need to research and clarify anything which looks vague and then enshrine this knowledge in a unit-test which makes the original intent quite explicit.</p>
5
2009-06-17T10:20:17Z
1,006,225
<p>For the code coverage alone, you could use <a href="http://nedbatchelder.com/code/coverage/" rel="nofollow">coverage.py</a>.</p> <p>As for coverage.py vs <a href="http://darcs.idyll.org/~t/projects/figleaf/doc/" rel="nofollow">figleaf</a>:</p> <blockquote> <p>figleaf differs from the gold standard of Python coverage tools ('coverage.py') in several ways. First and foremost, figleaf uses the same criterion for "interesting" lines of code as the sys.settrace function, which obviates some of the complexity in coverage.py (but does mean that your "loc" count goes down). Second, figleaf does not record code executed in the Python standard library, which results in a significant speedup. And third, the format in which the coverage format is saved is very simple and easy to work with.</p> <p>You might want to use figleaf if you're recording coverage from multiple types of tests and need to aggregate the coverage in interesting ways, and/or control when coverage is recorded. coverage.py is a better choice for command-line execution, and its reporting is a fair bit nicer.</p> </blockquote> <p>I guess both have their pros and cons.</p>
6
2009-06-17T10:27:46Z
[ "python", "testing" ]
How to do a meaningful code-coverage analysis of my unit-tests?
1,006,189
<p>I manage the testing for a very large financial pricing system. Recently our HQ have insisted that we verify that every single part of our project has a meaningful test in place. At the very least they want a system which guarantees that when we change something we can spot unintentional changes to other sub-systems. Preferably they want something which validates the correctness of every component in our system.</p> <p>That's obviously going to be quite a lot of work! It could take years, but for this kind of project it's worth it. </p> <p>I need to find out which parts of our code are not covered by any of our unit-tests. If I knew which parts of my system were untested then I could set about developing new tests which would eventually approach towards my goal of complete test-coverage. </p> <p>So how can I go about running this kind of analysis. What tools are available to me?</p> <p>I use Python 2.4 on Windows 32bit XP</p> <p>UPDATE0:</p> <p>Just to clarify: We have a very comprehensive unit-test suite (plus a seperate and very comprehensive regtest suite which is outside the scope of this exercise). We also have a very stable continuous integration platform (built with Hudson) which is designed to split-up and run standard python unit-tests across our test facility: Approx 20 PCs built to the company spec.</p> <p>The object of this exercise is to plug any gaps in our python unittest suite (only) suite so that every component has some degree of unittest coverage. Other developers will be taking responsibility for non Python components of the project (which are also outside of scope).</p> <p>"<strong>Component</strong>" is intentionally vague: Sometime it will be a class, other time an entire module or assembly of modules. It might even refer to a single financial concept (e.g. a single type of financial option or a financial model used by many types of option). This cake can be cut in many ways. </p> <p>"<strong>Meaningful</strong>" tests (to me) are ones which validate that the function does what the developer originally intended. We do not want to simply reproduce the regtests in pure python. Often the developer's intent is not immediatly obvious, hence the need to research and clarify anything which looks vague and then enshrine this knowledge in a unit-test which makes the original intent quite explicit.</p>
5
2009-06-17T10:20:17Z
1,006,244
<p>Assuming you already have a relatively comprehensive test suite, there are tools for the python part. The C part is much more problematic, depending on tools availability.</p> <ul> <li><p>For <a href="http://darcs.idyll.org/~t/projects/figleaf/doc/" rel="nofollow">python unit tests</a></p></li> <li><p>For C code, it is difficult on many platforms because gprof, the Gnu code profiler cannot handle code built with -fPIC. So you have to build every extension statically in this case, which is not supported by many extensions (see my <a href="http://cournape.wordpress.com/2009/05/08/first-steps-toward-c-code-coverage-in-numpy/" rel="nofollow">blog post for numpy</a>, for example). On windows, there may be better code coverage tools for compiled code, but that may require you to recompile the extensions with MS compilers.</p></li> </ul> <p>As for the "right" code coverage, I think a good balance it to avoid writing complicated unit tests as much as possible. If a unit test is more complicated than the thing it tests, then it is a probably not a good test, or a broken test.</p>
1
2009-06-17T10:31:10Z
[ "python", "testing" ]
How to do a meaningful code-coverage analysis of my unit-tests?
1,006,189
<p>I manage the testing for a very large financial pricing system. Recently our HQ have insisted that we verify that every single part of our project has a meaningful test in place. At the very least they want a system which guarantees that when we change something we can spot unintentional changes to other sub-systems. Preferably they want something which validates the correctness of every component in our system.</p> <p>That's obviously going to be quite a lot of work! It could take years, but for this kind of project it's worth it. </p> <p>I need to find out which parts of our code are not covered by any of our unit-tests. If I knew which parts of my system were untested then I could set about developing new tests which would eventually approach towards my goal of complete test-coverage. </p> <p>So how can I go about running this kind of analysis. What tools are available to me?</p> <p>I use Python 2.4 on Windows 32bit XP</p> <p>UPDATE0:</p> <p>Just to clarify: We have a very comprehensive unit-test suite (plus a seperate and very comprehensive regtest suite which is outside the scope of this exercise). We also have a very stable continuous integration platform (built with Hudson) which is designed to split-up and run standard python unit-tests across our test facility: Approx 20 PCs built to the company spec.</p> <p>The object of this exercise is to plug any gaps in our python unittest suite (only) suite so that every component has some degree of unittest coverage. Other developers will be taking responsibility for non Python components of the project (which are also outside of scope).</p> <p>"<strong>Component</strong>" is intentionally vague: Sometime it will be a class, other time an entire module or assembly of modules. It might even refer to a single financial concept (e.g. a single type of financial option or a financial model used by many types of option). This cake can be cut in many ways. </p> <p>"<strong>Meaningful</strong>" tests (to me) are ones which validate that the function does what the developer originally intended. We do not want to simply reproduce the regtests in pure python. Often the developer's intent is not immediatly obvious, hence the need to research and clarify anything which looks vague and then enshrine this knowledge in a unit-test which makes the original intent quite explicit.</p>
5
2009-06-17T10:20:17Z
1,006,261
<p>First step would be writing meaningfull tests. If you'll be writing tests only meant to reach full coverage, you'll be counter-productive; it will probably mean you'll focus on unit's implementation details instead of it's expectations.</p> <p>BTW, I'd use nose as unittest framework (<a href="http://somethingaboutorange.com/mrl/projects/nose/0.11.1/" rel="nofollow">http://somethingaboutorange.com/mrl/projects/nose/0.11.1/</a>); it's plugin system is very good and leaves coverage option to you (--with-coverage for Ned's coverage, --with-figleaf for Titus one; support for coverage3 should be coming), and you can write plugisn for your own build system, too.</p>
4
2009-06-17T10:35:01Z
[ "python", "testing" ]
How to do a meaningful code-coverage analysis of my unit-tests?
1,006,189
<p>I manage the testing for a very large financial pricing system. Recently our HQ have insisted that we verify that every single part of our project has a meaningful test in place. At the very least they want a system which guarantees that when we change something we can spot unintentional changes to other sub-systems. Preferably they want something which validates the correctness of every component in our system.</p> <p>That's obviously going to be quite a lot of work! It could take years, but for this kind of project it's worth it. </p> <p>I need to find out which parts of our code are not covered by any of our unit-tests. If I knew which parts of my system were untested then I could set about developing new tests which would eventually approach towards my goal of complete test-coverage. </p> <p>So how can I go about running this kind of analysis. What tools are available to me?</p> <p>I use Python 2.4 on Windows 32bit XP</p> <p>UPDATE0:</p> <p>Just to clarify: We have a very comprehensive unit-test suite (plus a seperate and very comprehensive regtest suite which is outside the scope of this exercise). We also have a very stable continuous integration platform (built with Hudson) which is designed to split-up and run standard python unit-tests across our test facility: Approx 20 PCs built to the company spec.</p> <p>The object of this exercise is to plug any gaps in our python unittest suite (only) suite so that every component has some degree of unittest coverage. Other developers will be taking responsibility for non Python components of the project (which are also outside of scope).</p> <p>"<strong>Component</strong>" is intentionally vague: Sometime it will be a class, other time an entire module or assembly of modules. It might even refer to a single financial concept (e.g. a single type of financial option or a financial model used by many types of option). This cake can be cut in many ways. </p> <p>"<strong>Meaningful</strong>" tests (to me) are ones which validate that the function does what the developer originally intended. We do not want to simply reproduce the regtests in pure python. Often the developer's intent is not immediatly obvious, hence the need to research and clarify anything which looks vague and then enshrine this knowledge in a unit-test which makes the original intent quite explicit.</p>
5
2009-06-17T10:20:17Z
1,006,454
<p><strong>"every single part of our project has a meaningful test in place"</strong></p> <p>"Part" is undefined. "Meaningful" is undefined. That's okay, however, since it gets better further on.</p> <p><strong>"validates the correctness of every component in our system"</strong></p> <p>"Component" is undefined. But correctness is defined, and we can assign a number of alternatives to component. You only mention Python, so I'll assume the entire project is pure Python.</p> <ul> <li><p>Validates the correctness of every module.</p></li> <li><p>Validates the correctness of every class of every module.</p></li> <li><p>Validates the correctness of every method of every class of every module.</p></li> </ul> <p>You haven't asked about line of code coverage or logic path coverage, which is a good thing. That way lies madness.</p> <p><strong>"guarantees that when we change something we can spot unintentional changes to other sub-systems"</strong></p> <p>This is regression testing. That's a logical consequence of any unit testing discipline.</p> <p>Here's what you can do.</p> <ol> <li><p>Enumerate every module. Create a unittest for that module that is just a unittest.main(). This should be quick -- a few days at most.</p></li> <li><p>Write a nice top-level unittest script that uses a testLoader to all unit tests in your tests directory and runs them through the text runner. At this point, you'll have a lot of files -- one per module -- but no actual test cases. Getting the testloader and the top-level script to work will take a few days. It's important to have this overall harness working.</p></li> <li><p>Prioritize your modules. A good rule is "most heavily reused". Another rule is "highest risk from failure". Another rule is "most bugs reported". This takes a few hours.</p></li> <li><p>Start at the top of the list. Write a TestCase per class with no real methods or anything. Just a framework. This takes a few days at most. Be sure the docstring for each TestCase positively identifies the Module and Class under test and the status of the test code. You can use these docstrings to determine test coverage.</p></li> </ol> <p>At this point you'll have two parallel tracks. You have to actually design and implement the tests. Depending on the class under test, you may have to build test databases, mock objects, all kinds of supporting material.</p> <ul> <li><p>Testing Rework. Starting with your highest priority untested module, start filling in the TestCases for each class in each module.</p></li> <li><p>New Development. For <strong>every</strong> code change, a unittest.TestCase must be created for the class being changed.</p></li> </ul> <p>The test code follows the same rules as any other code. Everything is checked in at the end of the day. It has to run -- even if the tests don't all pass.</p> <p>Give the test script to the product manager (not the QA manager, the actual product manager who is responsible for shipping product to customers) and make sure they run the script every day and find out why it didn't run or why tests are failing.</p> <p>The actual running of the master test script is not a QA job -- it's everyone's job. Every manager at every level of the organization has to be part of the daily build script output. <strong>All</strong> of their jobs have to depend on "all tests passed last night". Otherwise, the product manager will simply pull resources away from testing and you'll have nothing.</p>
3
2009-06-17T11:25:47Z
[ "python", "testing" ]
How to do a meaningful code-coverage analysis of my unit-tests?
1,006,189
<p>I manage the testing for a very large financial pricing system. Recently our HQ have insisted that we verify that every single part of our project has a meaningful test in place. At the very least they want a system which guarantees that when we change something we can spot unintentional changes to other sub-systems. Preferably they want something which validates the correctness of every component in our system.</p> <p>That's obviously going to be quite a lot of work! It could take years, but for this kind of project it's worth it. </p> <p>I need to find out which parts of our code are not covered by any of our unit-tests. If I knew which parts of my system were untested then I could set about developing new tests which would eventually approach towards my goal of complete test-coverage. </p> <p>So how can I go about running this kind of analysis. What tools are available to me?</p> <p>I use Python 2.4 on Windows 32bit XP</p> <p>UPDATE0:</p> <p>Just to clarify: We have a very comprehensive unit-test suite (plus a seperate and very comprehensive regtest suite which is outside the scope of this exercise). We also have a very stable continuous integration platform (built with Hudson) which is designed to split-up and run standard python unit-tests across our test facility: Approx 20 PCs built to the company spec.</p> <p>The object of this exercise is to plug any gaps in our python unittest suite (only) suite so that every component has some degree of unittest coverage. Other developers will be taking responsibility for non Python components of the project (which are also outside of scope).</p> <p>"<strong>Component</strong>" is intentionally vague: Sometime it will be a class, other time an entire module or assembly of modules. It might even refer to a single financial concept (e.g. a single type of financial option or a financial model used by many types of option). This cake can be cut in many ways. </p> <p>"<strong>Meaningful</strong>" tests (to me) are ones which validate that the function does what the developer originally intended. We do not want to simply reproduce the regtests in pure python. Often the developer's intent is not immediatly obvious, hence the need to research and clarify anything which looks vague and then enshrine this knowledge in a unit-test which makes the original intent quite explicit.</p>
5
2009-06-17T10:20:17Z
1,008,603
<p>FWIW, this is what we do. Since I don't know about your Unit-Test and Regression-Test setup, you have to decide yourself whether this is helpful.</p> <ul> <li>Every Python package has <a href="http://docs.python.org/library/unittest.html" rel="nofollow">UnitTests</a>.</li> <li>We automatically detect unit tests using <a href="http://somethingaboutorange.com/mrl/projects/nose/0.11.1/testing.html" rel="nofollow">nose</a>. Nose automagically detects standard Python unit tests (basically everything that <a href="http://somethingaboutorange.com/mrl/projects/nose/0.11.1/finding%5Ftests.html" rel="nofollow">looks like a test</a>). Thereby we don't miss unit-tests. Nose also has a plug-in concept so that you can produce, e.g. nice output.</li> <li>We strive for 100% coverage for unit-testing. To this end, we use <a href="http://nedbatchelder.com/code/coverage/" rel="nofollow">Coverage</a> to check, because <a href="http://somethingaboutorange.com/mrl/projects/nose/0.11.1/plugins/cover.html" rel="nofollow">a nose-plugin provides integration</a>.</li> <li>We have set up Eclipse (our IDE) to <a href="http://www.machine-envy.com/blog/2006/07/29/automated-python-testing-with-nose-and-eclipse/" rel="nofollow">automatically run nose</a> whenever a file changes so that the unit-tests always get executed, which shows code-coverage as a by-product.</li> </ul>
3
2009-06-17T17:51:28Z
[ "python", "testing" ]
How to find out the number of CPUs using python
1,006,289
<p>I want to know the number of CPUs on the local machine using Python. The result should be <code>user/real</code> as output by <code>time(1)</code> when called with an optimally scaling userspace-only program.</p>
230
2009-06-17T10:41:44Z
1,006,301
<p>If you're interested into the number of processors <em>available</em> to your current process, you have to check <a href="http://man7.org/linux/man-pages/man7/cpuset.7.html">cpuset</a> first. Otherwise (or if cpuset is not in use), <a href="http://docs.python.org/library/multiprocessing.html#multiprocessing.cpu_count"><code>multiprocessing.cpu_count()</code></a> is the way to go in Python 2.6. The following method falls back to a couple of alternative methods in older versions of Python:</p> <pre><code>import os import re import subprocess def available_cpu_count(): """ Number of available virtual or physical CPUs on this system, i.e. user/real as output by time(1) when called with an optimally scaling userspace-only program""" # cpuset # cpuset may restrict the number of *available* processors try: m = re.search(r'(?m)^Cpus_allowed:\s*(.*)$', open('/proc/self/status').read()) if m: res = bin(int(m.group(1).replace(',', ''), 16)).count('1') if res &gt; 0: return res except IOError: pass # Python 2.6+ try: import multiprocessing return multiprocessing.cpu_count() except (ImportError, NotImplementedError): pass # http://code.google.com/p/psutil/ try: import psutil return psutil.cpu_count() # psutil.NUM_CPUS on old versions except (ImportError, AttributeError): pass # POSIX try: res = int(os.sysconf('SC_NPROCESSORS_ONLN')) if res &gt; 0: return res except (AttributeError, ValueError): pass # Windows try: res = int(os.environ['NUMBER_OF_PROCESSORS']) if res &gt; 0: return res except (KeyError, ValueError): pass # jython try: from java.lang import Runtime runtime = Runtime.getRuntime() res = runtime.availableProcessors() if res &gt; 0: return res except ImportError: pass # BSD try: sysctl = subprocess.Popen(['sysctl', '-n', 'hw.ncpu'], stdout=subprocess.PIPE) scStdout = sysctl.communicate()[0] res = int(scStdout) if res &gt; 0: return res except (OSError, ValueError): pass # Linux try: res = open('/proc/cpuinfo').read().count('processor\t:') if res &gt; 0: return res except IOError: pass # Solaris try: pseudoDevices = os.listdir('/devices/pseudo/') res = 0 for pd in pseudoDevices: if re.match(r'^cpuid@[0-9]+$', pd): res += 1 if res &gt; 0: return res except OSError: pass # Other UNIXes (heuristic) try: try: dmesg = open('/var/run/dmesg.boot').read() except IOError: dmesgProcess = subprocess.Popen(['dmesg'], stdout=subprocess.PIPE) dmesg = dmesgProcess.communicate()[0] res = 0 while '\ncpu' + str(res) + ':' in dmesg: res += 1 if res &gt; 0: return res except OSError: pass raise Exception('Can not determine number of CPUs on this system') </code></pre>
118
2009-06-17T10:43:28Z
[ "python", "system-information" ]
How to find out the number of CPUs using python
1,006,289
<p>I want to know the number of CPUs on the local machine using Python. The result should be <code>user/real</code> as output by <code>time(1)</code> when called with an optimally scaling userspace-only program.</p>
230
2009-06-17T10:41:44Z
1,006,337
<p>If you have python with a version >= 2.6 you can simply use</p> <pre><code>import multiprocessing multiprocessing.cpu_count() </code></pre> <p><a href="http://docs.python.org/library/multiprocessing.html#multiprocessing.cpu_count">http://docs.python.org/library/multiprocessing.html#multiprocessing.cpu_count</a></p>
401
2009-06-17T10:53:53Z
[ "python", "system-information" ]
How to find out the number of CPUs using python
1,006,289
<p>I want to know the number of CPUs on the local machine using Python. The result should be <code>user/real</code> as output by <code>time(1)</code> when called with an optimally scaling userspace-only program.</p>
230
2009-06-17T10:41:44Z
3,845,635
<p>Can't figure out how to add to the code or reply to the message but here's support for jython that you can tack in before you give up:</p> <pre><code># jython try: from java.lang import Runtime runtime = Runtime.getRuntime() res = runtime.availableProcessors() if res &gt; 0: return res except ImportError: pass </code></pre>
7
2010-10-02T12:16:02Z
[ "python", "system-information" ]
How to find out the number of CPUs using python
1,006,289
<p>I want to know the number of CPUs on the local machine using Python. The result should be <code>user/real</code> as output by <code>time(1)</code> when called with an optimally scaling userspace-only program.</p>
230
2009-06-17T10:41:44Z
14,840,102
<p>An other option is to use the <a href="http://code.google.com/p/psutil/"><code>psutil</code></a> library, which always turn out useful in these situations:</p> <pre><code>&gt;&gt;&gt; import psutil &gt;&gt;&gt; psutil.cpu_count() 2 </code></pre> <p>This should work on any platform supported by <code>psutil</code>(unix and windows).</p> <p>Note that in some occasions <code>multiprocessing.cpu_count</code> may raise a <code>NotImplementedError</code> while <code>psutil</code> will be able to obtain the number of CPUs. This is simply because <code>psutil</code> first tries to use the same techniques used by <code>multiprocessing</code> and, if those fail, it also uses other techniques.</p>
39
2013-02-12T19:19:05Z
[ "python", "system-information" ]
How to find out the number of CPUs using python
1,006,289
<p>I want to know the number of CPUs on the local machine using Python. The result should be <code>user/real</code> as output by <code>time(1)</code> when called with an optimally scaling userspace-only program.</p>
230
2009-06-17T10:41:44Z
24,805,009
<p><code>multiprocessing.cpu_count()</code> will return the number of logical CPUs, so if you have a quad-core CPU with hyperthreading, it will return <code>8</code>. If you want the number of physical CPUs, use the python bindings to hwloc:</p> <pre><code>#!/usr/bin/env python import hwloc topology = hwloc.Topology() topology.load() print topology.get_nbobjs_by_type(hwloc.OBJ_CORE) </code></pre> <p>hwloc is designed to be portable across OSes and architectures.</p>
11
2014-07-17T13:32:10Z
[ "python", "system-information" ]
How to find out the number of CPUs using python
1,006,289
<p>I want to know the number of CPUs on the local machine using Python. The result should be <code>user/real</code> as output by <code>time(1)</code> when called with an optimally scaling userspace-only program.</p>
230
2009-06-17T10:41:44Z
25,569,974
<p>Another option if you don't have Python 2.6:</p> <pre><code>import commands n = commands.getoutput("grep -c processor /proc/cpuinfo") </code></pre>
2
2014-08-29T14:05:39Z
[ "python", "system-information" ]
How to find out the number of CPUs using python
1,006,289
<p>I want to know the number of CPUs on the local machine using Python. The result should be <code>user/real</code> as output by <code>time(1)</code> when called with an optimally scaling userspace-only program.</p>
230
2009-06-17T10:41:44Z
25,636,145
<p>In Python 3.4+: <a href="https://docs.python.org/3/library/os.html#os.cpu_count">os.cpu_count()</a>.</p> <p><code>multiprocessing.cpu_count()</code> is implemented in terms of this function but raises <code>NotImplementedError</code> if <code>os.cpu_count()</code> returns <code>None</code> ("can't determine number of CPUs").</p>
8
2014-09-03T04:16:56Z
[ "python", "system-information" ]
How to find out the number of CPUs using python
1,006,289
<p>I want to know the number of CPUs on the local machine using Python. The result should be <code>user/real</code> as output by <code>time(1)</code> when called with an optimally scaling userspace-only program.</p>
230
2009-06-17T10:41:44Z
29,770,622
<p>You can also use "joblib" for this purpose. </p> <pre><code>import joblib print joblib.cpu_count() </code></pre> <p>This method will give you the number of cpus in the system. joblib needs to be installed though. More information on joblib can be found here <a href="https://pythonhosted.org/joblib/parallel.html" rel="nofollow">https://pythonhosted.org/joblib/parallel.html</a></p> <p>Alternatively you can use numexpr package of python. It has lot of simple functions helpful for getting information about the system cpu.</p> <pre><code>import numexpr as ne print ne.detect_number_of_cores() </code></pre>
2
2015-04-21T11:14:43Z
[ "python", "system-information" ]
How to find out the number of CPUs using python
1,006,289
<p>I want to know the number of CPUs on the local machine using Python. The result should be <code>user/real</code> as output by <code>time(1)</code> when called with an optimally scaling userspace-only program.</p>
230
2009-06-17T10:41:44Z
36,540,625
<p>platform independent:</p> <blockquote> <p>psutil.cpu_count(logical=False)</p> </blockquote> <p><a href="https://github.com/giampaolo/psutil/blob/master/INSTALL.rst" rel="nofollow">https://github.com/giampaolo/psutil/blob/master/INSTALL.rst</a></p>
3
2016-04-11T05:42:55Z
[ "python", "system-information" ]
Capitalizing non-ASCII words in Python
1,006,450
<p>How to capitalize words containing non-ASCII characters in Python? Is there a way to tune <code>string</code>'s <code>capitalize()</code> method to do that?</p>
5
2009-06-17T11:24:42Z
1,006,463
<p>Use Unicode strings:</p> <pre><code># coding: cp1252 print u"é".capitalize() # Prints É </code></pre> <p>If all you have is an 8-bit string, decode it into Unicode first:</p> <pre><code># coding: cp1252 print "é".decode('cp1252').capitalize() # Prints É </code></pre> <p>If you then need it as an 8-bit string again, encode it:</p> <pre><code># coding: cp1252 print "é".decode('cp1252').capitalize().encode('cp1252') # Prints É (assuming your terminal is happy to receive cp1252) </code></pre>
10
2009-06-17T11:30:16Z
[ "python", "unicode", "ascii", "capitalization" ]
Capitalizing non-ASCII words in Python
1,006,450
<p>How to capitalize words containing non-ASCII characters in Python? Is there a way to tune <code>string</code>'s <code>capitalize()</code> method to do that?</p>
5
2009-06-17T11:24:42Z
1,006,467
<p><code>capitalize()</code> should Just Work&trade; for Unicode strings.</p>
1
2009-06-17T11:32:52Z
[ "python", "unicode", "ascii", "capitalization" ]
Simple python plugin system
1,006,556
<p><br /> I'm writing a parser for an internal xml-based metadata format in python. I need to provide different classes for handling different tags. There will be a need for a rather big collection of handlers, so I've envisioned it as a simple plugin system. What I want to do is simply load every class in a package, and register it with my parser. My current attempt looks like this:<br /> (Handlers is the package containing the handlers, each handler has a static member tags, which is a tuple of strings)</p> <pre><code>class MetadataParser: def __init__(self): #... self.handlers={} self.currentHandler=None for handler in dir(Handlers): # Make a list of all symbols exported by Handlers if handler[-7:] == 'Handler': # and for each of those ending in "Handler" handlerMod=my_import('MetadataLoader.Handlers.' + handler) self.registerHandler(handlerMod, handlerMod.tags) # register them for their tags # ... def registerHandler(self, handler, tags): """ Register a handler class for each xml tag in a given list of tags """ if not isSequenceType(tags): tags=(tags,) # Sanity check, make sure the tag-list is indeed a list for tag in tags: self.handlers[tag]=handler </code></pre> <p>However, this does not work. I get the error <code>AttributeError: 'module' object has no attribute 'tags'</code> What am I doing wrong? </p>
0
2009-06-17T11:57:14Z
1,006,595
<p>Probably one of your <code>handlerMod</code> modules does not contain any <code>tags</code> variable.</p>
0
2009-06-17T12:06:15Z
[ "python" ]
Simple python plugin system
1,006,556
<p><br /> I'm writing a parser for an internal xml-based metadata format in python. I need to provide different classes for handling different tags. There will be a need for a rather big collection of handlers, so I've envisioned it as a simple plugin system. What I want to do is simply load every class in a package, and register it with my parser. My current attempt looks like this:<br /> (Handlers is the package containing the handlers, each handler has a static member tags, which is a tuple of strings)</p> <pre><code>class MetadataParser: def __init__(self): #... self.handlers={} self.currentHandler=None for handler in dir(Handlers): # Make a list of all symbols exported by Handlers if handler[-7:] == 'Handler': # and for each of those ending in "Handler" handlerMod=my_import('MetadataLoader.Handlers.' + handler) self.registerHandler(handlerMod, handlerMod.tags) # register them for their tags # ... def registerHandler(self, handler, tags): """ Register a handler class for each xml tag in a given list of tags """ if not isSequenceType(tags): tags=(tags,) # Sanity check, make sure the tag-list is indeed a list for tag in tags: self.handlers[tag]=handler </code></pre> <p>However, this does not work. I get the error <code>AttributeError: 'module' object has no attribute 'tags'</code> What am I doing wrong? </p>
0
2009-06-17T11:57:14Z
1,007,289
<p>I suggest you read the example and explanation on <a href="http://www.diveintopython.net/html_processing/all_together.html" rel="nofollow">this page</a> where how to write a plug-in architecture is explained.</p>
0
2009-06-17T14:11:20Z
[ "python" ]
Simple python plugin system
1,006,556
<p><br /> I'm writing a parser for an internal xml-based metadata format in python. I need to provide different classes for handling different tags. There will be a need for a rather big collection of handlers, so I've envisioned it as a simple plugin system. What I want to do is simply load every class in a package, and register it with my parser. My current attempt looks like this:<br /> (Handlers is the package containing the handlers, each handler has a static member tags, which is a tuple of strings)</p> <pre><code>class MetadataParser: def __init__(self): #... self.handlers={} self.currentHandler=None for handler in dir(Handlers): # Make a list of all symbols exported by Handlers if handler[-7:] == 'Handler': # and for each of those ending in "Handler" handlerMod=my_import('MetadataLoader.Handlers.' + handler) self.registerHandler(handlerMod, handlerMod.tags) # register them for their tags # ... def registerHandler(self, handler, tags): """ Register a handler class for each xml tag in a given list of tags """ if not isSequenceType(tags): tags=(tags,) # Sanity check, make sure the tag-list is indeed a list for tag in tags: self.handlers[tag]=handler </code></pre> <p>However, this does not work. I get the error <code>AttributeError: 'module' object has no attribute 'tags'</code> What am I doing wrong? </p>
0
2009-06-17T11:57:14Z
1,087,194
<p>First off, apologies for poorly formated/incorrect code.<br /> Also thanks for looking at it. However, the culprit was, as so often, between the chair and the keyboard. I confused myself by having classes and modules of the same name. The result of my_import (which I now realize I didn't even mention where it comes from... It's from SO: <a href="http://stackoverflow.com/questions/211100/pythons-import-doesnt-work-as-expected/211101#211101">link</a>) is a module named for instance areaHandler. I want the class, also named areaHandler. So I merely had to pick out the class by eval('Handlers.' + handler + '.' + handler).<br /> Again, thanks for your time, and sorry about the bandwidth</p>
0
2009-07-06T14:11:35Z
[ "python" ]
Simple python plugin system
1,006,556
<p><br /> I'm writing a parser for an internal xml-based metadata format in python. I need to provide different classes for handling different tags. There will be a need for a rather big collection of handlers, so I've envisioned it as a simple plugin system. What I want to do is simply load every class in a package, and register it with my parser. My current attempt looks like this:<br /> (Handlers is the package containing the handlers, each handler has a static member tags, which is a tuple of strings)</p> <pre><code>class MetadataParser: def __init__(self): #... self.handlers={} self.currentHandler=None for handler in dir(Handlers): # Make a list of all symbols exported by Handlers if handler[-7:] == 'Handler': # and for each of those ending in "Handler" handlerMod=my_import('MetadataLoader.Handlers.' + handler) self.registerHandler(handlerMod, handlerMod.tags) # register them for their tags # ... def registerHandler(self, handler, tags): """ Register a handler class for each xml tag in a given list of tags """ if not isSequenceType(tags): tags=(tags,) # Sanity check, make sure the tag-list is indeed a list for tag in tags: self.handlers[tag]=handler </code></pre> <p>However, this does not work. I get the error <code>AttributeError: 'module' object has no attribute 'tags'</code> What am I doing wrong? </p>
0
2009-06-17T11:57:14Z
32,276,389
<p>Simple and completly extensible implementation via <a href="https://github.com/katyukha/extend-me" rel="nofollow">extend_me</a> library.</p> <p>Code could look like</p> <pre><code>from extend_me import ExtensibleByHash # create meta class tagMeta = ExtensibleByHash._('Tag', hashattr='name') # create base class for all tags class BaseTag(object): __metaclass__ = tagMeta def __init__(self, tag): self.tag = tag def process(self, *args, **kwargs): raise NotImeplemntedError() # create classes for all required tags class BodyTag(BaseTag): class Meta: name = 'body' def process(self, *args, **kwargs): pass # do processing class HeadTag(BaseTag): class Meta: name = 'head' def process(self, *args, **kwargs): pass # do some processing here # implement other tags in this way # ... # process tags def process_tags(tags): res_tags = [] for tag in tags: cls = tagMeta.get_class(tag) # get correct class for each tag res_tags.append(cls(tag)) # and add its instance to result return res_tags </code></pre> <p>For more information look at <a href="http://pythonhosted.org/extend_me/" rel="nofollow">documentation</a> or <a href="https://github.com/katyukha/extend-me/blob/master/extend_me.py" rel="nofollow">code</a>. This lib is used in <a href="https://github.com/katyukha/openerp-proxy" rel="nofollow">OpenERP / Odoo RPC lib</a></p>
0
2015-08-28T17:11:33Z
[ "python" ]
What would the jvm have to sacrifice in order to implement tail call optimisation?
1,006,596
<p>People say that the clojure implementation is excellent apart from the limitation of having no tail call optimisation - a limitation of the jvm not the clojure implementation. </p> <p><a href="http://lambda-the-ultimate.org/node/2547" rel="nofollow">http://lambda-the-ultimate.org/node/2547</a></p> <p>It has been said that to implement TCO into Python would sacrifice </p> <ul> <li>stack-trace dumps, and </li> <li>debugging regularity.</li> </ul> <p><a href="http://stackoverflow.com/questions/890461/explain-to-me-what-the-big-deal-with-tail-call-optimization-is-and-why-python-nee">http://stackoverflow.com/questions/890461/explain-to-me-what-the-big-deal-with-tail-call-optimization-is-and-why-python-nee</a></p> <p>Would the same sacrifices have to be made for a jvm implementation of TCO? Would anything else have to be sacrificed?</p>
3
2009-06-17T12:06:19Z
1,006,726
<p>Whilst different (in that the il instructions existed already) it's worth noting the additional effort the .Net <a href="http://blogs.msdn.com/clrcodegeneration/archive/2009/05/11/tail-call-improvements-in-net-framework-4.aspx" rel="nofollow">64 bit JIT team</a> had to go through to respect all tail calls.</p> <p>I call out in particular the comment:</p> <blockquote> <p>The down side of course is that if you have to debug or profile optimized code, be prepared to deal with call stacks that look like they’re missing a few frames.</p> </blockquote> <p>I would think it highly unlikely the JVM could avoid this either.</p> <p>Given that, in circumstances where a tail call optimization was requested, the JIT should assume that it is <em>required</em> to avoid a stack overflow this is not something that can just be switched off in Debug builds. They aren't much use for debugging if they crash before you get to the interesting part. The 'optimization' is in fact is a permanent feature and an issue for stack traces affected by it.</p> <p>It is worth pointing out that any optimization which avoids creating a real stack frame when doing an operation which the programmer conceptually describes/understands as being a stack operation (calling a function for example) will inherently cause a disconnect between what is presented to the user when debugging/providing the stack trace and reality.<br /> This is unavoidable as the code that describes the operation becomes further and further separated from the mechanics of the state machine performing the operation.</p>
6
2009-06-17T12:33:34Z
[ "python", "clojure", "jvm", "stack-trace", "tail-call-optimization" ]
What would the jvm have to sacrifice in order to implement tail call optimisation?
1,006,596
<p>People say that the clojure implementation is excellent apart from the limitation of having no tail call optimisation - a limitation of the jvm not the clojure implementation. </p> <p><a href="http://lambda-the-ultimate.org/node/2547" rel="nofollow">http://lambda-the-ultimate.org/node/2547</a></p> <p>It has been said that to implement TCO into Python would sacrifice </p> <ul> <li>stack-trace dumps, and </li> <li>debugging regularity.</li> </ul> <p><a href="http://stackoverflow.com/questions/890461/explain-to-me-what-the-big-deal-with-tail-call-optimization-is-and-why-python-nee">http://stackoverflow.com/questions/890461/explain-to-me-what-the-big-deal-with-tail-call-optimization-is-and-why-python-nee</a></p> <p>Would the same sacrifices have to be made for a jvm implementation of TCO? Would anything else have to be sacrificed?</p>
3
2009-06-17T12:06:19Z
1,013,576
<p>Work is <a href="http://challenge.openjdk.org/projects/mlvm/subprojects.html" rel="nofollow">underway now</a> to add tail calls to the JVM. There's a <a href="http://wikis.sun.com/display/mlvm/TailCalls" rel="nofollow">wiki page</a> talking about some details.</p>
2
2009-06-18T16:03:42Z
[ "python", "clojure", "jvm", "stack-trace", "tail-call-optimization" ]
What would the jvm have to sacrifice in order to implement tail call optimisation?
1,006,596
<p>People say that the clojure implementation is excellent apart from the limitation of having no tail call optimisation - a limitation of the jvm not the clojure implementation. </p> <p><a href="http://lambda-the-ultimate.org/node/2547" rel="nofollow">http://lambda-the-ultimate.org/node/2547</a></p> <p>It has been said that to implement TCO into Python would sacrifice </p> <ul> <li>stack-trace dumps, and </li> <li>debugging regularity.</li> </ul> <p><a href="http://stackoverflow.com/questions/890461/explain-to-me-what-the-big-deal-with-tail-call-optimization-is-and-why-python-nee">http://stackoverflow.com/questions/890461/explain-to-me-what-the-big-deal-with-tail-call-optimization-is-and-why-python-nee</a></p> <p>Would the same sacrifices have to be made for a jvm implementation of TCO? Would anything else have to be sacrificed?</p>
3
2009-06-17T12:06:19Z
2,949,094
<p>Yes it is generally the case that implementing TCO will prevent you from getting full stack traces. This is inevitable because the whole point of TCO is to avoid creating additional stack frames.</p> <p>It's also worth interesting to note that Clojure has an non-stack-consuming "recur" feature to get around this constraint on current JVM versions.</p> <p>Example:</p> <pre><code>(defn triangle [n accumulator] (if (&lt;= n 0) accumulator (recur (dec n) (+ n accumulator)))) (triangle 1000000 0) =&gt; 500000500000 (note stack does not explode here!) </code></pre>
0
2010-06-01T10:53:54Z
[ "python", "clojure", "jvm", "stack-trace", "tail-call-optimization" ]
wxProgressDialog like behaviour for a wxDialog
1,006,598
<p>I want to create modal dialog but which shouldn't behave in a modal way i.e. control flow should continue</p> <p>if i do</p> <pre><code> dlg = wx.Dialog(parent) dlg.ShowModal() print "xxx" dlg.Destroy() </code></pre> <p>"xxx" will not get printed, but in case of progress dialog</p> <pre><code>dlg = wx.ProgressDialog.__init__(self,title, title, parent=parent, style=wx.PD_APP_MODAL) print "xxx" dlg.Destroy() </code></pre> <p>"xxx" will get printed</p> <p>so basically <strong>i want to achieve wx.PD__APP__MODAL for a normal dialog?</strong></p>
0
2009-06-17T12:06:23Z
1,007,845
<p>Just use <code>Show</code> instead of <code>ShowModal</code>.</p> <p>If your function (the <code>print "xxx"</code> part) runs for a long time you will either have to manually call <code>wx.SafeYield</code> every so often or move your work to a separate thread and send custom events to your dialog from it.</p> <p>One more tip. As I understand, you want to execute some code after the modal dialog is shown, here is a little trick for a special bind to <code>EVT_INIT_DIALOG</code> that accomplishes just that.</p> <pre><code>import wx class TestFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None) btn = wx.Button(self, label="Show Dialog") btn.Bind(wx.EVT_BUTTON, self.ShowDialog) def ShowDialog(self, event): dlg = wx.Dialog(self) dlg.Bind(wx.EVT_INIT_DIALOG, lambda e: wx.CallAfter(self.OnModal, e)) dlg.ShowModal() dlg.Destroy() def OnModal(self, event): wx.MessageBox("Executed after ShowModal") app = wx.PySimpleApp() app.TopWindow = TestFrame() app.TopWindow.Show() app.MainLoop() </code></pre>
1
2009-06-17T15:37:32Z
[ "python", "wxpython", "modal-dialog" ]
wxProgressDialog like behaviour for a wxDialog
1,006,598
<p>I want to create modal dialog but which shouldn't behave in a modal way i.e. control flow should continue</p> <p>if i do</p> <pre><code> dlg = wx.Dialog(parent) dlg.ShowModal() print "xxx" dlg.Destroy() </code></pre> <p>"xxx" will not get printed, but in case of progress dialog</p> <pre><code>dlg = wx.ProgressDialog.__init__(self,title, title, parent=parent, style=wx.PD_APP_MODAL) print "xxx" dlg.Destroy() </code></pre> <p>"xxx" will get printed</p> <p>so basically <strong>i want to achieve wx.PD__APP__MODAL for a normal dialog?</strong></p>
0
2009-06-17T12:06:23Z
1,017,277
<p>It was very trivial, just using wx.PD_APP_MODAL style in wx.Dialog allows it to be modal without stopping the program flow, only user input to app is blocked, i thought PD_APP_MODAL is only for progress dialog</p>
0
2009-06-19T10:17:09Z
[ "python", "wxpython", "modal-dialog" ]
OLE Compound Documents in Python
1,006,682
<p><br /> how would you parse a Microsoft <a href="http://www.forensicswiki.org/wiki/OLE%5FCompound%5FFile" rel="nofollow">OLE compound document</a> using Python?</p> <p><strong>Edit:</strong> Sorry, I forgot to say that I need write support too.. In short, I have an OLE compound file that I have to read, modify a bit and write back to disk (it's a file made with a CAD application)</p>
3
2009-06-17T12:27:12Z
1,006,732
<p>Just found <a href="http://www.decalage.info/python/olefileio" rel="nofollow">OleFileIO_PL</a>, but it doesn't have write support.. :/</p> <p><strong>Edit:</strong> Looks like there's a way (though Windows-only) that supports writing too.. The <a href="http://python.net/crew/mhammond/win32/" rel="nofollow">pywin32</a> extensions (<a href="http://docs.activestate.com/activepython/2.6/pywin32/pythoncom%5F%5FStgOpenStorage%5Fmeth.html" rel="nofollow">StgOpenStorage</a> function and related)</p>
3
2009-06-17T12:34:37Z
[ "python", "ole" ]
OLE Compound Documents in Python
1,006,682
<p><br /> how would you parse a Microsoft <a href="http://www.forensicswiki.org/wiki/OLE%5FCompound%5FFile" rel="nofollow">OLE compound document</a> using Python?</p> <p><strong>Edit:</strong> Sorry, I forgot to say that I need write support too.. In short, I have an OLE compound file that I have to read, modify a bit and write back to disk (it's a file made with a CAD application)</p>
3
2009-06-17T12:27:12Z
1,007,375
<p>An alternative: The xlrd package has a reader. The xlwt package (a fork of pyExcelerator) has a writer. They handle filesizes of 100s of MB cheerfully; the packages have been widely used for about 4 years. The compound document modules are targetted at getting "Workbook" streams into and out of Excel .xls files as efficiently as possible, but are reasonably general-purpose. Unlike OleFileIO_PL, they don't provide access to the internals of Property streams.</p> <pre><code>http://pypi.python.org/pypi/xlrd http://pypi.python.org/pypi/xlwt </code></pre> <p>If you decide to use them and need help, ask in this forum:</p> <p><code>http://groups.google.com/group/python-excel</code></p>
2
2009-06-17T14:26:23Z
[ "python", "ole" ]
OLE Compound Documents in Python
1,006,682
<p><br /> how would you parse a Microsoft <a href="http://www.forensicswiki.org/wiki/OLE%5FCompound%5FFile" rel="nofollow">OLE compound document</a> using Python?</p> <p><strong>Edit:</strong> Sorry, I forgot to say that I need write support too.. In short, I have an OLE compound file that I have to read, modify a bit and write back to disk (it's a file made with a CAD application)</p>
3
2009-06-17T12:27:12Z
12,296,246
<p>For completeness: on Linux there's also the <a href="http://projects.gnome.org/libgsf/" rel="nofollow">GNOME Structured File Library</a> (but the default package for Debian/Ubuntu has Python support disabled, since the Python bindings are <a href="http://git.gnome.org/browse/libgsf/tree/python/README-python" rel="nofollow">unsupported since 2006</a>) and the <a href="http://poi.apache.org/poifs/index.html" rel="nofollow">POIFS</a> Java library.</p>
0
2012-09-06T08:45:59Z
[ "python", "ole" ]
How to retrieve the selected text from the active window
1,007,185
<p>I am trying to create a simple open source utility for windows using <strong>Python</strong> that can perform user-defined actions on the selected text of the currently active window. The utility should be activated using a pre-defined keyboard shortcut.</p> <p>Usage is partially outlined in the following example:</p> <ol> <li>The user selects some text using the mouse or the keyboard (in any application window)</li> <li>The user presses a pre-defined keyboard shortcut</li> <li>The selected text is retrieved by our utility or copied to clipboard (both approaches should be fine)</li> <li>The keyboard shortcut-dependent action is performed on the selected text</li> </ol> <p>What puzzles me is <strong>step 3</strong>. <em>How the selected text is retrieved from the active window</em>. This should work with all applications.</p> <p>I use the <strong>pywin32</strong> module.</p> <p>Thanks in advance for your answers and tips.</p> <p><strong>Update #1</strong>:</p> <p>Turns out that there are two approaches to accomplish the task:</p> <ol> <li>Find the active window, then send a message/keystroke (Ctrl-C) to it in order to copy the selected text to the clipboard. Then the utility can work on the text by accessing it using the clipboard-related functions.</li> <li>Find the active Window, then retrieve the selected text directly (without copying it to clipboard). This seems more difficult than the 1st approach.</li> </ol> <p>As starting points:</p> <p>Get the active window ID as Anurag Uniyal has pointed out in his <a href="http://stackoverflow.com/questions/1007185/how-to-retrieve-the-selected-text-from-the-active-window/1007553#1007553">reply</a>.</p> <p>Or get the window object with the following code:</p> <pre><code>import win32ui wnd = win32ui.GetForegroundWindow() print wnd.GetWindowText() </code></pre>
11
2009-06-17T13:54:58Z
1,007,553
<p>It won't be trivial but here is the starting point</p> <pre><code>import win32gui hwnd = win32gui.GetForegroundWindow() print win32gui.GetWindowText(hwnd) </code></pre> <p>Maybe you will have to use <code>FindWindow</code>,<code>FindWindowEx</code> to get child windows with focus</p> <p>edit: also while experimenting use spy++ to see how it retrieves information about various windows, see hwnd, window class etc</p> <p>basically if you can find a example in C/C++/C# it won't be difficult to translate that into pywin32 equivalent, so in a way it is win32 api specific question </p>
1
2009-06-17T14:52:30Z
[ "python", "windows", "winapi", "pywin32" ]
How to retrieve the selected text from the active window
1,007,185
<p>I am trying to create a simple open source utility for windows using <strong>Python</strong> that can perform user-defined actions on the selected text of the currently active window. The utility should be activated using a pre-defined keyboard shortcut.</p> <p>Usage is partially outlined in the following example:</p> <ol> <li>The user selects some text using the mouse or the keyboard (in any application window)</li> <li>The user presses a pre-defined keyboard shortcut</li> <li>The selected text is retrieved by our utility or copied to clipboard (both approaches should be fine)</li> <li>The keyboard shortcut-dependent action is performed on the selected text</li> </ol> <p>What puzzles me is <strong>step 3</strong>. <em>How the selected text is retrieved from the active window</em>. This should work with all applications.</p> <p>I use the <strong>pywin32</strong> module.</p> <p>Thanks in advance for your answers and tips.</p> <p><strong>Update #1</strong>:</p> <p>Turns out that there are two approaches to accomplish the task:</p> <ol> <li>Find the active window, then send a message/keystroke (Ctrl-C) to it in order to copy the selected text to the clipboard. Then the utility can work on the text by accessing it using the clipboard-related functions.</li> <li>Find the active Window, then retrieve the selected text directly (without copying it to clipboard). This seems more difficult than the 1st approach.</li> </ol> <p>As starting points:</p> <p>Get the active window ID as Anurag Uniyal has pointed out in his <a href="http://stackoverflow.com/questions/1007185/how-to-retrieve-the-selected-text-from-the-active-window/1007553#1007553">reply</a>.</p> <p>Or get the window object with the following code:</p> <pre><code>import win32ui wnd = win32ui.GetForegroundWindow() print wnd.GetWindowText() </code></pre>
11
2009-06-17T13:54:58Z
1,009,487
<p>You're far better off using the Ctrl-C method. Fetching text directly will work for something like an edit control, but is useless for retrieving text that an application has painted directly on its own window. </p>
1
2009-06-17T20:58:12Z
[ "python", "windows", "winapi", "pywin32" ]
How to retrieve the selected text from the active window
1,007,185
<p>I am trying to create a simple open source utility for windows using <strong>Python</strong> that can perform user-defined actions on the selected text of the currently active window. The utility should be activated using a pre-defined keyboard shortcut.</p> <p>Usage is partially outlined in the following example:</p> <ol> <li>The user selects some text using the mouse or the keyboard (in any application window)</li> <li>The user presses a pre-defined keyboard shortcut</li> <li>The selected text is retrieved by our utility or copied to clipboard (both approaches should be fine)</li> <li>The keyboard shortcut-dependent action is performed on the selected text</li> </ol> <p>What puzzles me is <strong>step 3</strong>. <em>How the selected text is retrieved from the active window</em>. This should work with all applications.</p> <p>I use the <strong>pywin32</strong> module.</p> <p>Thanks in advance for your answers and tips.</p> <p><strong>Update #1</strong>:</p> <p>Turns out that there are two approaches to accomplish the task:</p> <ol> <li>Find the active window, then send a message/keystroke (Ctrl-C) to it in order to copy the selected text to the clipboard. Then the utility can work on the text by accessing it using the clipboard-related functions.</li> <li>Find the active Window, then retrieve the selected text directly (without copying it to clipboard). This seems more difficult than the 1st approach.</li> </ol> <p>As starting points:</p> <p>Get the active window ID as Anurag Uniyal has pointed out in his <a href="http://stackoverflow.com/questions/1007185/how-to-retrieve-the-selected-text-from-the-active-window/1007553#1007553">reply</a>.</p> <p>Or get the window object with the following code:</p> <pre><code>import win32ui wnd = win32ui.GetForegroundWindow() print wnd.GetWindowText() </code></pre>
11
2009-06-17T13:54:58Z
7,535,892
<p>the code below will work only on simple text boxes (just did it in VB6, and ported to python)</p> <p>edit: <strong>it was tested only on python 2.6</strong></p> <pre><code>from ctypes import * import win32gui import win32api import win32con user32 = windll.user32 kernel32 = windll.kernel32 class RECT(Structure): _fields_ = [ ("left", c_ulong), ("top", c_ulong), ("right", c_ulong), ("bottom", c_ulong) ] class GUITHREADINFO(Structure): _fields_ = [ ("cbSize", c_ulong), ("flags", c_ulong), ("hwndActive", c_ulong), ("hwndFocus", c_ulong), ("hwndCapture", c_ulong), ("hwndMenuOwner", c_ulong), ("hwndMoveSize", c_ulong), ("hwndCaret", c_ulong), ("rcCaret", RECT) ] def get_selected_text_from_front_window(): # As String ''' vb6 to python translation ''' gui = GUITHREADINFO(cbSize=sizeof(GUITHREADINFO)) txt='' ast_Clipboard_Obj=None Last_Clipboard_Temp = -1 user32.GetGUIThreadInfo(0, byref(gui)) txt = GetCaretWindowText(gui.hwndCaret, True) ''' if Txt = "" Then LastClipboardClip = "" Last_Clipboard_Obj = GetClipboard Last_Clipboard_Temp = LastClipboardFormat SendKeys "^(c)" GetClipboard Txt = LastClipboardClip if LastClipboardClip &lt;&gt; "" Then Txt = LastClipboardClip RestoreClipboard Last_Clipboard_Obj, Last_Clipboard_Temp print "clbrd: " + Txt End If ''' return txt def GetCaretWindowText(hWndCaret, Selected = False): # As String startpos =0 endpos =0 txt = "" if hWndCaret: buf_size = 1 + win32gui.SendMessage(hWndCaret, win32con.WM_GETTEXTLENGTH, 0, 0) if buf_size: buffer = win32gui.PyMakeBuffer(buf_size) win32gui.SendMessage(hWndCaret, win32con.WM_GETTEXT, buf_size, buffer) txt = buffer[:buf_size] if Selected and buf_size: selinfo = win32gui.SendMessage(hWndCaret, win32con.EM_GETSEL, 0, 0) endpos = win32api.HIWORD(selinfo) startpos = win32api.LOWORD(selinfo) return txt[startpos: endpos] return txt if __name__ == '__main__': print get_selected_text_from_front_window() </code></pre>
1
2011-09-23T23:40:01Z
[ "python", "windows", "winapi", "pywin32" ]
How do you make this code more pythonic?
1,007,215
<p>Could you guys please tell me how I can make the following code more pythonic? </p> <p>The code is correct. Full disclosure - it's problem 1b in Handout #4 of <a href="http://www.stanford.edu/class/cs229/materials.html" rel="nofollow">this</a> machine learning course. I'm supposed to use newton's algorithm on the two data sets for fitting a logistic hypothesis. But they use matlab &amp; I'm using scipy</p> <p>Eg one question i have is the matrixes kept rounding to integers until I initialized one value to 0.0. Is there a better way?</p> <p>Thanks</p> <pre><code>import os.path import math from numpy import matrix from scipy.linalg import inv #, det, eig x = matrix( '0.0;0;1' ) y = 11 grad = matrix( '0.0;0;0' ) hess = matrix('0.0,0,0;0,0,0;0,0,0') theta = matrix( '0.0;0;0' ) # run until convergence=6or7 for i in range(1, 6): #reset grad = matrix( '0.0;0;0' ) hess = matrix('0.0,0,0;0,0,0;0,0,0') xfile = open("q1x.dat", "r") yfile = open("q1y.dat", "r") #over whole set=99 items for i in range(1, 100): xline = xfile.readline() s= xline.split(" ") x[0] = float(s[1]) x[1] = float(s[2]) y = float(yfile.readline()) hypoth = 1/ (1+ math.exp(-(theta.transpose() * x))) for j in range(0,3): grad[j] = grad[j] + (y-hypoth)* x[j] for k in range(0,3): hess[j,k] = hess[j,k] - (hypoth *(1-hypoth)*x[j]*x[k]) theta = theta - inv(hess)*grad #update theta after construction xfile.close() yfile.close() print "done" print theta </code></pre>
3
2009-06-17T14:00:46Z
1,007,222
<p>You could make use of the <b><a href="http://www.python.org/dev/peps/pep-0343/" rel="nofollow">with</a></b> statement.</p>
0
2009-06-17T14:02:42Z
[ "python", "machine-learning", "scipy" ]
How do you make this code more pythonic?
1,007,215
<p>Could you guys please tell me how I can make the following code more pythonic? </p> <p>The code is correct. Full disclosure - it's problem 1b in Handout #4 of <a href="http://www.stanford.edu/class/cs229/materials.html" rel="nofollow">this</a> machine learning course. I'm supposed to use newton's algorithm on the two data sets for fitting a logistic hypothesis. But they use matlab &amp; I'm using scipy</p> <p>Eg one question i have is the matrixes kept rounding to integers until I initialized one value to 0.0. Is there a better way?</p> <p>Thanks</p> <pre><code>import os.path import math from numpy import matrix from scipy.linalg import inv #, det, eig x = matrix( '0.0;0;1' ) y = 11 grad = matrix( '0.0;0;0' ) hess = matrix('0.0,0,0;0,0,0;0,0,0') theta = matrix( '0.0;0;0' ) # run until convergence=6or7 for i in range(1, 6): #reset grad = matrix( '0.0;0;0' ) hess = matrix('0.0,0,0;0,0,0;0,0,0') xfile = open("q1x.dat", "r") yfile = open("q1y.dat", "r") #over whole set=99 items for i in range(1, 100): xline = xfile.readline() s= xline.split(" ") x[0] = float(s[1]) x[1] = float(s[2]) y = float(yfile.readline()) hypoth = 1/ (1+ math.exp(-(theta.transpose() * x))) for j in range(0,3): grad[j] = grad[j] + (y-hypoth)* x[j] for k in range(0,3): hess[j,k] = hess[j,k] - (hypoth *(1-hypoth)*x[j]*x[k]) theta = theta - inv(hess)*grad #update theta after construction xfile.close() yfile.close() print "done" print theta </code></pre>
3
2009-06-17T14:00:46Z
1,007,355
<p>One obvious change is to get rid of the "for i in range(1, 100):" and just iterate over the file lines. To iterate over both files (xfile and yfile), zip them. ie replace that block with something like:</p> <pre><code> import itertools for xline, yline in itertools.izip(xfile, yfile): s= xline.split(" ") x[0] = float(s[1]) x[1] = float(s[2]) y = float(yline) ... </code></pre> <p>(This is assuming the file is 100 lines, (ie. you want the whole file). If you're deliberately restricting to the <em>first</em> 100 lines, you could use something like:</p> <pre><code> for i, xline, yline in itertools.izip(range(100), xfile, yfile): </code></pre> <p>However, its also inefficient to iterate over the same file 6 times - better to load it into memory in advance, and loop over it there, ie. outside your loop, have:</p> <pre><code>xfile = open("q1x.dat", "r") yfile = open("q1y.dat", "r") data = zip([line.split(" ")[1:3] for line in xfile], map(float, yfile)) </code></pre> <p>And inside just:</p> <pre><code>for (x1,x2), y in data: x[0] = x1 x[1] = x2 ... </code></pre>
9
2009-06-17T14:23:22Z
[ "python", "machine-learning", "scipy" ]
How do you make this code more pythonic?
1,007,215
<p>Could you guys please tell me how I can make the following code more pythonic? </p> <p>The code is correct. Full disclosure - it's problem 1b in Handout #4 of <a href="http://www.stanford.edu/class/cs229/materials.html" rel="nofollow">this</a> machine learning course. I'm supposed to use newton's algorithm on the two data sets for fitting a logistic hypothesis. But they use matlab &amp; I'm using scipy</p> <p>Eg one question i have is the matrixes kept rounding to integers until I initialized one value to 0.0. Is there a better way?</p> <p>Thanks</p> <pre><code>import os.path import math from numpy import matrix from scipy.linalg import inv #, det, eig x = matrix( '0.0;0;1' ) y = 11 grad = matrix( '0.0;0;0' ) hess = matrix('0.0,0,0;0,0,0;0,0,0') theta = matrix( '0.0;0;0' ) # run until convergence=6or7 for i in range(1, 6): #reset grad = matrix( '0.0;0;0' ) hess = matrix('0.0,0,0;0,0,0;0,0,0') xfile = open("q1x.dat", "r") yfile = open("q1y.dat", "r") #over whole set=99 items for i in range(1, 100): xline = xfile.readline() s= xline.split(" ") x[0] = float(s[1]) x[1] = float(s[2]) y = float(yfile.readline()) hypoth = 1/ (1+ math.exp(-(theta.transpose() * x))) for j in range(0,3): grad[j] = grad[j] + (y-hypoth)* x[j] for k in range(0,3): hess[j,k] = hess[j,k] - (hypoth *(1-hypoth)*x[j]*x[k]) theta = theta - inv(hess)*grad #update theta after construction xfile.close() yfile.close() print "done" print theta </code></pre>
3
2009-06-17T14:00:46Z
1,007,368
<p>the code that reads the files into lists could be drastically simpler</p> <pre><code>for line in open("q1x.dat", "r"): x = map(float,line.split(" ")[1:]) y = map(float, open("q1y.dat", "r").readlines()) </code></pre>
0
2009-06-17T14:25:21Z
[ "python", "machine-learning", "scipy" ]
How do you make this code more pythonic?
1,007,215
<p>Could you guys please tell me how I can make the following code more pythonic? </p> <p>The code is correct. Full disclosure - it's problem 1b in Handout #4 of <a href="http://www.stanford.edu/class/cs229/materials.html" rel="nofollow">this</a> machine learning course. I'm supposed to use newton's algorithm on the two data sets for fitting a logistic hypothesis. But they use matlab &amp; I'm using scipy</p> <p>Eg one question i have is the matrixes kept rounding to integers until I initialized one value to 0.0. Is there a better way?</p> <p>Thanks</p> <pre><code>import os.path import math from numpy import matrix from scipy.linalg import inv #, det, eig x = matrix( '0.0;0;1' ) y = 11 grad = matrix( '0.0;0;0' ) hess = matrix('0.0,0,0;0,0,0;0,0,0') theta = matrix( '0.0;0;0' ) # run until convergence=6or7 for i in range(1, 6): #reset grad = matrix( '0.0;0;0' ) hess = matrix('0.0,0,0;0,0,0;0,0,0') xfile = open("q1x.dat", "r") yfile = open("q1y.dat", "r") #over whole set=99 items for i in range(1, 100): xline = xfile.readline() s= xline.split(" ") x[0] = float(s[1]) x[1] = float(s[2]) y = float(yfile.readline()) hypoth = 1/ (1+ math.exp(-(theta.transpose() * x))) for j in range(0,3): grad[j] = grad[j] + (y-hypoth)* x[j] for k in range(0,3): hess[j,k] = hess[j,k] - (hypoth *(1-hypoth)*x[j]*x[k]) theta = theta - inv(hess)*grad #update theta after construction xfile.close() yfile.close() print "done" print theta </code></pre>
3
2009-06-17T14:00:46Z
1,007,377
<pre><code>x = matrix([[0.],[0],[1]]) theta = matrix(zeros([3,1])) for i in range(5): grad = matrix(zeros([3,1])) hess = matrix(zeros([3,3])) [xfile, yfile] = [open('q1'+a+'.dat', 'r') for a in 'xy'] for xline, yline in zip(xfile, yfile): x.transpose()[0,:2] = [map(float, xline.split(" ")[1:3])] y = float(yline) hypoth = 1 / (1 + math.exp(theta.transpose() * x)) grad += (y - hypoth) * x hess -= hypoth * (1 - hypoth) * x * x.transpose() theta += inv(hess) * grad print "done" print theta </code></pre>
4
2009-06-17T14:26:48Z
[ "python", "machine-learning", "scipy" ]
How do you make this code more pythonic?
1,007,215
<p>Could you guys please tell me how I can make the following code more pythonic? </p> <p>The code is correct. Full disclosure - it's problem 1b in Handout #4 of <a href="http://www.stanford.edu/class/cs229/materials.html" rel="nofollow">this</a> machine learning course. I'm supposed to use newton's algorithm on the two data sets for fitting a logistic hypothesis. But they use matlab &amp; I'm using scipy</p> <p>Eg one question i have is the matrixes kept rounding to integers until I initialized one value to 0.0. Is there a better way?</p> <p>Thanks</p> <pre><code>import os.path import math from numpy import matrix from scipy.linalg import inv #, det, eig x = matrix( '0.0;0;1' ) y = 11 grad = matrix( '0.0;0;0' ) hess = matrix('0.0,0,0;0,0,0;0,0,0') theta = matrix( '0.0;0;0' ) # run until convergence=6or7 for i in range(1, 6): #reset grad = matrix( '0.0;0;0' ) hess = matrix('0.0,0,0;0,0,0;0,0,0') xfile = open("q1x.dat", "r") yfile = open("q1y.dat", "r") #over whole set=99 items for i in range(1, 100): xline = xfile.readline() s= xline.split(" ") x[0] = float(s[1]) x[1] = float(s[2]) y = float(yfile.readline()) hypoth = 1/ (1+ math.exp(-(theta.transpose() * x))) for j in range(0,3): grad[j] = grad[j] + (y-hypoth)* x[j] for k in range(0,3): hess[j,k] = hess[j,k] - (hypoth *(1-hypoth)*x[j]*x[k]) theta = theta - inv(hess)*grad #update theta after construction xfile.close() yfile.close() print "done" print theta </code></pre>
3
2009-06-17T14:00:46Z
1,009,035
<blockquote> <p>the matrixes kept rounding to integers until I initialized one value to 0.0. Is there a better way?</p> </blockquote> <p>At the top of your code:</p> <pre><code>from __future__ import division </code></pre> <p>In Python 2.6 and earlier, integer division always returns an integer unless there is at least one floating point number within. In Python 3.0 (and in <strong>future</strong> division in 2.6), division works more how we humans might expect it to.</p> <p>If you <em>want</em> integer division to return an integer, and you've imported from <strong>future</strong>, use a double //. That is</p> <pre><code>from __future__ import division print 1//2 # prints 0 print 5//2 # prints 2 print 1/2 # prints 0.5 print 5/2 # prints 2.5 </code></pre>
3
2009-06-17T19:19:45Z
[ "python", "machine-learning", "scipy" ]
Using Perl, Python, or Ruby, how to write a program to "click" on the screen at scheduled time?
1,007,391
<p>Using Perl, Python, or Ruby, can I write a program, probably calling Win32 API, to "click" on the screen at scheduled time, like every 1 hour?</p> <p><strong>Details:</strong> </p> <p>This is for experimentation -- and can the clicking be effective on Flash content as well as any element on screen? It can be nice if the program can record where on screen the click needs to happen, or at least draw a red dot on the screen to show where it is clicking on. </p> <p>Can the click be targeted towards a window or is it only a general pixel on the screen? What if some virus scanning program pops up covering up the place where the click should happen? (although if the program clicks on the white space of a window first, then it can bring that window to the foreground first).</p> <p>By the way, can Grease Monkey or any Firefox add-on be used to do this too?</p>
1
2009-06-17T14:29:06Z
1,007,426
<p>In Python there is <a href="http://www.python.org/doc/2.5.2/lib/module-ctypes.html" rel="nofollow">ctypes</a> and in Perl there is <a href="http://search.cpan.org/~cosimo/Win32-API-0.58/API.pm" rel="nofollow">Win32::API</a></p> <p><strong>ctypes Example</strong></p> <pre><code>from ctypes import * windll.user32.MessageBoxA(None, "Hey MessageBox", "ctypes", 0); </code></pre> <p><strong>Win32::Api Example</strong></p> <pre><code>use Win32::GUI qw( WM_CLOSE ); my $tray = Win32::GUI::FindWindow("WindowISearchFor","WindowISearchFor"); Win32::GUI::SendMessage($tray,WM_CLOSE,0,0); </code></pre>
7
2009-06-17T14:34:34Z
[ "python", "ruby", "perl", "winapi" ]
Using Perl, Python, or Ruby, how to write a program to "click" on the screen at scheduled time?
1,007,391
<p>Using Perl, Python, or Ruby, can I write a program, probably calling Win32 API, to "click" on the screen at scheduled time, like every 1 hour?</p> <p><strong>Details:</strong> </p> <p>This is for experimentation -- and can the clicking be effective on Flash content as well as any element on screen? It can be nice if the program can record where on screen the click needs to happen, or at least draw a red dot on the screen to show where it is clicking on. </p> <p>Can the click be targeted towards a window or is it only a general pixel on the screen? What if some virus scanning program pops up covering up the place where the click should happen? (although if the program clicks on the white space of a window first, then it can bring that window to the foreground first).</p> <p>By the way, can Grease Monkey or any Firefox add-on be used to do this too?</p>
1
2009-06-17T14:29:06Z
1,007,441
<p>If you are trying to automate some task in a website you might want to look at <a href="http://search.cpan.org/dist/Test-WWW-Selenium/lib/WWW/Selenium.pm" rel="nofollow"><code>WWW::Selenium</code></a>. It, along with <a href="http://seleniumhq.org/projects/remote-control/" rel="nofollow">Selenium Remote Control</a>, allows you to remote control a web browser.</p>
8
2009-06-17T14:35:58Z
[ "python", "ruby", "perl", "winapi" ]
Using Perl, Python, or Ruby, how to write a program to "click" on the screen at scheduled time?
1,007,391
<p>Using Perl, Python, or Ruby, can I write a program, probably calling Win32 API, to "click" on the screen at scheduled time, like every 1 hour?</p> <p><strong>Details:</strong> </p> <p>This is for experimentation -- and can the clicking be effective on Flash content as well as any element on screen? It can be nice if the program can record where on screen the click needs to happen, or at least draw a red dot on the screen to show where it is clicking on. </p> <p>Can the click be targeted towards a window or is it only a general pixel on the screen? What if some virus scanning program pops up covering up the place where the click should happen? (although if the program clicks on the white space of a window first, then it can bring that window to the foreground first).</p> <p>By the way, can Grease Monkey or any Firefox add-on be used to do this too?</p>
1
2009-06-17T14:29:06Z
1,007,452
<p>I find this is easier to approach in Java or C++. Java has a <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/awt/Robot.html" rel="nofollow">Robot class</a> that allows you to just pass x, y coordinates and click somewhere. Using C++, you can achieve that same functionality using <code>mouse_event()</code> or <code>SendMessage()</code> with the <code>WM_MOUSE_DOWN</code> flag. SendMessage is more technical but it allows you to use <code>FindWindow()</code> and send mouse clicks to a specific window, even if it's minimized.</p> <p>Using a scripting language like Python or Ruby, I'd guess that you'd end up hooking into one of these Windows API functions anyway.</p>
0
2009-06-17T14:37:34Z
[ "python", "ruby", "perl", "winapi" ]
Using Perl, Python, or Ruby, how to write a program to "click" on the screen at scheduled time?
1,007,391
<p>Using Perl, Python, or Ruby, can I write a program, probably calling Win32 API, to "click" on the screen at scheduled time, like every 1 hour?</p> <p><strong>Details:</strong> </p> <p>This is for experimentation -- and can the clicking be effective on Flash content as well as any element on screen? It can be nice if the program can record where on screen the click needs to happen, or at least draw a red dot on the screen to show where it is clicking on. </p> <p>Can the click be targeted towards a window or is it only a general pixel on the screen? What if some virus scanning program pops up covering up the place where the click should happen? (although if the program clicks on the white space of a window first, then it can bring that window to the foreground first).</p> <p>By the way, can Grease Monkey or any Firefox add-on be used to do this too?</p>
1
2009-06-17T14:29:06Z
1,009,497
<p>To answer the actual question, in Perl, you would use the SendMouse (and the associated functions) provided by the <a href="http://search.cpan.org/~karasik/Win32-GuiTest-1.56/" rel="nofollow">Win32::GuiTest</a> module.</p> <pre><code>#!/usr/bin/perl use strict; use warnings; use Win32::GuiTest qw( MouseMoveAbsPix SendMouse ); MouseMoveAbsPix(640,400); SendMouse "{LEFTCLICK}"; __END__ </code></pre> <p><strong>UPDATE:</strong></p> <blockquote> <p>What if some virus scanning program pops up covering up the place where the click should happen? </p> </blockquote> <p>In that case, you would use <code>FindWindowLike</code> to find the window and <code>MouseClick</code> to send a click to that specific window.</p>
6
2009-06-17T21:01:00Z
[ "python", "ruby", "perl", "winapi" ]
Using Perl, Python, or Ruby, how to write a program to "click" on the screen at scheduled time?
1,007,391
<p>Using Perl, Python, or Ruby, can I write a program, probably calling Win32 API, to "click" on the screen at scheduled time, like every 1 hour?</p> <p><strong>Details:</strong> </p> <p>This is for experimentation -- and can the clicking be effective on Flash content as well as any element on screen? It can be nice if the program can record where on screen the click needs to happen, or at least draw a red dot on the screen to show where it is clicking on. </p> <p>Can the click be targeted towards a window or is it only a general pixel on the screen? What if some virus scanning program pops up covering up the place where the click should happen? (although if the program clicks on the white space of a window first, then it can bring that window to the foreground first).</p> <p>By the way, can Grease Monkey or any Firefox add-on be used to do this too?</p>
1
2009-06-17T14:29:06Z
1,009,537
<p>If using a different tool is allowed, you should take a look at <a href="http://www.autohotkey.com/" rel="nofollow">AutoHotkey</a> or <a href="http://www.autoitscript.com/autoit3/" rel="nofollow">AutoIt</a>. These tools were made for this sort of thing, and I've always been keen on using the right tools for the right jobs.</p> <p>AutoHotkey is based on AutoIt I believe, and it is my personal preference. You only really need 2 functions for what you're trying to achieve, <a href="http://www.autohotkey.com/docs/commands/MouseMove.htm" rel="nofollow">MouseMove</a> and <a href="http://www.autohotkey.com/docs/commands/MouseClick.htm" rel="nofollow">MouseClick</a>.</p>
1
2009-06-17T21:09:40Z
[ "python", "ruby", "perl", "winapi" ]
mrdivide function in MATLAB: what is it doing, and how can I do it in Python?
1,007,442
<p>I have this line of MATLAB code:</p> <pre><code>a/b </code></pre> <p>I am using these inputs:</p> <pre><code>a = [1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9] b = ones(25, 18) </code></pre> <p>This is the result (a 1x25 matrix):</p> <pre><code>[5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] </code></pre> <p>What is MATLAB doing? I am trying to duplicate this behavior in Python, and the <code>mrdivide</code> documentation in MATLAB was unhelpful. Where does the 5 come from, and why are the rest of the values 0?</p> <p>I have tried this with other inputs and receive similar results, usually just a different first element and zeros filling the remainder of the matrix. In Python when I use <code>linalg.lstsq(b.T,a.T)</code>, all of the values in the first matrix returned (i.e. not the singular one) are 0.2. I have already tried right division in Python and it gives something completely off with the wrong dimensions.</p> <p>I understand what a least square approximation is, I just need to know what <code>mrdivide</code> is doing.</p> <h3>Related:</h3> <ul> <li><a href="http://stackoverflow.com/questions/1001634/array-division-translating-from-matlab-to-python">Array division- translating from MATLAB to Python</a></li> </ul>
6
2009-06-17T14:36:13Z
1,007,469
<p>a/b finds the least square solution to the system of linear equations bx = a</p> <p>if b is invertible, this is a*inv(b), but if it isn't, the it is the x which minimises norm(bx-a)</p> <p>You can read more about least squares on <a href="http://en.wikipedia.org/wiki/Least%5Fsquares" rel="nofollow">wikipedia</a>.</p> <p>according to <a href="http://www.mathworks.co.uk/access/helpdesk/help/techdoc/index.html?/access/helpdesk/help/techdoc/ref/mldivide.html" rel="nofollow">matlab documentation</a>, mrdivide will return at most k non-zero values, where k is the computed rank of b. my guess is that matlab in your case solves the least squares problem given by replacing b by b(:1) (which has the same rank). In this case the moore-penrose inverse <code>b2 = b(1,:); inv(b2*b2')*b2*a'</code> is defined and gives the same answer</p>
1
2009-06-17T14:40:02Z
[ "python", "matlab", "numpy", "linear-algebra" ]
mrdivide function in MATLAB: what is it doing, and how can I do it in Python?
1,007,442
<p>I have this line of MATLAB code:</p> <pre><code>a/b </code></pre> <p>I am using these inputs:</p> <pre><code>a = [1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9] b = ones(25, 18) </code></pre> <p>This is the result (a 1x25 matrix):</p> <pre><code>[5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] </code></pre> <p>What is MATLAB doing? I am trying to duplicate this behavior in Python, and the <code>mrdivide</code> documentation in MATLAB was unhelpful. Where does the 5 come from, and why are the rest of the values 0?</p> <p>I have tried this with other inputs and receive similar results, usually just a different first element and zeros filling the remainder of the matrix. In Python when I use <code>linalg.lstsq(b.T,a.T)</code>, all of the values in the first matrix returned (i.e. not the singular one) are 0.2. I have already tried right division in Python and it gives something completely off with the wrong dimensions.</p> <p>I understand what a least square approximation is, I just need to know what <code>mrdivide</code> is doing.</p> <h3>Related:</h3> <ul> <li><a href="http://stackoverflow.com/questions/1001634/array-division-translating-from-matlab-to-python">Array division- translating from MATLAB to Python</a></li> </ul>
6
2009-06-17T14:36:13Z
1,007,532
<p>Per <a href="http://mathesaurus.sourceforge.net/matlab-numpy.html" rel="nofollow">this handy "cheat sheet"</a> of numpy for matlab users, <code>linalg.lstsq(b,a)</code> -- <code>linalg</code> is <a href="http://www.scipy.org/doc/numpy%5Fapi%5Fdocs/numpy.linalg.linalg.html" rel="nofollow">numpy.linalg.linalg</a>, a light-weight version of the full <code>scipy.linalg</code>.</p>
1
2009-06-17T14:49:28Z
[ "python", "matlab", "numpy", "linear-algebra" ]
mrdivide function in MATLAB: what is it doing, and how can I do it in Python?
1,007,442
<p>I have this line of MATLAB code:</p> <pre><code>a/b </code></pre> <p>I am using these inputs:</p> <pre><code>a = [1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9] b = ones(25, 18) </code></pre> <p>This is the result (a 1x25 matrix):</p> <pre><code>[5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] </code></pre> <p>What is MATLAB doing? I am trying to duplicate this behavior in Python, and the <code>mrdivide</code> documentation in MATLAB was unhelpful. Where does the 5 come from, and why are the rest of the values 0?</p> <p>I have tried this with other inputs and receive similar results, usually just a different first element and zeros filling the remainder of the matrix. In Python when I use <code>linalg.lstsq(b.T,a.T)</code>, all of the values in the first matrix returned (i.e. not the singular one) are 0.2. I have already tried right division in Python and it gives something completely off with the wrong dimensions.</p> <p>I understand what a least square approximation is, I just need to know what <code>mrdivide</code> is doing.</p> <h3>Related:</h3> <ul> <li><a href="http://stackoverflow.com/questions/1001634/array-division-translating-from-matlab-to-python">Array division- translating from MATLAB to Python</a></li> </ul>
6
2009-06-17T14:36:13Z
15,739,248
<p><a href="http://www.mathworks.com/help/matlab/ref/mrdivide.html" rel="nofollow">MRDIVIDE</a> or the <code>/</code> operator actually solves the <code>xb = a</code> linear system, as opposed to <a href="http://www.mathworks.com/help/matlab/ref/mldivide.html" rel="nofollow">MLDIVIDE</a> or the <code>\</code> operator which will solve the system <code>bx = a</code>. </p> <p>To solve a system <code>xb = a</code> with a non-symmetric, non-invertible matrix <code>b</code>, you can either rely on <code>mridivide()</code>, which is done via factorization of <code>b</code> with Gauss elimination, or <code>pinv()</code>, which is done via Singular Value Decomposition, and zero-ing of the singular values below a (default) tolerance level. </p> <p>Here is the difference (for the case of <code>mldivide</code>): <a href="https://www.mathworks.com/support/solutions/en/data/1-3TPS3Y/index.html?product=ML&amp;solution=1-3TPS3Y" rel="nofollow">What is the difference between PINV and MLDIVIDE when I solve A*x=b?</a> </p> <blockquote> <p>When the system is overdetermined, both algorithms provide the same answer. When the system is underdetermined, PINV will return the solution x, that has the minimum norm (min NORM(x)). MLDIVIDE will pick the solution with least number of non-zero elements.</p> </blockquote> <p>In your example: </p> <pre><code>% solve xb = a a = [1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9]; b = ones(25, 18); </code></pre> <p>the system is underdetermined, and the two different solutions will be: </p> <pre><code>x1 = a/b; % MRDIVIDE: sparsest solution (min L0 norm) x2 = a*pinv(b); % PINV: minimum norm solution (min L2) &gt;&gt; x1 = a/b Warning: Rank deficient, rank = 1, tol = 2.3551e-014. ans = 5.0000 0 0 ... 0 &gt;&gt; x2 = a*pinv(b) ans = 0.2 0.2 0.2 ... 0.2 </code></pre> <p>In both cases the approximation error of <code>xb-a</code> is non-negligible (non-exact solution) and the same, i.e. <code>norm(x1*b-a)</code> and <code>norm(x2*b-a)</code> will return the same result.</p> <p><strong>What is MATLAB doing?</strong> </p> <p>A great break-down of the algorithms (and checks on properties) invoked by the '\' operator, depending upon the structure of matrix <code>b</code> is given in this post in <a href="http://scicomp.stackexchange.com/a/1004/4014">scicomp.stackexchange.com</a>. I am assuming similar options apply for the <code>/</code> operator.</p> <p>For your example, MATLAB is most probably doing a Gaussian elimination, giving the sparsest solution amongst a infinitude (that's where the 5 comes from). </p> <p><strong>What is Python doing?</strong> </p> <p>Python, in <code>linalg.lstsq</code> uses pseudo-inverse/SVD, as demonstrated above (that's why you get a vector of 0.2's). In effect, the following will both give you the same result as MATLAB's <code>pinv()</code>: </p> <pre><code>from numpy import * a = array([1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9]) b = ones((25, 18)) # xb = a: solve b.T x.T = a.T instead x2 = linalg.lstsq(b.T, a.T)[0] x2 = dot(a, linalg.pinv(b)) </code></pre>
3
2013-04-01T07:14:36Z
[ "python", "matlab", "numpy", "linear-algebra" ]
How do I replace whitespaces with underscore and vice versa?
1,007,481
<p>I want to replace whitespace with underscore in a string to create nice URLs. So that for example:</p> <pre><code>"This should be connected" becomes "This_should_be_connected" </code></pre> <p>I am using Python with Django. Can this be solved using regular expressions? </p>
77
2009-06-17T14:41:36Z
1,007,499
<p>You don't need regular expressions, Python has a string method that does what you need:</p> <pre><code>mystring.replace (" ", "_") </code></pre>
137
2009-06-17T14:44:23Z
[ "python", "regex", "django" ]
How do I replace whitespaces with underscore and vice versa?
1,007,481
<p>I want to replace whitespace with underscore in a string to create nice URLs. So that for example:</p> <pre><code>"This should be connected" becomes "This_should_be_connected" </code></pre> <p>I am using Python with Django. Can this be solved using regular expressions? </p>
77
2009-06-17T14:41:36Z
1,007,503
<p>Using the <code>re</code> module:</p> <pre><code>import re re.sub('\s+', '_', "This should be connected") # This_should_be_connected re.sub('\s+', '_', 'And so\tshould this') # And_so_should_this </code></pre> <p>Unless you have multiple spaces or other whitespace possibilities as above, you may just wish to use <code>string.replace</code> as others have suggested.</p>
11
2009-06-17T14:45:07Z
[ "python", "regex", "django" ]
How do I replace whitespaces with underscore and vice versa?
1,007,481
<p>I want to replace whitespace with underscore in a string to create nice URLs. So that for example:</p> <pre><code>"This should be connected" becomes "This_should_be_connected" </code></pre> <p>I am using Python with Django. Can this be solved using regular expressions? </p>
77
2009-06-17T14:41:36Z
1,007,508
<p>use string's replace method:</p> <p><code>"this should be connected".replace(" ", "_")</code></p> <p><code>"this_should_be_disconnected".replace("_", " ")</code></p>
9
2009-06-17T14:45:30Z
[ "python", "regex", "django" ]
How do I replace whitespaces with underscore and vice versa?
1,007,481
<p>I want to replace whitespace with underscore in a string to create nice URLs. So that for example:</p> <pre><code>"This should be connected" becomes "This_should_be_connected" </code></pre> <p>I am using Python with Django. Can this be solved using regular expressions? </p>
77
2009-06-17T14:41:36Z
1,007,615
<p>Replacing spaces is fine, but I might suggest going a little further to handle other URL-hostile characters like question marks, apostrophes, exclamation points, etc. </p> <p>Also note that the general consensus among SEO experts is that <a href="http://www.google.com/search?q=dashes+underscores+seo">dashes are preferred to underscores in URLs.</a></p> <pre><code>def urlify(s): # Remove all non-word characters (everything except numbers and letters) s = re.sub(r"[^\w\s]", '', s) # Replace all runs of whitespace with a single dash s = re.sub(r"\s+", '-', s) return s # Prints: I-cant-get-no-satisfaction" print urlify("I can't get no satisfaction!") </code></pre>
42
2009-06-17T15:03:21Z
[ "python", "regex", "django" ]
How do I replace whitespaces with underscore and vice versa?
1,007,481
<p>I want to replace whitespace with underscore in a string to create nice URLs. So that for example:</p> <pre><code>"This should be connected" becomes "This_should_be_connected" </code></pre> <p>I am using Python with Django. Can this be solved using regular expressions? </p>
77
2009-06-17T14:41:36Z
1,007,685
<p>Django has a 'slugify' function which does this, as well as other URL-friendly optimisations. It's hidden away in the defaultfilters module.</p> <pre><code>&gt;&gt;&gt; from django.template.defaultfilters import slugify &gt;&gt;&gt; slugify("This should be connected") this-should-be-connected </code></pre> <p>This isn't exactly the output you asked for, but IMO it's better for use in URLs.</p>
33
2009-06-17T15:15:21Z
[ "python", "regex", "django" ]
How do I replace whitespaces with underscore and vice versa?
1,007,481
<p>I want to replace whitespace with underscore in a string to create nice URLs. So that for example:</p> <pre><code>"This should be connected" becomes "This_should_be_connected" </code></pre> <p>I am using Python with Django. Can this be solved using regular expressions? </p>
77
2009-06-17T14:41:36Z
1,007,836
<p>I'm using the following piece of code for my friendly urls:</p> <pre><code>from unicodedata import normalize from re import sub def slugify(title): name = normalize('NFKD', title).encode('ascii', 'ignore').replace(' ', '-').lower() #remove `other` characters name = sub('[^a-zA-Z0-9_-]', '', name) #nomalize dashes name = sub('-+', '-', name) return name </code></pre> <p>It works fine with unicode characters as well.</p>
5
2009-06-17T15:36:32Z
[ "python", "regex", "django" ]
How do I replace whitespaces with underscore and vice versa?
1,007,481
<p>I want to replace whitespace with underscore in a string to create nice URLs. So that for example:</p> <pre><code>"This should be connected" becomes "This_should_be_connected" </code></pre> <p>I am using Python with Django. Can this be solved using regular expressions? </p>
77
2009-06-17T14:41:36Z
1,012,401
<p>Python has a built in method on strings called replace which is used as so:</p> <pre><code>string.replace(old, new) </code></pre> <p>So you would use:</p> <pre><code>string.replace(" ", "_") </code></pre> <p>I had this problem a while ago and I wrote code to replace characters in a string. I have to start remembering to check the python documentation because they've got built in functions for everything.</p>
1
2009-06-18T12:34:42Z
[ "python", "regex", "django" ]
How do I replace whitespaces with underscore and vice versa?
1,007,481
<p>I want to replace whitespace with underscore in a string to create nice URLs. So that for example:</p> <pre><code>"This should be connected" becomes "This_should_be_connected" </code></pre> <p>I am using Python with Django. Can this be solved using regular expressions? </p>
77
2009-06-17T14:41:36Z
1,016,761
<pre><code>perl -e 'map { $on=$_; s/ /_/; rename($on, $_) or warn $!; } &lt;*&gt;;' </code></pre> <p>Match et replace space > underscore of all files in current directory</p>
-1
2009-06-19T07:30:53Z
[ "python", "regex", "django" ]
How do I replace whitespaces with underscore and vice versa?
1,007,481
<p>I want to replace whitespace with underscore in a string to create nice URLs. So that for example:</p> <pre><code>"This should be connected" becomes "This_should_be_connected" </code></pre> <p>I am using Python with Django. Can this be solved using regular expressions? </p>
77
2009-06-17T14:41:36Z
3,176,580
<p>OP is using python, but in javascript (something to be careful of since the syntaxes are similar.</p> <pre><code>// only replaces the first instance of ' ' with '_' "one two three".replace(' ', '_'); =&gt; "one_two three" // replaces all instances of ' ' with '_' "one two three".replace(/\s/g, '_'); =&gt; "one_two_three" </code></pre>
2
2010-07-04T23:34:14Z
[ "python", "regex", "django" ]
How do I replace whitespaces with underscore and vice versa?
1,007,481
<p>I want to replace whitespace with underscore in a string to create nice URLs. So that for example:</p> <pre><code>"This should be connected" becomes "This_should_be_connected" </code></pre> <p>I am using Python with Django. Can this be solved using regular expressions? </p>
77
2009-06-17T14:41:36Z
10,376,875
<p>This takes into account blank characters other than space and I think it's faster than using <code>re</code> module:</p> <pre><code>url = "_".join( title.split() ) </code></pre>
16
2012-04-29T23:18:36Z
[ "python", "regex", "django" ]
How do I replace whitespaces with underscore and vice versa?
1,007,481
<p>I want to replace whitespace with underscore in a string to create nice URLs. So that for example:</p> <pre><code>"This should be connected" becomes "This_should_be_connected" </code></pre> <p>I am using Python with Django. Can this be solved using regular expressions? </p>
77
2009-06-17T14:41:36Z
32,827,222
<p>Surprisingly this library not mentioned yet</p> <p>python package named python-slugify, which does a pretty good job of slugifying:</p> <pre><code>pip install python-slugify </code></pre> <p>Works like this:</p> <pre><code>from slugify import slugify txt = "This is a test ---" r = slugify(txt) self.assertEquals(r, "this-is-a-test") txt = "This -- is a ## test ---" r = slugify(txt) self.assertEquals(r, "this-is-a-test") txt = 'C\'est déjà l\'été.' r = slugify(txt) self.assertEquals(r, "cest-deja-lete") txt = 'Nín hǎo. Wǒ shì zhōng guó rén' r = slugify(txt) self.assertEquals(r, "nin-hao-wo-shi-zhong-guo-ren") txt = 'Компьютер' r = slugify(txt) self.assertEquals(r, "kompiuter") txt = 'jaja---lol-méméméoo--a' r = slugify(txt) self.assertEquals(r, "jaja-lol-mememeoo-a") </code></pre>
1
2015-09-28T16:01:41Z
[ "python", "regex", "django" ]
How do I replace whitespaces with underscore and vice versa?
1,007,481
<p>I want to replace whitespace with underscore in a string to create nice URLs. So that for example:</p> <pre><code>"This should be connected" becomes "This_should_be_connected" </code></pre> <p>I am using Python with Django. Can this be solved using regular expressions? </p>
77
2009-06-17T14:41:36Z
38,686,304
<pre><code>mystring.replace (" ", "_") </code></pre> <p>if you assign this value to any variable, it will work</p> <pre><code>s = mystring.replace (" ", "_") </code></pre> <p>by default mystring wont have this</p>
0
2016-07-31T16:51:23Z
[ "python", "regex", "django" ]
How to tell Buildout to install a egg from a URL (w/o pypi)
1,007,488
<p>I have some egg accessible as a URL, say <a href="http://myhosting.com/somepkg.egg" rel="nofollow">http://myhosting.com/somepkg.egg</a> . Now I don't have this somepkg listed on pypi. How do I tell buildout to fetch and install it for me. I have tried a few recipes but no luck so far.</p> <p>TIA</p>
5
2009-06-17T14:43:00Z
1,007,770
<p>You should just be able to add a 'find-links' option to your [buildout] section within the buildout.cfg file. I just tested this internally with the following buildout.cfg.</p> <pre><code>[buildout] find-links = http://buildslave01/eggs/hostapi.core-1.0_r102-py2.4.egg parts = mypython [mypython] recipe = zc.recipe.egg interpreter = mypython eggs = hostapi.core </code></pre> <p>You can just specify the full path to the egg as the value to 'find-links.' Make sure the egg's 'pyx.y' version matches your local Python version. If they don't match, you'll get a not found error which is slightly misleading.</p>
5
2009-06-17T15:27:51Z
[ "python", "buildout", "egg" ]
How do I build a list of all possible tuples from this table?
1,007,666
<p>Suppose I have a set of column definitions:</p> <pre><code>Col1: value11 value12 value13 Col2: value21 value22 Col3: value31 value32 value33 ... </code></pre> <p>Given some subset of columns -- 2 or more -- I want to find all possible values for those columns. Suppose I choose columns 1 and 2, above:</p> <pre><code>(value11 value21) (value11 value22) (value12 value21) (value12 value22) (value13 value21) (value13 value22) </code></pre> <p>If I'd chosen 2:3:</p> <pre><code>(value21 value31) (value21 value32) (value21 value33) (value22 value31) (value22 value32) (value22 value33) </code></pre> <p>If I'd chosen all three:</p> <pre><code>(value11 value21 value31) (value11 value21 value32) ... </code></pre> <p>I'm implementing this in python, and I'd like a <em>fast</em> algorithm to do this. My input is a list of tuples: (columnName, columnValueList)</p> <p>Any suggestions?</p>
2
2009-06-17T15:12:01Z
1,007,739
<p>Looks like itertools.combination could help you.</p> <pre><code>&gt;&gt;&gt; from itertools import combinations &gt;&gt;&gt; list(combinations(xrange(5), 2)) [(0, 1), (0, 2), (0, 3), (0, 4), (1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)] &gt;&gt;&gt; list(combinations(xrange(5), 3)) [(0, 1, 2), (0, 1, 3), (0, 1, 4), (0, 2, 3), (0, 2, 4), (0, 3, 4), (1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)] </code></pre>
0
2009-06-17T15:21:58Z
[ "python", "algorithm" ]
How do I build a list of all possible tuples from this table?
1,007,666
<p>Suppose I have a set of column definitions:</p> <pre><code>Col1: value11 value12 value13 Col2: value21 value22 Col3: value31 value32 value33 ... </code></pre> <p>Given some subset of columns -- 2 or more -- I want to find all possible values for those columns. Suppose I choose columns 1 and 2, above:</p> <pre><code>(value11 value21) (value11 value22) (value12 value21) (value12 value22) (value13 value21) (value13 value22) </code></pre> <p>If I'd chosen 2:3:</p> <pre><code>(value21 value31) (value21 value32) (value21 value33) (value22 value31) (value22 value32) (value22 value33) </code></pre> <p>If I'd chosen all three:</p> <pre><code>(value11 value21 value31) (value11 value21 value32) ... </code></pre> <p>I'm implementing this in python, and I'd like a <em>fast</em> algorithm to do this. My input is a list of tuples: (columnName, columnValueList)</p> <p>Any suggestions?</p>
2
2009-06-17T15:12:01Z
1,007,741
<p>The best way to get this is going to be using itertools.product(). For example:</p> <pre><code>import itertools group1 = ['a', 'b'] group2 = ['c', 'd'] print list(itertools.product(group1, group2)) #==&gt; [('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd')] </code></pre> <p>This function accepts multiple arguments (i.e. multiple columns).</p> <p>For more help on iterools.product() see <a href="http://docs.python.org/library/itertools.html#itertools.product">this</a>.</p>
13
2009-06-17T15:22:28Z
[ "python", "algorithm" ]
How do I build a list of all possible tuples from this table?
1,007,666
<p>Suppose I have a set of column definitions:</p> <pre><code>Col1: value11 value12 value13 Col2: value21 value22 Col3: value31 value32 value33 ... </code></pre> <p>Given some subset of columns -- 2 or more -- I want to find all possible values for those columns. Suppose I choose columns 1 and 2, above:</p> <pre><code>(value11 value21) (value11 value22) (value12 value21) (value12 value22) (value13 value21) (value13 value22) </code></pre> <p>If I'd chosen 2:3:</p> <pre><code>(value21 value31) (value21 value32) (value21 value33) (value22 value31) (value22 value32) (value22 value33) </code></pre> <p>If I'd chosen all three:</p> <pre><code>(value11 value21 value31) (value11 value21 value32) ... </code></pre> <p>I'm implementing this in python, and I'd like a <em>fast</em> algorithm to do this. My input is a list of tuples: (columnName, columnValueList)</p> <p>Any suggestions?</p>
2
2009-06-17T15:12:01Z
1,007,853
<p>In addition to using itertools.product() as jeremy suggests, you might want to consider converting your list of tuples to a dict to make lookups for columnName fast:</p> <p><code>dict(tupleList)</code></p>
1
2009-06-17T15:38:13Z
[ "python", "algorithm" ]
How do I build a list of all possible tuples from this table?
1,007,666
<p>Suppose I have a set of column definitions:</p> <pre><code>Col1: value11 value12 value13 Col2: value21 value22 Col3: value31 value32 value33 ... </code></pre> <p>Given some subset of columns -- 2 or more -- I want to find all possible values for those columns. Suppose I choose columns 1 and 2, above:</p> <pre><code>(value11 value21) (value11 value22) (value12 value21) (value12 value22) (value13 value21) (value13 value22) </code></pre> <p>If I'd chosen 2:3:</p> <pre><code>(value21 value31) (value21 value32) (value21 value33) (value22 value31) (value22 value32) (value22 value33) </code></pre> <p>If I'd chosen all three:</p> <pre><code>(value11 value21 value31) (value11 value21 value32) ... </code></pre> <p>I'm implementing this in python, and I'd like a <em>fast</em> algorithm to do this. My input is a list of tuples: (columnName, columnValueList)</p> <p>Any suggestions?</p>
2
2009-06-17T15:12:01Z
1,007,859
<p>more general solutions that Jeremy's would be:</p> <pre><code>import itertools full = [[value11, value12, value13], [value21, value22], [value31, value32, value33]] ids = 0, 2 </code></pre> <p>or if it is a dict (as it should be):</p> <pre><code>full = {'col1': [value11, value12, value13], 'col2': [value21, value22], 'col3': [value31, value32, value33]} ids = 'col1', 'col3' selected = (full[i] for i in ids) list(itertools.product(*selected)) </code></pre>
2
2009-06-17T15:38:55Z
[ "python", "algorithm" ]
How do I build a list of all possible tuples from this table?
1,007,666
<p>Suppose I have a set of column definitions:</p> <pre><code>Col1: value11 value12 value13 Col2: value21 value22 Col3: value31 value32 value33 ... </code></pre> <p>Given some subset of columns -- 2 or more -- I want to find all possible values for those columns. Suppose I choose columns 1 and 2, above:</p> <pre><code>(value11 value21) (value11 value22) (value12 value21) (value12 value22) (value13 value21) (value13 value22) </code></pre> <p>If I'd chosen 2:3:</p> <pre><code>(value21 value31) (value21 value32) (value21 value33) (value22 value31) (value22 value32) (value22 value33) </code></pre> <p>If I'd chosen all three:</p> <pre><code>(value11 value21 value31) (value11 value21 value32) ... </code></pre> <p>I'm implementing this in python, and I'd like a <em>fast</em> algorithm to do this. My input is a list of tuples: (columnName, columnValueList)</p> <p>Any suggestions?</p>
2
2009-06-17T15:12:01Z
1,007,880
<p>I'll bet <code>itertools</code>-based solutions are going to be faster, but if they need to be avoided (e.g. stuck on Python 2.5 without itertools.product, etc), it can of course be entirely coded in "base Python" when one must.</p> <p>Trying to "pull out all the stops" for speed, maybe something like:</p> <pre><code>def odo(*names_and_valuelists): aux = [[vl, 0] for n, vl in names_and_valuelists] if any(len(vl)==0 for vl, _ in aux): return while True: yield tuple(vl[i] for vl, i in aux) for vlandi in reversed(aux): if vlandi[1] == len(vlandi[0])-1: vlandi[1] = 0 else: vlandi[1] += 1 break else: return </code></pre> <p>though minor tweaks might still accelerate it (needs thorough profiling with realistic sample data!).</p> <p>Here's your example of use:</p> <pre><code>def main(): data = [ ('Col1', 'value11 value12 value13'.split()), ('Col2', 'value21 value22'.split()), ('Col3', 'value31 value32 value33'.split()), ] for tup in odo(data[0], data[1]): print tup print for tup in odo(data[1], data[2]): print tup print for i, tup in enumerate(odo(*data)): print tup if i&gt;5: break if __name__ == '__main__': main() </code></pre> <p>which emits the results:</p> <pre><code>('value11', 'value21') ('value11', 'value22') ('value12', 'value21') ('value12', 'value22') ('value13', 'value21') ('value13', 'value22') ('value21', 'value31') ('value21', 'value32') ('value21', 'value33') ('value22', 'value31') ('value22', 'value32') ('value22', 'value33') ('value11', 'value21', 'value31') ('value11', 'value21', 'value32') ('value11', 'value21', 'value33') ('value11', 'value22', 'value31') ('value11', 'value22', 'value32') ('value11', 'value22', 'value33') ('value12', 'value21', 'value31') </code></pre>
1
2009-06-17T15:41:24Z
[ "python", "algorithm" ]
Popen and python
1,007,855
<p>Working on some code and I'm given the error when running it from the command prompt...</p> <pre><code>NameError: name 'Popen' is not defined </code></pre> <p>but I've imported both <code>import os</code> and <code>import sys</code>.</p> <p>Here's part of the code</p> <pre><code>exepath = os.path.join(EXE File location is here) exepath = '"' + os.path.normpath(exepath) + '"' cmd = [exepath, '-el', str(el), '-n', str(z)] print 'The python program is running this command:' print cmd process = Popen(cmd, stderr=STDOUT, stdout=PIPE) outputstring = process.communicate()[0] </code></pre> <p>Am I missing something elementary? I wouldn't doubt it. Thanks!</p>
4
2009-06-17T15:38:25Z
1,007,873
<p>You should be using os.popen() if you simply import os.</p>
-1
2009-06-17T15:40:26Z
[ "python", "popen" ]
Popen and python
1,007,855
<p>Working on some code and I'm given the error when running it from the command prompt...</p> <pre><code>NameError: name 'Popen' is not defined </code></pre> <p>but I've imported both <code>import os</code> and <code>import sys</code>.</p> <p>Here's part of the code</p> <pre><code>exepath = os.path.join(EXE File location is here) exepath = '"' + os.path.normpath(exepath) + '"' cmd = [exepath, '-el', str(el), '-n', str(z)] print 'The python program is running this command:' print cmd process = Popen(cmd, stderr=STDOUT, stdout=PIPE) outputstring = process.communicate()[0] </code></pre> <p>Am I missing something elementary? I wouldn't doubt it. Thanks!</p>
4
2009-06-17T15:38:25Z
1,007,878
<p>Popen is defined in the subprocess module</p> <pre><code>import subprocess ... subprocess.Popen(...) </code></pre> <p>Or:</p> <pre><code>from subprocess import Popen Popen(...) </code></pre>
7
2009-06-17T15:41:15Z
[ "python", "popen" ]
Popen and python
1,007,855
<p>Working on some code and I'm given the error when running it from the command prompt...</p> <pre><code>NameError: name 'Popen' is not defined </code></pre> <p>but I've imported both <code>import os</code> and <code>import sys</code>.</p> <p>Here's part of the code</p> <pre><code>exepath = os.path.join(EXE File location is here) exepath = '"' + os.path.normpath(exepath) + '"' cmd = [exepath, '-el', str(el), '-n', str(z)] print 'The python program is running this command:' print cmd process = Popen(cmd, stderr=STDOUT, stdout=PIPE) outputstring = process.communicate()[0] </code></pre> <p>Am I missing something elementary? I wouldn't doubt it. Thanks!</p>
4
2009-06-17T15:38:25Z
1,007,890
<p>If your import looks like this:</p> <pre><code>import os </code></pre> <p>Then you need to reference the things included in os like this:</p> <pre><code>os.popen() </code></pre> <p>If you dont want to do that, you can change your import to look like this:</p> <pre><code>from os import * </code></pre> <p>Which is not recommended because it can lead to namespace ambiguities (things in your code conflicting with things imported elsewhere.) You could also just do:</p> <pre><code>from os import popen </code></pre> <p>Which is more explicit and easier to read than from os import *</p>
1
2009-06-17T15:42:13Z
[ "python", "popen" ]
Popen and python
1,007,855
<p>Working on some code and I'm given the error when running it from the command prompt...</p> <pre><code>NameError: name 'Popen' is not defined </code></pre> <p>but I've imported both <code>import os</code> and <code>import sys</code>.</p> <p>Here's part of the code</p> <pre><code>exepath = os.path.join(EXE File location is here) exepath = '"' + os.path.normpath(exepath) + '"' cmd = [exepath, '-el', str(el), '-n', str(z)] print 'The python program is running this command:' print cmd process = Popen(cmd, stderr=STDOUT, stdout=PIPE) outputstring = process.communicate()[0] </code></pre> <p>Am I missing something elementary? I wouldn't doubt it. Thanks!</p>
4
2009-06-17T15:38:25Z
1,007,897
<p>When you import a module, the module's members don't become part of the global namespace: you still have to prefix them with <code>modulename.</code>. So, you have to say</p> <pre><code>import os process = os.popen(command, mode, bufsize) </code></pre> <p>Alternatively, you can use the <code>from module import names</code> syntax to import things into the global namespace:</p> <pre><code>from os import popen # Or, from os import * to import everything process = popen(command, mode, bufsize) </code></pre>
0
2009-06-17T15:43:08Z
[ "python", "popen" ]
Popen and python
1,007,855
<p>Working on some code and I'm given the error when running it from the command prompt...</p> <pre><code>NameError: name 'Popen' is not defined </code></pre> <p>but I've imported both <code>import os</code> and <code>import sys</code>.</p> <p>Here's part of the code</p> <pre><code>exepath = os.path.join(EXE File location is here) exepath = '"' + os.path.normpath(exepath) + '"' cmd = [exepath, '-el', str(el), '-n', str(z)] print 'The python program is running this command:' print cmd process = Popen(cmd, stderr=STDOUT, stdout=PIPE) outputstring = process.communicate()[0] </code></pre> <p>Am I missing something elementary? I wouldn't doubt it. Thanks!</p>
4
2009-06-17T15:38:25Z
1,007,900
<p>This looks like Popen from the subprocess module (python >= 2.4)</p> <pre><code>from subprocess import Popen </code></pre>
1
2009-06-17T15:43:12Z
[ "python", "popen" ]
Popen and python
1,007,855
<p>Working on some code and I'm given the error when running it from the command prompt...</p> <pre><code>NameError: name 'Popen' is not defined </code></pre> <p>but I've imported both <code>import os</code> and <code>import sys</code>.</p> <p>Here's part of the code</p> <pre><code>exepath = os.path.join(EXE File location is here) exepath = '"' + os.path.normpath(exepath) + '"' cmd = [exepath, '-el', str(el), '-n', str(z)] print 'The python program is running this command:' print cmd process = Popen(cmd, stderr=STDOUT, stdout=PIPE) outputstring = process.communicate()[0] </code></pre> <p>Am I missing something elementary? I wouldn't doubt it. Thanks!</p>
4
2009-06-17T15:38:25Z
1,007,901
<p>you should do:</p> <pre><code>import subprocess subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE) # etc. </code></pre>
26
2009-06-17T15:43:15Z
[ "python", "popen" ]
How do I test if a string exists in a Genshi stream?
1,008,038
<p>I'm working on a plugin for Trac and am inserting some javascript into the rendered HTML by manipulating the Genshi stream.</p> <p>I need to test if a javascript function is already in the HTML and if it is then overwrite it with a new version, if it isn't then add it to the HTML.</p> <p>How do I perform a search to see if the function is already there?</p>
0
2009-06-17T16:04:19Z
1,008,223
<p>Aha!! I have solved this by first attempting to remove the function from the stream: </p> <pre><code>stream = stream | Transformer('.//head/script["functionName()"]').remove() </code></pre> <p>and then adding the updated/new version:</p> <pre><code>stream = stream | Transformer('.//head').append(tag.script(functionNameCode, type="text/javascript")) </code></pre>
1
2009-06-17T16:35:49Z
[ "python", "stream", "genshi" ]
Execution order with threads and PyGTK on Windows
1,008,322
<p>I'm having issues with threads and PyGTK on Windows. According the the <a href="http://faq.pygtk.org/index.py?req=show&amp;file=faq21.003.htp" rel="nofollow">PyGTK FAQ</a> (and my own experimentation), the only way to reliably update the GUI from a child thread is to use the <code>gobject.idle_add</code> function. However, it can't be guaranteed when this function will be called. How can I guarantee that the line following the <code>gobject.idle_add</code> gets called after the function it points to?</p> <p>Very simple and contrived example: <pre><code>import gtk import gobject from threading import Thread<br /> class Gui(object): def __init__(self): self.button = gtk.Button("Click") self.button.connect("clicked", self.onButtonClicked) self.textEntry = gtk.Entry() self.content = gtk.HBox() self.content.pack_start(self.button) self.content.pack_start(self.textEntry) self.window = gtk.Window() self.window.connect("destroy", self.quit) self.window.add(self.content) self.window.show_all()<br /> def onButtonClicked(self, button): Thread(target=self.startThread).start()<br /> def startThread(self): #I want these next 2 lines to run in order gobject.idle_add(self.updateText) print self.textEntry.get_text()<br /> def updateText(self): self.textEntry.set_text("Hello!")<br /> def quit(self, widget): gtk.main_quit()</p> <p>gobject.threads_init() x = Gui() gtk.main()</pre></code></p>
1
2009-06-17T16:56:41Z
1,008,365
<p>You could wrap the two functions into another function and call idle_add on this function:</p> <pre><code>def update_and_print(self): self.updateText() print self.textEntry.get_text() def startThread(self): gobject.idle_add(self.update_and_print) </code></pre>
1
2009-06-17T17:04:14Z
[ "python", "windows", "multithreading", "pygtk" ]
Execution order with threads and PyGTK on Windows
1,008,322
<p>I'm having issues with threads and PyGTK on Windows. According the the <a href="http://faq.pygtk.org/index.py?req=show&amp;file=faq21.003.htp" rel="nofollow">PyGTK FAQ</a> (and my own experimentation), the only way to reliably update the GUI from a child thread is to use the <code>gobject.idle_add</code> function. However, it can't be guaranteed when this function will be called. How can I guarantee that the line following the <code>gobject.idle_add</code> gets called after the function it points to?</p> <p>Very simple and contrived example: <pre><code>import gtk import gobject from threading import Thread<br /> class Gui(object): def __init__(self): self.button = gtk.Button("Click") self.button.connect("clicked", self.onButtonClicked) self.textEntry = gtk.Entry() self.content = gtk.HBox() self.content.pack_start(self.button) self.content.pack_start(self.textEntry) self.window = gtk.Window() self.window.connect("destroy", self.quit) self.window.add(self.content) self.window.show_all()<br /> def onButtonClicked(self, button): Thread(target=self.startThread).start()<br /> def startThread(self): #I want these next 2 lines to run in order gobject.idle_add(self.updateText) print self.textEntry.get_text()<br /> def updateText(self): self.textEntry.set_text("Hello!")<br /> def quit(self, widget): gtk.main_quit()</p> <p>gobject.threads_init() x = Gui() gtk.main()</pre></code></p>
1
2009-06-17T16:56:41Z
1,012,052
<p>Don't try to update or access your GUI from a thread. You're just asking for trouble. For example, the fact that "<code>get_text</code>" works <em>at all</em> in a thread is almost an accident. You might be able to rely on it in GTK - although I'm not even sure about that - but you won't be able to do so in other GUI toolkits.</p> <p>If you have things that really need doing in threads, you should get the data you need from the GUI <em>before</em> launching the thread, and then update the GUI from the thread by using <code>idle_add</code>, like this:</p> <pre><code>import time import gtk import gobject from threading import Thread w = gtk.Window() h = gtk.HBox() v = gtk.VBox() addend1 = gtk.Entry() h.add(addend1) h.add(gtk.Label(" + ")) addend2 = gtk.Entry() h.add(addend2) h.add(gtk.Label(" = ")) summation = gtk.Entry() summation.set_text("?") summation.set_editable(False) h.add(summation) v.add(h) progress = gtk.ProgressBar() v.add(progress) b = gtk.Button("Do It") v.add(b) w.add(v) status = gtk.Statusbar() v.add(status) w.show_all() def hardWork(a1, a2): messages = ["Doing the hard work to add %s to %s..." % (a1, a2), "Oof, I'm working so hard...", "Almost done..."] for index, message in enumerate(messages): fraction = index / float(len(messages)) gobject.idle_add(progress.set_fraction, fraction) gobject.idle_add(status.push, 4321, message) time.sleep(1) result = a1 + a2 gobject.idle_add(summation.set_text, str(result)) gobject.idle_add(status.push, 4321, "Done!") gobject.idle_add(progress.set_fraction, 1.0) def addthem(*ignored): a1 = int(addend1.get_text()) a2 = int(addend2.get_text()) Thread(target=lambda : hardWork(a1, a2)).start() b.connect("clicked", addthem) gtk.gdk.threads_init() gtk.main() </code></pre> <p>If you really, absolutely need to read data from the GUI in the middle of a thread (this is a really bad idea, don't do it - you can get into really surprising deadlocks, especially when the program is shutting down) there is a utility in Twisted, <a href="http://twistedmatrix.com/documents/8.2.0/api/twisted.internet.threads.html#blockingCallFromThread" rel="nofollow">blockingCallFromThread</a>, which will do the hard work for you. You can use it like this:</p> <pre><code>from twisted.internet.gtk2reactor import install install() from twisted.internet import reactor from twisted.internet.threads import blockingCallFromThread from threading import Thread import gtk w = gtk.Window() v = gtk.VBox() e = gtk.Entry() b = gtk.Button("Get Text") v.add(e) v.add(b) w.add(v) def inThread(): print 'Getting value' textValue = blockingCallFromThread(reactor, e.get_text) print 'Got it!', repr(textValue) def kickOffThread(*ignored): Thread(target=inThread).start() b.connect("clicked", kickOffThread) w.show_all() reactor.run() </code></pre> <p>If you want to see how the magic works, you can always <a href="http://twistedmatrix.com/trac/browser/trunk/twisted/internet/threads.py#L89" rel="nofollow">read the source</a>.</p>
2
2009-06-18T10:59:31Z
[ "python", "windows", "multithreading", "pygtk" ]
Name of file I'm editing
1,008,557
<p>I'm editing a file in ~/Documents. However, my working directory is somewhere else, say ~/Desktop.</p> <p>The file I'm editing is a Python script. I'm interested in doing a command like...</p> <p>:!python </p> <p>without needing to do</p> <p>:!python ~/Documents/script.py</p> <p>Is that possible? If so, what would be the command?</p> <p>Thank you.</p>
2
2009-06-17T17:45:14Z
1,008,586
<p>Try: !python %</p>
9
2009-06-17T17:48:58Z
[ "python", "vim" ]
Name of file I'm editing
1,008,557
<p>I'm editing a file in ~/Documents. However, my working directory is somewhere else, say ~/Desktop.</p> <p>The file I'm editing is a Python script. I'm interested in doing a command like...</p> <p>:!python </p> <p>without needing to do</p> <p>:!python ~/Documents/script.py</p> <p>Is that possible? If so, what would be the command?</p> <p>Thank you.</p>
2
2009-06-17T17:45:14Z
1,008,733
<p>I quite often map a key to do this for me. I usually use the F5 key as that has no command associated with it by default in vim.</p> <p>The mapping I like to use is:</p> <pre><code>:map &lt;F5&gt; :w&lt;CR&gt;:!python % 2&gt;&amp;1 \| tee /var/tmp/robertw/results&lt;CR&gt; </code></pre> <p>this will also make sure that you've written out your script before running it. It also captures any output, after duplicating stderr onto stdout, in a temp file.</p> <p>If you've done a:</p> <pre><code>:set autoread </code></pre> <p>and a:</p> <pre><code>:sb /var/tmp/robertw/results </code></pre> <p>you will finish up with two buffers being displayed. One containing the script and the other containing the output, incl. errors, from your script. By setting autoread the window displaying the output will be automatically loaded after pressing the v key.</p> <p>A trick to remember is to use cntl-ww to toggle between the windows and that the mapping, because it refers to % (the current file) will only work when the cursor is in the window containing the Python script.</p> <p>I find this really cuts down on my code, test, debug cycle time.</p>
6
2009-06-17T18:19:26Z
[ "python", "vim" ]
Lookup and combine data in Python
1,008,587
<p>I have 3 text files</p> <ol> <li>many lines of <code>value1&lt;tab&gt;value2</code> (maybe 600)</li> <li>many more lines of <code>value2&lt;tab&gt;value3</code> (maybe 1000)</li> <li>many more lines of <code>value2&lt;tab&gt;value4</code> (maybe 2000)</li> </ol> <p>Not all lines match, some will have one or more vals missing. I want to take file 1, read down it and lookup corresponding values in files 2 &amp; 3, and write the output as - for example</p> <pre><code>value1&lt;tab&gt;value2&lt;tab&gt;value3&lt;tab&gt;value4 value1&lt;tab&gt;value2&lt;tab&gt;blank &lt;tab&gt;value4 </code></pre> <p>i.e. indicate that the value is missing by printing a bit of text</p> <p>in awk I can BEGIN by reading the files into arrays up front then END and step through them. But I want to use Python (3) for portability. I do it on a pc using MS Access and linking tables but there is a time penalty for each time I use this method.</p> <p>All efforts to understand this in dictionaries or lists have confused me. I now seem to have every Python book!</p> <p>Many thanks to anyone who can offer advice. (if interested, it's arp, mac and vendor codes)</p>
1
2009-06-17T17:49:09Z
1,008,643
<p>Start with this.</p> <pre><code>def loadDictionaryFromAFile( aFile ): dictionary = {} for line in aFile: fields = line.split('\t') dictionary[fields[0]]= fields dict2 = loadDictionaryFromAFile( open("file2","r" ) dict3 = loadDictionaryFromAFile( open("file3","r" ) for line in open("file1","r"): fields = line.split("/t") d2= dict2.get( fields[0], None ) d3= dict3.get( fields[0], None ) print fields, d2, d3 </code></pre> <p>You may want to customize it to change the formatting of the output.</p>
3
2009-06-17T18:00:45Z
[ "python", "string", "file" ]
Lookup and combine data in Python
1,008,587
<p>I have 3 text files</p> <ol> <li>many lines of <code>value1&lt;tab&gt;value2</code> (maybe 600)</li> <li>many more lines of <code>value2&lt;tab&gt;value3</code> (maybe 1000)</li> <li>many more lines of <code>value2&lt;tab&gt;value4</code> (maybe 2000)</li> </ol> <p>Not all lines match, some will have one or more vals missing. I want to take file 1, read down it and lookup corresponding values in files 2 &amp; 3, and write the output as - for example</p> <pre><code>value1&lt;tab&gt;value2&lt;tab&gt;value3&lt;tab&gt;value4 value1&lt;tab&gt;value2&lt;tab&gt;blank &lt;tab&gt;value4 </code></pre> <p>i.e. indicate that the value is missing by printing a bit of text</p> <p>in awk I can BEGIN by reading the files into arrays up front then END and step through them. But I want to use Python (3) for portability. I do it on a pc using MS Access and linking tables but there is a time penalty for each time I use this method.</p> <p>All efforts to understand this in dictionaries or lists have confused me. I now seem to have every Python book!</p> <p>Many thanks to anyone who can offer advice. (if interested, it's arp, mac and vendor codes)</p>
1
2009-06-17T17:49:09Z
1,008,647
<p>Untested:</p> <pre><code>f1 = open("file1.txt") f2 = open("file2.txt") f3 = open("file3.txt") v1 = [line.split() for line in f1] # dict comprehensions following, these need Python 3 v2 = {vals[0]:vals[1] for vals in line.split() for line in f2} v3 = {vals[0]:vals[1] for vals in line.split() for line in f3} for v in v1: print( v[0] + "\t" + v[1] + "\t" + v2.get(v[1],"blank ") + "\t" + v3.get(v[1],"blank ") ) </code></pre>
5
2009-06-17T18:01:14Z
[ "python", "string", "file" ]
Popen.communicate() throws OSError: "[Errno 10] No child processes"
1,008,858
<p>I'm trying to start up a child process and get its output on Linux from Python using the subprocess module:</p> <pre><code>#!/usr/bin/python2.4 import subprocess p = subprocess.Popen(['ls', '-l', '/etc'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() </code></pre> <p>However, I experience some flakiness: sometimes, p.communicate() would throw </p> <pre><code>OSError: [Errno 10] No child processes </code></pre> <p>What can cause this exception? Is there any non-determinism or race condition here that can cause flakiness?</p>
8
2009-06-17T18:40:15Z
1,009,382
<p>You might be running into the bug mentioned here: <a href="http://bugs.python.org/issue1731717" rel="nofollow">http://bugs.python.org/issue1731717</a></p>
3
2009-06-17T20:32:03Z
[ "python", "linux" ]
Popen.communicate() throws OSError: "[Errno 10] No child processes"
1,008,858
<p>I'm trying to start up a child process and get its output on Linux from Python using the subprocess module:</p> <pre><code>#!/usr/bin/python2.4 import subprocess p = subprocess.Popen(['ls', '-l', '/etc'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() </code></pre> <p>However, I experience some flakiness: sometimes, p.communicate() would throw </p> <pre><code>OSError: [Errno 10] No child processes </code></pre> <p>What can cause this exception? Is there any non-determinism or race condition here that can cause flakiness?</p>
8
2009-06-17T18:40:15Z
1,198,166
<p>I'm not able to reproduce this on my Python (2.4.6-1ubuntu3). How are you running your script? How often does this occur?</p>
0
2009-07-29T05:18:29Z
[ "python", "linux" ]
Popen.communicate() throws OSError: "[Errno 10] No child processes"
1,008,858
<p>I'm trying to start up a child process and get its output on Linux from Python using the subprocess module:</p> <pre><code>#!/usr/bin/python2.4 import subprocess p = subprocess.Popen(['ls', '-l', '/etc'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() </code></pre> <p>However, I experience some flakiness: sometimes, p.communicate() would throw </p> <pre><code>OSError: [Errno 10] No child processes </code></pre> <p>What can cause this exception? Is there any non-determinism or race condition here that can cause flakiness?</p>
8
2009-06-17T18:40:15Z
2,321,095
<p>I ran into this problem using Python 2.6.4 which I built into my home directory (because I don't want to upgrade the "built-in" Python on the machine).</p> <p>I worked around it by replacing <code>subprocess.Popen()</code> with (the deprecated) <code>os.popen3()</code>.</p>
0
2010-02-23T19:35:22Z
[ "python", "linux" ]
Popen.communicate() throws OSError: "[Errno 10] No child processes"
1,008,858
<p>I'm trying to start up a child process and get its output on Linux from Python using the subprocess module:</p> <pre><code>#!/usr/bin/python2.4 import subprocess p = subprocess.Popen(['ls', '-l', '/etc'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() </code></pre> <p>However, I experience some flakiness: sometimes, p.communicate() would throw </p> <pre><code>OSError: [Errno 10] No child processes </code></pre> <p>What can cause this exception? Is there any non-determinism or race condition here that can cause flakiness?</p>
8
2009-06-17T18:40:15Z
3,837,851
<p>Are you intercepting SIGCHLD in the script? If you are then Popen will not run as expected since it relies on it's own handler for that signal. </p> <p>You can check for SIGCHLD handlers by commenting out the Popen call and then running:</p> <pre><code>strace python &lt;your_script.py&gt; | grep SIGCHLD </code></pre> <p>if you see something similar to:</p> <pre><code>rt_sigaction(SIGCHLD, ...) </code></pre> <p>then, you are in trouble. You need to disable the handler prior to calling Popen and then resetting it after communicate is done (this might introduce a race conditions so beware). </p> <pre><code>signal.signal(SIGCHLD, handler) ... signal.signal(SIGCHLD, signal.SIG_DFL) ''' now you can go wild with Popen. WARNING!!! during this time no signals will be delivered to handler ''' ... signal.signal(SIGCHLD, handler) </code></pre> <p>There is a python bug reported on this and as far as I see it hasn't been resolved yet:</p> <p><a href="http://bugs.python.org/issue9127">http://bugs.python.org/issue9127</a></p> <p>Hope that helps.</p>
6
2010-10-01T09:16:34Z
[ "python", "linux" ]
Processing pairs of values from two sequences in Clojure
1,009,037
<p>I'm trying to get into the Clojure community. I've been working a lot with Python, and one of the features I make extensive use of is the zip() method, for iterating over pairs of values. Is there a (clever and short) way of achieving the same in Clojure?</p>
8
2009-06-17T19:20:23Z
1,009,078
<pre><code>(zipmap [:a :b :c] (range 3)) -&gt; {:c 2, :b 1, :a 0} </code></pre> <p>Iterating over maps happens pairwise, e.g. like this:</p> <pre><code>(doseq [[k v] (zipmap [:a :b :c] (range 3))] (printf "key: %s, value: %s\n" k v)) </code></pre> <p>prints:</p> <pre><code>key: :c, value: 2 key: :b, value: 1 key: :a, value: 0 </code></pre>
4
2009-06-17T19:30:16Z
[ "python", "clojure", "zip" ]
Processing pairs of values from two sequences in Clojure
1,009,037
<p>I'm trying to get into the Clojure community. I've been working a lot with Python, and one of the features I make extensive use of is the zip() method, for iterating over pairs of values. Is there a (clever and short) way of achieving the same in Clojure?</p>
8
2009-06-17T19:20:23Z
1,009,096
<p>Another way is to simply use map together with some function that collects its arguments in a sequence, like this:</p> <pre><code>user=&gt; (map vector '(1 2 3) "abc") ([1 \a] [2 \b] [3 \c]) </code></pre>
12
2009-06-17T19:34:06Z
[ "python", "clojure", "zip" ]
Processing pairs of values from two sequences in Clojure
1,009,037
<p>I'm trying to get into the Clojure community. I've been working a lot with Python, and one of the features I make extensive use of is the zip() method, for iterating over pairs of values. Is there a (clever and short) way of achieving the same in Clojure?</p>
8
2009-06-17T19:20:23Z
1,016,876
<p>The question has been answered, but there's still <code>interleave</code>, which also handles an arbitrary number of sequences, but does not group the resulting sequence into tuples (but you can use <code>partition</code> for that).</p>
3
2009-06-19T08:16:43Z
[ "python", "clojure", "zip" ]
Obtaining financial data from Google Finance which is outside the scope of the API
1,009,524
<p>Google's finance API is incomplete -- many of the figures on a page such as:</p> <p><a href="http://www.google.com/finance?fstype=ii&amp;q=NYSE:GE" rel="nofollow">http://www.google.com/finance?fstype=ii&amp;q=NYSE:GE</a></p> <p>are not available via the API. </p> <p>I need this data to rank companies on Canadian stock exchanges according to the formula of Greenblatt, available via google search for "greenblatt index scans".</p> <p>My question: what is the most intelligent/clean/efficient way of accessing and processing the data on these webpages. Is the tedious approach really necessary in this case, and if so, what is the best way of going about it? I'm currently learning Python for projects related to this one. </p>
5
2009-06-17T21:07:00Z
1,009,573
<p>Scraping web pages always sucks, but I would recommend converting them to xml (via tidy or some other HTML -> XML program) and then using xpath to walk the nodes that you are interested in.</p>
0
2009-06-17T21:20:17Z
[ "python", "api", "data-mining", "google-finance" ]
Obtaining financial data from Google Finance which is outside the scope of the API
1,009,524
<p>Google's finance API is incomplete -- many of the figures on a page such as:</p> <p><a href="http://www.google.com/finance?fstype=ii&amp;q=NYSE:GE" rel="nofollow">http://www.google.com/finance?fstype=ii&amp;q=NYSE:GE</a></p> <p>are not available via the API. </p> <p>I need this data to rank companies on Canadian stock exchanges according to the formula of Greenblatt, available via google search for "greenblatt index scans".</p> <p>My question: what is the most intelligent/clean/efficient way of accessing and processing the data on these webpages. Is the tedious approach really necessary in this case, and if so, what is the best way of going about it? I'm currently learning Python for projects related to this one. </p>
5
2009-06-17T21:07:00Z
1,009,673
<p><a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">BeautifulSoup</a> would be the preferred method of HTML parsing with Python</p> <p>Have you looked into options besides Google (e.g. Yahoo Finance API)?</p>
3
2009-06-17T21:42:24Z
[ "python", "api", "data-mining", "google-finance" ]
Obtaining financial data from Google Finance which is outside the scope of the API
1,009,524
<p>Google's finance API is incomplete -- many of the figures on a page such as:</p> <p><a href="http://www.google.com/finance?fstype=ii&amp;q=NYSE:GE" rel="nofollow">http://www.google.com/finance?fstype=ii&amp;q=NYSE:GE</a></p> <p>are not available via the API. </p> <p>I need this data to rank companies on Canadian stock exchanges according to the formula of Greenblatt, available via google search for "greenblatt index scans".</p> <p>My question: what is the most intelligent/clean/efficient way of accessing and processing the data on these webpages. Is the tedious approach really necessary in this case, and if so, what is the best way of going about it? I'm currently learning Python for projects related to this one. </p>
5
2009-06-17T21:07:00Z
1,010,083
<p>You could try asking Google to provide the missing APIs. Otherwise, you're stuck with <a href="http://en.wikipedia.org/wiki/Screen_scraping" rel="nofollow">screen scraping</a>, which is never fun, prone to breaking without notice, and <strong>likely in violation of Google's terms of service</strong>.</p> <p>But, if you still want to write a screen scraper, it's hard to beat a combination of <a href="http://wwwsearch.sourceforge.net/mechanize/" rel="nofollow">mechanize</a> and <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">BeautifulSoup</a>. BeautifulSoup is an HTML parser and mechanize is a Python-based web browser that will let you log in, store cookies, and generally navigate around like any other web browser. </p>
4
2009-06-17T23:55:59Z
[ "python", "api", "data-mining", "google-finance" ]
Output 2 dim array 'list of lists" to text file in python
1,009,712
<p>Simple question - I am creating a two dim array (<code>ddist = [[0]*d for _ in [0]*d]</code>) using lists in the code below. It outputs distance using gis data. I just want a simple way to take the result of my array/list and output to a text file keeping the same N*N structure. I have used output from print statements in the past but not a good solution in this case. </p> <p>I am new to python by way of SAS. </p> <pre><code>def match_bg(): #as the name suggests this function will match the variations of blockgroups with grid travel time. Then output into two arras time and distance. count = -1 countwo = -1 ctime = -1 ddist = [[0]*d for _ in [0]*d] #cratesan N*N array list dtime = -1 while count &lt; 10: count = count +1 #j[count][7] = float(j[count][7]) #j[count][6] = float(j[count][6]) while countwo &lt; d: countwo = countwo+1 if count &lt; 1: #change values in bg file j[countwo][7] = float(j[countwo][7]) j[countwo][6] = float(j[countwo][6]) #print j[count], j[countwo] while ctime &lt; RowsT: #print ctime, lenth, t[ctime][0], count, countwo ctime = ctime + 1 #takes both verations of big zone which should be end of the file and matches to travetime file - note 0 and 1 for t[] should be same for different files if ((j[count][lenth-1] == t[ctime][0]) and (j[countwo][lenth-1] == t[ctime][1])) or ((j[countwo][lenth-1] == t[ctime][0]) and (j[count][lenth-1] == t[ctime][1])): if t[ctime][0] != t[ctime][1]: #jkdljf x1=3963*j[count][7]*(math.pi/180) x2=3963*j[countwo][7]*(math.pi/180) y1=math.cos(j[count][6]*math.pi/180)*3963*j[count][7]*(math.pi/180) y2=math.cos(j[countwo][6]*math.pi/180)*3963*j[countwo][7]*(math.pi/180) dist=math.sqrt(pow(( x1-x2), 2) + pow((y1-y2), 2)) dtime = dist/t[ctime][11] print countwo, count ddist[count-1][countwo-1] = dist/t[ctime][lenth] print dtime, "ajusted time", "not same grid" print elif j[count][5] != j[countwo][5]: #ljdkjfs x1=3963*j[count][7]*(math.pi/180) x2=3963*j[countwo][7]*(math.pi/180) y1=math.cos(j[count][6]*math.pi/180)*3963*j[count][7]*(math.pi/180) y2=math.cos(j[countwo][6]*math.pi/180)*3963*j[countwo][7]*(math.pi/180) dist=math.sqrt(pow(( x1-x2), 2) + pow((y1-y2), 2)) # could change to calculation dtime = (dist/.65)/(t[ctime][10]/60.0) print dtime, dist, "not in the same bg", j[count], j[countwo], t[ctime] elif j[count][5] == j[countwo][5]: if t[count][7] &lt; 3000000: dtime = 3 elif t[count][7] &lt; 20000000: dtime = 8 else: dtime = 12 print dtime, "same bg" print t[ctime][0], t[ctime], 1, j[count], j[countwo] else: print "error is skip logic", j[count], j[countwo], t[ctime] break #elif (j[countwo][lenth-1] == t[ctime][0]) and (j[count][lenth-1] == t[ctime][1]): #print t[ctime][0], t[ctime], 2, j[count], j[countwo] #break ctime = -1 countwo = -1 </code></pre>
1
2009-06-17T21:49:26Z
1,009,764
<p>that's what you could to output your 2-d list (or any 2d list for that matter):</p> <pre><code>with open(outfile, 'w') as file: file.writelines('\t'.join(str(j) for j in i) + '\n' for i in top_list) </code></pre>
2
2009-06-17T22:05:40Z
[ "python", "list", "text" ]
Timestamp conversion is off by an hour
1,009,812
<p>I'm trying to parse a twitter feed in django, and I'm having a strange problem converting the published time:</p> <p>I've got the time from the feed into a full 9-tuple correctly:</p> <pre><code>&gt;&gt; print tweet_time time.struct_time(tm_year=2009, tm_mon=6, tm_mday=17, tm_hour=14, tm_min=35, tm_sec=28, tm_wday=2, tm_yday=168, tm_isdst=0) </code></pre> <p>But when I call this:</p> <pre><code>tweet_time = datetime.fromtimestamp(time.mktime(tweet_time)) </code></pre> <p>I end up with the a time 1 hour ahead:</p> <pre><code>&gt;&gt; print tweet_time 2009-06-17 15:35:28 </code></pre> <p>What am I missing here?</p>
2
2009-06-17T22:22:35Z
1,009,828
<p>try flipping the isdst (is daylight savings flag) to a -1 and see if that fixes it. -1 tells it to use (guess) the local daylight savings setting and roll with that. </p>
5
2009-06-17T22:26:28Z
[ "python", "django", "datetime", "time" ]
How to embed some application window in my application using any Python GUI framework
1,009,813
<p>I want some application to look like widget inside my Python application.</p> <p>That's all. I dont need any interaction between them. I'm interested in solutions in <strong>any</strong> GUI toolkit for both windows and x windows.</p> <p>It would be nice to have a solution with Tkinter but it's not crucial.</p>
5
2009-06-17T22:22:44Z
1,009,942
<p>Using GTK on X windows (i.e. Linux, FreeBSD, Solaris), you can use the XEMBED protocol to embed widgets using <a href="http://www.pygtk.org/docs/pygtk/class-gtksocket.html"><code>gtk.Socket</code></a>. Unfortunately, the application that you're launching has to explicitly support it so that you can tell it to embed itself. Some applications don't support this. Notably, I can't find a way to do it with Firefox.</p> <p>Nonetheless, here's a sample program that will run either an X terminal or an Emacs session inside a GTK window:</p> <pre><code>import os import gtk from gtk import Socket, Button, Window, VBox, HBox w = Window() e = Button("Emacs") x = Button("XTerm") s = Socket() v = VBox() h = HBox() w.add(v) v.add(s) h.add(e) h.add(x) v.pack_start(h, expand=False) def runemacs(btn): x.set_sensitive(False); e.set_sensitive(False) os.spawnlp(os.P_NOWAIT, "emacs", "emacs", "--parent-id", str(s.get_id())) def runxterm(btn): x.set_sensitive(False); e.set_sensitive(False) os.spawnlp(os.P_NOWAIT, "xterm", "xterm", "-into", str(s.get_id())) e.connect('clicked', runemacs) x.connect('clicked', runxterm) w.show_all() gtk.main() </code></pre>
5
2009-06-17T23:01:29Z
[ "python", "user-interface" ]
Using string as variable name
1,009,831
<p>Is there any way for me to use a string to call a method of a class? Here's an example that will hopefully explain better (using the way I think it should be):</p> <pre><code>class helloworld(): def world(self): print "Hello World!" str = "world" hello = helloworld() hello.`str`() </code></pre> <p>Which would output <code>Hello World!</code>.</p> <p>Thanks in advance.</p>
6
2009-06-17T22:27:22Z
1,009,837
<p>You can use <a href="http://docs.python.org/3.0/library/functions.html#getattr"><code>getattr</code></a>:</p> <pre><code>&gt;&gt;&gt; class helloworld: ... def world(self): ... print("Hello World!") ... &gt;&gt;&gt; m = "world" &gt;&gt;&gt; hello = helloworld() &gt;&gt;&gt; getattr(hello, m)() Hello World! </code></pre> <ul> <li>Note that the parens in <code>class helloworld()</code> as in your example are unnecessary, in this case.</li> <li>And, as <a href="http://stackoverflow.com/users/12855/silentghost">SilentGhost</a> points out, <a href="http://docs.python.org/3.0/library/functions.html#str"><code>str</code></a> is an unfortunate name for a variable.</li> </ul>
16
2009-06-17T22:31:03Z
[ "python" ]
Using string as variable name
1,009,831
<p>Is there any way for me to use a string to call a method of a class? Here's an example that will hopefully explain better (using the way I think it should be):</p> <pre><code>class helloworld(): def world(self): print "Hello World!" str = "world" hello = helloworld() hello.`str`() </code></pre> <p>Which would output <code>Hello World!</code>.</p> <p>Thanks in advance.</p>
6
2009-06-17T22:27:22Z
1,009,848
<p>one way is you can set variables to be equal to functions just like data</p> <pre><code>def thing1(): print "stuff" def thing2(): print "other stuff" avariable = thing1 avariable () avariable = thing2 avariable () </code></pre> <p>And the output you'l get is </p> <pre><code>stuff other stuff </code></pre> <p>Then you can get more complicated and have</p> <pre><code>somedictionary["world"] = world somedictionary["anotherfunction"] = anotherfunction </code></pre> <p>and so on. If you want to automatically compile a modules methods into the dictionary use dir()</p>
-3
2009-06-17T22:33:33Z
[ "python" ]
Using string as variable name
1,009,831
<p>Is there any way for me to use a string to call a method of a class? Here's an example that will hopefully explain better (using the way I think it should be):</p> <pre><code>class helloworld(): def world(self): print "Hello World!" str = "world" hello = helloworld() hello.`str`() </code></pre> <p>Which would output <code>Hello World!</code>.</p> <p>Thanks in advance.</p>
6
2009-06-17T22:27:22Z
1,009,862
<p><em>Warning: exec is a dangerous function to use, study it before using it</em></p> <p>You can also use the built-in function "exec":</p> <pre><code>&gt;&gt;&gt; def foo(): print('foo was called'); ... &gt;&gt;&gt; some_string = 'foo'; &gt;&gt;&gt; exec(some_string + '()'); foo was called &gt;&gt;&gt; </code></pre>
2
2009-06-17T22:38:55Z
[ "python" ]
Using string as variable name
1,009,831
<p>Is there any way for me to use a string to call a method of a class? Here's an example that will hopefully explain better (using the way I think it should be):</p> <pre><code>class helloworld(): def world(self): print "Hello World!" str = "world" hello = helloworld() hello.`str`() </code></pre> <p>Which would output <code>Hello World!</code>.</p> <p>Thanks in advance.</p>
6
2009-06-17T22:27:22Z
1,009,894
<p>What you're looking for is <a href="http://www.python.org/doc/2.5.2/ref/exec.html" rel="nofollow">exec</a></p> <pre><code>class helloworld(): def world(self): print "Hello World!" str = "world" hello = helloworld() completeString = "hello.%s()" % str exec(completString) </code></pre>
-3
2009-06-17T22:45:19Z
[ "python" ]
Command Line Arguments In Python
1,009,860
<p>I am originally a C programmer. I have seen numerous tricks and "hacks" to read many different arguments. </p> <p>What are some of the ways Python programmers can do this?</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/20063/whats-the-best-way-to-grab-parse-command-line-arguments-passed-to-a-python-scrip">What’s the best way to grab/parse command line arguments passed to a Python script?</a></li> <li><a href="http://stackoverflow.com/questions/362426/implementing-a-command-action-parameter-style-command-line-interfaces">Implementing a “[command] [action] [parameter]” style command-line interfaces?</a></li> <li><a href="http://stackoverflow.com/questions/567879/how-can-i-process-command-line-arguments-in-python">How can I process command line arguments in Python?</a></li> <li><a href="http://stackoverflow.com/questions/642648/how-do-i-format-positional-argument-help-using-pythons-optparse">How do I format positional argument help using Python’s optparse?</a></li> </ul>
269
2009-06-17T22:38:30Z
1,009,864
<h2><em>Please</em> note that optparse was deprecated in version 2.7 of Python:</h2> <p><a href="http://docs.python.org/2/library/optparse.html">http://docs.python.org/2/library/optparse.html</a>. <strong>argparse</strong> is the replacement: <a href="http://docs.python.org/2/library/argparse.html#module-argparse">http://docs.python.org/2/library/argparse.html#module-argparse</a></p> <hr> <p>There are the following modules in the standard library:</p> <ul> <li>The <a href="http://docs.python.org/library/getopt.html">getopt</a> module is similar to GNU getopt.</li> <li>The <a href="http://docs.python.org/library/optparse.html#module-optparse">optparse</a> module offers object-oriented command line option parsing. </li> </ul> <p>Here is an example that uses the latter from the docs:</p> <pre><code>from optparse import OptionParser parser = OptionParser() parser.add_option("-f", "--file", dest="filename", help="write report to FILE", metavar="FILE") parser.add_option("-q", "--quiet", action="store_false", dest="verbose", default=True, help="don't print status messages to stdout") (options, args) = parser.parse_args() </code></pre> <p>optparse supports (among other things):</p> <ul> <li>Multiple options in any order.</li> <li>Short and long options.</li> <li>Default values.</li> <li>Generation of a usage help message.</li> </ul>
200
2009-06-17T22:39:49Z
[ "python", "command-line", "command-line-arguments" ]
Command Line Arguments In Python
1,009,860
<p>I am originally a C programmer. I have seen numerous tricks and "hacks" to read many different arguments. </p> <p>What are some of the ways Python programmers can do this?</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/20063/whats-the-best-way-to-grab-parse-command-line-arguments-passed-to-a-python-scrip">What’s the best way to grab/parse command line arguments passed to a Python script?</a></li> <li><a href="http://stackoverflow.com/questions/362426/implementing-a-command-action-parameter-style-command-line-interfaces">Implementing a “[command] [action] [parameter]” style command-line interfaces?</a></li> <li><a href="http://stackoverflow.com/questions/567879/how-can-i-process-command-line-arguments-in-python">How can I process command line arguments in Python?</a></li> <li><a href="http://stackoverflow.com/questions/642648/how-do-i-format-positional-argument-help-using-pythons-optparse">How do I format positional argument help using Python’s optparse?</a></li> </ul>
269
2009-06-17T22:38:30Z
1,009,879
<pre><code>import sys print "\n".join(sys.argv) </code></pre> <p><code>sys.argv</code> is a list that contains all the arguments passed to the script on the command line.</p> <p>Basically,</p> <pre><code>import sys print sys.argv[1:] </code></pre>
233
2009-06-17T22:42:25Z
[ "python", "command-line", "command-line-arguments" ]
Command Line Arguments In Python
1,009,860
<p>I am originally a C programmer. I have seen numerous tricks and "hacks" to read many different arguments. </p> <p>What are some of the ways Python programmers can do this?</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/20063/whats-the-best-way-to-grab-parse-command-line-arguments-passed-to-a-python-scrip">What’s the best way to grab/parse command line arguments passed to a Python script?</a></li> <li><a href="http://stackoverflow.com/questions/362426/implementing-a-command-action-parameter-style-command-line-interfaces">Implementing a “[command] [action] [parameter]” style command-line interfaces?</a></li> <li><a href="http://stackoverflow.com/questions/567879/how-can-i-process-command-line-arguments-in-python">How can I process command line arguments in Python?</a></li> <li><a href="http://stackoverflow.com/questions/642648/how-do-i-format-positional-argument-help-using-pythons-optparse">How do I format positional argument help using Python’s optparse?</a></li> </ul>
269
2009-06-17T22:38:30Z
1,009,882
<p>One way to do it is using <code>sys.argv</code>. This will print the script name as the first argument and all the other parameters that you pass to it.</p> <pre><code>import sys for arg in sys.argv: print arg </code></pre>
31
2009-06-17T22:43:08Z
[ "python", "command-line", "command-line-arguments" ]
Command Line Arguments In Python
1,009,860
<p>I am originally a C programmer. I have seen numerous tricks and "hacks" to read many different arguments. </p> <p>What are some of the ways Python programmers can do this?</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/20063/whats-the-best-way-to-grab-parse-command-line-arguments-passed-to-a-python-scrip">What’s the best way to grab/parse command line arguments passed to a Python script?</a></li> <li><a href="http://stackoverflow.com/questions/362426/implementing-a-command-action-parameter-style-command-line-interfaces">Implementing a “[command] [action] [parameter]” style command-line interfaces?</a></li> <li><a href="http://stackoverflow.com/questions/567879/how-can-i-process-command-line-arguments-in-python">How can I process command line arguments in Python?</a></li> <li><a href="http://stackoverflow.com/questions/642648/how-do-i-format-positional-argument-help-using-pythons-optparse">How do I format positional argument help using Python’s optparse?</a></li> </ul>
269
2009-06-17T22:38:30Z
1,010,367
<p>I like getopt from stdlib, eg:</p> <pre><code>try: opts, args = getopt.getopt(sys.argv[1:], 'h', ['help']) except getopt.GetoptError, err: usage(err) for opt, arg in opts: if opt in ('-h', '--help'): usage() if len(args) != 1: usage("specify thing...") </code></pre> <p>Lately I have been wrapping something similiar to this to make things less verbose (eg; making "-h" implicit).</p>
4
2009-06-18T01:30:28Z
[ "python", "command-line", "command-line-arguments" ]
Command Line Arguments In Python
1,009,860
<p>I am originally a C programmer. I have seen numerous tricks and "hacks" to read many different arguments. </p> <p>What are some of the ways Python programmers can do this?</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/20063/whats-the-best-way-to-grab-parse-command-line-arguments-passed-to-a-python-scrip">What’s the best way to grab/parse command line arguments passed to a Python script?</a></li> <li><a href="http://stackoverflow.com/questions/362426/implementing-a-command-action-parameter-style-command-line-interfaces">Implementing a “[command] [action] [parameter]” style command-line interfaces?</a></li> <li><a href="http://stackoverflow.com/questions/567879/how-can-i-process-command-line-arguments-in-python">How can I process command line arguments in Python?</a></li> <li><a href="http://stackoverflow.com/questions/642648/how-do-i-format-positional-argument-help-using-pythons-optparse">How do I format positional argument help using Python’s optparse?</a></li> </ul>
269
2009-06-17T22:38:30Z
1,010,597
<p>There is also <a href="https://docs.python.org/library/argparse.html" rel="nofollow"><code>argparse</code> stdlib module</a> (an "impovement" on stdlib's <code>optparse</code> module). Example from <a href="https://docs.python.org/howto/argparse.html" rel="nofollow">the introduction to argparse</a>:</p> <pre><code># script.py import argparse if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( 'integers', metavar='int', type=int, choices=range(10), nargs='+', help='an integer in the range 0..9') parser.add_argument( '--sum', dest='accumulate', action='store_const', const=sum, default=max, help='sum the integers (default: find the max)') args = parser.parse_args() print(args.accumulate(args.integers)) </code></pre> <p>Usage:</p> <pre><code>$ script.py 1 2 3 4 4 $ script.py --sum 1 2 3 4 10 </code></pre>
34
2009-06-18T03:12:25Z
[ "python", "command-line", "command-line-arguments" ]
Command Line Arguments In Python
1,009,860
<p>I am originally a C programmer. I have seen numerous tricks and "hacks" to read many different arguments. </p> <p>What are some of the ways Python programmers can do this?</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/20063/whats-the-best-way-to-grab-parse-command-line-arguments-passed-to-a-python-scrip">What’s the best way to grab/parse command line arguments passed to a Python script?</a></li> <li><a href="http://stackoverflow.com/questions/362426/implementing-a-command-action-parameter-style-command-line-interfaces">Implementing a “[command] [action] [parameter]” style command-line interfaces?</a></li> <li><a href="http://stackoverflow.com/questions/567879/how-can-i-process-command-line-arguments-in-python">How can I process command line arguments in Python?</a></li> <li><a href="http://stackoverflow.com/questions/642648/how-do-i-format-positional-argument-help-using-pythons-optparse">How do I format positional argument help using Python’s optparse?</a></li> </ul>
269
2009-06-17T22:38:30Z
1,010,728
<p>I use optparse myself, but really like the direction Simon Willison is taking with his recently introduced <a href="http://github.com/simonw/optfunc/tree/master">optfunc</a> library. It works by:</p> <blockquote> <p>"introspecting a function definition (including its arguments and their default values) and using that to construct a command line argument parser."</p> </blockquote> <p>So, for example, this function definition:</p> <pre><code>def geocode(s, api_key='', geocoder='google', list_geocoders=False): </code></pre> <p>is turned into this optparse help text:</p> <pre><code> Options: -h, --help show this help message and exit -l, --list-geocoders -a API_KEY, --api-key=API_KEY -g GEOCODER, --geocoder=GEOCODER </code></pre>
16
2009-06-18T04:07:57Z
[ "python", "command-line", "command-line-arguments" ]
Command Line Arguments In Python
1,009,860
<p>I am originally a C programmer. I have seen numerous tricks and "hacks" to read many different arguments. </p> <p>What are some of the ways Python programmers can do this?</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/20063/whats-the-best-way-to-grab-parse-command-line-arguments-passed-to-a-python-scrip">What’s the best way to grab/parse command line arguments passed to a Python script?</a></li> <li><a href="http://stackoverflow.com/questions/362426/implementing-a-command-action-parameter-style-command-line-interfaces">Implementing a “[command] [action] [parameter]” style command-line interfaces?</a></li> <li><a href="http://stackoverflow.com/questions/567879/how-can-i-process-command-line-arguments-in-python">How can I process command line arguments in Python?</a></li> <li><a href="http://stackoverflow.com/questions/642648/how-do-i-format-positional-argument-help-using-pythons-optparse">How do I format positional argument help using Python’s optparse?</a></li> </ul>
269
2009-06-17T22:38:30Z
1,050,472
<p>Just going around evangelizing for <a href="http://code.google.com/p/argparse/">argparse</a> which is better for <a href="http://argparse.googlecode.com/svn/trunk/doc/argparse-vs-optparse.html">these</a> reasons.. essentially:</p> <p><em>(copied from the link)</em></p> <ul> <li><p>argparse module can handle positional and optional arguments, while optparse can handle only optional arguments</p></li> <li><p>argparse isn’t dogmatic about what your command line interface should look like - options like -file or /file are supported, as are required options. Optparse refuses to support these features, preferring purity over practicality</p></li> <li><p>argparse produces more informative usage messages, including command-line usage determined from your arguments, and help messages for both positional and optional arguments. The optparse module requires you to write your own usage string, and has no way to display help for positional arguments.</p></li> <li><p>argparse supports action that consume a variable number of command-line args, while optparse requires that the exact number of arguments (e.g. 1, 2, or 3) be known in advance</p></li> <li><p>argparse supports parsers that dispatch to sub-commands, while optparse requires setting <code>allow_interspersed_args</code> and doing the parser dispatch manually</p></li> </ul> <p>And my personal favorite:</p> <ul> <li>argparse allows the type and action parameters to <code>add_argument()</code> to be specified with simple callables, while optparse requires hacking class attributes like <code>STORE_ACTIONS</code> or <code>CHECK_METHODS</code> to get proper argument checking</li> </ul>
102
2009-06-26T18:15:02Z
[ "python", "command-line", "command-line-arguments" ]
Command Line Arguments In Python
1,009,860
<p>I am originally a C programmer. I have seen numerous tricks and "hacks" to read many different arguments. </p> <p>What are some of the ways Python programmers can do this?</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/20063/whats-the-best-way-to-grab-parse-command-line-arguments-passed-to-a-python-scrip">What’s the best way to grab/parse command line arguments passed to a Python script?</a></li> <li><a href="http://stackoverflow.com/questions/362426/implementing-a-command-action-parameter-style-command-line-interfaces">Implementing a “[command] [action] [parameter]” style command-line interfaces?</a></li> <li><a href="http://stackoverflow.com/questions/567879/how-can-i-process-command-line-arguments-in-python">How can I process command line arguments in Python?</a></li> <li><a href="http://stackoverflow.com/questions/642648/how-do-i-format-positional-argument-help-using-pythons-optparse">How do I format positional argument help using Python’s optparse?</a></li> </ul>
269
2009-06-17T22:38:30Z
4,915,576
<p>You may be interested in a little Python module I wrote to make handling of command line arguments even easier (open source and free to use) - <a href="http://freshmeat.net/projects/commando" rel="nofollow">Commando</a></p>
4
2011-02-06T19:28:43Z
[ "python", "command-line", "command-line-arguments" ]