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 |
|---|---|---|---|---|---|---|---|---|---|
Converting from mod_python to mod_wsgi
| 644,767
|
<p>My website is written in Python and currently runs under mod_python with Apache. Lately I've had to put in a few ugly hacks that make me think it might be worth converting the site to mod_wsgi. But I've gotten used to using some of mod_python's utility classes, especially <code>FieldStorage</code> and <code>Session</code> (and sometimes <code>Cookie</code>), and from a scan of <a href="http://www.python.org/dev/peps/pep-0333/">PEP 333</a>, I don't see any equivalents to these. (Not surprising, because I understand that those kinds of utilities don't belong in the WSGI spec)</p>
<p>Question is, are there "standard" (i.e. commonly accepted) replacements for these mod_python utility classes that I can use in WSGI, or could I/should I write my own?</p>
<p>(FYI: currently using Python 2.5)</p>
| 11
|
2009-03-13T21:56:15Z
| 644,774
|
<p>Look at <a href="http://werkzeug.pocoo.org/">Werkzeug</a>. You may have to do some rewriting. You will probably be pleased with the results of imposing the WSGI world-view on your application.</p>
| 9
|
2009-03-13T22:00:40Z
|
[
"python",
"mod-wsgi",
"mod-python"
] |
Converting from mod_python to mod_wsgi
| 644,767
|
<p>My website is written in Python and currently runs under mod_python with Apache. Lately I've had to put in a few ugly hacks that make me think it might be worth converting the site to mod_wsgi. But I've gotten used to using some of mod_python's utility classes, especially <code>FieldStorage</code> and <code>Session</code> (and sometimes <code>Cookie</code>), and from a scan of <a href="http://www.python.org/dev/peps/pep-0333/">PEP 333</a>, I don't see any equivalents to these. (Not surprising, because I understand that those kinds of utilities don't belong in the WSGI spec)</p>
<p>Question is, are there "standard" (i.e. commonly accepted) replacements for these mod_python utility classes that I can use in WSGI, or could I/should I write my own?</p>
<p>(FYI: currently using Python 2.5)</p>
| 11
|
2009-03-13T21:56:15Z
| 846,529
|
<p>Please look at <a href="http://aaron.oirt.rutgers.edu/myapp/docs/W.intro" rel="nofollow">
whiff</a> -- it provides built in functionality for manipulating field data
and sessions among others to wsgi based applications.</p>
| 1
|
2009-05-11T02:29:55Z
|
[
"python",
"mod-wsgi",
"mod-python"
] |
Converting from mod_python to mod_wsgi
| 644,767
|
<p>My website is written in Python and currently runs under mod_python with Apache. Lately I've had to put in a few ugly hacks that make me think it might be worth converting the site to mod_wsgi. But I've gotten used to using some of mod_python's utility classes, especially <code>FieldStorage</code> and <code>Session</code> (and sometimes <code>Cookie</code>), and from a scan of <a href="http://www.python.org/dev/peps/pep-0333/">PEP 333</a>, I don't see any equivalents to these. (Not surprising, because I understand that those kinds of utilities don't belong in the WSGI spec)</p>
<p>Question is, are there "standard" (i.e. commonly accepted) replacements for these mod_python utility classes that I can use in WSGI, or could I/should I write my own?</p>
<p>(FYI: currently using Python 2.5)</p>
| 11
|
2009-03-13T21:56:15Z
| 1,037,884
|
<p>You can use FieldStorage in 'cgi' module and the 'Cookie' module. There is no equivalent to Session in Python standard libraries. For WSGI applications you can use <a href="http://beaker.groovie.org/" rel="nofollow">Beaker</a> for sessions.</p>
| 2
|
2009-06-24T11:54:13Z
|
[
"python",
"mod-wsgi",
"mod-python"
] |
Matplotlib's GUI doesn't allow typing in save box?
| 644,812
|
<p>I've been using matplotlib in python for some time now and I've finally gotten around to asking this question about an issue on my mac. When a plot shows up (after the <code>plot()</code> command, <code>draw()</code>, or <code>show()</code>), I have all the functionality I could want; I can move, zoom, etc. that I didn't do in the code.</p>
<p>When I go to save a figure with the view as I desire the save as box opens up and prompts for a filename. Anything I type appears in the terminal I used to execute the command! Selecting X11 and then typing has same result. Nothing seems to put the keyboards output into that box, but I can paste into the box using the mouse->Paste action and I can select files in the menu to overwrite and it works fine.</p>
<p>What's up with this?</p>
<h2>Update:</h2>
<p>The problem was wonderfully outlined and now has some solutions posted <a href="http://stackoverflow.com/questions/3692928/why-doesnt-the-save-button-work-on-a-matplotlib-plot">in this post: Why doesn't the save button work on a matplotlib plot?</a></p>
| 4
|
2009-03-13T22:18:35Z
| 1,863,860
|
<p>Just installed matplotlib 0.99.1 on Python 2.6.2 on Snow Leopard and ran the following code:</p>
<pre><code>from pylab import *
plot([1,2,3])
show()
</code></pre>
<p>Then, I fiddled around with the plot for a while and clicked the save button. The save dialog box popped up normally and allowed me to save (and type) fine. This was using the TkAgg backend. However, I did get this error:</p>
<pre><code>2009-12-08 00:40:18.772 Python[728:60f] -deltaZ is deprecated for NSEventTypeMagnify. Please use -magnification.
</code></pre>
<p>Which seems to be something to do with Snow Leopard changing some APIs.</p>
<p>Sorry for using typing this as a post instead of a comment, but code tags aren't allowed in comments :(</p>
| 1
|
2009-12-08T00:47:12Z
|
[
"python",
"matplotlib"
] |
Python: How to run unittest.main() for all source files in a subdirectory?
| 644,821
|
<p>I am developing a Python module with several source files, each with its own test class derived from <a href="http://docs.python.org/library/unittest.html">unittest</a> right in the source. Consider the directory structure:</p>
<pre><code>dirFoo\
test.py
dirBar\
__init__.py
Foo.py
Bar.py
</code></pre>
<p>To test either Foo.py or Bar.py, I would add this at the end of the Foo.py and Bar.py source files:</p>
<pre><code>if __name__ == "__main__":
unittest.main()
</code></pre>
<p>And run Python on either source, i.e.</p>
<pre><code>$ python Foo.py
...........
----------------------------------------------------------------------
Ran 11 tests in 2.314s
OK
</code></pre>
<p>Ideally, I would have "test.py" automagically search dirBar for any unittest derived classes and make one call to "unittest.main()". What's the best way to do this in practice? </p>
<p>I tried using Python to call <a href="http://docs.python.org/library/functions.html#execfile">execfile</a> for every *.py file in dirBar, which runs once for the first .py file found & exits the calling test.py, plus then I have to duplicate my code by adding unittest.main() in every source file--which violates DRY principles. </p>
| 41
|
2009-03-13T22:20:31Z
| 644,844
|
<p>I knew there was an obvious solution:</p>
<pre><code>dirFoo\
__init__.py
test.py
dirBar\
Foo.py
Bar.py
</code></pre>
<p>Contents of dirFoo/test.py</p>
<pre><code>from dirBar import *
import unittest
if __name__ == "__main__":
unittest.main()
</code></pre>
<p>Run the tests:</p>
<pre><code>$ python test.py
...........
----------------------------------------------------------------------
Ran 11 tests in 2.305s
OK
</code></pre>
<p>Sorry for the silly question.</p>
| 18
|
2009-03-13T22:29:58Z
|
[
"python",
"unit-testing"
] |
Python: How to run unittest.main() for all source files in a subdirectory?
| 644,821
|
<p>I am developing a Python module with several source files, each with its own test class derived from <a href="http://docs.python.org/library/unittest.html">unittest</a> right in the source. Consider the directory structure:</p>
<pre><code>dirFoo\
test.py
dirBar\
__init__.py
Foo.py
Bar.py
</code></pre>
<p>To test either Foo.py or Bar.py, I would add this at the end of the Foo.py and Bar.py source files:</p>
<pre><code>if __name__ == "__main__":
unittest.main()
</code></pre>
<p>And run Python on either source, i.e.</p>
<pre><code>$ python Foo.py
...........
----------------------------------------------------------------------
Ran 11 tests in 2.314s
OK
</code></pre>
<p>Ideally, I would have "test.py" automagically search dirBar for any unittest derived classes and make one call to "unittest.main()". What's the best way to do this in practice? </p>
<p>I tried using Python to call <a href="http://docs.python.org/library/functions.html#execfile">execfile</a> for every *.py file in dirBar, which runs once for the first .py file found & exits the calling test.py, plus then I have to duplicate my code by adding unittest.main() in every source file--which violates DRY principles. </p>
| 41
|
2009-03-13T22:20:31Z
| 644,987
|
<p>You should try <a href="http://nose.readthedocs.io/en/latest/" rel="nofollow">nose</a>. It's a library to help create tests and it integrates with <code>unittest</code> or <code>doctest</code>. All you need to do is run <code>nosetests</code> and it'll find all your unittests for you.</p>
<pre><code>% nosetests # finds all tests in all subdirectories
% nosetests tests/ # find all tests in the tests directory
</code></pre>
| 15
|
2009-03-13T23:35:04Z
|
[
"python",
"unit-testing"
] |
Python: How to run unittest.main() for all source files in a subdirectory?
| 644,821
|
<p>I am developing a Python module with several source files, each with its own test class derived from <a href="http://docs.python.org/library/unittest.html">unittest</a> right in the source. Consider the directory structure:</p>
<pre><code>dirFoo\
test.py
dirBar\
__init__.py
Foo.py
Bar.py
</code></pre>
<p>To test either Foo.py or Bar.py, I would add this at the end of the Foo.py and Bar.py source files:</p>
<pre><code>if __name__ == "__main__":
unittest.main()
</code></pre>
<p>And run Python on either source, i.e.</p>
<pre><code>$ python Foo.py
...........
----------------------------------------------------------------------
Ran 11 tests in 2.314s
OK
</code></pre>
<p>Ideally, I would have "test.py" automagically search dirBar for any unittest derived classes and make one call to "unittest.main()". What's the best way to do this in practice? </p>
<p>I tried using Python to call <a href="http://docs.python.org/library/functions.html#execfile">execfile</a> for every *.py file in dirBar, which runs once for the first .py file found & exits the calling test.py, plus then I have to duplicate my code by adding unittest.main() in every source file--which violates DRY principles. </p>
| 41
|
2009-03-13T22:20:31Z
| 645,485
|
<p>I came up with a snippet that may do what you want. It walks a path that you provide looking for Python packages/modules and accumulates a set of test suites from those modules, which it then executes all at once.</p>
<p>The nice thing about this is that it will work on all packages nested under the directory you specify, and you won't have to manually change the imports as you add new components.</p>
<pre><code>import logging
import os
import unittest
MODULE_EXTENSIONS = set('.py .pyc .pyo'.split())
def unit_test_extractor(tup, path, filenames):
"""Pull ``unittest.TestSuite``s from modules in path
if the path represents a valid Python package. Accumulate
results in `tup[1]`.
"""
package_path, suites = tup
logging.debug('Path: %s', path)
logging.debug('Filenames: %s', filenames)
relpath = os.path.relpath(path, package_path)
relpath_pieces = relpath.split(os.sep)
if relpath_pieces[0] == '.': # Base directory.
relpath_pieces.pop(0) # Otherwise, screws up module name.
elif not any(os.path.exists(os.path.join(path, '__init__' + ext))
for ext in MODULE_EXTENSIONS):
return # Not a package directory and not the base directory, reject.
logging.info('Base: %s', '.'.join(relpath_pieces))
for filename in filenames:
base, ext = os.path.splitext(filename)
if ext not in MODULE_EXTENSIONS: # Not a Python module.
continue
logging.info('Module: %s', base)
module_name = '.'.join(relpath_pieces + [base])
logging.info('Importing from %s', module_name)
module = __import__(module_name)
module_suites = unittest.defaultTestLoader.loadTestsFromModule(module)
logging.info('Got suites: %s', module_suites)
suites += module_suites
def get_test_suites(path):
""":return: Iterable of suites for the packages/modules
present under :param:`path`.
"""
logging.info('Base path: %s', package_path)
suites = []
os.path.walk(package_path, unit_test_extractor, (package_path, suites))
logging.info('Got suites: %s', suites)
return suites
if __name__ == '__main__':
logging.basicConfig(level=logging.WARN)
package_path = os.path.dirname(os.path.abspath(__file__))
suites = get_test_suites(package_path)
for suite in suites:
unittest.TextTestRunner(verbosity=2).run(suite)
</code></pre>
| 2
|
2009-03-14T06:01:05Z
|
[
"python",
"unit-testing"
] |
Python: How to run unittest.main() for all source files in a subdirectory?
| 644,821
|
<p>I am developing a Python module with several source files, each with its own test class derived from <a href="http://docs.python.org/library/unittest.html">unittest</a> right in the source. Consider the directory structure:</p>
<pre><code>dirFoo\
test.py
dirBar\
__init__.py
Foo.py
Bar.py
</code></pre>
<p>To test either Foo.py or Bar.py, I would add this at the end of the Foo.py and Bar.py source files:</p>
<pre><code>if __name__ == "__main__":
unittest.main()
</code></pre>
<p>And run Python on either source, i.e.</p>
<pre><code>$ python Foo.py
...........
----------------------------------------------------------------------
Ran 11 tests in 2.314s
OK
</code></pre>
<p>Ideally, I would have "test.py" automagically search dirBar for any unittest derived classes and make one call to "unittest.main()". What's the best way to do this in practice? </p>
<p>I tried using Python to call <a href="http://docs.python.org/library/functions.html#execfile">execfile</a> for every *.py file in dirBar, which runs once for the first .py file found & exits the calling test.py, plus then I have to duplicate my code by adding unittest.main() in every source file--which violates DRY principles. </p>
| 41
|
2009-03-13T22:20:31Z
| 9,407,536
|
<p>As of Python 2.7, test discovery is automated in the unittest package. From the <a href="http://docs.python.org/library/unittest.html">docs</a>:</p>
<blockquote>
<p>Unittest supports simple test discovery. In order to be compatible
with test discovery, all of the test files must be modules or packages
importable from the top-level directory of the project (this means
that their filenames must be valid identifiers).</p>
<p>Test discovery is implemented in <code>TestLoader.discover()</code>, but can also
be used from the command line. The basic command-line usage is:</p>
<pre><code>cd project_directory
python -m unittest discover
</code></pre>
</blockquote>
<p>By default it looks for packages named <code>test*.py</code>, but this can be changed so you might use something like</p>
<pre><code>python -m unittest discover --pattern=*.py
</code></pre>
<p>In place of your test.py script.</p>
| 43
|
2012-02-23T05:12:03Z
|
[
"python",
"unit-testing"
] |
Python: How to run unittest.main() for all source files in a subdirectory?
| 644,821
|
<p>I am developing a Python module with several source files, each with its own test class derived from <a href="http://docs.python.org/library/unittest.html">unittest</a> right in the source. Consider the directory structure:</p>
<pre><code>dirFoo\
test.py
dirBar\
__init__.py
Foo.py
Bar.py
</code></pre>
<p>To test either Foo.py or Bar.py, I would add this at the end of the Foo.py and Bar.py source files:</p>
<pre><code>if __name__ == "__main__":
unittest.main()
</code></pre>
<p>And run Python on either source, i.e.</p>
<pre><code>$ python Foo.py
...........
----------------------------------------------------------------------
Ran 11 tests in 2.314s
OK
</code></pre>
<p>Ideally, I would have "test.py" automagically search dirBar for any unittest derived classes and make one call to "unittest.main()". What's the best way to do this in practice? </p>
<p>I tried using Python to call <a href="http://docs.python.org/library/functions.html#execfile">execfile</a> for every *.py file in dirBar, which runs once for the first .py file found & exits the calling test.py, plus then I have to duplicate my code by adding unittest.main() in every source file--which violates DRY principles. </p>
| 41
|
2009-03-13T22:20:31Z
| 13,533,236
|
<p>Here is my test discovery code that seems to do the job. I wanted to make sure I can extend the tests easily without having to list them in any of the involved files, but also avoid writing all tests in one single Ãbertest file. </p>
<p>So the structure is </p>
<pre><code>myTests.py
testDir\
__init__.py
testA.py
testB.py
</code></pre>
<p>myTest.py look like this:</p>
<pre><code>import unittest
if __name__ == '__main__':
testsuite = unittest.TestLoader().discover('.')
unittest.TextTestRunner(verbosity=1).run(testsuite)
</code></pre>
<p>I believe this is the simplest solution for writing several test cases in one directory. The solution requires Python 2.7 or Python 3.</p>
| 18
|
2012-11-23T17:02:19Z
|
[
"python",
"unit-testing"
] |
Python: How to run unittest.main() for all source files in a subdirectory?
| 644,821
|
<p>I am developing a Python module with several source files, each with its own test class derived from <a href="http://docs.python.org/library/unittest.html">unittest</a> right in the source. Consider the directory structure:</p>
<pre><code>dirFoo\
test.py
dirBar\
__init__.py
Foo.py
Bar.py
</code></pre>
<p>To test either Foo.py or Bar.py, I would add this at the end of the Foo.py and Bar.py source files:</p>
<pre><code>if __name__ == "__main__":
unittest.main()
</code></pre>
<p>And run Python on either source, i.e.</p>
<pre><code>$ python Foo.py
...........
----------------------------------------------------------------------
Ran 11 tests in 2.314s
OK
</code></pre>
<p>Ideally, I would have "test.py" automagically search dirBar for any unittest derived classes and make one call to "unittest.main()". What's the best way to do this in practice? </p>
<p>I tried using Python to call <a href="http://docs.python.org/library/functions.html#execfile">execfile</a> for every *.py file in dirBar, which runs once for the first .py file found & exits the calling test.py, plus then I have to duplicate my code by adding unittest.main() in every source file--which violates DRY principles. </p>
| 41
|
2009-03-13T22:20:31Z
| 27,630,375
|
<p>In case it happens to help anyone, here is the approach I arrived at for solving this problem. I had the use case where I have the following directory structure:</p>
<pre><code>mypackage/
tests/
test_category_1/
tests_1a.py
tests_1b.py
...
test_category_2/
tests_2a.py
tests_2b.py
...
...
</code></pre>
<p>and I want all of the following to work in the obvious way and to be able to be supplied the same commandline arguments as are accepted by unittest:</p>
<pre><code>python -m mypackage.tests
python -m mypackage.tests.test_category_1
python -m mypackage.tests.test_category_1.tests_1a
</code></pre>
<p>The solution was to set up <code>mypackage/tests/__init__.py</code> like this:</p>
<pre><code>import unittest
def prepare_load_tests_function (the__path__):
test_suite = unittest.TestLoader().discover(the__path__[0])
def load_tests (_a, _b, _c):
return test_suite
return load_tests
</code></pre>
<p>and to set up <code>mypackage/tests/__main__.py</code> like this:</p>
<pre><code>import unittest
from . import prepare_load_tests_function, __path__
load_tests = prepare_load_tests_function(__path__)
unittest.main()
</code></pre>
<p>and to copy and paste an empty <code>__init__.py</code> and the following <code>__main__.py</code> in each <code>mypackage/tests/test_category_n/</code>:</p>
<pre><code>import unittest
from .. import prepare_load_tests_function
from . import __path__
load_tests = prepare_load_tests_function(__path__)
unittest.main()
</code></pre>
<p>and also to add the standard <code>if __name__ == '__main__': unittest.main()</code> in each actual tests file.</p>
<p>(Works for me on Python 3.3 on Windows, ymmv.)</p>
| 0
|
2014-12-24T01:36:41Z
|
[
"python",
"unit-testing"
] |
What is the quickest way to HTTP GET in Python?
| 645,312
|
<p>What is the quickest way to HTTP GET in Python if I know the Content will be a string? I am searching the docs for a quick one-liner like:</p>
<pre><code>contents = url.get("http://example.com/foo/bar")
</code></pre>
<p>But all I can find using Google are <code>httplib</code> and <code>urllib</code> - and I am unable to find a shortcut in those libraries.</p>
<p>Does standard Python 2.5 have a shortcut in some form as above, or should I write a function <code>url_get</code>?</p>
<ol>
<li>I would prefer not to capture the output of shelling out to <code>wget</code> or <code>curl</code>.</li>
</ol>
| 267
|
2009-03-14T03:44:22Z
| 645,318
|
<p>Python 2.x:</p>
<pre><code>import urllib2
urllib2.urlopen("http://example.com/foo/bar").read()
</code></pre>
<p>Python 3.x:</p>
<pre><code>import urllib.request
urllib.request.urlopen("http://example.com/foo/bar").read()
</code></pre>
<p>Documentation for <a href="https://docs.python.org/3.5/library/urllib.request.html">urllib.request</a> and <a href="https://docs.python.org/3.3/tutorial/inputoutput.html#methods-of-file-objects">read</a>.</p>
<p>How is that?</p>
| 386
|
2009-03-14T03:48:24Z
|
[
"python",
"http",
"networking"
] |
What is the quickest way to HTTP GET in Python?
| 645,312
|
<p>What is the quickest way to HTTP GET in Python if I know the Content will be a string? I am searching the docs for a quick one-liner like:</p>
<pre><code>contents = url.get("http://example.com/foo/bar")
</code></pre>
<p>But all I can find using Google are <code>httplib</code> and <code>urllib</code> - and I am unable to find a shortcut in those libraries.</p>
<p>Does standard Python 2.5 have a shortcut in some form as above, or should I write a function <code>url_get</code>?</p>
<ol>
<li>I would prefer not to capture the output of shelling out to <code>wget</code> or <code>curl</code>.</li>
</ol>
| 267
|
2009-03-14T03:44:22Z
| 646,159
|
<p>Have a look at <a href="http://code.google.com/p/httplib2/">httplib2</a>, which - next to a lot of very useful features - provides exactly what you want.</p>
<pre><code>import httplib2
resp, content = httplib2.Http().request("http://example.com/foo/bar")
</code></pre>
<p>Where content would be the response body (as a string), and resp would contain the status and response headers.</p>
<p>It doesn't come included with a standard python install though (but it only requires standard python), but it's definitely worth checking out.</p>
| 13
|
2009-03-14T16:13:13Z
|
[
"python",
"http",
"networking"
] |
What is the quickest way to HTTP GET in Python?
| 645,312
|
<p>What is the quickest way to HTTP GET in Python if I know the Content will be a string? I am searching the docs for a quick one-liner like:</p>
<pre><code>contents = url.get("http://example.com/foo/bar")
</code></pre>
<p>But all I can find using Google are <code>httplib</code> and <code>urllib</code> - and I am unable to find a shortcut in those libraries.</p>
<p>Does standard Python 2.5 have a shortcut in some form as above, or should I write a function <code>url_get</code>?</p>
<ol>
<li>I would prefer not to capture the output of shelling out to <code>wget</code> or <code>curl</code>.</li>
</ol>
| 267
|
2009-03-14T03:44:22Z
| 646,213
|
<p>If you want solution with httplib2 to be oneliner consider instatntinating anonymous Http object</p>
<pre><code>import httplib2
resp, content = httplib2.Http().request("http://example.com/foo/bar")
</code></pre>
| 27
|
2009-03-14T16:40:06Z
|
[
"python",
"http",
"networking"
] |
What is the quickest way to HTTP GET in Python?
| 645,312
|
<p>What is the quickest way to HTTP GET in Python if I know the Content will be a string? I am searching the docs for a quick one-liner like:</p>
<pre><code>contents = url.get("http://example.com/foo/bar")
</code></pre>
<p>But all I can find using Google are <code>httplib</code> and <code>urllib</code> - and I am unable to find a shortcut in those libraries.</p>
<p>Does standard Python 2.5 have a shortcut in some form as above, or should I write a function <code>url_get</code>?</p>
<ol>
<li>I would prefer not to capture the output of shelling out to <code>wget</code> or <code>curl</code>.</li>
</ol>
| 267
|
2009-03-14T03:44:22Z
| 646,229
|
<p>Here is a wget script in Python:</p>
<pre><code># From python cookbook, 2nd edition, page 487
import sys, urllib
def reporthook(a, b, c):
print "% 3.1f%% of %d bytes\r" % (min(100, float(a * b) / c * 100), c),
for url in sys.argv[1:]:
i = url.rfind("/")
file = url[i+1:]
print url, "->", file
urllib.urlretrieve(url, file, reporthook)
print
</code></pre>
| 5
|
2009-03-14T16:47:32Z
|
[
"python",
"http",
"networking"
] |
What is the quickest way to HTTP GET in Python?
| 645,312
|
<p>What is the quickest way to HTTP GET in Python if I know the Content will be a string? I am searching the docs for a quick one-liner like:</p>
<pre><code>contents = url.get("http://example.com/foo/bar")
</code></pre>
<p>But all I can find using Google are <code>httplib</code> and <code>urllib</code> - and I am unable to find a shortcut in those libraries.</p>
<p>Does standard Python 2.5 have a shortcut in some form as above, or should I write a function <code>url_get</code>?</p>
<ol>
<li>I would prefer not to capture the output of shelling out to <code>wget</code> or <code>curl</code>.</li>
</ol>
| 267
|
2009-03-14T03:44:22Z
| 2,003,547
|
<p>theller's solution for wget is really useful, however, i found it does not print out the progress throughout the downloading process. It's perfect if you add one line after the print statement in reporthook.</p>
<pre><code>import sys, urllib
def reporthook(a, b, c):
print "% 3.1f%% of %d bytes\r" % (min(100, float(a * b) / c * 100), c),
sys.stdout.flush()
for url in sys.argv[1:]:
i = url.rfind("/")
file = url[i+1:]
print url, "->", file
urllib.urlretrieve(url, file, reporthook)
print
</code></pre>
| 6
|
2010-01-05T01:21:33Z
|
[
"python",
"http",
"networking"
] |
What is the quickest way to HTTP GET in Python?
| 645,312
|
<p>What is the quickest way to HTTP GET in Python if I know the Content will be a string? I am searching the docs for a quick one-liner like:</p>
<pre><code>contents = url.get("http://example.com/foo/bar")
</code></pre>
<p>But all I can find using Google are <code>httplib</code> and <code>urllib</code> - and I am unable to find a shortcut in those libraries.</p>
<p>Does standard Python 2.5 have a shortcut in some form as above, or should I write a function <code>url_get</code>?</p>
<ol>
<li>I would prefer not to capture the output of shelling out to <code>wget</code> or <code>curl</code>.</li>
</ol>
| 267
|
2009-03-14T03:44:22Z
| 15,869,929
|
<p>You could use a library called <a href="http://docs.python-requests.org/en/latest/">requests</a>.</p>
<pre><code>import requests
r = requests.get("http://example.com/foo/bar")
</code></pre>
<p>This is quite easy. Then you can do like this:</p>
<pre><code>>>> print r.status_code
>>> print r.headers
>>> print r.content
</code></pre>
| 153
|
2013-04-08T01:30:40Z
|
[
"python",
"http",
"networking"
] |
What is the quickest way to HTTP GET in Python?
| 645,312
|
<p>What is the quickest way to HTTP GET in Python if I know the Content will be a string? I am searching the docs for a quick one-liner like:</p>
<pre><code>contents = url.get("http://example.com/foo/bar")
</code></pre>
<p>But all I can find using Google are <code>httplib</code> and <code>urllib</code> - and I am unable to find a shortcut in those libraries.</p>
<p>Does standard Python 2.5 have a shortcut in some form as above, or should I write a function <code>url_get</code>?</p>
<ol>
<li>I would prefer not to capture the output of shelling out to <code>wget</code> or <code>curl</code>.</li>
</ol>
| 267
|
2009-03-14T03:44:22Z
| 23,813,181
|
<p>If you are working with HTTP APIs specifically, there are also more convenient choices such as <a href="https://github.com/kimmobrunfeldt/nap" rel="nofollow">Nap</a>.</p>
<p>For example, here's how to get gists from Github since <em>May 1st 2014</em>:</p>
<pre><code>from nap.url import Url
api = Url('https://api.github.com')
gists = api.join('gists')
response = gists.get(params={'since': '2014-05-01T00:00:00Z'})
print(response.json())
</code></pre>
<p>More examples: <a href="https://github.com/kimmobrunfeldt/nap#examples" rel="nofollow">https://github.com/kimmobrunfeldt/nap#examples</a></p>
| 2
|
2014-05-22T17:08:22Z
|
[
"python",
"http",
"networking"
] |
What is the quickest way to HTTP GET in Python?
| 645,312
|
<p>What is the quickest way to HTTP GET in Python if I know the Content will be a string? I am searching the docs for a quick one-liner like:</p>
<pre><code>contents = url.get("http://example.com/foo/bar")
</code></pre>
<p>But all I can find using Google are <code>httplib</code> and <code>urllib</code> - and I am unable to find a shortcut in those libraries.</p>
<p>Does standard Python 2.5 have a shortcut in some form as above, or should I write a function <code>url_get</code>?</p>
<ol>
<li>I would prefer not to capture the output of shelling out to <code>wget</code> or <code>curl</code>.</li>
</ol>
| 267
|
2009-03-14T03:44:22Z
| 31,029,124
|
<p>Excellent solutions Xuan, Theller.</p>
<p>For it to work with python 3 make the following changes</p>
<pre><code>import sys, urllib.request
def reporthook(a, b, c):
print ("% 3.1f%% of %d bytes\r" % (min(100, float(a * b) / c * 100), c))
sys.stdout.flush()
for url in sys.argv[1:]:
i = url.rfind("/")
file = url[i+1:]
print (url, "->", file)
urllib.request.urlretrieve(url, file, reporthook)
print
</code></pre>
<p>Also, the URL you enter should be preceded by a "http://", otherwise it returns a unknown url type error.</p>
| 1
|
2015-06-24T14:18:05Z
|
[
"python",
"http",
"networking"
] |
Discussion of multiple inheritance vs Composition for a project (+other things)
| 645,493
|
<p>I am writing a python platform for the simulation of distributed sensor swarms. The idea being that the end user can write a custom Node consisting of the SensorNode behaviour (communication, logging, etc) as well as implementing a number of different sensors.</p>
<p>The example below briefly demonstrates the concept.</p>
<pre><code>#prewritten
class Sensor(object):
def __init__(self):
print "Hello from Sensor"
#...
#prewritten
class PositionSensor(Sensor):
def __init__(self):
print "Hello from Position"
Sensor.__init__(self)
#...
#prewritten
class BearingSensor(Sensor):
def __init__(self):
print "Hello from Bearing"
Sensor.__init__(self)
#...
#prewritten
class SensorNode(object):
def __init__(self):
print "Hello from SensorNode"
#...
#USER WRITTEN
class MySensorNode(SensorNode,BearingSensor,PositionSensor):
def CustomMethod(self):
LogData={'Position':position(), 'Bearing':bearing()} #position() from PositionSensor, bearing() from BearingSensor
Log(LogData) #Log() from SensorNode
</code></pre>
<h2>NEW EDIT:</h2>
<p>Firstly an overview of what I am trying to achieve:
I am writing a simulator to simulate swarm intelligence algorithms with particular focus on mobile sensor networks. These networks consist of many small robots communicating individual sensor data to build a complex sensory map of the environment.</p>
<p>The underlying goal of this project is to develop a simulation platform that provides abstracted interfaces to sensors such that the same user-implemented functionality can be directly ported to a robotic swarm running embedded linux. As robotic implementation is the goal, I need to design such that the software node behaves the same, and only has access to information that an physical node would have.</p>
<p>As part of the simulation engine, I will be providing a set of classes modelling different types of sensors and different types of sensor node. I wish to abstract all this complexity away from the user such that all the user must do is define which sensors are present on the node, and what type of sensor node (mobile, fixed position) is being implemented.</p>
<p>My initial thinking was that every sensor would provide a read() method which would return the relevant values, however having read the responses to the question, I see that perhaps more descriptive method names would be beneficial (.distance(), .position(), .bearing(), etc).</p>
<p>I initially wanted use separate classes for the sensors (with common ancestors) so that a more technical user can easily extend one of the existing classes to create a new sensor if they wish. For example:</p>
<pre><code>Sensor
|
DistanceSensor(designed for 360 degree scan range)
| | |
IR Sensor Ultrasonic SickLaser
(narrow) (wider) (very wide)
</code></pre>
<p>The reason I was initially thinking of Multiple Inheritance (although it semi-breaks the IS-A relationship of inheritance) was due to the underlying principle behind the simulation system. Let me explain:</p>
<p>The user-implemented MySensorNode should not have direct access to its position within the environment (akin to a robot, the access is indirect through a sensor interface), similarly, the sensors should not know where they are. However, this lack of direct knowledge poses a problem, as the return values of the sensors are all dependent on their position and orientation within the environment (which needs to be simulated to return the correct values).</p>
<p>SensorNode, as a class implemented within the simulation libraries, is responsible for drawing the MySensorNode within the pygame environment - thus, it is the only class that should have direct access to the position and orientation of the sensor node within the environment.</p>
<p>SensorNode is also responsible for translation and rotation within the environment, however this translation and rotation is a side effect of motor actuation.</p>
<p>What I mean by this is that robots cannot directly alter their position within the world, all they can do is provide power to motors, and movement within the world is a side-effect of the motors interaction with the environment. I need to model this accurately within the simulation.</p>
<p>So, to move, the user-implemented functionality may use:</p>
<pre><code>motors(50,50)
</code></pre>
<p>This call will, as a side-effect, alter the position of the node within the world. </p>
<p>If SensorNode was implemented using composition, SensorNode.motors(...) would not be able to directly alter instance variables (such as position), nor would MySensorNode.draw() be resolved to SensorNode.draw(), so SensorNode imo should be implemented using inheritance.</p>
<p>In terms of the sensors, the benefit of composition for a problem like this is obvious, MySensorNode is composed of a number of sensors - enough said.</p>
<p>However the problem as I see it is that the Sensors need access to their position and orientation within the world, and if you use composition you will end up with a call like:</p>
<pre><code>>>> PosSensor.position((123,456))
(123,456)
</code></pre>
<p>Then again - thinking, you could pass self to the sensor upon initialisation, eg:</p>
<pre><code>PosSensor = PositionSensor(self)
</code></pre>
<p>then later</p>
<pre><code>PosSensor.position()
</code></pre>
<p>however this PosSensor.position() would then need to access information local to the instance (passed as self during <strong>init</strong>()), so why call PosSensor at all when you can access the information locally? Also passing your instance to an object you are composed of just seems not quite right, crossing the boundaries of encapsulation and information hiding (even though python doesn't do much to support the idea of information hiding).</p>
<p>If the solution was implemented using multiple inheritance, these problems would disappear:</p>
<pre><code>class MySensorNode(SensorNode,PositionSensor,BearingSensor):
def Think():
while bearing()>0:
# bearing() is provided by BearingSensor and in the simulator
# will simply access local variables provided by SensorNode
# to return the bearing. In robotic implementation, the
# bearing() method will instead access C routines to read
# the actual bearing from a compass sensor
motors(100,-100)
# spin on the spot, will as a side-effect alter the return
# value of bearing()
(Ox,Oy)=position() #provided by PositionSensor
while True:
(Cx,Cy)=position()
if Cx>=Ox+100:
break
else:
motors(100,100)
#full speed ahead!will alter the return value of position()
</code></pre>
<p><hr /></p>
<p>Hopefully this edit has clarified some things, if you have any questions I'm more than happy to try and clarify them</p>
<h2>OLD THINGS:</h2>
<p>When an object of type MySensorNode is constructed, all constructors from the superclasses need to be called. I do not want to complicate the user with having to write a custom constructor for MySensorNode which calls the constructor from each superclass. Ideally, what I would like to happen is:</p>
<pre><code>mSN = MySensorNode()
# at this point, the __init__() method is searched for
# and SensorNode.__init__() is called given the order
# of inheritance in MySensorNode.__mro__
# Somehow, I would also like to call all the other constructors
# that were not executed (ie BearingSensor and PositionSensor)
</code></pre>
<p>Any insight or general comments would be appreciated,
Cheers :)</p>
<p>OLD EDIT:
Doing something like:</p>
<pre><code>#prewritten
class SensorNode(object):
def __init__(self):
print "Hello from SensorNode"
for clss in type(self).__mro__:
if clss!=SensorNode and clss!=type(self):
clss.__init__(self)
</code></pre>
<p>This works, as self is an instance of MySensorNode. However this solution is messy.</p>
<p><hr /></p>
| 13
|
2009-03-14T06:04:55Z
| 645,597
|
<p><code>super</code> calls the next class in the mro-list. This works even if you leave out the <code>__init__</code> form some class.</p>
<pre><code>class A(object):
def __init__(self):
super(A,self).__init__()
print "Hello from A!"
class B(A):
def __init__(self):
super(B,self).__init__()
print "Hello from B!"
class C(A):
def __init__(self):
super(C,self).__init__()
print "Hello from C!"
class D(B,C):
def __init__(self):
super(D,self).__init__()
print "Hello from D!"
class E(B,C):
pass
</code></pre>
<p>Example:</p>
<pre><code>>>> x = D()
Hello from A!
Hello from C!
Hello from B!
Hello from D!
>>> y = E()
Hello from A!
Hello from C!
Hello from B!
>>>
</code></pre>
<p><strong>Edit:</strong> Rewrote the answer. (again)</p>
| 1
|
2009-03-14T07:44:16Z
|
[
"python",
"constructor",
"oop",
"multiple-inheritance"
] |
Discussion of multiple inheritance vs Composition for a project (+other things)
| 645,493
|
<p>I am writing a python platform for the simulation of distributed sensor swarms. The idea being that the end user can write a custom Node consisting of the SensorNode behaviour (communication, logging, etc) as well as implementing a number of different sensors.</p>
<p>The example below briefly demonstrates the concept.</p>
<pre><code>#prewritten
class Sensor(object):
def __init__(self):
print "Hello from Sensor"
#...
#prewritten
class PositionSensor(Sensor):
def __init__(self):
print "Hello from Position"
Sensor.__init__(self)
#...
#prewritten
class BearingSensor(Sensor):
def __init__(self):
print "Hello from Bearing"
Sensor.__init__(self)
#...
#prewritten
class SensorNode(object):
def __init__(self):
print "Hello from SensorNode"
#...
#USER WRITTEN
class MySensorNode(SensorNode,BearingSensor,PositionSensor):
def CustomMethod(self):
LogData={'Position':position(), 'Bearing':bearing()} #position() from PositionSensor, bearing() from BearingSensor
Log(LogData) #Log() from SensorNode
</code></pre>
<h2>NEW EDIT:</h2>
<p>Firstly an overview of what I am trying to achieve:
I am writing a simulator to simulate swarm intelligence algorithms with particular focus on mobile sensor networks. These networks consist of many small robots communicating individual sensor data to build a complex sensory map of the environment.</p>
<p>The underlying goal of this project is to develop a simulation platform that provides abstracted interfaces to sensors such that the same user-implemented functionality can be directly ported to a robotic swarm running embedded linux. As robotic implementation is the goal, I need to design such that the software node behaves the same, and only has access to information that an physical node would have.</p>
<p>As part of the simulation engine, I will be providing a set of classes modelling different types of sensors and different types of sensor node. I wish to abstract all this complexity away from the user such that all the user must do is define which sensors are present on the node, and what type of sensor node (mobile, fixed position) is being implemented.</p>
<p>My initial thinking was that every sensor would provide a read() method which would return the relevant values, however having read the responses to the question, I see that perhaps more descriptive method names would be beneficial (.distance(), .position(), .bearing(), etc).</p>
<p>I initially wanted use separate classes for the sensors (with common ancestors) so that a more technical user can easily extend one of the existing classes to create a new sensor if they wish. For example:</p>
<pre><code>Sensor
|
DistanceSensor(designed for 360 degree scan range)
| | |
IR Sensor Ultrasonic SickLaser
(narrow) (wider) (very wide)
</code></pre>
<p>The reason I was initially thinking of Multiple Inheritance (although it semi-breaks the IS-A relationship of inheritance) was due to the underlying principle behind the simulation system. Let me explain:</p>
<p>The user-implemented MySensorNode should not have direct access to its position within the environment (akin to a robot, the access is indirect through a sensor interface), similarly, the sensors should not know where they are. However, this lack of direct knowledge poses a problem, as the return values of the sensors are all dependent on their position and orientation within the environment (which needs to be simulated to return the correct values).</p>
<p>SensorNode, as a class implemented within the simulation libraries, is responsible for drawing the MySensorNode within the pygame environment - thus, it is the only class that should have direct access to the position and orientation of the sensor node within the environment.</p>
<p>SensorNode is also responsible for translation and rotation within the environment, however this translation and rotation is a side effect of motor actuation.</p>
<p>What I mean by this is that robots cannot directly alter their position within the world, all they can do is provide power to motors, and movement within the world is a side-effect of the motors interaction with the environment. I need to model this accurately within the simulation.</p>
<p>So, to move, the user-implemented functionality may use:</p>
<pre><code>motors(50,50)
</code></pre>
<p>This call will, as a side-effect, alter the position of the node within the world. </p>
<p>If SensorNode was implemented using composition, SensorNode.motors(...) would not be able to directly alter instance variables (such as position), nor would MySensorNode.draw() be resolved to SensorNode.draw(), so SensorNode imo should be implemented using inheritance.</p>
<p>In terms of the sensors, the benefit of composition for a problem like this is obvious, MySensorNode is composed of a number of sensors - enough said.</p>
<p>However the problem as I see it is that the Sensors need access to their position and orientation within the world, and if you use composition you will end up with a call like:</p>
<pre><code>>>> PosSensor.position((123,456))
(123,456)
</code></pre>
<p>Then again - thinking, you could pass self to the sensor upon initialisation, eg:</p>
<pre><code>PosSensor = PositionSensor(self)
</code></pre>
<p>then later</p>
<pre><code>PosSensor.position()
</code></pre>
<p>however this PosSensor.position() would then need to access information local to the instance (passed as self during <strong>init</strong>()), so why call PosSensor at all when you can access the information locally? Also passing your instance to an object you are composed of just seems not quite right, crossing the boundaries of encapsulation and information hiding (even though python doesn't do much to support the idea of information hiding).</p>
<p>If the solution was implemented using multiple inheritance, these problems would disappear:</p>
<pre><code>class MySensorNode(SensorNode,PositionSensor,BearingSensor):
def Think():
while bearing()>0:
# bearing() is provided by BearingSensor and in the simulator
# will simply access local variables provided by SensorNode
# to return the bearing. In robotic implementation, the
# bearing() method will instead access C routines to read
# the actual bearing from a compass sensor
motors(100,-100)
# spin on the spot, will as a side-effect alter the return
# value of bearing()
(Ox,Oy)=position() #provided by PositionSensor
while True:
(Cx,Cy)=position()
if Cx>=Ox+100:
break
else:
motors(100,100)
#full speed ahead!will alter the return value of position()
</code></pre>
<p><hr /></p>
<p>Hopefully this edit has clarified some things, if you have any questions I'm more than happy to try and clarify them</p>
<h2>OLD THINGS:</h2>
<p>When an object of type MySensorNode is constructed, all constructors from the superclasses need to be called. I do not want to complicate the user with having to write a custom constructor for MySensorNode which calls the constructor from each superclass. Ideally, what I would like to happen is:</p>
<pre><code>mSN = MySensorNode()
# at this point, the __init__() method is searched for
# and SensorNode.__init__() is called given the order
# of inheritance in MySensorNode.__mro__
# Somehow, I would also like to call all the other constructors
# that were not executed (ie BearingSensor and PositionSensor)
</code></pre>
<p>Any insight or general comments would be appreciated,
Cheers :)</p>
<p>OLD EDIT:
Doing something like:</p>
<pre><code>#prewritten
class SensorNode(object):
def __init__(self):
print "Hello from SensorNode"
for clss in type(self).__mro__:
if clss!=SensorNode and clss!=type(self):
clss.__init__(self)
</code></pre>
<p>This works, as self is an instance of MySensorNode. However this solution is messy.</p>
<p><hr /></p>
| 13
|
2009-03-14T06:04:55Z
| 645,672
|
<p>Here's a partial solution:</p>
<pre><code>class NodeMeta(type):
def __init__(cls, name, bases, d):
setattr(cls, '__inherits__', bases)
class Node(object):
__metaclass__ = NodeMeta
def __init__(self):
for cls in self.__inherits__:
cls.cls_init(self)
class Sensor(Node):
def cls_init(self):
print "Sensor initialized"
class PositionSensor(Sensor):
def cls_init(self):
print "PositionSensor initialized"
self._bearing = 0
def bearing(self):
# calculate bearing:
return self._bearing
class BearingSensor(Sensor):
def cls_init(self):
print "BearingSensor initialized"
self._position = (0, 0)
def position(self):
# calculate position:
return self._position
# -------- custom sensors --------
class CustomSensor(PositionSensor, BearingSensor):
def think(self):
print "Current position:", self.position()
print "Current bearing:", self.bearing()
class CustomSensor2(PositionSensor, BearingSensor, Sensor):
pass
>>> s = CustomSensor()
PositionSensor initialized
BearingSensor initialized
>>> s.think()
Current position: (0, 9)
Current bearing: 0
</code></pre>
<p>You'll have to move your <code>__init__</code> code from the Node subclasses into some other method (I used <code>cls_init</code>).</p>
<p><strong>Edit:</strong> I posted this before I saw your updates; I'll re-read your question, and if necessary, update this solution.</p>
| 1
|
2009-03-14T09:14:50Z
|
[
"python",
"constructor",
"oop",
"multiple-inheritance"
] |
Discussion of multiple inheritance vs Composition for a project (+other things)
| 645,493
|
<p>I am writing a python platform for the simulation of distributed sensor swarms. The idea being that the end user can write a custom Node consisting of the SensorNode behaviour (communication, logging, etc) as well as implementing a number of different sensors.</p>
<p>The example below briefly demonstrates the concept.</p>
<pre><code>#prewritten
class Sensor(object):
def __init__(self):
print "Hello from Sensor"
#...
#prewritten
class PositionSensor(Sensor):
def __init__(self):
print "Hello from Position"
Sensor.__init__(self)
#...
#prewritten
class BearingSensor(Sensor):
def __init__(self):
print "Hello from Bearing"
Sensor.__init__(self)
#...
#prewritten
class SensorNode(object):
def __init__(self):
print "Hello from SensorNode"
#...
#USER WRITTEN
class MySensorNode(SensorNode,BearingSensor,PositionSensor):
def CustomMethod(self):
LogData={'Position':position(), 'Bearing':bearing()} #position() from PositionSensor, bearing() from BearingSensor
Log(LogData) #Log() from SensorNode
</code></pre>
<h2>NEW EDIT:</h2>
<p>Firstly an overview of what I am trying to achieve:
I am writing a simulator to simulate swarm intelligence algorithms with particular focus on mobile sensor networks. These networks consist of many small robots communicating individual sensor data to build a complex sensory map of the environment.</p>
<p>The underlying goal of this project is to develop a simulation platform that provides abstracted interfaces to sensors such that the same user-implemented functionality can be directly ported to a robotic swarm running embedded linux. As robotic implementation is the goal, I need to design such that the software node behaves the same, and only has access to information that an physical node would have.</p>
<p>As part of the simulation engine, I will be providing a set of classes modelling different types of sensors and different types of sensor node. I wish to abstract all this complexity away from the user such that all the user must do is define which sensors are present on the node, and what type of sensor node (mobile, fixed position) is being implemented.</p>
<p>My initial thinking was that every sensor would provide a read() method which would return the relevant values, however having read the responses to the question, I see that perhaps more descriptive method names would be beneficial (.distance(), .position(), .bearing(), etc).</p>
<p>I initially wanted use separate classes for the sensors (with common ancestors) so that a more technical user can easily extend one of the existing classes to create a new sensor if they wish. For example:</p>
<pre><code>Sensor
|
DistanceSensor(designed for 360 degree scan range)
| | |
IR Sensor Ultrasonic SickLaser
(narrow) (wider) (very wide)
</code></pre>
<p>The reason I was initially thinking of Multiple Inheritance (although it semi-breaks the IS-A relationship of inheritance) was due to the underlying principle behind the simulation system. Let me explain:</p>
<p>The user-implemented MySensorNode should not have direct access to its position within the environment (akin to a robot, the access is indirect through a sensor interface), similarly, the sensors should not know where they are. However, this lack of direct knowledge poses a problem, as the return values of the sensors are all dependent on their position and orientation within the environment (which needs to be simulated to return the correct values).</p>
<p>SensorNode, as a class implemented within the simulation libraries, is responsible for drawing the MySensorNode within the pygame environment - thus, it is the only class that should have direct access to the position and orientation of the sensor node within the environment.</p>
<p>SensorNode is also responsible for translation and rotation within the environment, however this translation and rotation is a side effect of motor actuation.</p>
<p>What I mean by this is that robots cannot directly alter their position within the world, all they can do is provide power to motors, and movement within the world is a side-effect of the motors interaction with the environment. I need to model this accurately within the simulation.</p>
<p>So, to move, the user-implemented functionality may use:</p>
<pre><code>motors(50,50)
</code></pre>
<p>This call will, as a side-effect, alter the position of the node within the world. </p>
<p>If SensorNode was implemented using composition, SensorNode.motors(...) would not be able to directly alter instance variables (such as position), nor would MySensorNode.draw() be resolved to SensorNode.draw(), so SensorNode imo should be implemented using inheritance.</p>
<p>In terms of the sensors, the benefit of composition for a problem like this is obvious, MySensorNode is composed of a number of sensors - enough said.</p>
<p>However the problem as I see it is that the Sensors need access to their position and orientation within the world, and if you use composition you will end up with a call like:</p>
<pre><code>>>> PosSensor.position((123,456))
(123,456)
</code></pre>
<p>Then again - thinking, you could pass self to the sensor upon initialisation, eg:</p>
<pre><code>PosSensor = PositionSensor(self)
</code></pre>
<p>then later</p>
<pre><code>PosSensor.position()
</code></pre>
<p>however this PosSensor.position() would then need to access information local to the instance (passed as self during <strong>init</strong>()), so why call PosSensor at all when you can access the information locally? Also passing your instance to an object you are composed of just seems not quite right, crossing the boundaries of encapsulation and information hiding (even though python doesn't do much to support the idea of information hiding).</p>
<p>If the solution was implemented using multiple inheritance, these problems would disappear:</p>
<pre><code>class MySensorNode(SensorNode,PositionSensor,BearingSensor):
def Think():
while bearing()>0:
# bearing() is provided by BearingSensor and in the simulator
# will simply access local variables provided by SensorNode
# to return the bearing. In robotic implementation, the
# bearing() method will instead access C routines to read
# the actual bearing from a compass sensor
motors(100,-100)
# spin on the spot, will as a side-effect alter the return
# value of bearing()
(Ox,Oy)=position() #provided by PositionSensor
while True:
(Cx,Cy)=position()
if Cx>=Ox+100:
break
else:
motors(100,100)
#full speed ahead!will alter the return value of position()
</code></pre>
<p><hr /></p>
<p>Hopefully this edit has clarified some things, if you have any questions I'm more than happy to try and clarify them</p>
<h2>OLD THINGS:</h2>
<p>When an object of type MySensorNode is constructed, all constructors from the superclasses need to be called. I do not want to complicate the user with having to write a custom constructor for MySensorNode which calls the constructor from each superclass. Ideally, what I would like to happen is:</p>
<pre><code>mSN = MySensorNode()
# at this point, the __init__() method is searched for
# and SensorNode.__init__() is called given the order
# of inheritance in MySensorNode.__mro__
# Somehow, I would also like to call all the other constructors
# that were not executed (ie BearingSensor and PositionSensor)
</code></pre>
<p>Any insight or general comments would be appreciated,
Cheers :)</p>
<p>OLD EDIT:
Doing something like:</p>
<pre><code>#prewritten
class SensorNode(object):
def __init__(self):
print "Hello from SensorNode"
for clss in type(self).__mro__:
if clss!=SensorNode and clss!=type(self):
clss.__init__(self)
</code></pre>
<p>This works, as self is an instance of MySensorNode. However this solution is messy.</p>
<p><hr /></p>
| 13
|
2009-03-14T06:04:55Z
| 645,819
|
<p>The sensor architecture can be solved by using composition if you want to stick to your original map-of-data design. You seem to be new to Python so I'll try to keep idioms to a minimum.</p>
<pre><code>class IRSensor:
def read(self): return {'ir_amplitude': 12}
class UltrasonicSensor:
def read(self): return {'ultrasonic_amplitude': 63}
class SickLaserSensor:
def read(self): return {'laser_amplitude': 55}
class CompositeSensor:
"""Wrap multiple component sensors, coalesce the results, and return
the composite readout.
"""
component_sensors = []
def __init__(self, component_sensors=None):
component_sensors = component_sensors or self.component_sensors
self.sensors = [cls() for cls in component_sensors]
def read(self):
measurements = {}
for sensor in self.sensors:
measurements.update(sensor.read())
return measurements
class MyCompositeSensor(CompositeSensor):
component_sensors = [UltrasonicSensor, IRSensor]
composite_sensor = MyCompositeSensor()
measurement_map = composite_sensor.read()
assert measurement_map['ultrasonic_amplitude'] == 63
assert measurement_map['ir_amplitude'] == 12
</code></pre>
<p>The architectural problem you're describing with the actuators is solved by using mixins and <strong>proxying</strong> (via <code>__getattr__</code>) rather than inheritance. (Proxying can be a nice alternative to inheritance because objects to proxy to can be bound/unbound at runtime. Also, you don't have to worry about handling all initialization in a single constructor using this technique.)</p>
<pre><code>class MovementActuator:
def __init__(self, x=0, y=0):
self.x, self.y = (x, y)
def move(self, x, y):
print 'Moving to', x, y
self.x, self.y = (x, y)
def get_position(self):
return (self.x, self.y)
class CommunicationActuator:
def communicate(self):
return 'Hey you out there!'
class CompositeActuator:
component_actuators = []
def __init__(self, component_actuators=None):
component_actuators = component_actuators \
or self.component_actuators
self.actuators = [cls() for cls in component_actuators]
def __getattr__(self, attr_name):
"""Look for value in component sensors."""
for actuator in self.actuators:
if hasattr(actuator, attr_name):
return getattr(actuator, attr_name)
raise AttributeError(attr_name)
class MyCompositeActuator(CompositeActuator):
component_actuators = [MovementActuator, CommunicationActuator]
composite_actuator = MyCompositeActuator()
assert composite_actuator.get_position() == (0, 0)
assert composite_actuator.communicate() == 'Hey you out there!'
</code></pre>
<p>And finally, you can throw it all together with a simple node declaration:</p>
<pre><code>from sensors import *
from actuators import *
class AbstractNode:
sensors = [] # Set of classes.
actuators = [] # Set of classes.
def __init__(self):
self.composite_sensor = CompositeSensor(self.sensors)
self.composite_actuator = CompositeActuator(self.actuators)
class MyNode(AbstractNode):
sensors = [UltrasonicSensor, SickLaserSensor]
actuators = [MovementActuator, CommunicationActuator]
def think(self):
measurement_map = self.composite_sensor.read()
while self.composite_actuator.get_position()[1] >= 0:
self.composite_actuator.move(100, -100)
my_node = MyNode()
my_node.think()
</code></pre>
<p>That should give you an idea of the alternatives to the rigid type system. Note that you don't have to rely on the type hierarchy at all -- just implement to a (potentially implicit) common interface.</p>
<h1>LESS OLD:</h1>
<p>After reading the question more carefully, I see that what you have is a classic example of <a href="http://en.wikipedia.org/wiki/Diamond%5Fproblem">diamond inheritance</a>, which is the <a href="http://code.activestate.com/recipes/146462/">evil that makes people flee</a> towards single inheritance.</p>
<p>You probably don't want this to begin with, since class hierarchy means squat in Python. What you want to do is make a <code>SensorInterface</code> (minimum requirements for a sensor) and have a bunch of "mixin" classes that have totally independent functionality that can be invoked through methods of various names. In your sensor framework you shouldn't say things like <code>isinstance(sensor, PositionSensor)</code> -- you should say things like "can this sensor geo-locate?" in the following form:</p>
<pre><code>def get_position(sensor):
try:
return sensor.geolocate()
except AttributeError:
return None
</code></pre>
<p>This is the heart of duck-typing philosophy and <a href="http://en.wikipedia.org/wiki/Python%5Fsyntax%5Fand%5Fsemantics#Exceptions">EAFP</a> (Easier to Ask for Forgiveness than Permission), both of which the Python language embraces.</p>
<p>You should probably describe what methods these sensors will actually implement so we can describe how you can use mixin classes for your plugin architecture.</p>
<h1>OLD:</h1>
<p>If they write the code in a module that gets put in a plugin package or what have you, you can magically instrument the classes for them when you import their plugin modules. Something along the lines of this snippet (untested):</p>
<pre><code> import inspect
import types
from sensors import Sensor
def is_class(obj):
return type(obj) in (types.ClassType, types.TypeType)
def instrumented_init(self, *args, **kwargs):
Sensor.__init__(self, *args, **kwargs)
for module in plugin_modules: # Get this from somewhere...
classes = inspect.getmembers(module, predicate=is_class)
for name, cls in classes:
if hasattr(cls, '__init__'):
# User specified own init, may be deriving from something else.
continue
if cls.__bases__ != tuple([Sensor]):
continue # Class doesn't singly inherit from sensor.
cls.__init__ = instrumented_init
</code></pre>
<p>You can <a href="http://stackoverflow.com/questions/487971/is-there-a-standard-way-to-list-names-of-python-modules-in-a-package">find the modules within a package</a> with another function.</p>
| 9
|
2009-03-14T12:11:31Z
|
[
"python",
"constructor",
"oop",
"multiple-inheritance"
] |
Changing prompt working directory via Python script
| 645,864
|
<p>Is it possible to change the Windows command prompt working directory via Python script?</p>
<p>e.g.</p>
<pre><code>>> cd
>> c:\windows\system32
>> make_decision_change_dir.py
>> cd
>> c:\windows
</code></pre>
<p>I have tried a few things which don't work:</p>
<pre><code>import os
os.chdir(path)
</code></pre>
<p><hr /></p>
<pre><code>import os, subprocess
subprocess.Popen("chdir /D \"%s\"" %path, shell=True)
</code></pre>
<p><hr /></p>
<pre><code>import os, subprocess
subprocess.Popen("cd \"%s\"" %path, shell=True)
</code></pre>
<p><hr /></p>
<pre><code>import os, subprocess
subprocess.Popen("CD=\"%s\"" %path, shell=True)
</code></pre>
<p>As I understand it and observe these operations change the current processes working directory - which is the Python process and not the prompt its executing from.</p>
<p>Thanks.</p>
<p>UPDATE</p>
<p>The path I would want to change to is dynamic (based on what project I am working on, the full path to a build location changes) hence I wanted to code a solution in Python rather than hack around with a Windows batch file.</p>
<p>UPDATE</p>
<p>I ended up hacking a batch file together to do this ;(
Thanks everyone.</p>
| 3
|
2009-03-14T12:45:32Z
| 645,874
|
<p>I'm not clear what you want to do here. Do you want a python script which you can run from a Windows command prompt which will change the working directory of the Windows command session?</p>
<p>If so, I'm 99.9% sure that's impossible. As you said yourself the <code>python.exe</code> process is a separate process from the Windows <code>cmd.exe</code> and anything you do in Python won't affect the Command prompt.</p>
<p>There may be something you can do via the Windows API by sending keystrokes to the Windows or something but it would be pretty brittle.</p>
<p>The only two practical options I can think of involve wrapping your Python script in a Batch file:</p>
<ol>
<li>Output your desired directory from the Python script, read the output in your Batch file and CD to it.</li>
<li>Start your Python script from a batch file, allow your Python script to start a new <code>cmd.exe</code> Window and get the Batch file to close the original Command window.</li>
</ol>
| 3
|
2009-03-14T12:52:06Z
|
[
"python",
"windows",
"scripting"
] |
Changing prompt working directory via Python script
| 645,864
|
<p>Is it possible to change the Windows command prompt working directory via Python script?</p>
<p>e.g.</p>
<pre><code>>> cd
>> c:\windows\system32
>> make_decision_change_dir.py
>> cd
>> c:\windows
</code></pre>
<p>I have tried a few things which don't work:</p>
<pre><code>import os
os.chdir(path)
</code></pre>
<p><hr /></p>
<pre><code>import os, subprocess
subprocess.Popen("chdir /D \"%s\"" %path, shell=True)
</code></pre>
<p><hr /></p>
<pre><code>import os, subprocess
subprocess.Popen("cd \"%s\"" %path, shell=True)
</code></pre>
<p><hr /></p>
<pre><code>import os, subprocess
subprocess.Popen("CD=\"%s\"" %path, shell=True)
</code></pre>
<p>As I understand it and observe these operations change the current processes working directory - which is the Python process and not the prompt its executing from.</p>
<p>Thanks.</p>
<p>UPDATE</p>
<p>The path I would want to change to is dynamic (based on what project I am working on, the full path to a build location changes) hence I wanted to code a solution in Python rather than hack around with a Windows batch file.</p>
<p>UPDATE</p>
<p>I ended up hacking a batch file together to do this ;(
Thanks everyone.</p>
| 3
|
2009-03-14T12:45:32Z
| 645,881
|
<p>The <a href="http://docs.python.org/library/subprocess.html#subprocess.Popen" rel="nofollow"><code>subprocess.Popen()</code> doc page</a> says a child process will be created for the sub-process, so any working directory changes will be local to that subprocess.</p>
<blockquote>
<p>If cwd is not None, the <strong>childâs</strong> current directory will be changed to cwd before it is executed. Note that this directory is not considered when searching the executable, so you canât specify the programâs path relative to cwd.</p>
</blockquote>
<p>This will be the same for any changes done explicitly inside the subproceess, similar to the commands that appear in the question.</p>
| 0
|
2009-03-14T13:02:21Z
|
[
"python",
"windows",
"scripting"
] |
Changing prompt working directory via Python script
| 645,864
|
<p>Is it possible to change the Windows command prompt working directory via Python script?</p>
<p>e.g.</p>
<pre><code>>> cd
>> c:\windows\system32
>> make_decision_change_dir.py
>> cd
>> c:\windows
</code></pre>
<p>I have tried a few things which don't work:</p>
<pre><code>import os
os.chdir(path)
</code></pre>
<p><hr /></p>
<pre><code>import os, subprocess
subprocess.Popen("chdir /D \"%s\"" %path, shell=True)
</code></pre>
<p><hr /></p>
<pre><code>import os, subprocess
subprocess.Popen("cd \"%s\"" %path, shell=True)
</code></pre>
<p><hr /></p>
<pre><code>import os, subprocess
subprocess.Popen("CD=\"%s\"" %path, shell=True)
</code></pre>
<p>As I understand it and observe these operations change the current processes working directory - which is the Python process and not the prompt its executing from.</p>
<p>Thanks.</p>
<p>UPDATE</p>
<p>The path I would want to change to is dynamic (based on what project I am working on, the full path to a build location changes) hence I wanted to code a solution in Python rather than hack around with a Windows batch file.</p>
<p>UPDATE</p>
<p>I ended up hacking a batch file together to do this ;(
Thanks everyone.</p>
| 3
|
2009-03-14T12:45:32Z
| 645,967
|
<p>One common solution is a two-part script.</p>
<p>Part 1 is Python, which creates a temporary .BAT file that contains the appropriate CD command.</p>
<p>Part 2 is the temporary .BAT file.</p>
<p>fancycd.bat</p>
<pre><code>python figurethepath.py >temp.bat
temp.bat
</code></pre>
| 1
|
2009-03-14T14:09:16Z
|
[
"python",
"windows",
"scripting"
] |
Changing prompt working directory via Python script
| 645,864
|
<p>Is it possible to change the Windows command prompt working directory via Python script?</p>
<p>e.g.</p>
<pre><code>>> cd
>> c:\windows\system32
>> make_decision_change_dir.py
>> cd
>> c:\windows
</code></pre>
<p>I have tried a few things which don't work:</p>
<pre><code>import os
os.chdir(path)
</code></pre>
<p><hr /></p>
<pre><code>import os, subprocess
subprocess.Popen("chdir /D \"%s\"" %path, shell=True)
</code></pre>
<p><hr /></p>
<pre><code>import os, subprocess
subprocess.Popen("cd \"%s\"" %path, shell=True)
</code></pre>
<p><hr /></p>
<pre><code>import os, subprocess
subprocess.Popen("CD=\"%s\"" %path, shell=True)
</code></pre>
<p>As I understand it and observe these operations change the current processes working directory - which is the Python process and not the prompt its executing from.</p>
<p>Thanks.</p>
<p>UPDATE</p>
<p>The path I would want to change to is dynamic (based on what project I am working on, the full path to a build location changes) hence I wanted to code a solution in Python rather than hack around with a Windows batch file.</p>
<p>UPDATE</p>
<p>I ended up hacking a batch file together to do this ;(
Thanks everyone.</p>
| 3
|
2009-03-14T12:45:32Z
| 646,103
|
<p>I have a Python script to make moving around a file tree easier: <a href="http://nedbatchelder.com/code/utilities/xdir%5Fpy.html" rel="nofollow">xdir.py</a></p>
<p>Briefly, I have an xdir.py file, which writes Windows commands to stdout:</p>
<pre><code># Obviously, this should be more interesting..
import sys
print "cd", sys.argv[1]
</code></pre>
<p>Then an xdir.cmd file:</p>
<pre><code>@echo off
python xdir.py %* >%TEMP%\__xdir.cmd
call %TEMP%\__xdir.cmd
</code></pre>
<p>Then I create a doskey alias:</p>
<pre><code>doskey x=xdir.cmd $*
</code></pre>
<p>The end result is that I can type</p>
<pre><code>$ x subdir
</code></pre>
<p>and change into subdir.</p>
<p>The script I linked to above does much more, including remembering history, maintaining a stack of directories, accepting shorthand for directories, and so on.</p>
| 2
|
2009-03-14T15:33:59Z
|
[
"python",
"windows",
"scripting"
] |
Changing prompt working directory via Python script
| 645,864
|
<p>Is it possible to change the Windows command prompt working directory via Python script?</p>
<p>e.g.</p>
<pre><code>>> cd
>> c:\windows\system32
>> make_decision_change_dir.py
>> cd
>> c:\windows
</code></pre>
<p>I have tried a few things which don't work:</p>
<pre><code>import os
os.chdir(path)
</code></pre>
<p><hr /></p>
<pre><code>import os, subprocess
subprocess.Popen("chdir /D \"%s\"" %path, shell=True)
</code></pre>
<p><hr /></p>
<pre><code>import os, subprocess
subprocess.Popen("cd \"%s\"" %path, shell=True)
</code></pre>
<p><hr /></p>
<pre><code>import os, subprocess
subprocess.Popen("CD=\"%s\"" %path, shell=True)
</code></pre>
<p>As I understand it and observe these operations change the current processes working directory - which is the Python process and not the prompt its executing from.</p>
<p>Thanks.</p>
<p>UPDATE</p>
<p>The path I would want to change to is dynamic (based on what project I am working on, the full path to a build location changes) hence I wanted to code a solution in Python rather than hack around with a Windows batch file.</p>
<p>UPDATE</p>
<p>I ended up hacking a batch file together to do this ;(
Thanks everyone.</p>
| 3
|
2009-03-14T12:45:32Z
| 647,744
|
<p>As people mentioned, child processes (i.e. your program) can't change the current working directory of a parent process (i.e. the terminal). This is why you need the two steps that everybody is describing. In most shells there's a way to make a macro or function to perform this two-step functionality.</p>
<p>For example, in <code>bash</code>, you can make a single alias to compute the path and change the current working directory, similar to what <a href="http://stackoverflow.com/questions/645864/python-scripting-changing-prompt-working-directory/645967#645967">@S.Lott</a> describes for Windows:</p>
<pre><code>alias my_cd='TMP=`compute_path.py`; cd $TMP;'
</code></pre>
<p>Note that the <code>cd</code> command is still being interpreted in the parent process (the terminal), which has the ability to change its own current working directory.</p>
| 1
|
2009-03-15T12:33:24Z
|
[
"python",
"windows",
"scripting"
] |
Is there a way to build a C-like DLL from a Python module?
| 645,892
|
<p>I have a Python module with nothing but regular global functions. I need to call it from another business-domain scripting environment that can only call out to C DLLs. Is there anyway to build my Python modules so that to other code it can be called like a standard C function that's exported from a DLL? This is for a Windows environment. I'm aware of IronPython, but as far as I know it can only build .NET Assemblies, which are not callable as C DLL functions.</p>
| 7
|
2009-03-14T13:11:49Z
| 645,905
|
<p>Take a look at <a href="http://www.codeproject.com/KB/cpp/embedpython%5F1.aspx">this</a> Codeproject article. One way would be wrap your python functions in a C dll and expose this to the callee.</p>
<p>COM is a binary protocol to solve this issue. But you will have to wrap this python dll in a COM wrapper. And add some code on the calling side as well.</p>
| 6
|
2009-03-14T13:24:45Z
|
[
"python"
] |
Is there a way to build a C-like DLL from a Python module?
| 645,892
|
<p>I have a Python module with nothing but regular global functions. I need to call it from another business-domain scripting environment that can only call out to C DLLs. Is there anyway to build my Python modules so that to other code it can be called like a standard C function that's exported from a DLL? This is for a Windows environment. I'm aware of IronPython, but as far as I know it can only build .NET Assemblies, which are not callable as C DLL functions.</p>
| 7
|
2009-03-14T13:11:49Z
| 645,924
|
<p>The standard solution is to embed the Python interpreter (which is already a C DLL) in your application.</p>
<p><a href="https://docs.python.org/extending/windows.html#using-dlls-in-practice" rel="nofollow">https://docs.python.org/extending/windows.html#using-dlls-in-practice</a></p>
<p><a href="http://docs.python.org/extending/embedding.html" rel="nofollow">http://docs.python.org/extending/embedding.html</a></p>
| 3
|
2009-03-14T13:41:54Z
|
[
"python"
] |
Is there a way to build a C-like DLL from a Python module?
| 645,892
|
<p>I have a Python module with nothing but regular global functions. I need to call it from another business-domain scripting environment that can only call out to C DLLs. Is there anyway to build my Python modules so that to other code it can be called like a standard C function that's exported from a DLL? This is for a Windows environment. I'm aware of IronPython, but as far as I know it can only build .NET Assemblies, which are not callable as C DLL functions.</p>
| 7
|
2009-03-14T13:11:49Z
| 645,935
|
<p>Py2exe can generate COM dlls from python code, by compiling and embedding python code + interpreter. It does not, AFAIK, support regular DLLs yet. For that, see dirkgently's answer about embedding python yourself.</p>
| 2
|
2009-03-14T13:49:25Z
|
[
"python"
] |
Integrating MySQL with Python in Windows
| 645,943
|
<p>I am finding it difficult to use MySQL with Python in my windows system.</p>
<p>I am currently using Python 2.6. I have tried to compile MySQL-python-1.2.3b1 (which is supposed to work for Python 2.6 ?) source code using the provided setup scripts. The setup script runs and it doesn't report any error but it doesn't generate _mysql module. </p>
<p>I have also tried setting up MySQL for Python 2.5 with out success. The problem with using 2.5 is that Python 2.5 is compiled with visual studio 2003 (I installed it using the provided binaries). I have visual studio 2005 on my windows system. Hence setuptools fails to generate _mysql module.</p>
<p>Any help ?</p>
| 94
|
2009-03-14T13:53:28Z
| 645,958
|
<p>You're not the only person having problems with Python 2.6 and MySQL (<a href="http://blog.contriving.net/2009/03/04/using-python-26-mysql-on-windows-is-nearly-impossible/" rel="nofollow">http://blog.contriving.net/2009/03/04/using-python-26-mysql-on-windows-is-nearly-impossible/</a>). Here's an explanation how it should run under Python 2.5 <a href="http://i.justrealized.com/2008/04/08/how-to-install-python-and-django-in-windows-vista/" rel="nofollow">http://i.justrealized.com/2008/04/08/how-to-install-python-and-django-in-windows-vista/</a>
Good luck</p>
| 2
|
2009-03-14T14:04:00Z
|
[
"python",
"mysql",
"windows"
] |
Integrating MySQL with Python in Windows
| 645,943
|
<p>I am finding it difficult to use MySQL with Python in my windows system.</p>
<p>I am currently using Python 2.6. I have tried to compile MySQL-python-1.2.3b1 (which is supposed to work for Python 2.6 ?) source code using the provided setup scripts. The setup script runs and it doesn't report any error but it doesn't generate _mysql module. </p>
<p>I have also tried setting up MySQL for Python 2.5 with out success. The problem with using 2.5 is that Python 2.5 is compiled with visual studio 2003 (I installed it using the provided binaries). I have visual studio 2005 on my windows system. Hence setuptools fails to generate _mysql module.</p>
<p>Any help ?</p>
| 94
|
2009-03-14T13:53:28Z
| 645,961
|
<p>There are <a href="http://sourceforge.net/project/showfiles.php?group%5Fid=22307&package%5Fid=15775" rel="nofollow">Windows binaries for MySQL-Python (2.4 & 2.5) available on Sourceforge</a>. Have you tried those?</p>
| 2
|
2009-03-14T14:05:12Z
|
[
"python",
"mysql",
"windows"
] |
Integrating MySQL with Python in Windows
| 645,943
|
<p>I am finding it difficult to use MySQL with Python in my windows system.</p>
<p>I am currently using Python 2.6. I have tried to compile MySQL-python-1.2.3b1 (which is supposed to work for Python 2.6 ?) source code using the provided setup scripts. The setup script runs and it doesn't report any error but it doesn't generate _mysql module. </p>
<p>I have also tried setting up MySQL for Python 2.5 with out success. The problem with using 2.5 is that Python 2.5 is compiled with visual studio 2003 (I installed it using the provided binaries). I have visual studio 2005 on my windows system. Hence setuptools fails to generate _mysql module.</p>
<p>Any help ?</p>
| 94
|
2009-03-14T13:53:28Z
| 647,469
|
<p>I found a location were one person had successfully built mysql for python2.6, sharing the link, <a href="http://www.technicalbard.com/files/MySQL-python-1.2.2.win32-py2.6.exe" rel="nofollow">http://www.technicalbard.com/files/MySQL-python-1.2.2.win32-py2.6.exe</a></p>
<p>...you might see a warning while import MySQLdb which is fine and that wonât hurt anything,</p>
<p>C:\Python26\lib\site-packages\MySQLdb__init__.py:34: DeprecationWarning: the sets module is deprecated
from sets import ImmutableSet</p>
| 7
|
2009-03-15T08:11:23Z
|
[
"python",
"mysql",
"windows"
] |
Integrating MySQL with Python in Windows
| 645,943
|
<p>I am finding it difficult to use MySQL with Python in my windows system.</p>
<p>I am currently using Python 2.6. I have tried to compile MySQL-python-1.2.3b1 (which is supposed to work for Python 2.6 ?) source code using the provided setup scripts. The setup script runs and it doesn't report any error but it doesn't generate _mysql module. </p>
<p>I have also tried setting up MySQL for Python 2.5 with out success. The problem with using 2.5 is that Python 2.5 is compiled with visual studio 2003 (I installed it using the provided binaries). I have visual studio 2005 on my windows system. Hence setuptools fails to generate _mysql module.</p>
<p>Any help ?</p>
| 94
|
2009-03-14T13:53:28Z
| 749,854
|
<p>You might want to also consider making use of <a href="http://cygwin.org" rel="nofollow">Cygwin</a>, it has mysql python libraries in the repository. </p>
| 0
|
2009-04-15T00:25:59Z
|
[
"python",
"mysql",
"windows"
] |
Integrating MySQL with Python in Windows
| 645,943
|
<p>I am finding it difficult to use MySQL with Python in my windows system.</p>
<p>I am currently using Python 2.6. I have tried to compile MySQL-python-1.2.3b1 (which is supposed to work for Python 2.6 ?) source code using the provided setup scripts. The setup script runs and it doesn't report any error but it doesn't generate _mysql module. </p>
<p>I have also tried setting up MySQL for Python 2.5 with out success. The problem with using 2.5 is that Python 2.5 is compiled with visual studio 2003 (I installed it using the provided binaries). I have visual studio 2005 on my windows system. Hence setuptools fails to generate _mysql module.</p>
<p>Any help ?</p>
| 94
|
2009-03-14T13:53:28Z
| 817,760
|
<p>As Python newbie learning the Python ecosystem I've just completed this.</p>
<ol>
<li><p>Install setuptools <a href="http://stackoverflow.com/questions/309412/how-to-setup-setuptools-for-python-2-6-on-windows">instructions</a></p></li>
<li><p>Install MySQL 5.1. Download the 97.6MB MSI from <a href="http://dev.mysql.com/downloads/mysql/5.1.html#win32">here</a> You can't use the essentials version because it doesnt contain the C libraries.<br />
Be sure to select a custom install, and mark the development tools / libraries for installation as that is not done by default. This is needed to get the C header files.<br />
You can verify you have done this correctly by looking in your install directory for a folder named "include". E.G C:\Program Files\MySQL\MySQL Server 5.1\include. It should have a whole bunch of .h files.</p></li>
<li><p>Install Microsoft Visual Studio C++ Express 2008 from <a href="http://www.microsoft.com/express/vc/">here</a> This is needed to get a C compiler.</p></li>
<li><p>Open up a command line as administrator (right click on the Cmd shortcut and then "run as administrator". Be sure to open a fresh window <em>after</em> you have installed those things or your path won't be updated and the install will still fail.</p></li>
<li><p>From the command prompt:</p>
<p>easy_install -b C:\temp\sometempdir mysql-python</p>
<p>That will fail - which is OK.</p>
<p>Now open site.cfg in your temp directory C:\temp\sometempdir and edit the "registry_key" setting to:</p>
<p>registry_key = SOFTWARE\MySQL AB\MySQL Server 5.1</p>
<p>now CD into your temp dir and:</p>
<p>python setup.py clean</p>
<p>python setup.py install </p>
<p>You should be ready to rock!</p></li>
<li><p><a href="http://www.kitebird.com/articles/pydbapi.html">Here</a> is a super simple script to start off learning the Python DB API for you - if you need it.</p></li>
</ol>
| 14
|
2009-05-03T19:13:31Z
|
[
"python",
"mysql",
"windows"
] |
Integrating MySQL with Python in Windows
| 645,943
|
<p>I am finding it difficult to use MySQL with Python in my windows system.</p>
<p>I am currently using Python 2.6. I have tried to compile MySQL-python-1.2.3b1 (which is supposed to work for Python 2.6 ?) source code using the provided setup scripts. The setup script runs and it doesn't report any error but it doesn't generate _mysql module. </p>
<p>I have also tried setting up MySQL for Python 2.5 with out success. The problem with using 2.5 is that Python 2.5 is compiled with visual studio 2003 (I installed it using the provided binaries). I have visual studio 2005 on my windows system. Hence setuptools fails to generate _mysql module.</p>
<p>Any help ?</p>
| 94
|
2009-03-14T13:53:28Z
| 847,577
|
<p><a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python">Download page for python-mysqldb</a>. The page includes binaries for 32 and 64 bit versions of for Python 2.5, 2.6 and 2.7. </p>
<p>There's also <a href="http://sourceforge.net/forum/message.php?msg_id=5808948">discussion on getting rid of the deprecation warning</a>.</p>
<p><strong>UPDATE</strong>: This is an old answer. Currently, I would recommend using PyMySQL. It's pure python, so it supports all OSes equally, it's almost a drop-in replacement for mysqldb, and it also works with python 3. The best way to install it is using pip. You can install it from <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#pip">here</a> (more instructions <a href="http://stackoverflow.com/a/12476379/7581">here</a>), and then run:</p>
<pre><code>pip install pymysql
</code></pre>
| 124
|
2009-05-11T10:43:27Z
|
[
"python",
"mysql",
"windows"
] |
Integrating MySQL with Python in Windows
| 645,943
|
<p>I am finding it difficult to use MySQL with Python in my windows system.</p>
<p>I am currently using Python 2.6. I have tried to compile MySQL-python-1.2.3b1 (which is supposed to work for Python 2.6 ?) source code using the provided setup scripts. The setup script runs and it doesn't report any error but it doesn't generate _mysql module. </p>
<p>I have also tried setting up MySQL for Python 2.5 with out success. The problem with using 2.5 is that Python 2.5 is compiled with visual studio 2003 (I installed it using the provided binaries). I have visual studio 2005 on my windows system. Hence setuptools fails to generate _mysql module.</p>
<p>Any help ?</p>
| 94
|
2009-03-14T13:53:28Z
| 3,242,143
|
<p>This may read like your grandpa givin advice, but all answers here did not mention the best way: go nd install <a href="http://www.activestate.com/activepython/downloads">ActivePython</a> instead of python.org windows binaries. I was really wondering for a long time why Python development on windows was such a pita - until I installed activestate python. I am not affiliated with them. It is just the plain truth. Write it on every wall: <strong>Python development on Windows = ActiveState</strong>!
you then just <a href="http://code.activestate.com/pypm/mysql-python/"><code>pypm install mysql-python</code></a> and everything works smoothly. <strong>no compile orgy. no strange errors. no terror.</strong> Just start coding and doing real work after five minutes.
This is the only way to go on windows. Really.</p>
| 30
|
2010-07-13T22:44:36Z
|
[
"python",
"mysql",
"windows"
] |
Integrating MySQL with Python in Windows
| 645,943
|
<p>I am finding it difficult to use MySQL with Python in my windows system.</p>
<p>I am currently using Python 2.6. I have tried to compile MySQL-python-1.2.3b1 (which is supposed to work for Python 2.6 ?) source code using the provided setup scripts. The setup script runs and it doesn't report any error but it doesn't generate _mysql module. </p>
<p>I have also tried setting up MySQL for Python 2.5 with out success. The problem with using 2.5 is that Python 2.5 is compiled with visual studio 2003 (I installed it using the provided binaries). I have visual studio 2005 on my windows system. Hence setuptools fails to generate _mysql module.</p>
<p>Any help ?</p>
| 94
|
2009-03-14T13:53:28Z
| 4,304,554
|
<p>What about <a href="http://code.google.com/p/pymysql/">pymysql</a>? It's pure Python, and I've used it on Windows with considerable success, bypassing the difficulties of compiling and installing mysql-python.</p>
| 5
|
2010-11-29T14:13:38Z
|
[
"python",
"mysql",
"windows"
] |
Integrating MySQL with Python in Windows
| 645,943
|
<p>I am finding it difficult to use MySQL with Python in my windows system.</p>
<p>I am currently using Python 2.6. I have tried to compile MySQL-python-1.2.3b1 (which is supposed to work for Python 2.6 ?) source code using the provided setup scripts. The setup script runs and it doesn't report any error but it doesn't generate _mysql module. </p>
<p>I have also tried setting up MySQL for Python 2.5 with out success. The problem with using 2.5 is that Python 2.5 is compiled with visual studio 2003 (I installed it using the provided binaries). I have visual studio 2005 on my windows system. Hence setuptools fails to generate _mysql module.</p>
<p>Any help ?</p>
| 94
|
2009-03-14T13:53:28Z
| 5,294,670
|
<p>Because I am running python in a (pylons/pyramid) virtualenv, I could not run the binary installers (helpfully) linked to previously. </p>
<p>I had problems following the steps with Willie's answer, but I determined that the problem is (probably) that I am running windows 7 x64 install, which puts the registry key for mysql in a slightly different location, specifically in my case (note: I am running version 5.5) in: "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MySQL AB\MySQL Server 5.5".</p>
<p>HOWEVER, "HKEY_LOCAL_MACHINE\" cannot be included in the path or it will fail.</p>
<p>Also, I had to do a restart between steps 3 and 4.</p>
<p>After working through all of this, IMO it would have been smarter to run the entire python dev environment from cygwin.</p>
| 1
|
2011-03-14T04:15:55Z
|
[
"python",
"mysql",
"windows"
] |
Integrating MySQL with Python in Windows
| 645,943
|
<p>I am finding it difficult to use MySQL with Python in my windows system.</p>
<p>I am currently using Python 2.6. I have tried to compile MySQL-python-1.2.3b1 (which is supposed to work for Python 2.6 ?) source code using the provided setup scripts. The setup script runs and it doesn't report any error but it doesn't generate _mysql module. </p>
<p>I have also tried setting up MySQL for Python 2.5 with out success. The problem with using 2.5 is that Python 2.5 is compiled with visual studio 2003 (I installed it using the provided binaries). I have visual studio 2005 on my windows system. Hence setuptools fails to generate _mysql module.</p>
<p>Any help ?</p>
| 94
|
2009-03-14T13:53:28Z
| 6,727,250
|
<p>You can try to use the myPySQL, its realy easy to use it, no compilation for windows, and even if you need to compilate it for any reason, you only need python and visual C installed, don't need mysql installed.</p>
<p><a href="http://code.google.com/p/mypysql/" rel="nofollow">http://code.google.com/p/mypysql/</a></p>
<p>Good luck</p>
| 2
|
2011-07-17T22:37:27Z
|
[
"python",
"mysql",
"windows"
] |
Integrating MySQL with Python in Windows
| 645,943
|
<p>I am finding it difficult to use MySQL with Python in my windows system.</p>
<p>I am currently using Python 2.6. I have tried to compile MySQL-python-1.2.3b1 (which is supposed to work for Python 2.6 ?) source code using the provided setup scripts. The setup script runs and it doesn't report any error but it doesn't generate _mysql module. </p>
<p>I have also tried setting up MySQL for Python 2.5 with out success. The problem with using 2.5 is that Python 2.5 is compiled with visual studio 2003 (I installed it using the provided binaries). I have visual studio 2005 on my windows system. Hence setuptools fails to generate _mysql module.</p>
<p>Any help ?</p>
| 94
|
2009-03-14T13:53:28Z
| 7,729,931
|
<p>You can also use <a href="http://code.google.com/p/pyodbc/" rel="nofollow">pyodbc</a> with the <a href="http://dev.mysql.com/downloads/connector/odbc/" rel="nofollow">MySQL Connector/ODBC</a> to use MySQL on Windows. <a href="http://www.unixodbc.org/" rel="nofollow">Unixodbc</a> is also available to make the code compatible on Linux. Pyodbc uses the standard Python <a href="http://www.python.org/dev/peps/pep-0249/" rel="nofollow">DB API 2.0</a> so if you stick with that switching between MySQL/PostgreSQL/SQLite/ODBC/JDBC drivers etc. should be relatively painless.</p>
| 0
|
2011-10-11T17:20:14Z
|
[
"python",
"mysql",
"windows"
] |
Integrating MySQL with Python in Windows
| 645,943
|
<p>I am finding it difficult to use MySQL with Python in my windows system.</p>
<p>I am currently using Python 2.6. I have tried to compile MySQL-python-1.2.3b1 (which is supposed to work for Python 2.6 ?) source code using the provided setup scripts. The setup script runs and it doesn't report any error but it doesn't generate _mysql module. </p>
<p>I have also tried setting up MySQL for Python 2.5 with out success. The problem with using 2.5 is that Python 2.5 is compiled with visual studio 2003 (I installed it using the provided binaries). I have visual studio 2005 on my windows system. Hence setuptools fails to generate _mysql module.</p>
<p>Any help ?</p>
| 94
|
2009-03-14T13:53:28Z
| 9,385,307
|
<p>upvoted itsadok's answer because it led me to the installation for python 2.7 as well, which is located here: <a href="http://www.codegood.com/archives/129" rel="nofollow">http://www.codegood.com/archives/129</a></p>
| 0
|
2012-02-21T21:17:50Z
|
[
"python",
"mysql",
"windows"
] |
Integrating MySQL with Python in Windows
| 645,943
|
<p>I am finding it difficult to use MySQL with Python in my windows system.</p>
<p>I am currently using Python 2.6. I have tried to compile MySQL-python-1.2.3b1 (which is supposed to work for Python 2.6 ?) source code using the provided setup scripts. The setup script runs and it doesn't report any error but it doesn't generate _mysql module. </p>
<p>I have also tried setting up MySQL for Python 2.5 with out success. The problem with using 2.5 is that Python 2.5 is compiled with visual studio 2003 (I installed it using the provided binaries). I have visual studio 2005 on my windows system. Hence setuptools fails to generate _mysql module.</p>
<p>Any help ?</p>
| 94
|
2009-03-14T13:53:28Z
| 11,784,789
|
<p>If you are looking for Python 3.2 this seems the best solution I found so far </p>
<ul>
<li>for Python 2.4 - 3.2 <a href="https://github.com/petehunt/PyMySQL" rel="nofollow">PyMySQL</a> </li>
<li>for Python 2.3 - 2.6 <a href="http://sourceforge.net/projects/mysql-python" rel="nofollow">MySQL for Python</a> </li>
</ul>
<p>Source: <a href="http://wiki.python.org/moin/MySQL" rel="nofollow">http://wiki.python.org/moin/MySQL</a></p>
| 1
|
2012-08-02T19:53:09Z
|
[
"python",
"mysql",
"windows"
] |
Integrating MySQL with Python in Windows
| 645,943
|
<p>I am finding it difficult to use MySQL with Python in my windows system.</p>
<p>I am currently using Python 2.6. I have tried to compile MySQL-python-1.2.3b1 (which is supposed to work for Python 2.6 ?) source code using the provided setup scripts. The setup script runs and it doesn't report any error but it doesn't generate _mysql module. </p>
<p>I have also tried setting up MySQL for Python 2.5 with out success. The problem with using 2.5 is that Python 2.5 is compiled with visual studio 2003 (I installed it using the provided binaries). I have visual studio 2005 on my windows system. Hence setuptools fails to generate _mysql module.</p>
<p>Any help ?</p>
| 94
|
2009-03-14T13:53:28Z
| 12,160,302
|
<p>Got sick of the installation troubles with MySQLdb and tried <a href="http://www.pymysql.org/" rel="nofollow">pymysql</a> instead.</p>
<p>Easy setup;</p>
<pre><code>git clone https://github.com/petehunt/PyMySQL.git
python setup.py install
</code></pre>
<p>And APIs are pretty much the same.</p>
| 0
|
2012-08-28T13:27:27Z
|
[
"python",
"mysql",
"windows"
] |
Integrating MySQL with Python in Windows
| 645,943
|
<p>I am finding it difficult to use MySQL with Python in my windows system.</p>
<p>I am currently using Python 2.6. I have tried to compile MySQL-python-1.2.3b1 (which is supposed to work for Python 2.6 ?) source code using the provided setup scripts. The setup script runs and it doesn't report any error but it doesn't generate _mysql module. </p>
<p>I have also tried setting up MySQL for Python 2.5 with out success. The problem with using 2.5 is that Python 2.5 is compiled with visual studio 2003 (I installed it using the provided binaries). I have visual studio 2005 on my windows system. Hence setuptools fails to generate _mysql module.</p>
<p>Any help ?</p>
| 94
|
2009-03-14T13:53:28Z
| 30,490,323
|
<p>The precompiled binaries on <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python" rel="nofollow">http://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python</a> is just worked for me.</p>
<ol>
<li>Open <code>MySQL_python-1.2.5-cp27-none-win_amd64.whl</code> file with zip
extractor program.</li>
<li>Copy the contents to
<code>C:\Python27\Lib\site-packages\</code></li>
</ol>
| 2
|
2015-05-27T18:24:37Z
|
[
"python",
"mysql",
"windows"
] |
Integrating MySQL with Python in Windows
| 645,943
|
<p>I am finding it difficult to use MySQL with Python in my windows system.</p>
<p>I am currently using Python 2.6. I have tried to compile MySQL-python-1.2.3b1 (which is supposed to work for Python 2.6 ?) source code using the provided setup scripts. The setup script runs and it doesn't report any error but it doesn't generate _mysql module. </p>
<p>I have also tried setting up MySQL for Python 2.5 with out success. The problem with using 2.5 is that Python 2.5 is compiled with visual studio 2003 (I installed it using the provided binaries). I have visual studio 2005 on my windows system. Hence setuptools fails to generate _mysql module.</p>
<p>Any help ?</p>
| 94
|
2009-03-14T13:53:28Z
| 30,493,219
|
<p>On Python 3.4 I've installed mysqlclient from <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/" rel="nofollow">http://www.lfd.uci.edu/~gohlke/pythonlibs/</a> with pip install mysqlclient and it's working.</p>
| 2
|
2015-05-27T21:11:21Z
|
[
"python",
"mysql",
"windows"
] |
Python PIL: how to write PNG image to string
| 646,286
|
<p>I have generated an image using <a href="http://www.pythonware.com/products/pil/">PIL</a>. How can I save it to a string in memory?
The <code>Image.save()</code> method requires a file.</p>
<p>I'd like to have several such images stored in dictionary.</p>
| 64
|
2009-03-14T17:15:17Z
| 646,297
|
<p>You can probably use the <a href="http://docs.python.org/library/stringio.html">StringIO</a> class to get a wrapper around strings that behaves like a file. The StringIO object provides the same interface as a file, but saves the contents just in memory:</p>
<pre><code>import StringIO
output = StringIO.StringIO()
image.save(output)
contents = output.getvalue()
output.close()
</code></pre>
<p>This might lead to a <code>KeyError</code> if PIL tries to automatically detect the output format. To avoid this problem you can specify the format manually:</p>
<pre><code>image.save(output, format="GIF")
</code></pre>
| 129
|
2009-03-14T17:21:04Z
|
[
"python",
"python-imaging-library"
] |
Python PIL: how to write PNG image to string
| 646,286
|
<p>I have generated an image using <a href="http://www.pythonware.com/products/pil/">PIL</a>. How can I save it to a string in memory?
The <code>Image.save()</code> method requires a file.</p>
<p>I'd like to have several such images stored in dictionary.</p>
| 64
|
2009-03-14T17:15:17Z
| 646,336
|
<p>When you say "I'd like to have number of such images stored in dictionary", it's not clear if this is an in-memory structure or not.</p>
<p>You don't need to do any of this to meek an image in memory. Just keep the <code>image</code> object in your dictionary.</p>
<p>If you're going to write your dictionary to a file, you might want to look at <code>im.tostring()</code> method and the <code>Image.fromstring()</code> function</p>
<p><a href="http://effbot.org/imagingbook/image.htm" rel="nofollow">http://effbot.org/imagingbook/image.htm</a></p>
<blockquote>
<p>im.tostring() => string</p>
<p>Returns a string containing pixel
data, using the standard "raw"
encoder.</p>
<p>Image.fromstring(mode, size, data) =>
image</p>
<p>Creates an image memory from pixel
data in a string, using the standard
"raw" decoder.</p>
</blockquote>
<p>The "format" (.jpeg, .png, etc.) only matters on disk when you are exchanging the files. If you're not exchanging files, format doesn't matter.</p>
| 6
|
2009-03-14T17:36:43Z
|
[
"python",
"python-imaging-library"
] |
Python PIL: how to write PNG image to string
| 646,286
|
<p>I have generated an image using <a href="http://www.pythonware.com/products/pil/">PIL</a>. How can I save it to a string in memory?
The <code>Image.save()</code> method requires a file.</p>
<p>I'd like to have several such images stored in dictionary.</p>
| 64
|
2009-03-14T17:15:17Z
| 646,339
|
<p>save() can take a file-like object as well as a path, so you can use an in-memory buffer like a StringIO:</p>
<pre><code>buf= StringIO.StringIO()
im.save(buf, format= 'JPEG')
jpeg= buf.getvalue()
</code></pre>
| 12
|
2009-03-14T17:39:25Z
|
[
"python",
"python-imaging-library"
] |
Python PIL: how to write PNG image to string
| 646,286
|
<p>I have generated an image using <a href="http://www.pythonware.com/products/pil/">PIL</a>. How can I save it to a string in memory?
The <code>Image.save()</code> method requires a file.</p>
<p>I'd like to have several such images stored in dictionary.</p>
| 64
|
2009-03-14T17:15:17Z
| 5,504,072
|
<p>sth's solution didn't work for me<br>
because in ...</p>
<blockquote>
<p>Imaging/PIL/Image.pyc line 1423 ->
raise KeyError(ext) # unknown
extension</p>
</blockquote>
<p>It was trying to detect the format from the extension in the filename , which doesn't exist in StringIO case </p>
<p>You can bypass the format detection by setting the format yourself in a parameter </p>
<pre><code>import StringIO
output = StringIO.StringIO()
format = 'PNG' # or 'JPEG' or whatever you want
image.save(output, format)
contents = output.getvalue()
output.close()
</code></pre>
| 16
|
2011-03-31T17:46:26Z
|
[
"python",
"python-imaging-library"
] |
Python PIL: how to write PNG image to string
| 646,286
|
<p>I have generated an image using <a href="http://www.pythonware.com/products/pil/">PIL</a>. How can I save it to a string in memory?
The <code>Image.save()</code> method requires a file.</p>
<p>I'd like to have several such images stored in dictionary.</p>
| 64
|
2009-03-14T17:15:17Z
| 29,971,514
|
<p>For Python3 it is required to use BytesIO: <a href="http://fadeit.dk/blog/post/python3-flask-pil-in-memory-image">http://fadeit.dk/blog/post/python3-flask-pil-in-memory-image</a></p>
| 8
|
2015-04-30T15:16:32Z
|
[
"python",
"python-imaging-library"
] |
What is an elegant way to find versions of packages on a pypi package index?
| 646,515
|
<p>Currently I'm using a very ugly approach based on a regex for finding links and taking them apart.</p>
<p>I'm unhappy with the code, so I'm asking for nicer solutions, preferably using only the stdlib.</p>
<h3>Edit</h3>
<p>The task at hand has 2 parts:</p>
<ol>
<li>Find all distributions that match a certain criteria (like prefix of the name).</li>
<li>Find all versions available in each found distribution.</li>
</ol>
<p>The expected result is a mapping of distribution -> versions -> files.</p>
| 4
|
2009-03-14T19:07:17Z
| 646,524
|
<p>In a buildout which access pypi i pin versions like this:</p>
<p>Products.PloneFormGen==1.2.5</p>
<p>Here it searches for version 1.2.5 an uses this..</p>
<p>Dont know if it is this what u looking for...</p>
| -1
|
2009-03-14T19:15:17Z
|
[
"python",
"package",
"search",
"pypi"
] |
What is an elegant way to find versions of packages on a pypi package index?
| 646,515
|
<p>Currently I'm using a very ugly approach based on a regex for finding links and taking them apart.</p>
<p>I'm unhappy with the code, so I'm asking for nicer solutions, preferably using only the stdlib.</p>
<h3>Edit</h3>
<p>The task at hand has 2 parts:</p>
<ol>
<li>Find all distributions that match a certain criteria (like prefix of the name).</li>
<li>Find all versions available in each found distribution.</li>
</ol>
<p>The expected result is a mapping of distribution -> versions -> files.</p>
| 4
|
2009-03-14T19:07:17Z
| 647,784
|
<p>There is an XML-RPC interface. See the <a href="http://wiki.python.org/moin/PyPiXmlRpc?action=show&redirect=CheeseShopXmlRpc" rel="nofollow">Python.org wiki page on Cheese Shop (old name for PyPi) API</a>. </p>
<p>Excerpt from that wiki:</p>
<pre><code>>>> import xmlrpclib
>>> server = xmlrpclib.Server('http://pypi.python.org/pypi')
>>> server.package_releases('roundup')
['1.1.2']
>>> server.package_urls('roundup', '1.1.2')
[{'has_sig': True, 'comment_text': '', 'python_version': 'source', 'url': 'http://pypi.python.org/packages/source/r/roundup/roundup-1.1.2.tar.gz', 'md5_digest': '7c395da56412e263d7600fa7f0afa2e5', 'downloads': 2989, 'filename': 'roundup-1.1.2.tar.gz', 'packagetype': 'sdist', 'size': 876455}, {'has_sig': True, 'comment_text': '', 'python_version': 'any', 'url': 'http://pypi.python.org/packages/any/r/roundup/roundup-1.1.2.win32.exe', 'md5_digest': '983d565b0b87f83f1b6460e54554a845', 'downloads': 2020, 'filename': 'roundup-1.1.2.win32.exe', 'packagetype': 'bdist_wininst', 'size': 614270}]
</code></pre>
<p><code>list_packages</code> and <code>package_releases</code> seem to be exactly what you're looking for.</p>
<h3>@Ronny's Comment</h3>
<p>You just have to write some code in Python to determine which of the listed packages satisfy the criterion; i.e. if the package name must start with <code>foo</code>:</p>
<pre><code>>>> packages = server.list_packages()
>>> match_foo = [package for package in packages if package.startswith('foo')]
>>> print len(match_foo)
2
</code></pre>
| 2
|
2009-03-15T13:02:06Z
|
[
"python",
"package",
"search",
"pypi"
] |
What is an elegant way to find versions of packages on a pypi package index?
| 646,515
|
<p>Currently I'm using a very ugly approach based on a regex for finding links and taking them apart.</p>
<p>I'm unhappy with the code, so I'm asking for nicer solutions, preferably using only the stdlib.</p>
<h3>Edit</h3>
<p>The task at hand has 2 parts:</p>
<ol>
<li>Find all distributions that match a certain criteria (like prefix of the name).</li>
<li>Find all versions available in each found distribution.</li>
</ol>
<p>The expected result is a mapping of distribution -> versions -> files.</p>
| 4
|
2009-03-14T19:07:17Z
| 7,714,844
|
<p>We are going to release distutils2 to PyPI in the short-term future. It contains a distutils2.pypi module which lets you search PyPI from Python code and a pysetup program which is a command-line script to do the same thing (among others). The doc is still a work in progress, but there are some examples and an API reference:</p>
<ul>
<li><a href="http://docs.python.org/dev/library/packaging.pypi.simple" rel="nofollow">http://docs.python.org/dev/library/packaging.pypi.simple</a></li>
<li><a href="http://docs.python.org/dev/library/packaging.pypi.xmlrpc" rel="nofollow">http://docs.python.org/dev/library/packaging.pypi.xmlrpc</a></li>
</ul>
| 1
|
2011-10-10T15:08:34Z
|
[
"python",
"package",
"search",
"pypi"
] |
What is an elegant way to find versions of packages on a pypi package index?
| 646,515
|
<p>Currently I'm using a very ugly approach based on a regex for finding links and taking them apart.</p>
<p>I'm unhappy with the code, so I'm asking for nicer solutions, preferably using only the stdlib.</p>
<h3>Edit</h3>
<p>The task at hand has 2 parts:</p>
<ol>
<li>Find all distributions that match a certain criteria (like prefix of the name).</li>
<li>Find all versions available in each found distribution.</li>
</ol>
<p>The expected result is a mapping of distribution -> versions -> files.</p>
| 4
|
2009-03-14T19:07:17Z
| 13,274,944
|
<p>its unfortunate, but due to the lack of xmlrpc on other indexes i need to keep my solution</p>
| 0
|
2012-11-07T17:27:20Z
|
[
"python",
"package",
"search",
"pypi"
] |
Python: How to detect debug interpreter
| 646,518
|
<p>How can I detect in my python script if its being run by the debug interpreter (ie python_d.exe rather than python.exe)? I need to change the paths to some dlls that I pass to an extension.</p>
<p>eg Id like to do something like this at the start of my python script:</p>
<pre><code>#get paths to graphics dlls
if debug_build:
d3d9Path = "bin\\debug\\direct3d9.dll"
d3d10Path = "bin\\debug\\direct3d10.dll"
openGLPath = "bin\\debug\\openGL2.dll"
else:
d3d9Path = "bin\\direct3d9.dll"
d3d10Path = "bin\\direct3d10.dll"
openGLPath = "bin\\openGL2.dll"
</code></pre>
<p>I thought about adding an "IsDebug()" method to the extension which would return true if it is the debug build (ie was built with "#define DEBUG") and false otherwise. But this seems a bit of a hack for somthing Im sure I can get python to tell me...</p>
| 11
|
2009-03-14T19:10:14Z
| 646,544
|
<p>An easy way, if you don't mind relying on the file name:</p>
<pre><code>if sys.executable.endswith("_d.exe"):
print "running on debug interpreter"
</code></pre>
<p>You can read more about the <code>sys</code> module and its various facilities <a href="http://docs.python.org/library/sys.html" rel="nofollow">here</a>.</p>
| 2
|
2009-03-14T19:24:01Z
|
[
"python",
"debugging"
] |
Python: How to detect debug interpreter
| 646,518
|
<p>How can I detect in my python script if its being run by the debug interpreter (ie python_d.exe rather than python.exe)? I need to change the paths to some dlls that I pass to an extension.</p>
<p>eg Id like to do something like this at the start of my python script:</p>
<pre><code>#get paths to graphics dlls
if debug_build:
d3d9Path = "bin\\debug\\direct3d9.dll"
d3d10Path = "bin\\debug\\direct3d10.dll"
openGLPath = "bin\\debug\\openGL2.dll"
else:
d3d9Path = "bin\\direct3d9.dll"
d3d10Path = "bin\\direct3d10.dll"
openGLPath = "bin\\openGL2.dll"
</code></pre>
<p>I thought about adding an "IsDebug()" method to the extension which would return true if it is the debug build (ie was built with "#define DEBUG") and false otherwise. But this seems a bit of a hack for somthing Im sure I can get python to tell me...</p>
| 11
|
2009-03-14T19:10:14Z
| 646,658
|
<p>Better, because it also works when you are running an embedded Python interpreter is to check the return value of</p>
<pre><code>imp.get_suffixes()
</code></pre>
<p>For a debug build it contains a tuple starting with '_d.pyd':</p>
<pre><code># debug build:
[('_d.pyd', 'rb', 3), ('.py', 'U', 1), ('.pyw', 'U', 1), ('.pyc', 'rb', 2)]
# release build:
[('.pyd', 'rb', 3), ('.py', 'U', 1), ('.pyw', 'U', 1), ('.pyc', 'rb', 2)]
</code></pre>
| 3
|
2009-03-14T20:25:31Z
|
[
"python",
"debugging"
] |
Python: How to detect debug interpreter
| 646,518
|
<p>How can I detect in my python script if its being run by the debug interpreter (ie python_d.exe rather than python.exe)? I need to change the paths to some dlls that I pass to an extension.</p>
<p>eg Id like to do something like this at the start of my python script:</p>
<pre><code>#get paths to graphics dlls
if debug_build:
d3d9Path = "bin\\debug\\direct3d9.dll"
d3d10Path = "bin\\debug\\direct3d10.dll"
openGLPath = "bin\\debug\\openGL2.dll"
else:
d3d9Path = "bin\\direct3d9.dll"
d3d10Path = "bin\\direct3d10.dll"
openGLPath = "bin\\openGL2.dll"
</code></pre>
<p>I thought about adding an "IsDebug()" method to the extension which would return true if it is the debug build (ie was built with "#define DEBUG") and false otherwise. But this seems a bit of a hack for somthing Im sure I can get python to tell me...</p>
| 11
|
2009-03-14T19:10:14Z
| 647,312
|
<p><a href="http://bugs.python.org/file2086/build.py.diff">Distutils use <code>sys.gettotalrefcount</code> to detect a debug python build</a>:</p>
<pre><code># ...
if hasattr(sys, 'gettotalrefcount'):
plat_specifier += '-pydebug'
</code></pre>
<ul>
<li>this method doesn't rely on an executable name '<code>*_d.exe</code>'. It works for any name.</li>
<li>this method is cross-platform. It doesn't depend on '<code>_d.pyd</code>' suffix.</li>
</ul>
<p>See <a href="http://docs.python.org/c-api/intro.html#debugging-builds">Debugging Builds</a> and <a href="http://svn.python.org/view/python/trunk/Misc/SpecialBuilds.txt?view=markup">Misc/SpecialBuilds.txt</a> </p>
| 12
|
2009-03-15T04:39:26Z
|
[
"python",
"debugging"
] |
In what way would you present an algorithm to detect collisions between diffrent objects?
| 646,539
|
<p>While working on a really only-for-fun project I encountered some problem.</p>
<p>There is a 2D world populated with Round Balls, Pointy Triangles and Skinny Lines (and other wildlife too, maybe). They all are subclasses of WorldCreatures. They can move inside this world. When they meet each other, a Collision happens.</p>
<p>The thing I'd like to do is to make a way of detecting Collision between them. Here's what I'm standing on right now:</p>
<ul>
<li>For me Ball-Ball is easy, I just calculate their distance from their positions and compare it with the sum of their 'sizes'.</li>
<li>Collision between Ball and edge of the world is simple too - I just check the distance from it, which, in Cartesian coordinates, is simple.</li>
<li>More generic problems are - how to detect a collision between Line (starting and ending at some points) or other objects I could have there? Distance between a line and a point can be calculated easily too, but what I'd like is to have</li>
</ul>
<p>Some kind of generic way to say if Obcject <code>A</code> collides with Object <code>B</code>. The code as it is now looks somewhat like:</p>
<pre><code>class WorldCreature:
def detectCollision(self, otherObject):
# do something
if collision:
self.onCollision(otherObject)
otherObject.onCollision(self)
class Ball(WorldCreature):
# someing here
class Line(WorldCreature):
# someing here
</code></pre>
<p>Now, the collision detection mechanizm should depend on what objects can collide. So will the effect.</p>
<p>Should I just keep a list of all the objects in memory and loop through all them in <em>every single</em> step? Or, is there some better way to improve the performance of this task?</p>
| 3
|
2009-03-14T19:21:13Z
| 646,548
|
<p>Use a <a href="http://en.wikipedia.org/wiki/Quadtree" rel="nofollow">quadtree</a>. They're used to eliminate large regions that you know are outside a collision radius, plus they let you quickly search for the closest point.</p>
<p>As far as actual collision detection goes, since you're only using convex objects, take a look at <a href="http://www.metanetsoftware.com/technique/tutorialA.html" rel="nofollow">Metanet Software's tutorial</a> on <a href="http://en.wikipedia.org/wiki/Separating%5Faxis%5Ftheorem" rel="nofollow">the separating axis theorem</a>. In their flagship game, they actually use a grid to find all the objects to check for collision against, but it shouldn't be too hard to use a quadtree instead.</p>
<p>(I remember reading an article on quadtrees that used circles in a grid to illustrate how you can find the points within a radius. I can't seem to find it though.)</p>
| 5
|
2009-03-14T19:24:59Z
|
[
"python",
"collision-detection"
] |
In what way would you present an algorithm to detect collisions between diffrent objects?
| 646,539
|
<p>While working on a really only-for-fun project I encountered some problem.</p>
<p>There is a 2D world populated with Round Balls, Pointy Triangles and Skinny Lines (and other wildlife too, maybe). They all are subclasses of WorldCreatures. They can move inside this world. When they meet each other, a Collision happens.</p>
<p>The thing I'd like to do is to make a way of detecting Collision between them. Here's what I'm standing on right now:</p>
<ul>
<li>For me Ball-Ball is easy, I just calculate their distance from their positions and compare it with the sum of their 'sizes'.</li>
<li>Collision between Ball and edge of the world is simple too - I just check the distance from it, which, in Cartesian coordinates, is simple.</li>
<li>More generic problems are - how to detect a collision between Line (starting and ending at some points) or other objects I could have there? Distance between a line and a point can be calculated easily too, but what I'd like is to have</li>
</ul>
<p>Some kind of generic way to say if Obcject <code>A</code> collides with Object <code>B</code>. The code as it is now looks somewhat like:</p>
<pre><code>class WorldCreature:
def detectCollision(self, otherObject):
# do something
if collision:
self.onCollision(otherObject)
otherObject.onCollision(self)
class Ball(WorldCreature):
# someing here
class Line(WorldCreature):
# someing here
</code></pre>
<p>Now, the collision detection mechanizm should depend on what objects can collide. So will the effect.</p>
<p>Should I just keep a list of all the objects in memory and loop through all them in <em>every single</em> step? Or, is there some better way to improve the performance of this task?</p>
| 3
|
2009-03-14T19:21:13Z
| 646,558
|
<p>The answer to this depends on a number of factors, such as how many objects there are, how many are moving vs. non-moving, how fast they move, etc. I think that the right place to start is by getting the core collision detection and behavior code correct while ignoring the optimizations you might do to prune collision checks, etc.</p>
<p>Once the core code is correct, you can start running experiments to see what will perform well for you. I would recommend some kind of spatial subdivision technique, such as kd-trees (although in 2d, you may as well use quadtrees). </p>
<p>Fundamentally, though, there's probably no single right answer, except what you are able to determine by coding up your game and experimenting with it.</p>
| 1
|
2009-03-14T19:30:03Z
|
[
"python",
"collision-detection"
] |
In what way would you present an algorithm to detect collisions between diffrent objects?
| 646,539
|
<p>While working on a really only-for-fun project I encountered some problem.</p>
<p>There is a 2D world populated with Round Balls, Pointy Triangles and Skinny Lines (and other wildlife too, maybe). They all are subclasses of WorldCreatures. They can move inside this world. When they meet each other, a Collision happens.</p>
<p>The thing I'd like to do is to make a way of detecting Collision between them. Here's what I'm standing on right now:</p>
<ul>
<li>For me Ball-Ball is easy, I just calculate their distance from their positions and compare it with the sum of their 'sizes'.</li>
<li>Collision between Ball and edge of the world is simple too - I just check the distance from it, which, in Cartesian coordinates, is simple.</li>
<li>More generic problems are - how to detect a collision between Line (starting and ending at some points) or other objects I could have there? Distance between a line and a point can be calculated easily too, but what I'd like is to have</li>
</ul>
<p>Some kind of generic way to say if Obcject <code>A</code> collides with Object <code>B</code>. The code as it is now looks somewhat like:</p>
<pre><code>class WorldCreature:
def detectCollision(self, otherObject):
# do something
if collision:
self.onCollision(otherObject)
otherObject.onCollision(self)
class Ball(WorldCreature):
# someing here
class Line(WorldCreature):
# someing here
</code></pre>
<p>Now, the collision detection mechanizm should depend on what objects can collide. So will the effect.</p>
<p>Should I just keep a list of all the objects in memory and loop through all them in <em>every single</em> step? Or, is there some better way to improve the performance of this task?</p>
| 3
|
2009-03-14T19:21:13Z
| 646,580
|
<p>I think <a href="http://en.wikipedia.org/wiki/Hough%5Ftransform" rel="nofollow"><strong>Hough Transform</strong></a> should help somehow.</p>
| 0
|
2009-03-14T19:46:19Z
|
[
"python",
"collision-detection"
] |
In what way would you present an algorithm to detect collisions between diffrent objects?
| 646,539
|
<p>While working on a really only-for-fun project I encountered some problem.</p>
<p>There is a 2D world populated with Round Balls, Pointy Triangles and Skinny Lines (and other wildlife too, maybe). They all are subclasses of WorldCreatures. They can move inside this world. When they meet each other, a Collision happens.</p>
<p>The thing I'd like to do is to make a way of detecting Collision between them. Here's what I'm standing on right now:</p>
<ul>
<li>For me Ball-Ball is easy, I just calculate their distance from their positions and compare it with the sum of their 'sizes'.</li>
<li>Collision between Ball and edge of the world is simple too - I just check the distance from it, which, in Cartesian coordinates, is simple.</li>
<li>More generic problems are - how to detect a collision between Line (starting and ending at some points) or other objects I could have there? Distance between a line and a point can be calculated easily too, but what I'd like is to have</li>
</ul>
<p>Some kind of generic way to say if Obcject <code>A</code> collides with Object <code>B</code>. The code as it is now looks somewhat like:</p>
<pre><code>class WorldCreature:
def detectCollision(self, otherObject):
# do something
if collision:
self.onCollision(otherObject)
otherObject.onCollision(self)
class Ball(WorldCreature):
# someing here
class Line(WorldCreature):
# someing here
</code></pre>
<p>Now, the collision detection mechanizm should depend on what objects can collide. So will the effect.</p>
<p>Should I just keep a list of all the objects in memory and loop through all them in <em>every single</em> step? Or, is there some better way to improve the performance of this task?</p>
| 3
|
2009-03-14T19:21:13Z
| 818,157
|
<p>Python. Kinda strange beast for me 8)</p>
<p>I have c++ experience creating games -- so I talk from this point of view.</p>
<p>First of all (you can skip this if you have low number of objects) you need broad-phase collision detection. Already mentioned quadtree is just one possible implementation.
Broad-phase is needed to find pairs of possibly colliding objects.</p>
<p>Then goes the narrow phase -- when pairs are checked.</p>
<p>I used the following scheme (note -- this was created with primitives in mind, if you need polyhedra collisions -- just use GJK and spheres, plus rays,segments):</p>
<p>Everything that needs collisions have CollisionObject which handles transform and store CollisionPrimitive (box, sphere etc)</p>
<p>Each CollisionPrimitive has type_id -- when you write A_B_CheckIntersection -- the first object always have lower type_id</p>
<p>For each Pair in the list that you get from broad phase -- you swap objects if needed and index an array where pointers to specific collision functions are stored.
Sure -- for that you should have them have identical interfaces (c++) but it is easy 8)</p>
<p>As for specific collision routines: visit <a href="http://realtimerendering.com/intersections.html" rel="nofollow">http://realtimerendering.com/intersections.html</a>
It is good place to start</p>
| 1
|
2009-05-03T22:18:52Z
|
[
"python",
"collision-detection"
] |
How to get last items of a list in Python?
| 646,644
|
<p>I need the last 9 numbers of a list and I'm sure there is a way to do it with slicing, but I can't seem to get it. I can get the first 9 like this:</p>
<pre><code>num_list[0:9]
</code></pre>
<p>Any help would be great.</p>
| 85
|
2009-03-14T20:19:44Z
| 646,646
|
<p>a negative index will count from the end of the list, so:</p>
<pre><code>num_list[-9:]
</code></pre>
| 43
|
2009-03-14T20:21:07Z
|
[
"python",
"list",
"slice"
] |
How to get last items of a list in Python?
| 646,644
|
<p>I need the last 9 numbers of a list and I'm sure there is a way to do it with slicing, but I can't seem to get it. I can get the first 9 like this:</p>
<pre><code>num_list[0:9]
</code></pre>
<p>Any help would be great.</p>
| 85
|
2009-03-14T20:19:44Z
| 646,654
|
<p>You can use negative integers with the slicing operator for that. Here's an example using the python CLI interpreter:</p>
<pre><code>>>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
>>> a[-9:]
[4, 5, 6, 7, 8, 9, 10, 11, 12]
</code></pre>
<p>the important line is <code>a[-9:]</code></p>
| 180
|
2009-03-14T20:22:54Z
|
[
"python",
"list",
"slice"
] |
How to get last items of a list in Python?
| 646,644
|
<p>I need the last 9 numbers of a list and I'm sure there is a way to do it with slicing, but I can't seem to get it. I can get the first 9 like this:</p>
<pre><code>num_list[0:9]
</code></pre>
<p>Any help would be great.</p>
| 85
|
2009-03-14T20:19:44Z
| 647,299
|
<p>The last 9 elements can be read from left to right using numlist[-9:], or from right to left using numlist[:-10:-1], as you want.</p>
<pre><code>>>> a=range(17)
>>> print a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
>>> print a[-9:]
[8, 9, 10, 11, 12, 13, 14, 15, 16]
>>> print a[:-10:-1]
[16, 15, 14, 13, 12, 11, 10, 9, 8]
</code></pre>
| 24
|
2009-03-15T04:27:16Z
|
[
"python",
"list",
"slice"
] |
How to get last items of a list in Python?
| 646,644
|
<p>I need the last 9 numbers of a list and I'm sure there is a way to do it with slicing, but I can't seem to get it. I can get the first 9 like this:</p>
<pre><code>num_list[0:9]
</code></pre>
<p>Any help would be great.</p>
| 85
|
2009-03-14T20:19:44Z
| 24,620,740
|
<h1>Slicing</h1>
<p>Python slicing is an incredibly fast operation, and it's a handy way to quickly access parts of your data. </p>
<p>Slice notation to get the last nine elements from a list (or any other sequence that supports it, like a string) would look like this:</p>
<pre><code>num_list[-9:]
</code></pre>
<p>When I see this, I read the part in the brackets as "9th from the end, to the end." (Actually, I abbreviate it mentally as "-9, on")</p>
<h2>Explanation:</h2>
<p>The full notation is </p>
<pre><code>sequence[start:stop:step]
</code></pre>
<p>But the colon is what tells Python you're giving it a slice and not a regular index. That's why the idiomatic way of copying lists is </p>
<pre><code>list_copy = sequence[:]
</code></pre>
<p>And clearing them is with:</p>
<pre><code>del my_list[:]
</code></pre>
<h2>Give your slices a descriptive name!</h2>
<p>You may find it useful to separate forming the slice from passing it to the <code>list.__getitem__</code> method (<a href="https://docs.python.org/2/reference/datamodel.html#object.__getitem__" rel="nofollow">that's what the square brackets do</a>). Even if you're not new to it, it keeps your code more readable so that others that may have to read your code can more readily understand what you're doing.</p>
<p>However, you can't just assign some integers separated by colons to a variable. You need to use the slice object:</p>
<pre><code>last_nine_slice = slice(-9, None)
</code></pre>
<p>The second argument, <code>None</code>, is required, so that the first argument is interpreted as the <code>start</code> argument <a href="https://docs.python.org/2/library/functions.html#slice" rel="nofollow">otherwise it would be the <code>stop</code> argument</a>. </p>
<p>You can then pass the slice object to your sequence:</p>
<pre><code>>>> list(range(100))[last_nine_slice]
[91, 92, 93, 94, 95, 96, 97, 98, 99]
</code></pre>
<h1><code>islice</code></h1>
<p><code>islice</code> from the itertools module is another possibly performant way to get this. <code>islice</code> doesn't take negative arguments, so ideally your iterable has a <code>__reversed__</code> special method - which list <em>does</em> have - so you must first pass your list (or iterable with <code>__reversed__</code>) to <code>reversed</code>.</p>
<pre><code>>>> from itertools import islice
>>> islice(reversed(range(100)), 0, 9)
<itertools.islice object at 0xffeb87fc>
</code></pre>
<p>islice allows for lazy evaluation of the data pipeline, so to materialize the data, pass it to a constructor (like <code>list</code>):</p>
<pre><code>>>> list(islice(reversed(range(100)), 0, 9))
[99, 98, 97, 96, 95, 94, 93, 92, 91]
</code></pre>
| 12
|
2014-07-07T22:10:41Z
|
[
"python",
"list",
"slice"
] |
PIR sensors + Arduino + Python + email alerts
| 646,903
|
<p>We are working on a project for school, and we have 2 <a href="http://en.wikipedia.org/wiki/Passive_infrared_sensor" rel="nofollow">PIR</a> motion sensors running off an Arduino microcontroller. We are able to view the output of the serial port in both the Ardunio IDE and Python <a href="http://en.wikipedia.org/wiki/IDLE_%28Python%29" rel="nofollow">IDLE</a>.</p>
<p>What we want to do next is, after about 30 seconds of motion being detected, sending out an email alert, seeing that we don't have Ethernet capability at this point, we figured the easiest way would be to grab the emailing through Python.</p>
<p>How to achieve this?</p>
<h3>Update:</h3>
<p>At this point we can send an email from Python, we can read the Arduino serial port in Python, but we just have an issue putting it all together.</p>
<p>This is what our Python code looks like, at the while 1: is where confusion happens:</p>
<pre><code>import smtplib,serial
ser = serial.Serial(port=2, baudrate=9200)
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders
import os
gmail_user = "usr@gmail.com"
gmail_pwd = "pw"
def mail(to, subject, text, attach):
msg = MIMEMultipart()
msg['From'] = gmail_user
msg['To'] = to
msg['Subject'] = subject
msg.attach(MIMEText(text))
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(attach, 'rb').read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition',
'attachment; filename="%s"' % os.path.basename(attach))
msg.attach(part)
mailServer = smtplib.SMTP("smtp.gmail.com", 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(gmail_user, gmail_pwd)
mailServer.sendmail(gmail_user, to, msg.as_string())
# Should be mailServer.quit(), but that crashes...
mailServer.close()
while 1: **// CONFUSION HAPPENS HERE //** <----------------------
ser.readline()
if ser.readline() = "motion"
do this mail sequence?
mail("usr2@gmail.com",
"Alarm Alert!",
"Both Motion Sensor A & B have been active for over # seconds",
"stor_fight.jpg")
</code></pre>
<p>Any tips would be much appreciated.</p>
| 5
|
2009-03-14T23:08:52Z
| 646,967
|
<p>I'm not sure exactly which part of this process you're having trouble with, but here's a sketch of a solution:</p>
<p>You can use the <a href="http://pyserial.wiki.sourceforge.net/pySerial" rel="nofollow">pyserial</a> library to communicate with the Arduino from python when the Arduino is plugged into the computer via USB. </p>
<p>On the python side, your code would look like this:</p>
<pre><code>serial = serial.Serial("/dev/tty.usbserial-A6007btF", 38400) # the serial name you can see in the Arduino GUI - you might just need to say "COM1" on Windows
result = serial.readline(); # blocks until you get something from the Arduino
if result == "motion":
# send email here
</code></pre>
<p>On the Arduino side, you'd just do something like this:</p>
<pre><code>void loop()
{
if(30 seconds have passed with motion)
Serial.println("motion");
}
</code></pre>
<p>Make sense?</p>
| 1
|
2009-03-14T23:56:53Z
|
[
"python",
"email",
"arduino"
] |
PIR sensors + Arduino + Python + email alerts
| 646,903
|
<p>We are working on a project for school, and we have 2 <a href="http://en.wikipedia.org/wiki/Passive_infrared_sensor" rel="nofollow">PIR</a> motion sensors running off an Arduino microcontroller. We are able to view the output of the serial port in both the Ardunio IDE and Python <a href="http://en.wikipedia.org/wiki/IDLE_%28Python%29" rel="nofollow">IDLE</a>.</p>
<p>What we want to do next is, after about 30 seconds of motion being detected, sending out an email alert, seeing that we don't have Ethernet capability at this point, we figured the easiest way would be to grab the emailing through Python.</p>
<p>How to achieve this?</p>
<h3>Update:</h3>
<p>At this point we can send an email from Python, we can read the Arduino serial port in Python, but we just have an issue putting it all together.</p>
<p>This is what our Python code looks like, at the while 1: is where confusion happens:</p>
<pre><code>import smtplib,serial
ser = serial.Serial(port=2, baudrate=9200)
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders
import os
gmail_user = "usr@gmail.com"
gmail_pwd = "pw"
def mail(to, subject, text, attach):
msg = MIMEMultipart()
msg['From'] = gmail_user
msg['To'] = to
msg['Subject'] = subject
msg.attach(MIMEText(text))
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(attach, 'rb').read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition',
'attachment; filename="%s"' % os.path.basename(attach))
msg.attach(part)
mailServer = smtplib.SMTP("smtp.gmail.com", 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(gmail_user, gmail_pwd)
mailServer.sendmail(gmail_user, to, msg.as_string())
# Should be mailServer.quit(), but that crashes...
mailServer.close()
while 1: **// CONFUSION HAPPENS HERE //** <----------------------
ser.readline()
if ser.readline() = "motion"
do this mail sequence?
mail("usr2@gmail.com",
"Alarm Alert!",
"Both Motion Sensor A & B have been active for over # seconds",
"stor_fight.jpg")
</code></pre>
<p>Any tips would be much appreciated.</p>
| 5
|
2009-03-14T23:08:52Z
| 646,971
|
<p>From what I can tell the board has a standard RS-232 port. You can make a listener Python script that accepts a signal from the board when the event occurs then fire off a method that sends the email. If you want a nicely designed piece look into Twisted, which has packages for serial port comm and mail. Otherwise check:</p>
<p><a href="http://docs.python.org/library/email" rel="nofollow">http://docs.python.org/library/email</a></p>
<p><a href="http://www.varesano.net/blog/fabio/serial+rs232+connections+python" rel="nofollow">http://www.varesano.net/blog/fabio/serial+rs232+connections+python</a></p>
| 0
|
2009-03-15T00:00:18Z
|
[
"python",
"email",
"arduino"
] |
PIR sensors + Arduino + Python + email alerts
| 646,903
|
<p>We are working on a project for school, and we have 2 <a href="http://en.wikipedia.org/wiki/Passive_infrared_sensor" rel="nofollow">PIR</a> motion sensors running off an Arduino microcontroller. We are able to view the output of the serial port in both the Ardunio IDE and Python <a href="http://en.wikipedia.org/wiki/IDLE_%28Python%29" rel="nofollow">IDLE</a>.</p>
<p>What we want to do next is, after about 30 seconds of motion being detected, sending out an email alert, seeing that we don't have Ethernet capability at this point, we figured the easiest way would be to grab the emailing through Python.</p>
<p>How to achieve this?</p>
<h3>Update:</h3>
<p>At this point we can send an email from Python, we can read the Arduino serial port in Python, but we just have an issue putting it all together.</p>
<p>This is what our Python code looks like, at the while 1: is where confusion happens:</p>
<pre><code>import smtplib,serial
ser = serial.Serial(port=2, baudrate=9200)
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders
import os
gmail_user = "usr@gmail.com"
gmail_pwd = "pw"
def mail(to, subject, text, attach):
msg = MIMEMultipart()
msg['From'] = gmail_user
msg['To'] = to
msg['Subject'] = subject
msg.attach(MIMEText(text))
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(attach, 'rb').read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition',
'attachment; filename="%s"' % os.path.basename(attach))
msg.attach(part)
mailServer = smtplib.SMTP("smtp.gmail.com", 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(gmail_user, gmail_pwd)
mailServer.sendmail(gmail_user, to, msg.as_string())
# Should be mailServer.quit(), but that crashes...
mailServer.close()
while 1: **// CONFUSION HAPPENS HERE //** <----------------------
ser.readline()
if ser.readline() = "motion"
do this mail sequence?
mail("usr2@gmail.com",
"Alarm Alert!",
"Both Motion Sensor A & B have been active for over # seconds",
"stor_fight.jpg")
</code></pre>
<p>Any tips would be much appreciated.</p>
| 5
|
2009-03-14T23:08:52Z
| 648,132
|
<p>You need to use the serial library in your Arduino sketch. See section <code>Communication/Serial</code> on this page:</p>
<p><a href="http://arduino.cc/en/Reference/HomePage" rel="nofollow">http://arduino.cc/en/Reference/HomePage</a></p>
<p>There are examples for the serial library in folder <code>4.Communication</code> of the Arduino environment.</p>
<p>On your host machine, use the pySerial module, as suggested by jder.</p>
<p>You might also find this page in the Arduino Playground to be a useful starting point:</p>
<p><a href="http://www.arduino.cc/playground/Interfacing/Python" rel="nofollow">http://www.arduino.cc/playground/Interfacing/Python</a></p>
| 0
|
2009-03-15T16:57:20Z
|
[
"python",
"email",
"arduino"
] |
PIR sensors + Arduino + Python + email alerts
| 646,903
|
<p>We are working on a project for school, and we have 2 <a href="http://en.wikipedia.org/wiki/Passive_infrared_sensor" rel="nofollow">PIR</a> motion sensors running off an Arduino microcontroller. We are able to view the output of the serial port in both the Ardunio IDE and Python <a href="http://en.wikipedia.org/wiki/IDLE_%28Python%29" rel="nofollow">IDLE</a>.</p>
<p>What we want to do next is, after about 30 seconds of motion being detected, sending out an email alert, seeing that we don't have Ethernet capability at this point, we figured the easiest way would be to grab the emailing through Python.</p>
<p>How to achieve this?</p>
<h3>Update:</h3>
<p>At this point we can send an email from Python, we can read the Arduino serial port in Python, but we just have an issue putting it all together.</p>
<p>This is what our Python code looks like, at the while 1: is where confusion happens:</p>
<pre><code>import smtplib,serial
ser = serial.Serial(port=2, baudrate=9200)
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders
import os
gmail_user = "usr@gmail.com"
gmail_pwd = "pw"
def mail(to, subject, text, attach):
msg = MIMEMultipart()
msg['From'] = gmail_user
msg['To'] = to
msg['Subject'] = subject
msg.attach(MIMEText(text))
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(attach, 'rb').read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition',
'attachment; filename="%s"' % os.path.basename(attach))
msg.attach(part)
mailServer = smtplib.SMTP("smtp.gmail.com", 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(gmail_user, gmail_pwd)
mailServer.sendmail(gmail_user, to, msg.as_string())
# Should be mailServer.quit(), but that crashes...
mailServer.close()
while 1: **// CONFUSION HAPPENS HERE //** <----------------------
ser.readline()
if ser.readline() = "motion"
do this mail sequence?
mail("usr2@gmail.com",
"Alarm Alert!",
"Both Motion Sensor A & B have been active for over # seconds",
"stor_fight.jpg")
</code></pre>
<p>Any tips would be much appreciated.</p>
| 5
|
2009-03-14T23:08:52Z
| 648,184
|
<p>From the question, I think you already know how to read from the serial port.</p>
<p>So I'd suggest something like this</p>
<pre><code>import time,smtplib
beginTime = time.time() + 86400 # stay one day ahead for now
while True:
if serial port has values : # ie. motion detected
beginTime = time.time()
if time.time() - beginTime > 30 :
mailObj = smtplib.SMTP('smtp_server_here', smtp_server_port)
mailObj.sendmail('from', 'to..', 'message')
beginTime = time.time() + 86400 # reset time
</code></pre>
<p>I hope that helps</p>
| 0
|
2009-03-15T17:26:07Z
|
[
"python",
"email",
"arduino"
] |
PIR sensors + Arduino + Python + email alerts
| 646,903
|
<p>We are working on a project for school, and we have 2 <a href="http://en.wikipedia.org/wiki/Passive_infrared_sensor" rel="nofollow">PIR</a> motion sensors running off an Arduino microcontroller. We are able to view the output of the serial port in both the Ardunio IDE and Python <a href="http://en.wikipedia.org/wiki/IDLE_%28Python%29" rel="nofollow">IDLE</a>.</p>
<p>What we want to do next is, after about 30 seconds of motion being detected, sending out an email alert, seeing that we don't have Ethernet capability at this point, we figured the easiest way would be to grab the emailing through Python.</p>
<p>How to achieve this?</p>
<h3>Update:</h3>
<p>At this point we can send an email from Python, we can read the Arduino serial port in Python, but we just have an issue putting it all together.</p>
<p>This is what our Python code looks like, at the while 1: is where confusion happens:</p>
<pre><code>import smtplib,serial
ser = serial.Serial(port=2, baudrate=9200)
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders
import os
gmail_user = "usr@gmail.com"
gmail_pwd = "pw"
def mail(to, subject, text, attach):
msg = MIMEMultipart()
msg['From'] = gmail_user
msg['To'] = to
msg['Subject'] = subject
msg.attach(MIMEText(text))
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(attach, 'rb').read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition',
'attachment; filename="%s"' % os.path.basename(attach))
msg.attach(part)
mailServer = smtplib.SMTP("smtp.gmail.com", 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(gmail_user, gmail_pwd)
mailServer.sendmail(gmail_user, to, msg.as_string())
# Should be mailServer.quit(), but that crashes...
mailServer.close()
while 1: **// CONFUSION HAPPENS HERE //** <----------------------
ser.readline()
if ser.readline() = "motion"
do this mail sequence?
mail("usr2@gmail.com",
"Alarm Alert!",
"Both Motion Sensor A & B have been active for over # seconds",
"stor_fight.jpg")
</code></pre>
<p>Any tips would be much appreciated.</p>
| 5
|
2009-03-14T23:08:52Z
| 11,761,445
|
<pre><code>ser.readline()
if ser.readline() = "motion"
</code></pre>
<p>This code reads a line from the serial port twice and discards the first one.</p>
<p>You also need a double-equals for comparison, and the line will (I assume...) have carriage-return characters on the end of it.</p>
<p>You might want to try something like</p>
<pre><code>if ser.readline().starts_with("motion")
</code></pre>
| 1
|
2012-08-01T14:27:35Z
|
[
"python",
"email",
"arduino"
] |
How to tell whether a file is executable on Windows in Python?
| 646,955
|
<p>I'm writing <a href="http://gist.github.com/79233"><code>grepath</code></a> utility that finds executables in <code>%PATH%</code> that match a pattern.
I need to define whether given filename in the path is executable (emphasis is on command line scripts).</p>
<p>Based on <a href="http://timgolden.me.uk/python/win32%5Fhow%5Fdo%5Fi/tell-if-a-file-is-executable.html">"Tell if a file is executable"</a> I've got:</p>
<pre><code>import os
from pywintypes import error
from win32api import FindExecutable, GetLongPathName
def is_executable_win(path):
try:
_, executable = FindExecutable(path)
ext = lambda p: os.path.splitext(p)[1].lower()
if (ext(path) == ext(executable) # reject *.cmd~, *.bat~ cases
and samefile(GetLongPathName(executable), path)):
return True
# path is a document with assoc. check whether it has extension
# from %PATHEXT%
pathexts = os.environ.get('PATHEXT', '').split(os.pathsep)
return any(ext(path) == e.lower() for e in pathexts)
except error:
return None # not an exe or a document with assoc.
</code></pre>
<p>Where <code>samefile</code> is:</p>
<pre><code>try: samefile = os.path.samefile
except AttributeError:
def samefile(path1, path2):
rp = lambda p: os.path.realpath(os.path.normcase(p))
return rp(path1) == rp(path2)
</code></pre>
<p>How <code>is_executable_win</code> could be improved in the given context? What functions from Win32 API could help?</p>
<p>P.S.</p>
<ul>
<li>time performance doesn't matter</li>
<li><code>subst</code> drives and UNC, unicode paths are not under consideration</li>
<li>C++ answer is OK if it uses functions available on Windows XP</li>
</ul>
<h3>Examples</h3>
<ul>
<li><code>notepad.exe</code> is executable (as a rule)</li>
<li><p><code>which.py</code> is executable if it is associated with some executable (e.g., python.exe) and <code>.PY</code> is in <code>%PATHEXT%</code> i.e., <code>'C:\> which'</code> could start:</p>
<pre><code>some\path\python.exe another\path\in\PATH\which.py
</code></pre></li>
<li><p><code>somefile.doc</code> most probably is <em>not</em> executable (when it is associated with Word for example)</p></li>
<li><code>another_file.txt</code> is <em>not</em> executable (as a rule)</li>
<li><code>ack.pl</code> is executable if it is associated with some executable (most probably perl.exe) and <code>.PL</code> is in <code>%PATHEXT%</code> (i.e. I can run <code>ack</code> without specifing extension if it is in the path)</li>
</ul>
<h3>What is "executable" in this question</h3>
<pre><code>def is_executable_win_destructive(path):
#NOTE: it assumes `path` <-> `barename` for the sake of example
barename = os.path.splitext(os.path.basename(path))[0]
p = Popen(barename, stdout=PIPE, stderr=PIPE, shell=True)
stdout, stderr = p.communicate()
return p.poll() != 1 or stdout != '' or stderr != error_message(barename)
</code></pre>
<p>Where <code>error_message()</code> depends on language. English version is:</p>
<pre><code>def error_message(barename):
return "'%(barename)s' is not recognized as an internal" \
" or external\r\ncommand, operable program or batch file.\r\n" \
% dict(barename=barename)
</code></pre>
<p>If <code>is_executable_win_destructive()</code> returns when it defines whether the path points to an executable for the purpose of this question.</p>
<p>Example:</p>
<pre><code>>>> path = r"c:\docs\somefile.doc"
>>> barename = "somefile"
</code></pre>
<p>After that it executes %COMSPEC% (cmd.exe by default):</p>
<pre><code>c:\cwd> cmd.exe /c somefile
</code></pre>
<p>If output looks like this:</p>
<pre>
'somefile' is not recognized as an internal or external
command, operable program or batch file.
</pre>
<p>Then the <code>path</code> is not an executable else it is (lets assume there is one-to-one correspondence between <code>path</code> and <code>barename</code> for the sake of example).</p>
<p>Another example:</p>
<pre><code>>>> path = r'c:\bin\grepath.py'
>>> barename = 'grepath'
</code></pre>
<p>If <code>.PY</code> in <code>%PATHEXT%</code> and <code>c:\bin</code> is in <code>%PATH%</code> then:</p>
<pre><code>c:\docs> grepath
Usage:
grepath.py [options] PATTERN
grepath.py [options] -e PATTERN
grepath.py: error: incorrect number of arguments
</code></pre>
<p>The above output is not equal to <code>error_message(barename)</code> therefore <code>'c:\bin\grepath.py'</code> is an "executable".</p>
<p>So the question is how to find out whether the <code>path</code> will produce the error without actually running it? What Win32 API function and what conditions used to trigger the 'is not recognized as an internal..' error?</p>
| 7
|
2009-03-14T23:48:40Z
| 646,965
|
<p>A windows <a href="http://en.wikipedia.org/wiki/Portable%5FExecutable" rel="nofollow">PE</a> always starts with the characters "MZ". This includes however also any kind of DLLs which are not necessarily executables.<br />
To check for this however you'll have to open the file and read the header so that's probably not what you're looking for.</p>
| 2
|
2009-03-14T23:55:21Z
|
[
"c++",
"python",
"windows",
"winapi"
] |
How to tell whether a file is executable on Windows in Python?
| 646,955
|
<p>I'm writing <a href="http://gist.github.com/79233"><code>grepath</code></a> utility that finds executables in <code>%PATH%</code> that match a pattern.
I need to define whether given filename in the path is executable (emphasis is on command line scripts).</p>
<p>Based on <a href="http://timgolden.me.uk/python/win32%5Fhow%5Fdo%5Fi/tell-if-a-file-is-executable.html">"Tell if a file is executable"</a> I've got:</p>
<pre><code>import os
from pywintypes import error
from win32api import FindExecutable, GetLongPathName
def is_executable_win(path):
try:
_, executable = FindExecutable(path)
ext = lambda p: os.path.splitext(p)[1].lower()
if (ext(path) == ext(executable) # reject *.cmd~, *.bat~ cases
and samefile(GetLongPathName(executable), path)):
return True
# path is a document with assoc. check whether it has extension
# from %PATHEXT%
pathexts = os.environ.get('PATHEXT', '').split(os.pathsep)
return any(ext(path) == e.lower() for e in pathexts)
except error:
return None # not an exe or a document with assoc.
</code></pre>
<p>Where <code>samefile</code> is:</p>
<pre><code>try: samefile = os.path.samefile
except AttributeError:
def samefile(path1, path2):
rp = lambda p: os.path.realpath(os.path.normcase(p))
return rp(path1) == rp(path2)
</code></pre>
<p>How <code>is_executable_win</code> could be improved in the given context? What functions from Win32 API could help?</p>
<p>P.S.</p>
<ul>
<li>time performance doesn't matter</li>
<li><code>subst</code> drives and UNC, unicode paths are not under consideration</li>
<li>C++ answer is OK if it uses functions available on Windows XP</li>
</ul>
<h3>Examples</h3>
<ul>
<li><code>notepad.exe</code> is executable (as a rule)</li>
<li><p><code>which.py</code> is executable if it is associated with some executable (e.g., python.exe) and <code>.PY</code> is in <code>%PATHEXT%</code> i.e., <code>'C:\> which'</code> could start:</p>
<pre><code>some\path\python.exe another\path\in\PATH\which.py
</code></pre></li>
<li><p><code>somefile.doc</code> most probably is <em>not</em> executable (when it is associated with Word for example)</p></li>
<li><code>another_file.txt</code> is <em>not</em> executable (as a rule)</li>
<li><code>ack.pl</code> is executable if it is associated with some executable (most probably perl.exe) and <code>.PL</code> is in <code>%PATHEXT%</code> (i.e. I can run <code>ack</code> without specifing extension if it is in the path)</li>
</ul>
<h3>What is "executable" in this question</h3>
<pre><code>def is_executable_win_destructive(path):
#NOTE: it assumes `path` <-> `barename` for the sake of example
barename = os.path.splitext(os.path.basename(path))[0]
p = Popen(barename, stdout=PIPE, stderr=PIPE, shell=True)
stdout, stderr = p.communicate()
return p.poll() != 1 or stdout != '' or stderr != error_message(barename)
</code></pre>
<p>Where <code>error_message()</code> depends on language. English version is:</p>
<pre><code>def error_message(barename):
return "'%(barename)s' is not recognized as an internal" \
" or external\r\ncommand, operable program or batch file.\r\n" \
% dict(barename=barename)
</code></pre>
<p>If <code>is_executable_win_destructive()</code> returns when it defines whether the path points to an executable for the purpose of this question.</p>
<p>Example:</p>
<pre><code>>>> path = r"c:\docs\somefile.doc"
>>> barename = "somefile"
</code></pre>
<p>After that it executes %COMSPEC% (cmd.exe by default):</p>
<pre><code>c:\cwd> cmd.exe /c somefile
</code></pre>
<p>If output looks like this:</p>
<pre>
'somefile' is not recognized as an internal or external
command, operable program or batch file.
</pre>
<p>Then the <code>path</code> is not an executable else it is (lets assume there is one-to-one correspondence between <code>path</code> and <code>barename</code> for the sake of example).</p>
<p>Another example:</p>
<pre><code>>>> path = r'c:\bin\grepath.py'
>>> barename = 'grepath'
</code></pre>
<p>If <code>.PY</code> in <code>%PATHEXT%</code> and <code>c:\bin</code> is in <code>%PATH%</code> then:</p>
<pre><code>c:\docs> grepath
Usage:
grepath.py [options] PATTERN
grepath.py [options] -e PATTERN
grepath.py: error: incorrect number of arguments
</code></pre>
<p>The above output is not equal to <code>error_message(barename)</code> therefore <code>'c:\bin\grepath.py'</code> is an "executable".</p>
<p>So the question is how to find out whether the <code>path</code> will produce the error without actually running it? What Win32 API function and what conditions used to trigger the 'is not recognized as an internal..' error?</p>
| 7
|
2009-03-14T23:48:40Z
| 646,968
|
<p>shoosh beat me to it :)</p>
<p>If I remember correctly, you should try to read the first 2 characters in the file. If you get back "MZ", you have an exe.</p>
<pre><code>
hnd = open(file,"rb")
if hnd.read(2) == "MZ":
print "exe"
</code></pre>
| 3
|
2009-03-14T23:56:53Z
|
[
"c++",
"python",
"windows",
"winapi"
] |
How to tell whether a file is executable on Windows in Python?
| 646,955
|
<p>I'm writing <a href="http://gist.github.com/79233"><code>grepath</code></a> utility that finds executables in <code>%PATH%</code> that match a pattern.
I need to define whether given filename in the path is executable (emphasis is on command line scripts).</p>
<p>Based on <a href="http://timgolden.me.uk/python/win32%5Fhow%5Fdo%5Fi/tell-if-a-file-is-executable.html">"Tell if a file is executable"</a> I've got:</p>
<pre><code>import os
from pywintypes import error
from win32api import FindExecutable, GetLongPathName
def is_executable_win(path):
try:
_, executable = FindExecutable(path)
ext = lambda p: os.path.splitext(p)[1].lower()
if (ext(path) == ext(executable) # reject *.cmd~, *.bat~ cases
and samefile(GetLongPathName(executable), path)):
return True
# path is a document with assoc. check whether it has extension
# from %PATHEXT%
pathexts = os.environ.get('PATHEXT', '').split(os.pathsep)
return any(ext(path) == e.lower() for e in pathexts)
except error:
return None # not an exe or a document with assoc.
</code></pre>
<p>Where <code>samefile</code> is:</p>
<pre><code>try: samefile = os.path.samefile
except AttributeError:
def samefile(path1, path2):
rp = lambda p: os.path.realpath(os.path.normcase(p))
return rp(path1) == rp(path2)
</code></pre>
<p>How <code>is_executable_win</code> could be improved in the given context? What functions from Win32 API could help?</p>
<p>P.S.</p>
<ul>
<li>time performance doesn't matter</li>
<li><code>subst</code> drives and UNC, unicode paths are not under consideration</li>
<li>C++ answer is OK if it uses functions available on Windows XP</li>
</ul>
<h3>Examples</h3>
<ul>
<li><code>notepad.exe</code> is executable (as a rule)</li>
<li><p><code>which.py</code> is executable if it is associated with some executable (e.g., python.exe) and <code>.PY</code> is in <code>%PATHEXT%</code> i.e., <code>'C:\> which'</code> could start:</p>
<pre><code>some\path\python.exe another\path\in\PATH\which.py
</code></pre></li>
<li><p><code>somefile.doc</code> most probably is <em>not</em> executable (when it is associated with Word for example)</p></li>
<li><code>another_file.txt</code> is <em>not</em> executable (as a rule)</li>
<li><code>ack.pl</code> is executable if it is associated with some executable (most probably perl.exe) and <code>.PL</code> is in <code>%PATHEXT%</code> (i.e. I can run <code>ack</code> without specifing extension if it is in the path)</li>
</ul>
<h3>What is "executable" in this question</h3>
<pre><code>def is_executable_win_destructive(path):
#NOTE: it assumes `path` <-> `barename` for the sake of example
barename = os.path.splitext(os.path.basename(path))[0]
p = Popen(barename, stdout=PIPE, stderr=PIPE, shell=True)
stdout, stderr = p.communicate()
return p.poll() != 1 or stdout != '' or stderr != error_message(barename)
</code></pre>
<p>Where <code>error_message()</code> depends on language. English version is:</p>
<pre><code>def error_message(barename):
return "'%(barename)s' is not recognized as an internal" \
" or external\r\ncommand, operable program or batch file.\r\n" \
% dict(barename=barename)
</code></pre>
<p>If <code>is_executable_win_destructive()</code> returns when it defines whether the path points to an executable for the purpose of this question.</p>
<p>Example:</p>
<pre><code>>>> path = r"c:\docs\somefile.doc"
>>> barename = "somefile"
</code></pre>
<p>After that it executes %COMSPEC% (cmd.exe by default):</p>
<pre><code>c:\cwd> cmd.exe /c somefile
</code></pre>
<p>If output looks like this:</p>
<pre>
'somefile' is not recognized as an internal or external
command, operable program or batch file.
</pre>
<p>Then the <code>path</code> is not an executable else it is (lets assume there is one-to-one correspondence between <code>path</code> and <code>barename</code> for the sake of example).</p>
<p>Another example:</p>
<pre><code>>>> path = r'c:\bin\grepath.py'
>>> barename = 'grepath'
</code></pre>
<p>If <code>.PY</code> in <code>%PATHEXT%</code> and <code>c:\bin</code> is in <code>%PATH%</code> then:</p>
<pre><code>c:\docs> grepath
Usage:
grepath.py [options] PATTERN
grepath.py [options] -e PATTERN
grepath.py: error: incorrect number of arguments
</code></pre>
<p>The above output is not equal to <code>error_message(barename)</code> therefore <code>'c:\bin\grepath.py'</code> is an "executable".</p>
<p>So the question is how to find out whether the <code>path</code> will produce the error without actually running it? What Win32 API function and what conditions used to trigger the 'is not recognized as an internal..' error?</p>
| 7
|
2009-03-14T23:48:40Z
| 647,441
|
<p>Parse the PE format.</p>
<p><a href="http://code.google.com/p/pefile/" rel="nofollow">http://code.google.com/p/pefile/</a></p>
<p>This is probably the best solution you will get other than using python to actually try to run the program.</p>
<p>Edit: I see you also want files that have associations. This will require mucking in the registry which I don't have the information for.</p>
<p>Edit2: I also see that you differentiate between .doc and .py. This is a rather arbitrary differentiation which must be specified with manual rules, because to windows, they are both file extensions that a program reads.</p>
| 0
|
2009-03-15T07:25:12Z
|
[
"c++",
"python",
"windows",
"winapi"
] |
How to tell whether a file is executable on Windows in Python?
| 646,955
|
<p>I'm writing <a href="http://gist.github.com/79233"><code>grepath</code></a> utility that finds executables in <code>%PATH%</code> that match a pattern.
I need to define whether given filename in the path is executable (emphasis is on command line scripts).</p>
<p>Based on <a href="http://timgolden.me.uk/python/win32%5Fhow%5Fdo%5Fi/tell-if-a-file-is-executable.html">"Tell if a file is executable"</a> I've got:</p>
<pre><code>import os
from pywintypes import error
from win32api import FindExecutable, GetLongPathName
def is_executable_win(path):
try:
_, executable = FindExecutable(path)
ext = lambda p: os.path.splitext(p)[1].lower()
if (ext(path) == ext(executable) # reject *.cmd~, *.bat~ cases
and samefile(GetLongPathName(executable), path)):
return True
# path is a document with assoc. check whether it has extension
# from %PATHEXT%
pathexts = os.environ.get('PATHEXT', '').split(os.pathsep)
return any(ext(path) == e.lower() for e in pathexts)
except error:
return None # not an exe or a document with assoc.
</code></pre>
<p>Where <code>samefile</code> is:</p>
<pre><code>try: samefile = os.path.samefile
except AttributeError:
def samefile(path1, path2):
rp = lambda p: os.path.realpath(os.path.normcase(p))
return rp(path1) == rp(path2)
</code></pre>
<p>How <code>is_executable_win</code> could be improved in the given context? What functions from Win32 API could help?</p>
<p>P.S.</p>
<ul>
<li>time performance doesn't matter</li>
<li><code>subst</code> drives and UNC, unicode paths are not under consideration</li>
<li>C++ answer is OK if it uses functions available on Windows XP</li>
</ul>
<h3>Examples</h3>
<ul>
<li><code>notepad.exe</code> is executable (as a rule)</li>
<li><p><code>which.py</code> is executable if it is associated with some executable (e.g., python.exe) and <code>.PY</code> is in <code>%PATHEXT%</code> i.e., <code>'C:\> which'</code> could start:</p>
<pre><code>some\path\python.exe another\path\in\PATH\which.py
</code></pre></li>
<li><p><code>somefile.doc</code> most probably is <em>not</em> executable (when it is associated with Word for example)</p></li>
<li><code>another_file.txt</code> is <em>not</em> executable (as a rule)</li>
<li><code>ack.pl</code> is executable if it is associated with some executable (most probably perl.exe) and <code>.PL</code> is in <code>%PATHEXT%</code> (i.e. I can run <code>ack</code> without specifing extension if it is in the path)</li>
</ul>
<h3>What is "executable" in this question</h3>
<pre><code>def is_executable_win_destructive(path):
#NOTE: it assumes `path` <-> `barename` for the sake of example
barename = os.path.splitext(os.path.basename(path))[0]
p = Popen(barename, stdout=PIPE, stderr=PIPE, shell=True)
stdout, stderr = p.communicate()
return p.poll() != 1 or stdout != '' or stderr != error_message(barename)
</code></pre>
<p>Where <code>error_message()</code> depends on language. English version is:</p>
<pre><code>def error_message(barename):
return "'%(barename)s' is not recognized as an internal" \
" or external\r\ncommand, operable program or batch file.\r\n" \
% dict(barename=barename)
</code></pre>
<p>If <code>is_executable_win_destructive()</code> returns when it defines whether the path points to an executable for the purpose of this question.</p>
<p>Example:</p>
<pre><code>>>> path = r"c:\docs\somefile.doc"
>>> barename = "somefile"
</code></pre>
<p>After that it executes %COMSPEC% (cmd.exe by default):</p>
<pre><code>c:\cwd> cmd.exe /c somefile
</code></pre>
<p>If output looks like this:</p>
<pre>
'somefile' is not recognized as an internal or external
command, operable program or batch file.
</pre>
<p>Then the <code>path</code> is not an executable else it is (lets assume there is one-to-one correspondence between <code>path</code> and <code>barename</code> for the sake of example).</p>
<p>Another example:</p>
<pre><code>>>> path = r'c:\bin\grepath.py'
>>> barename = 'grepath'
</code></pre>
<p>If <code>.PY</code> in <code>%PATHEXT%</code> and <code>c:\bin</code> is in <code>%PATH%</code> then:</p>
<pre><code>c:\docs> grepath
Usage:
grepath.py [options] PATTERN
grepath.py [options] -e PATTERN
grepath.py: error: incorrect number of arguments
</code></pre>
<p>The above output is not equal to <code>error_message(barename)</code> therefore <code>'c:\bin\grepath.py'</code> is an "executable".</p>
<p>So the question is how to find out whether the <code>path</code> will produce the error without actually running it? What Win32 API function and what conditions used to trigger the 'is not recognized as an internal..' error?</p>
| 7
|
2009-03-14T23:48:40Z
| 647,466
|
<p>Your question can't be answered. Windows can't tell the difference between a file which is associated with a scripting language vs. some other arbitrary program. As Windows is concerned, a .PY file is simply a document which is opened by python.exe.</p>
| -1
|
2009-03-15T08:00:04Z
|
[
"c++",
"python",
"windows",
"winapi"
] |
How to tell whether a file is executable on Windows in Python?
| 646,955
|
<p>I'm writing <a href="http://gist.github.com/79233"><code>grepath</code></a> utility that finds executables in <code>%PATH%</code> that match a pattern.
I need to define whether given filename in the path is executable (emphasis is on command line scripts).</p>
<p>Based on <a href="http://timgolden.me.uk/python/win32%5Fhow%5Fdo%5Fi/tell-if-a-file-is-executable.html">"Tell if a file is executable"</a> I've got:</p>
<pre><code>import os
from pywintypes import error
from win32api import FindExecutable, GetLongPathName
def is_executable_win(path):
try:
_, executable = FindExecutable(path)
ext = lambda p: os.path.splitext(p)[1].lower()
if (ext(path) == ext(executable) # reject *.cmd~, *.bat~ cases
and samefile(GetLongPathName(executable), path)):
return True
# path is a document with assoc. check whether it has extension
# from %PATHEXT%
pathexts = os.environ.get('PATHEXT', '').split(os.pathsep)
return any(ext(path) == e.lower() for e in pathexts)
except error:
return None # not an exe or a document with assoc.
</code></pre>
<p>Where <code>samefile</code> is:</p>
<pre><code>try: samefile = os.path.samefile
except AttributeError:
def samefile(path1, path2):
rp = lambda p: os.path.realpath(os.path.normcase(p))
return rp(path1) == rp(path2)
</code></pre>
<p>How <code>is_executable_win</code> could be improved in the given context? What functions from Win32 API could help?</p>
<p>P.S.</p>
<ul>
<li>time performance doesn't matter</li>
<li><code>subst</code> drives and UNC, unicode paths are not under consideration</li>
<li>C++ answer is OK if it uses functions available on Windows XP</li>
</ul>
<h3>Examples</h3>
<ul>
<li><code>notepad.exe</code> is executable (as a rule)</li>
<li><p><code>which.py</code> is executable if it is associated with some executable (e.g., python.exe) and <code>.PY</code> is in <code>%PATHEXT%</code> i.e., <code>'C:\> which'</code> could start:</p>
<pre><code>some\path\python.exe another\path\in\PATH\which.py
</code></pre></li>
<li><p><code>somefile.doc</code> most probably is <em>not</em> executable (when it is associated with Word for example)</p></li>
<li><code>another_file.txt</code> is <em>not</em> executable (as a rule)</li>
<li><code>ack.pl</code> is executable if it is associated with some executable (most probably perl.exe) and <code>.PL</code> is in <code>%PATHEXT%</code> (i.e. I can run <code>ack</code> without specifing extension if it is in the path)</li>
</ul>
<h3>What is "executable" in this question</h3>
<pre><code>def is_executable_win_destructive(path):
#NOTE: it assumes `path` <-> `barename` for the sake of example
barename = os.path.splitext(os.path.basename(path))[0]
p = Popen(barename, stdout=PIPE, stderr=PIPE, shell=True)
stdout, stderr = p.communicate()
return p.poll() != 1 or stdout != '' or stderr != error_message(barename)
</code></pre>
<p>Where <code>error_message()</code> depends on language. English version is:</p>
<pre><code>def error_message(barename):
return "'%(barename)s' is not recognized as an internal" \
" or external\r\ncommand, operable program or batch file.\r\n" \
% dict(barename=barename)
</code></pre>
<p>If <code>is_executable_win_destructive()</code> returns when it defines whether the path points to an executable for the purpose of this question.</p>
<p>Example:</p>
<pre><code>>>> path = r"c:\docs\somefile.doc"
>>> barename = "somefile"
</code></pre>
<p>After that it executes %COMSPEC% (cmd.exe by default):</p>
<pre><code>c:\cwd> cmd.exe /c somefile
</code></pre>
<p>If output looks like this:</p>
<pre>
'somefile' is not recognized as an internal or external
command, operable program or batch file.
</pre>
<p>Then the <code>path</code> is not an executable else it is (lets assume there is one-to-one correspondence between <code>path</code> and <code>barename</code> for the sake of example).</p>
<p>Another example:</p>
<pre><code>>>> path = r'c:\bin\grepath.py'
>>> barename = 'grepath'
</code></pre>
<p>If <code>.PY</code> in <code>%PATHEXT%</code> and <code>c:\bin</code> is in <code>%PATH%</code> then:</p>
<pre><code>c:\docs> grepath
Usage:
grepath.py [options] PATTERN
grepath.py [options] -e PATTERN
grepath.py: error: incorrect number of arguments
</code></pre>
<p>The above output is not equal to <code>error_message(barename)</code> therefore <code>'c:\bin\grepath.py'</code> is an "executable".</p>
<p>So the question is how to find out whether the <code>path</code> will produce the error without actually running it? What Win32 API function and what conditions used to trigger the 'is not recognized as an internal..' error?</p>
| 7
|
2009-03-14T23:48:40Z
| 1,738,701
|
<p>I think, that this should be sufficient:</p>
<ol>
<li>check file extension in PATHEXT - whether file is directly executable</li>
<li>using cmd.exe command "assoc .ext" you can see whether file is associated with some executable (some executable will be launched when you launch this file). You can parse capture output of assoc without arguments and collect all extensions that are associated and check tested file extension.</li>
<li>other file extensions will trigger error "command is not recognized ..." therefore you can assume that such files are NOT executable.</li>
</ol>
<p>I don't really understand how you can tell the difference between somefile.py and somefile.txt because association can be really the same. You can configure system to run .txt files the same way as .py files.</p>
| 3
|
2009-11-15T20:25:05Z
|
[
"c++",
"python",
"windows",
"winapi"
] |
How to tell whether a file is executable on Windows in Python?
| 646,955
|
<p>I'm writing <a href="http://gist.github.com/79233"><code>grepath</code></a> utility that finds executables in <code>%PATH%</code> that match a pattern.
I need to define whether given filename in the path is executable (emphasis is on command line scripts).</p>
<p>Based on <a href="http://timgolden.me.uk/python/win32%5Fhow%5Fdo%5Fi/tell-if-a-file-is-executable.html">"Tell if a file is executable"</a> I've got:</p>
<pre><code>import os
from pywintypes import error
from win32api import FindExecutable, GetLongPathName
def is_executable_win(path):
try:
_, executable = FindExecutable(path)
ext = lambda p: os.path.splitext(p)[1].lower()
if (ext(path) == ext(executable) # reject *.cmd~, *.bat~ cases
and samefile(GetLongPathName(executable), path)):
return True
# path is a document with assoc. check whether it has extension
# from %PATHEXT%
pathexts = os.environ.get('PATHEXT', '').split(os.pathsep)
return any(ext(path) == e.lower() for e in pathexts)
except error:
return None # not an exe or a document with assoc.
</code></pre>
<p>Where <code>samefile</code> is:</p>
<pre><code>try: samefile = os.path.samefile
except AttributeError:
def samefile(path1, path2):
rp = lambda p: os.path.realpath(os.path.normcase(p))
return rp(path1) == rp(path2)
</code></pre>
<p>How <code>is_executable_win</code> could be improved in the given context? What functions from Win32 API could help?</p>
<p>P.S.</p>
<ul>
<li>time performance doesn't matter</li>
<li><code>subst</code> drives and UNC, unicode paths are not under consideration</li>
<li>C++ answer is OK if it uses functions available on Windows XP</li>
</ul>
<h3>Examples</h3>
<ul>
<li><code>notepad.exe</code> is executable (as a rule)</li>
<li><p><code>which.py</code> is executable if it is associated with some executable (e.g., python.exe) and <code>.PY</code> is in <code>%PATHEXT%</code> i.e., <code>'C:\> which'</code> could start:</p>
<pre><code>some\path\python.exe another\path\in\PATH\which.py
</code></pre></li>
<li><p><code>somefile.doc</code> most probably is <em>not</em> executable (when it is associated with Word for example)</p></li>
<li><code>another_file.txt</code> is <em>not</em> executable (as a rule)</li>
<li><code>ack.pl</code> is executable if it is associated with some executable (most probably perl.exe) and <code>.PL</code> is in <code>%PATHEXT%</code> (i.e. I can run <code>ack</code> without specifing extension if it is in the path)</li>
</ul>
<h3>What is "executable" in this question</h3>
<pre><code>def is_executable_win_destructive(path):
#NOTE: it assumes `path` <-> `barename` for the sake of example
barename = os.path.splitext(os.path.basename(path))[0]
p = Popen(barename, stdout=PIPE, stderr=PIPE, shell=True)
stdout, stderr = p.communicate()
return p.poll() != 1 or stdout != '' or stderr != error_message(barename)
</code></pre>
<p>Where <code>error_message()</code> depends on language. English version is:</p>
<pre><code>def error_message(barename):
return "'%(barename)s' is not recognized as an internal" \
" or external\r\ncommand, operable program or batch file.\r\n" \
% dict(barename=barename)
</code></pre>
<p>If <code>is_executable_win_destructive()</code> returns when it defines whether the path points to an executable for the purpose of this question.</p>
<p>Example:</p>
<pre><code>>>> path = r"c:\docs\somefile.doc"
>>> barename = "somefile"
</code></pre>
<p>After that it executes %COMSPEC% (cmd.exe by default):</p>
<pre><code>c:\cwd> cmd.exe /c somefile
</code></pre>
<p>If output looks like this:</p>
<pre>
'somefile' is not recognized as an internal or external
command, operable program or batch file.
</pre>
<p>Then the <code>path</code> is not an executable else it is (lets assume there is one-to-one correspondence between <code>path</code> and <code>barename</code> for the sake of example).</p>
<p>Another example:</p>
<pre><code>>>> path = r'c:\bin\grepath.py'
>>> barename = 'grepath'
</code></pre>
<p>If <code>.PY</code> in <code>%PATHEXT%</code> and <code>c:\bin</code> is in <code>%PATH%</code> then:</p>
<pre><code>c:\docs> grepath
Usage:
grepath.py [options] PATTERN
grepath.py [options] -e PATTERN
grepath.py: error: incorrect number of arguments
</code></pre>
<p>The above output is not equal to <code>error_message(barename)</code> therefore <code>'c:\bin\grepath.py'</code> is an "executable".</p>
<p>So the question is how to find out whether the <code>path</code> will produce the error without actually running it? What Win32 API function and what conditions used to trigger the 'is not recognized as an internal..' error?</p>
| 7
|
2009-03-14T23:48:40Z
| 1,738,907
|
<p>Here's the <a href="http://gist.github.com/79233/" rel="nofollow">grepath.py</a> that I've linked in my question:</p>
<pre><code>#!/usr/bin/env python
"""Find executables in %PATH% that match PATTERN.
"""
#XXX: remove --use-pathext option
import fnmatch, itertools, os, re, sys, warnings
from optparse import OptionParser
from stat import S_IMODE, S_ISREG, ST_MODE
from subprocess import PIPE, Popen
def warn_import(*args):
"""pass '-Wd' option to python interpreter to see these warnings."""
warnings.warn("%r" % (args,), ImportWarning, stacklevel=2)
class samefile_win:
"""
http://timgolden.me.uk/python/win32_how_do_i/see_if_two_files_are_the_same_file.html
"""
@staticmethod
def get_read_handle (filename):
return win32file.CreateFile (
filename,
win32file.GENERIC_READ,
win32file.FILE_SHARE_READ,
None,
win32file.OPEN_EXISTING,
0,
None
)
@staticmethod
def get_unique_id (hFile):
(attributes,
created_at, accessed_at, written_at,
volume,
file_hi, file_lo,
n_links,
index_hi, index_lo
) = win32file.GetFileInformationByHandle (hFile)
return volume, index_hi, index_lo
@staticmethod
def samefile_win(filename1, filename2):
"""Whether filename1 and filename2 represent the same file.
It works for subst, ntfs hardlinks, junction points.
It works unreliably for network drives.
Based on GetFileInformationByHandle() Win32 API call.
http://timgolden.me.uk/python/win32_how_do_i/see_if_two_files_are_the_same_file.html
"""
if samefile_generic(filename1, filename2): return True
try:
hFile1 = samefile_win.get_read_handle (filename1)
hFile2 = samefile_win.get_read_handle (filename2)
are_equal = (samefile_win.get_unique_id (hFile1)
== samefile_win.get_unique_id (hFile2))
hFile2.Close ()
hFile1.Close ()
return are_equal
except win32file.error:
return None
def canonical_path(path):
"""NOTE: it might return wrong path for paths with symbolic links."""
return os.path.realpath(os.path.normcase(path))
def samefile_generic(path1, path2):
return canonical_path(path1) == canonical_path(path2)
class is_executable_destructive:
@staticmethod
def error_message(barename):
r"""
"'%(barename)s' is not recognized as an internal or external\r\n
command, operable program or batch file.\r\n"
in Russian:
"""
return '"%(barename)s" \xad\xa5 \xef\xa2\xab\xef\xa5\xe2\xe1\xef \xa2\xad\xe3\xe2\xe0\xa5\xad\xad\xa5\xa9 \xa8\xab\xa8 \xa2\xad\xa5\xe8\xad\xa5\xa9\r\n\xaa\xae\xac\xa0\xad\xa4\xae\xa9, \xa8\xe1\xaf\xae\xab\xad\xef\xa5\xac\xae\xa9 \xaf\xe0\xae\xa3\xe0\xa0\xac\xac\xae\xa9 \xa8\xab\xa8 \xaf\xa0\xaa\xa5\xe2\xad\xeb\xac \xe4\xa0\xa9\xab\xae\xac.\r\n' % dict(barename=barename)
@staticmethod
def is_executable_win_destructive(path):
# assume path <-> barename that is false in general
barename = os.path.splitext(os.path.basename(path))[0]
p = Popen(barename, stdout=PIPE, stderr=PIPE, shell=True)
stdout, stderr = p.communicate()
return p.poll() != 1 or stdout != '' or stderr != error_message(barename)
def is_executable_win(path):
"""Based on:
http://timgolden.me.uk/python/win32_how_do_i/tell-if-a-file-is-executable.html
Known bugs: treat some "*~" files as executable, e.g. some "*.bat~" files
"""
try:
_, executable = FindExecutable(path)
return bool(samefile(GetLongPathName(executable), path))
except error:
return None # not an exe or a document with assoc.
def is_executable_posix(path):
"""Whether the file is executable.
Based on which.py from stdlib
"""
#XXX it ignores effective uid, guid?
try: st = os.stat(path)
except os.error:
return None
isregfile = S_ISREG(st[ST_MODE])
isexemode = (S_IMODE(st[ST_MODE]) & 0111)
return bool(isregfile and isexemode)
try:
#XXX replace with ctypes?
from win32api import FindExecutable, GetLongPathName, error
is_executable = is_executable_win
except ImportError, e:
warn_import("is_executable: fall back on posix variant", e)
is_executable = is_executable_posix
try: samefile = os.path.samefile
except AttributeError, e:
warn_import("samefile: fallback to samefile_win", e)
try:
import win32file
samefile = samefile_win.samefile_win
except ImportError, e:
warn_import("samefile: fallback to generic", e)
samefile = samefile_generic
def main():
parser = OptionParser(usage="""
%prog [options] PATTERN
%prog [options] -e PATTERN""", description=__doc__)
opt = parser.add_option
opt("-e", "--regex", metavar="PATTERN",
help="use PATTERN as a regular expression")
opt("--ignore-case", action="store_true", default=True,
help="""[default] ignore case when --regex is present; for \
non-regex PATTERN both FILENAME and PATTERN are first \
case-normalized if the operating system requires it otherwise \
unchanged.""")
opt("--no-ignore-case", dest="ignore_case", action="store_false")
opt("--use-pathext", action="store_true", default=True,
help="[default] whether to use %PATHEXT% environment variable")
opt("--no-use-pathext", dest="use_pathext", action="store_false")
opt("--show-non-executable", action="store_true", default=False,
help="show non executable files")
(options, args) = parser.parse_args()
if len(args) != 1 and not options.regex:
parser.error("incorrect number of arguments")
if not options.regex:
pattern = args[0]
del args
if options.regex:
filepred = re.compile(options.regex, options.ignore_case and re.I).search
else:
fnmatch_ = fnmatch.fnmatch if options.ignore_case else fnmatch.fnmatchcase
for file_pattern_symbol in "*?":
if file_pattern_symbol in pattern:
break
else: # match in any place if no explicit file pattern symbols supplied
pattern = "*" + pattern + "*"
filepred = lambda fn: fnmatch_(fn, pattern)
if not options.regex and options.ignore_case:
filter_files = lambda files: fnmatch.filter(files, pattern)
else:
filter_files = lambda files: itertools.ifilter(filepred, files)
if options.use_pathext:
pathexts = frozenset(map(str.upper,
os.environ.get('PATHEXT', '').split(os.pathsep)))
seen = set()
for dirpath in os.environ.get('PATH', '').split(os.pathsep):
if os.path.isdir(dirpath): # assume no expansion needed
# visit "each" directory only once
# it is unaware of subst drives, junction points, symlinks, etc
rp = canonical_path(dirpath)
if rp in seen: continue
seen.add(rp); del rp
for filename in filter_files(os.listdir(dirpath)):
path = os.path.join(dirpath, filename)
isexe = is_executable(path)
if isexe == False and is_executable == is_executable_win:
# path is a document with associated program
# check whether it is a script (.pl, .rb, .py, etc)
if not isexe and options.use_pathext:
ext = os.path.splitext(path)[1]
isexe = ext.upper() in pathexts
if isexe:
print path
elif options.show_non_executable:
print "non-executable:", path
if __name__=="__main__":
main()
</code></pre>
| 1
|
2009-11-15T21:29:10Z
|
[
"c++",
"python",
"windows",
"winapi"
] |
Workflow for configuring apache on a webfaction account via ssh and ftp. (django/python)
| 647,005
|
<p>I'm new at this, however, when it comes to configuring mod_python/apache or wsgi/apache I suffer.</p>
<p>I've been able to use the python debugger tool.. <code>pdb.set_trace()</code> to success, especially when using the django development server, i.e. it out puts to the terminal all of the server activity, including the pdb interface.</p>
<p>So, how does one do something like this when trying to deploy a django website on an host such as webfaction?</p>
<p>Other than ftp into the error_log and read about it post failure, be able to interact with the system, as its happening?</p>
<p>Hopefully I'm clear enough here. </p>
<p>Btw, following is the file that I'm trying to configure.</p>
<pre><code>import os
import sys
from os.path import abspath, dirname, join
from site import addsitedir
from django.core.handlers.modpython import ModPythonHandler
import pdb
class PinaxModPythonHandler(ModPythonHandler):
def __call__(self, req):
# mod_python fakes the environ, and thus doesn't process SetEnv.
# This fixes that. Django will call this again since there is no way
# of overriding __call__ to just process the request.
os.environ.update(req.subprocess_env)
from django.conf import settings
sys.path.insert(0, abspath(join(dirname(__file__), "../../")))
sys.path.insert(0, os.path.join(settings.PINAX_ROOT, "apps/external_apps"))
sys.path.insert(0, os.path.join(settings.PINAX_ROOT, "apps/local_apps"))
sys.path.insert(0, join(settings.PINAX_ROOT, "apps"))
sys.path.insert(0, join(settings.PROJECT_ROOT, "apps"))
pdb.set_trace()
return super(PinaxModPythonHandler, self).__call__(req)
def handler(req):
# mod_python hooks into this function.
return PinaxModPythonHandler()(req)
</code></pre>
<p>and here's the resulting error page via http:</p>
<pre><code>MOD_PYTHON ERROR
ProcessId: 318
Interpreter: 'web25.webfaction.com'
ServerName: 'web25.webfaction.com'
DocumentRoot: '/etc/httpd/htdocs'
URI: '/'
Location: '/'
Directory: None
Filename: '/etc/httpd/htdocs'
PathInfo: '/'
Phase: 'PythonHandler'
Handler: 'bc.deploy.modpython'
Traceback (most recent call last):
File "/home/dalidada/webapps/birthconfidence/lib/python2.5/mod_python/importer.py", line 1537, in HandlerDispatch
default=default_handler, arg=req, silent=hlist.silent)
File "/home/dalidada/webapps/birthconfidence/lib/python2.5/mod_python/importer.py", line 1229, in _process_target
result = _execute_target(config, req, object, arg)
File "/home/dalidada/webapps/birthconfidence/lib/python2.5/mod_python/importer.py", line 1128, in _execute_target
result = object(arg)
File "/home/dalidada/webapps/birthconfidence/bc/deploy/modpython.py", line 33, in handler
return PinaxModPythonHandler()(req)
File "/home/dalidada/webapps/birthconfidence/bc/deploy/modpython.py", line 29, in __call__
return super(PinaxModPythonHandler, self).__call__(req)
File "/home/dalidada/webapps/birthconfidence/lib/python2.5/django/core/handlers/modpython.py", line 191, in __call__
self.load_middleware()
File "/home/dalidada/webapps/birthconfidence/lib/python2.5/django/core/handlers/base.py", line 40, in load_middleware
raise exceptions.ImproperlyConfigured, 'Error importing middleware %s: "%s"' % (mw_module, e)
ImproperlyConfigured: Error importing middleware django_openid.consumer: "No module named django_openid.consumer"
</code></pre>
| 0
|
2009-03-15T00:22:06Z
| 647,094
|
<p>How to use pdb with mod_wsgi is documented on the mod_wsgi site. See:</p>
<p><a href="http://code.google.com/p/modwsgi/wiki/DebuggingTechniques#Python_Interactive_Debugger" rel="nofollow">http://code.google.com/p/modwsgi/wiki/DebuggingTechniques#Python_Interactive_Debugger</a></p>
<p>Other debugging techniques are shown on the same page.</p>
| 1
|
2009-03-15T01:46:27Z
|
[
"python",
"django",
"apache",
"mod-python"
] |
Need a simple "Hello World" example using the Webkit library in Python
| 647,041
|
<p>Does anyone know of a simple "Hello World" example for using the Webkit library in Python? I have a GTK window, and inside I want to put Webkit.</p>
<p>With Python/mozembed (Mozilla/Gecko), this is simple:</p>
<pre><code>mozembed = gtkmozembed.MozEmbed()
mozembed.load_url('http://google.com/')
</code></pre>
<p>..and I have already created my browser, how do I do this with WebKit?</p>
| 13
|
2009-03-15T01:00:46Z
| 647,066
|
<p>Miuler: No les gusta que usted escribio la pregunta en espanol. Si se responde en ingles puedo ayudar traducir a espanlol otra vez. I said if the answers are in English I will make sure he understands by translating back to Spanish, which he is obviously more comfortable with...</p>
<p>I don't think we should be language elitist, here is a rough translation. I have no idea what webkit is though. I can not edit posts, can some one edit the post above and add this?
Begin transmission:</p>
<p>Anyone have a simple example for webkit? </p>
<p>Anyone know some simple example for hello world using the webkit library? I am making a gtk window and inside I want to put webkit. I have an example like python and mozembed (mozilla / gecko) which is very simple:</p>
<pre><code>mozembed = gtkmozembed.MozEmbed()
mozembed.load_url('http://google.com/')
</code></pre>
<p>and I have already created my browser, how do I do this with WebKit? Hay ejemplos sobre el uso de lo entre el directorio: python demos / tabbed_browser.py </p>
<p>--------UPDATE-------
karlcow dice:
Has visto los <a href="http://code.google.com/p/pywebkitgtk/" rel="nofollow">Python bindings for the WebKit GTK+ port</a>?
Ver este tambien, FOSDEM by Alp Toker on WebKit GTK+ (pdf) Developing hybrid <a href="http://www.atoker.com/webkit/webkitgtk-fosdem08.pdf" rel="nofollow">Web/GTK+</a> rich internet applications. </p>
| 2
|
2009-03-15T01:20:07Z
|
[
"python",
"webkit"
] |
Need a simple "Hello World" example using the Webkit library in Python
| 647,041
|
<p>Does anyone know of a simple "Hello World" example for using the Webkit library in Python? I have a GTK window, and inside I want to put Webkit.</p>
<p>With Python/mozembed (Mozilla/Gecko), this is simple:</p>
<pre><code>mozembed = gtkmozembed.MozEmbed()
mozembed.load_url('http://google.com/')
</code></pre>
<p>..and I have already created my browser, how do I do this with WebKit?</p>
| 13
|
2009-03-15T01:00:46Z
| 647,121
|
<p>Did you check the <a href="http://code.google.com/p/pywebkitgtk/">Python bindings for the WebKit GTK+ port</a>. In one of the directory there are demos on how to use it, including a browser: python demos/tabbed_browser.py</p>
<p>You could check also the slides of a FOSDEM by Alp Toker on <a href="http://www.atoker.com/webkit/webkitgtk-fosdem08.pdf">WebKit GTK+</a> (pdf) Developing hybrid Web/GTK+ rich internet applications.</p>
<pre><code>import gtk
import webkit
view = webkit.WebView()
sw = gtk.ScrolledWindow()
sw.add(view)
win = gtk.Window(gtk.WINDOW_TOPLEVEL)
win.add(sw)
win.show_all()
view.open("http://w3.org/")
gtk.main()
</code></pre>
<p>That should give you good hints for starting.</p>
| 30
|
2009-03-15T02:11:25Z
|
[
"python",
"webkit"
] |
Python xml ElementTree from a string source?
| 647,071
|
<p>The ElementTree.parse reads from a file, how can I use this if I already have the XML data in a string?</p>
<p>Maybe I am missing something here, but there must be a way to use the ElementTree without writing out the string to a file and reading it again.</p>
<p><a href="http://docs.python.org/library/xml.etree.elementtree.html">xml.etree.elementtree</a></p>
| 41
|
2009-03-15T01:24:19Z
| 647,081
|
<p>It's on the page you linked. Use fromstring.</p>
| 0
|
2009-03-15T01:36:39Z
|
[
"python",
"xml"
] |
Python xml ElementTree from a string source?
| 647,071
|
<p>The ElementTree.parse reads from a file, how can I use this if I already have the XML data in a string?</p>
<p>Maybe I am missing something here, but there must be a way to use the ElementTree without writing out the string to a file and reading it again.</p>
<p><a href="http://docs.python.org/library/xml.etree.elementtree.html">xml.etree.elementtree</a></p>
| 41
|
2009-03-15T01:24:19Z
| 647,082
|
<p>If you're using <code>xml.etree.ElementTree.parse</code> to parse from a file, then you can use <code>xml.etree.ElementTree.fromstring</code> to parse from text.</p>
<p>See <a href="http://docs.python.org/library/xml.etree.elementtree.html" rel="nofollow">xml.etree.ElementTree</a></p>
| 31
|
2009-03-15T01:36:44Z
|
[
"python",
"xml"
] |
Python xml ElementTree from a string source?
| 647,071
|
<p>The ElementTree.parse reads from a file, how can I use this if I already have the XML data in a string?</p>
<p>Maybe I am missing something here, but there must be a way to use the ElementTree without writing out the string to a file and reading it again.</p>
<p><a href="http://docs.python.org/library/xml.etree.elementtree.html">xml.etree.elementtree</a></p>
| 41
|
2009-03-15T01:24:19Z
| 647,084
|
<p>You need the xml.etree.ElementTree.fromstring(text)</p>
<pre><code>from xml.etree.ElementTree import XML, fromstring, tostring
myxml = fromstring(text)
</code></pre>
| 10
|
2009-03-15T01:37:22Z
|
[
"python",
"xml"
] |
Python xml ElementTree from a string source?
| 647,071
|
<p>The ElementTree.parse reads from a file, how can I use this if I already have the XML data in a string?</p>
<p>Maybe I am missing something here, but there must be a way to use the ElementTree without writing out the string to a file and reading it again.</p>
<p><a href="http://docs.python.org/library/xml.etree.elementtree.html">xml.etree.elementtree</a></p>
| 41
|
2009-03-15T01:24:19Z
| 18,281,386
|
<p>You can parse the text as a string, which creates an Element, and create an ElementTree using that Element.</p>
<pre><code>import xml.etree.ElementTree as ET
tree = ET.ElementTree(ET.fromstring(xmlstring))
</code></pre>
<p>I just came across this issue and the documentation, while complete, is not very straightforward on the difference in usage between the parse and fromstring methods.</p>
| 61
|
2013-08-16T20:09:47Z
|
[
"python",
"xml"
] |
Python: Abstract Base Class and ZopeInterface
| 647,110
|
<p>What's the point of both? When do you think it's appropriate to use either?</p>
| 4
|
2009-03-15T02:04:06Z
| 647,159
|
<p>There is an article <a href="http://griddlenoise.blogspot.com/2007/05/abc-may-be-easy-as-123-but-it-cant-beat.html">ABC may be easy as 123, but it can't beat zope.interface</a>, which goes into details comparing both and links to other documents.</p>
| 6
|
2009-03-15T02:35:46Z
|
[
"python",
"oop",
"design",
"zope.interface"
] |
Python: Abstract Base Class and ZopeInterface
| 647,110
|
<p>What's the point of both? When do you think it's appropriate to use either?</p>
| 4
|
2009-03-15T02:04:06Z
| 4,339,141
|
<p>See also <a href="http://glyph.twistedmatrix.com/2009/02/explaining-why-interfaces-are-great.html" rel="nofollow">Explaining Why Interfaces Are Great</a>.</p>
| 3
|
2010-12-02T19:46:24Z
|
[
"python",
"oop",
"design",
"zope.interface"
] |
Why can I not paste the output of Pythons REPL without manual-editing?
| 647,142
|
<p>A huge amount of example Python code shows the output of the Python REPL, for example:</p>
<pre><code>>>> class eg(object):
... def __init__(self, name):
... self.name = name
... def hi(self):
... print "Hi %s" % (self.name)
...
>>> greeter = eg("Bob")
>>> greeter.hi()
Hi Bob
>>>
</code></pre>
<p>Now, the obvious thing you want to do is run the above code.. so, I run "python" and paste the above text in..</p>
<pre><code>>>> >>> class eg(object):
File "<stdin>", line 1
>>> class eg(object):
^
SyntaxError: invalid syntax
>>> ... def __init__(self, name):
File "<stdin>", line 1
... def __init__(self, name):
^
</code></pre>
<p>The code is broken!?..</p>
<p>To get it to run, I would have to either..</p>
<ul>
<li>copy-and-paste the lines one at a time, making sure I copy all the indentation correctly. If you screw it up (say, miss a leading space, you have to start all over again)</li>
<li>use a text editor to remove <code>>>> </code> and <code>... </code>, then paste again</li>
</ul>
<p>It's not a huge issue, but given how much example code is presented in this format, it seems strange you have to do this..</p>
| 4
|
2009-03-15T02:23:48Z
| 647,154
|
<p>The code is presented this way, because it is meant to be a step by step process. The three characters you see ">>>" are the ones of the Python IDE, but it seems you know that already. When you have access to a console or a shell, and type python, you will get something like this.</p>
<pre><code>% python
Python 2.5.1 (r251:54863, Jan 13 2009, 10:26:13)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
</code></pre>
<p>So really take it as an educational tool. :)</p>
| 0
|
2009-03-15T02:30:43Z
|
[
"python",
"user-interface",
"read-eval-print-loop"
] |
Why can I not paste the output of Pythons REPL without manual-editing?
| 647,142
|
<p>A huge amount of example Python code shows the output of the Python REPL, for example:</p>
<pre><code>>>> class eg(object):
... def __init__(self, name):
... self.name = name
... def hi(self):
... print "Hi %s" % (self.name)
...
>>> greeter = eg("Bob")
>>> greeter.hi()
Hi Bob
>>>
</code></pre>
<p>Now, the obvious thing you want to do is run the above code.. so, I run "python" and paste the above text in..</p>
<pre><code>>>> >>> class eg(object):
File "<stdin>", line 1
>>> class eg(object):
^
SyntaxError: invalid syntax
>>> ... def __init__(self, name):
File "<stdin>", line 1
... def __init__(self, name):
^
</code></pre>
<p>The code is broken!?..</p>
<p>To get it to run, I would have to either..</p>
<ul>
<li>copy-and-paste the lines one at a time, making sure I copy all the indentation correctly. If you screw it up (say, miss a leading space, you have to start all over again)</li>
<li>use a text editor to remove <code>>>> </code> and <code>... </code>, then paste again</li>
</ul>
<p>It's not a huge issue, but given how much example code is presented in this format, it seems strange you have to do this..</p>
| 4
|
2009-03-15T02:23:48Z
| 647,185
|
<p>I don't know if there's a good solution out there for this. Ideally, there'd be some way to modify the behavior of the interpretter to accept copy/paste input of this sort. Here are some alternate suggestions:</p>
<p>Use triple quoting to save the example to a string. Then, use exec:</p>
<pre><code>>>> def chomp_prompt(s): return '\n'.join(ln[4:] for ln in s.splitlines())
...
>>> dirty = """>>> class eg(object):
... ... def __init__(self, name):
... ... self.name = name
... ... def hi(self):
... ... print "Hi %s" % (self.name)
... ...
... >>> greeter = eg("Bob")
... >>> greeter.hi()
... """
>>> clean = chomp_prompt(dirty)
>>> exec clean
Hi Bob
>>>
</code></pre>
<p>Not only does my solution all fit on one line (so it'll be easy for you to copy/paste it in the interpreter), it works on the above example :D :</p>
<pre><code>>>> s = r'''>>> def chomp_prompt(s): return '\n'.join(ln[4:] for ln in s.splitlines())
... ...
... >>> dirty = """>>> class eg(object):
... ... ... def __init__(self, name):
... ... ... self.name = name
... ... ... def hi(self):
... ... ... print "Hi %s" % (self.name)
... ... ...
... ... >>> greeter = eg("Bob")
... ... >>> greeter.hi()
... ... """
... >>> clean = chomp_prompt(dirty)
... >>> exec clean'''
>>> s2 = chomp_prompt(s)
>>> exec s2
Hi Bob
</code></pre>
<p>My second suggestion is to look at ipython's ability to open an editor for you and execute what you entered there after you're done editing:</p>
<p><a href="http://ipython.scipy.org/doc/rel-0.9.1/html/interactive/tutorial.html#source-code-handling-tips" rel="nofollow">http://ipython.scipy.org/doc/rel-0.9.1/html/interactive/tutorial.html#source-code-handling-tips</a></p>
<p>If you set emacs as your editor, I know it has the ability to delete a rectangle of text (you can probably guess the command: M-x delete-rectangle), which would work perfectly for getting rid of those pesky prompts. I'm sure many other editors have this as well.</p>
| 2
|
2009-03-15T02:56:35Z
|
[
"python",
"user-interface",
"read-eval-print-loop"
] |
Why can I not paste the output of Pythons REPL without manual-editing?
| 647,142
|
<p>A huge amount of example Python code shows the output of the Python REPL, for example:</p>
<pre><code>>>> class eg(object):
... def __init__(self, name):
... self.name = name
... def hi(self):
... print "Hi %s" % (self.name)
...
>>> greeter = eg("Bob")
>>> greeter.hi()
Hi Bob
>>>
</code></pre>
<p>Now, the obvious thing you want to do is run the above code.. so, I run "python" and paste the above text in..</p>
<pre><code>>>> >>> class eg(object):
File "<stdin>", line 1
>>> class eg(object):
^
SyntaxError: invalid syntax
>>> ... def __init__(self, name):
File "<stdin>", line 1
... def __init__(self, name):
^
</code></pre>
<p>The code is broken!?..</p>
<p>To get it to run, I would have to either..</p>
<ul>
<li>copy-and-paste the lines one at a time, making sure I copy all the indentation correctly. If you screw it up (say, miss a leading space, you have to start all over again)</li>
<li>use a text editor to remove <code>>>> </code> and <code>... </code>, then paste again</li>
</ul>
<p>It's not a huge issue, but given how much example code is presented in this format, it seems strange you have to do this..</p>
| 4
|
2009-03-15T02:23:48Z
| 647,244
|
<h3>How to run/adopt "the output of Pythons REPL"</h3>
<ul>
<li><p>Use <a href="http://ipython.scipy.org/moin/">IPython</a> shell</p>
<pre><code>In [99]: %cpaste
Pasting code; enter '--' alone on the line to stop.
:>>> class eg(object):
:... def __init__(self, name):
:... self.name = name
:... def hi(self):
:... print "Hi %s" % (self.name)
:...
:>>> greeter = eg("Bob")
:>>> greeter.hi()
:--
Hi Bob
</code></pre></li>
<li><p>Use a capable text editor (e.g., <code>C-x r k</code> kills rectangular region in <a href="http://www.enigmacurry.com/2008/05/09/emacs-as-a-powerful-python-ide/">Emacs</a>)</p></li>
<li><p>Use <a href="http://docs.python.org/library/doctest.html">doctest</a> module</p></li>
</ul>
<p>Copy without the shell prompt in the first place (though I don't know how to do it on Google Chrome, for example).</p>
<h3>Why the doctest format is used</h3>
<p>Save the following to <code>documentation.txt</code>:</p>
<pre>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo consequat.
>>> class eg(object):
... def __init__(self, name):
... self.name = name
... def hi(self):
... print "Hi %s" % (self.name)
...
>>> greeter = eg("Bob")
>>> greeter.hi()
Hi Bob
>>>
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum
dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est
laborum.
</pre>
<p>Run:</p>
<pre><code>$ python -c "import doctest; doctest.testfile('documentation.txt')" -v
</code></pre>
<p>Output:</p>
<pre><code>Trying:
class eg(object):
def __init__(self, name):
self.name = name
def hi(self):
print "Hi %s" % (self.name)
Expecting nothing
ok
Trying:
greeter = eg("Bob")
Expecting nothing
ok
Trying:
greeter.hi()
Expecting:
Hi Bob
ok
1 items passed all tests:
3 tests in doctest.txt
3 tests in 1 items.
3 passed and 0 failed.
Test passed.
</code></pre>
<p>If you add the following snippet at the end of your module it will test all code in its docstrings:</p>
<pre><code>if __name__=="__main__":
import doctest; doctest.testmod()
</code></pre>
<p><strong><code>QED</code></strong></p>
| 9
|
2009-03-15T03:36:36Z
|
[
"python",
"user-interface",
"read-eval-print-loop"
] |
Why can I not paste the output of Pythons REPL without manual-editing?
| 647,142
|
<p>A huge amount of example Python code shows the output of the Python REPL, for example:</p>
<pre><code>>>> class eg(object):
... def __init__(self, name):
... self.name = name
... def hi(self):
... print "Hi %s" % (self.name)
...
>>> greeter = eg("Bob")
>>> greeter.hi()
Hi Bob
>>>
</code></pre>
<p>Now, the obvious thing you want to do is run the above code.. so, I run "python" and paste the above text in..</p>
<pre><code>>>> >>> class eg(object):
File "<stdin>", line 1
>>> class eg(object):
^
SyntaxError: invalid syntax
>>> ... def __init__(self, name):
File "<stdin>", line 1
... def __init__(self, name):
^
</code></pre>
<p>The code is broken!?..</p>
<p>To get it to run, I would have to either..</p>
<ul>
<li>copy-and-paste the lines one at a time, making sure I copy all the indentation correctly. If you screw it up (say, miss a leading space, you have to start all over again)</li>
<li>use a text editor to remove <code>>>> </code> and <code>... </code>, then paste again</li>
</ul>
<p>It's not a huge issue, but given how much example code is presented in this format, it seems strange you have to do this..</p>
| 4
|
2009-03-15T02:23:48Z
| 647,706
|
<p>"Why" questions rarely have useful answers.</p>
<p>For example, if I said that the reason why was to avoid a complex intellectual property infringement lawsuit, what does that do? Nothing. You still have to stop copying and pasting and start thinking and typing.</p>
<p>Or, for example, if I said that the reason why was given <a href="http://www.python.org/doc/2.5.2/doc/showing-examples.html" rel="nofollow">here</a>, there's nothing actionable. The problem is that examples have to be typed instead of cut-and-pasted. And that problem is not solved by this information.</p>
<p>Indeed, the problem is really "I want to copy-and-paste without so much thinking and typing, how can I do that?" and the answer is the same. </p>
<p>You can't copy and paste the interactive session (except in doctest comments). You have to type it. Sorry.</p>
| 1
|
2009-03-15T12:10:47Z
|
[
"python",
"user-interface",
"read-eval-print-loop"
] |
Provide discount to preferred customer with Satchmo?
| 647,257
|
<p>I am new to Satchmo -- picked it up because I needed payment processing for site subscriptions and physical product.</p>
<p>My site will have two classes of users: paid subscribers and free users. Both can order a
physical product. Paid subscribers get an automatic discount on all orders.</p>
<p>I don't see a configuration for this in the admin. (Discount looks like it would apply to all users. If I'm missing something here, let me know.)</p>
<p>So what's the best place to automatically override the price depending on the user class? The displayed price should show up, say, 10% less for subscribers everywhere in the site, not just at the checkout.</p>
<p>Thanks.</p>
| 1
|
2009-03-15T03:46:33Z
| 1,198,670
|
<p>Checkout the tiered pricing module</p>
| 2
|
2009-07-29T07:57:12Z
|
[
"python",
"django",
"satchmo"
] |
Multiple overlapping plots with independent scaling in Matplotlib
| 647,443
|
<p>I currently have code that calls <code>matplotlib.pylab.plot</code> multiple times to display multiple sets of data on the same screen, and Matplotlib scales each to the global min and max, considering all plots. Is there a way to ask it to scale each plot independently, to the min and max of that particular plot?</p>
| 8
|
2009-03-15T07:28:34Z
| 647,712
|
<p>There's no direct support for this, but here's some code from a <a href="http://article.gmane.org/gmane.comp.python.matplotlib.general/1987" rel="nofollow">mailing list posting</a> that illlustrates two independent vertical axes:</p>
<pre><code>x=arange(10)
y1=sin(x)
y2=10*cos(x)
rect=[0.1,0.1,0.8,0.8]
a1=axes(rect)
a1.yaxis.tick_left()
plot(x,y1)
ylabel('axis 1')
xlabel('x')
a2=axes(rect,frameon=False)
a2.yaxis.tick_right()
plot(x,y2)
a2.yaxis.set_label_position('right')
ylabel('axis 2')
a2.set_xticks([])
</code></pre>
| 3
|
2009-03-15T12:14:35Z
|
[
"python",
"matplotlib"
] |
Multiple overlapping plots with independent scaling in Matplotlib
| 647,443
|
<p>I currently have code that calls <code>matplotlib.pylab.plot</code> multiple times to display multiple sets of data on the same screen, and Matplotlib scales each to the global min and max, considering all plots. Is there a way to ask it to scale each plot independently, to the min and max of that particular plot?</p>
| 8
|
2009-03-15T07:28:34Z
| 3,291,173
|
<p>This is how you create a single plot (add_subplot(1,1,1)) and limit the scale on the y-axes.</p>
<pre><code>myFig = figure()
myPlot = self.figure.add_subplot(1,1,1)
myPlot.plot([1,2,3,4,5], [5,4,3,2,1], '+r')
myPlot.set_ylim(1,5) # Limit y-axes min 1, max 5
</code></pre>
| 0
|
2010-07-20T14:46:26Z
|
[
"python",
"matplotlib"
] |
Multiple overlapping plots with independent scaling in Matplotlib
| 647,443
|
<p>I currently have code that calls <code>matplotlib.pylab.plot</code> multiple times to display multiple sets of data on the same screen, and Matplotlib scales each to the global min and max, considering all plots. Is there a way to ask it to scale each plot independently, to the min and max of that particular plot?</p>
| 8
|
2009-03-15T07:28:34Z
| 24,144,584
|
<p>I need something like this but wanted to create an example that you can copy and paste into the interactive shell and take a look at it. Here it is for those of you requiring a working solution:</p>
<pre><code>from numpy import arange
from math import sin, cos
import matplotlib.pyplot as plt
x = arange(10)
y1 = [sin(i) for i in x]
y2 = [10*cos(i) for i in x]
rect = [0.1, 0.1, 0.8, 0.8]
a1 = plt.axes(rect) # Create subplot, rect = [left, bottom, width, height] in normalized (0, 1) units
a1.yaxis.tick_left() # Use ticks only on left side of plot
plt.plot(x, y1)
plt.ylabel('axis 1')
plt.xlabel('x')
a2 = plt.axes(rect, frameon=False) # frameon, if False, suppress drawing the figure frame
a2.yaxis.tick_right()
plt.plot(x, y2)
a2.yaxis.set_label_position('right')
plt.ylabel('axis 2')
a2.set_xticks([])
plt.show()
</code></pre>
<p>Tested and works in python 2.7.6, numpy 1.8.1, matpotlib 1.3.1. I'm going to continue playing with it, looking for a neat way to work with overlaying date plots. I'll post back my findings.</p>
| 0
|
2014-06-10T15:11:38Z
|
[
"python",
"matplotlib"
] |
Multiple overlapping plots with independent scaling in Matplotlib
| 647,443
|
<p>I currently have code that calls <code>matplotlib.pylab.plot</code> multiple times to display multiple sets of data on the same screen, and Matplotlib scales each to the global min and max, considering all plots. Is there a way to ask it to scale each plot independently, to the min and max of that particular plot?</p>
| 8
|
2009-03-15T07:28:34Z
| 24,167,481
|
<p>Here is a solution using date plots, and I think its the most optimized solution using twinx() a short hand for adding a second y axis. </p>
<pre><code>import matplotlib.pyplot as plt
import matplotlib.dates as md
import datetime
import numpy
numpy.random.seed(0)
t = md.drange(datetime.datetime(2012, 11, 1),
datetime.datetime(2014, 4, 01),
datetime.timedelta(hours=1)) # takes start, end, delta
x1 = numpy.cumsum(numpy.random.random(len(t)) - 0.5) * 40000
x2 = numpy.cumsum(numpy.random.random(len(t)) - 0.5) * 0.002
fig = plt.figure()
ax1 = fig.add_subplot(111)
fig.suptitle('a title', fontsize=14)
fig.autofmt_xdate()
plt.ylabel('axis 1')
plt.xlabel('dates')
ax2 = ax1.twinx()
ax1.plot_date(t, x1, 'b-', alpha=.65)
ax2.plot_date(t, x2, 'r-', alpha=.65)
plt.ylabel('axis 2')
plt.show()
</code></pre>
<p>From the docs, matplotlib.pyplot.twinx(ax=None)
Make a second axes that shares the x-axis. The new axes will overlay ax (or the current axes if ax is None). The ticks for ax2 will be placed on the right, and the ax2 instance is returned. More <a href="http://matplotlib.org/api/pyplot_api.html" rel="nofollow">here</a>.</p>
| 0
|
2014-06-11T15:59:00Z
|
[
"python",
"matplotlib"
] |
How do I forward a complete email without downloading attachments?
| 647,500
|
<p>Hello (and thanks in advance!)</p>
<p>I'm working in Python and I got IMAP and SMTP to work with my Gmail account.
I now need to forward select messages to another account (after reading their body).</p>
<p>How do I do this without downloading the attachments and recreating the entire message?</p>
<p>Thanks!</p>
<p>Tal.</p>
| 1
|
2009-03-15T08:55:54Z
| 647,504
|
<p>Look at the IMAP and SMTP Lemonade extensions. There is support for forwarding messages without downloading. It's a very new extension, so not many IMAP servers support it yet; I'm not sure if Gmail is one of them.</p>
<p>Section 2 of <a href="ftp://ftp.rfc-editor.org/in-notes/rfc4550.txt" rel="nofollow">RFC 4550</a> contains the technical details on how this works.</p>
| 2
|
2009-03-15T09:00:27Z
|
[
"python",
"smtp",
"gmail",
"imap",
"forward"
] |
How can I know python's path under windows?
| 647,515
|
<p>I want to know where is the python's installation path. For example:</p>
<p>C:\Python25</p>
<p>But however, I have no idea how to do. How can I get the installation path of python?</p>
<p>Thanks.</p>
| 12
|
2009-03-15T09:09:18Z
| 647,564
|
<p>In the <code>sys</code> package, you can find a lot of useful information about your installation:</p>
<pre><code>import sys
print sys.executable
print sys.exec_prefix
</code></pre>
<p>I'm not sure what this will give on your Windows system, but on my Mac <code>executable</code> points to the Python binary and <code>exec_prefix</code> to the installation root.</p>
<p>You could also try this for inspecting your <code>sys</code> module:</p>
<pre><code>import sys
for k,v in sys.__dict__.items():
if not callable(v):
print "%20s: %s" % (k,repr(v))
</code></pre>
| 4
|
2009-03-15T09:41:58Z
|
[
"python",
"path"
] |
How can I know python's path under windows?
| 647,515
|
<p>I want to know where is the python's installation path. For example:</p>
<p>C:\Python25</p>
<p>But however, I have no idea how to do. How can I get the installation path of python?</p>
<p>Thanks.</p>
| 12
|
2009-03-15T09:09:18Z
| 647,600
|
<p>On my windows installation, I get these results:</p>
<pre><code>>>> import sys
>>> sys.executable
'C:\\Python26\\python.exe'
>>> sys.platform
'win32'
>>>
</code></pre>
<p>(You can also look in <code>sys.path</code> for reasonable locations.)</p>
| 2
|
2009-03-15T10:18:52Z
|
[
"python",
"path"
] |
How can I know python's path under windows?
| 647,515
|
<p>I want to know where is the python's installation path. For example:</p>
<p>C:\Python25</p>
<p>But however, I have no idea how to do. How can I get the installation path of python?</p>
<p>Thanks.</p>
| 12
|
2009-03-15T09:09:18Z
| 647,798
|
<pre><code>>>> import os
>>> import sys
>>> os.path.dirname(sys.executable)
'C:\\Python25'
</code></pre>
| 28
|
2009-03-15T13:17:29Z
|
[
"python",
"path"
] |
How can I know python's path under windows?
| 647,515
|
<p>I want to know where is the python's installation path. For example:</p>
<p>C:\Python25</p>
<p>But however, I have no idea how to do. How can I get the installation path of python?</p>
<p>Thanks.</p>
| 12
|
2009-03-15T09:09:18Z
| 648,552
|
<p>If you need to know the installed path under Windows <strong>without</strong> starting the python interpreter, have a look in the Windows registry.</p>
<p>Each installed Python version will have a registry key in either:</p>
<ul>
<li><code>HKLM\SOFTWARE\Python\PythonCore\versionnumber\InstallPath</code></li>
<li><code>HKCU\SOFTWARE\Python\PythonCore\versionnumber\InstallPath</code></li>
</ul>
<p>In 64-bit Windows, it will be under the <code>Wow6432Node</code> key:</p>
<ul>
<li><code>HKLM\SOFTWARE\Wow6432Node\Python\PythonCore\versionnumber\InstallPath</code></li>
</ul>
| 23
|
2009-03-15T21:08:54Z
|
[
"python",
"path"
] |
python, regex split and special character
| 647,655
|
<p>How can I split correctly a string containing a sentence with special chars using whitespaces as separator ?
Using regex split method I cannot obtain the desired result.</p>
<p>Example code:</p>
<pre><code># -*- coding: utf-8 -*-
import re
s="La felicità è tutto" # "The happiness is everything" in italian
l=re.compile("(\W)").split(s)
print " s> "+s
print " wordlist> "+str(l)
for i in l:
print " word> "+i
</code></pre>
<p>The output is :</p>
<pre><code> s> La felicità è tutto
wordlist> ['La', ' ', 'felicit', '\xc3', '', '\xa0', '', ' ', '', '\xc3', '', '\xa8', '', ' ', 'tutto']
word> La
word>
word> felicit
word> Ã
word>
word> ?
word>
word>
word>
word> Ã
word>
word> ?
word>
word>
word> tutto
</code></pre>
<p>while I'm looking for an output like:</p>
<pre><code> s> La felicità è tutto
wordlist> ['La', ' ', 'felicità ', ' ', 'è', ' ', 'tutto']
word> La
word>
word> felicitÃ
word>
word> è
word>
word> tutto
</code></pre>
<p>To be noted that s is a string that is returned from another method so I cannot force the encoding like</p>
<pre><code>s=u"La felicità è tutto"
</code></pre>
<p>On official python documentation of Unicode and reg-ex I haven't found a satisfactory explanation.</p>
<p>Thanks.</p>
<p>Alessandro</p>
| 11
|
2009-03-15T11:24:44Z
| 647,667
|
<p>Your regex should be <code>(\s)</code> instead of <code>(\W)</code> like this:</p>
<pre><code>l = re.compile("(\s)").split(s)
</code></pre>
<p>The code above will give you the exact output you requested. However the following line makes more sense:</p>
<pre><code>l = re.compile("\s").split(s)
</code></pre>
<p>which splits on whitespace characters and doesn't give you all the spaces as matches. You may need them though so I posted both answers.</p>
| 16
|
2009-03-15T11:32:00Z
|
[
"python",
"regex",
"unicode",
"split"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.