title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
sequence
How to add an automatic filter to a relation with SQLAlchemy?
267,861
<p>I'm using SQLAlchemy 0.5rc, and I'd like to add an automatic filter to a relation, so that every time it tries to fetch records for that relation, it ignores the "remote" ones if they're flagged as "logically_deleted" (a boolean field of the child table)</p> <p>For example, if an object "parent" has a "children" relation that has 3 records, but one of them is logically deleted, when I query for "Parent" I'd like SQLA to fetch the parent object with just two children..<br /> How should I do it? By adding an "and" condition to the primaryjoin parameter of the relation? (e.g. "<code>Children.parent_id == Parent.id and Children.logically_deleted == False</code>", but is it correct to write "and" in this way?)</p> <p><strong>Edit:</strong><br /> I managed to do it in this way</p> <pre><code>children = relation("Children", primaryjoin=and_(id == Children.parent_id, Children.logically_deleted==False)) </code></pre> <p>but is there a way to use a string as primaryjoin instead?</p>
7
2008-11-06T07:33:11Z
267,975
<p>I'm only currently developing agains 0.4.something, but here's how I'd suggest it:</p> <pre><code>db.query(Object).filter(Object.first==value).filter(Object.second==False).all() </code></pre> <p>I think that's what you are trying to do, right?</p> <p>(Note: written in a web browser, not real code!)</p>
-1
2008-11-06T08:48:54Z
[ "python", "sqlalchemy" ]
How to add an automatic filter to a relation with SQLAlchemy?
267,861
<p>I'm using SQLAlchemy 0.5rc, and I'd like to add an automatic filter to a relation, so that every time it tries to fetch records for that relation, it ignores the "remote" ones if they're flagged as "logically_deleted" (a boolean field of the child table)</p> <p>For example, if an object "parent" has a "children" relation that has 3 records, but one of them is logically deleted, when I query for "Parent" I'd like SQLA to fetch the parent object with just two children..<br /> How should I do it? By adding an "and" condition to the primaryjoin parameter of the relation? (e.g. "<code>Children.parent_id == Parent.id and Children.logically_deleted == False</code>", but is it correct to write "and" in this way?)</p> <p><strong>Edit:</strong><br /> I managed to do it in this way</p> <pre><code>children = relation("Children", primaryjoin=and_(id == Children.parent_id, Children.logically_deleted==False)) </code></pre> <p>but is there a way to use a string as primaryjoin instead?</p>
7
2008-11-06T07:33:11Z
278,710
<p>The and_() function is the correct way to do logical conjunctions in SQLAlchemy, together with the &amp; operator, but be careful with the latter as it has surprising precedence rules, i.e. higher precedence than comparison operators. </p> <p>You could also use a string as a primary join with the text() constructor, but that will make your code break with any table aliasing that comes with eagerloading and joins.</p> <p>For logical deletion, it might be better to map the whole class over a select that ignores deleted values:</p> <pre><code>mapper(Something, select([sometable], sometable.c.deleted == False)) </code></pre>
3
2008-11-10T18:23:30Z
[ "python", "sqlalchemy" ]
How to add an automatic filter to a relation with SQLAlchemy?
267,861
<p>I'm using SQLAlchemy 0.5rc, and I'd like to add an automatic filter to a relation, so that every time it tries to fetch records for that relation, it ignores the "remote" ones if they're flagged as "logically_deleted" (a boolean field of the child table)</p> <p>For example, if an object "parent" has a "children" relation that has 3 records, but one of them is logically deleted, when I query for "Parent" I'd like SQLA to fetch the parent object with just two children..<br /> How should I do it? By adding an "and" condition to the primaryjoin parameter of the relation? (e.g. "<code>Children.parent_id == Parent.id and Children.logically_deleted == False</code>", but is it correct to write "and" in this way?)</p> <p><strong>Edit:</strong><br /> I managed to do it in this way</p> <pre><code>children = relation("Children", primaryjoin=and_(id == Children.parent_id, Children.logically_deleted==False)) </code></pre> <p>but is there a way to use a string as primaryjoin instead?</p>
7
2008-11-06T07:33:11Z
13,887,876
<blockquote> <p>but is there a way to use a string as primaryjoin instead?</p> </blockquote> <p>You can use the following:</p> <pre><code>children = relationship("Children", primaryjoin="and_(Parent.id==Children.parent_id, Children.logically_deleted==False)" </code></pre> <p>This worked for me!</p>
5
2012-12-14T23:51:38Z
[ "python", "sqlalchemy" ]
Python distutils and replacing strings in code
267,977
<p>I often find a need to put paths in my code in order to find data or in some cases tool-specific modules. I've so far always used autotools because of this--it's just so easy to call sed to replace a few strings at build time. However, I'd like to find a more Pythonic way of doing this, i.e. use distutils or some other blessed way of building/installing. I've never managed to find anything relating to this in distutils documentation though so how do other people solve this problem?</p>
2
2008-11-06T08:50:09Z
267,992
<p>For modules paths, a common practice is putting them in <em>.pth</em> files, as <a href="http://docs.python.org/library/site.html#module-site" rel="nofollow">documented here</a>. The <em>site</em> module provides a space for Site-specific configuration hooks, you can use it to tailor your environment.</p>
1
2008-11-06T08:58:39Z
[ "python" ]
Python distutils and replacing strings in code
267,977
<p>I often find a need to put paths in my code in order to find data or in some cases tool-specific modules. I've so far always used autotools because of this--it's just so easy to call sed to replace a few strings at build time. However, I'd like to find a more Pythonic way of doing this, i.e. use distutils or some other blessed way of building/installing. I've never managed to find anything relating to this in distutils documentation though so how do other people solve this problem?</p>
2
2008-11-06T08:50:09Z
268,189
<p>Well, with distutils (in the standard library) you have "package data". This is data that lives inside the package itself. <a href="http://docs.python.org/distutils/setupscript.html#installing-package-data" rel="nofollow">Explained here how to do it.</a> This is clearly not ideal, as you will have to use some kind of <code>__file__</code> hacks to look up the location of the data at runtime.</p> <p>So then comes setuptools (not in the standard library), which additionally has ways of looking up the location of that data at runtime. <a href="http://peak.telecommunity.com/DevCenter/setuptools#including-data-files" rel="nofollow">Explained here how to do it</a>. But again that has it's own set of problems, for example, it may have trouble finding the data files on an uninstalled raw package.</p> <p>There are also additional third party tools. The one I have used is <a href="http://www.async.com.br/projects/kiwi/api/kiwi.environ.html" rel="nofollow">kiwi.environ</a>. It offers data directories, and runtime lookup, but I wouldn't recommend it for general use, as it is geared towards PyGTK development and Glade file location.</p> <p>I would imagine there are other third party tools around, and others will elaborate.</p>
1
2008-11-06T10:11:50Z
[ "python" ]
Python distutils and replacing strings in code
267,977
<p>I often find a need to put paths in my code in order to find data or in some cases tool-specific modules. I've so far always used autotools because of this--it's just so easy to call sed to replace a few strings at build time. However, I'd like to find a more Pythonic way of doing this, i.e. use distutils or some other blessed way of building/installing. I've never managed to find anything relating to this in distutils documentation though so how do other people solve this problem?</p>
2
2008-11-06T08:50:09Z
268,348
<p>"I often find a need to put paths in my code" -- this isn't very Pythonic to begin with.</p> <p>Ideally, your code lives in some place like site-packages and that's the end of that.</p> <p>Often, we have an installed "application" that uses a fairly fixed set of directories for working files. In linux, we get this information from environment variables and configuration files owned by the specific userid that's running the application.</p> <p>I don't think that you should be putting paths in your code. I think there's a better way.</p> <p>[I just wrote our app installation tool, which does create all the config files for a fairly complex app. I used the Mako templates tool to generate all four files from templates.]</p>
-1
2008-11-06T11:28:13Z
[ "python" ]
Python distutils and replacing strings in code
267,977
<p>I often find a need to put paths in my code in order to find data or in some cases tool-specific modules. I've so far always used autotools because of this--it's just so easy to call sed to replace a few strings at build time. However, I'd like to find a more Pythonic way of doing this, i.e. use distutils or some other blessed way of building/installing. I've never managed to find anything relating to this in distutils documentation though so how do other people solve this problem?</p>
2
2008-11-06T08:50:09Z
348,082
<p>The OP here, I've not finally managed to log in using my OpenID.</p> <p>@S.Lott</p> <p>Point well taken, but for some Linux distros it seems to be standard to install application-specific data and application-specific modules in specific locations. I think that making these locations configurable at build/install time is a nice thing to do for people packaging my application. AFAICS “the pythonic way” in this case would force these packagers to apply patches to my code.</p> <p>I'm also in the habit of writing applications where the executable part is a tiny wrapper around a main function in an application-specific module. To me it doesn't seem right to stick this application-specific module in <code>/usr/lib/python2.5/site-packages</code>.</p>
0
2008-12-07T21:09:31Z
[ "python" ]
Python distutils and replacing strings in code
267,977
<p>I often find a need to put paths in my code in order to find data or in some cases tool-specific modules. I've so far always used autotools because of this--it's just so easy to call sed to replace a few strings at build time. However, I'd like to find a more Pythonic way of doing this, i.e. use distutils or some other blessed way of building/installing. I've never managed to find anything relating to this in distutils documentation though so how do other people solve this problem?</p>
2
2008-11-06T08:50:09Z
349,509
<p>Currently, the best way to bundle data with code is going the <a href="http://peak.telecommunity.com/DevCenter/setuptools" rel="nofollow">setuptools</a> way and use <code>pkg_resources</code>:</p> <pre><code>from pkg_resources import resource_filename, resource_stream stream = resource_stream("PACKAGE", "path/to/data_f.ile") </code></pre> <p>This has the advantage of also working with Python eggs. It has the (IMHO) disadvantage that you need to put your data files into your code directory, which is accepted practice (one of the very, very few practices I disagree with). </p> <p>As for Linux distros, I can (reasonably) assure you that your program will run without any problems (and patches) on any modern Debian-derived system if you use <code>pkg_resources</code>. I don't know about Fedora/openSUSE, but I would assume that it works as well.</p> <p>It works on Windows, but it does currently not work with py2exe - there are simple workarounds for that, however.</p>
1
2008-12-08T13:11:51Z
[ "python" ]
apache user can not write to .python-eggs
268,015
<p>I have read that I need to set the <code>PYTHON_EGG_CACHE</code> environment variable, or install the python library as an uncompressed .egg</p> <p>Which do you suggest?</p>
3
2008-11-06T09:11:07Z
268,087
<p>It totally depends on if you want to make the egg available as a generally available library or just for a single (or a handful of applications). Are you talking about a Trac installation? If so, there are also a handful of alternatives to make the egg available per instance:</p> <p><a href="http://trac.edgewall.org/wiki/TracPlugins" rel="nofollow">http://trac.edgewall.org/wiki/TracPlugins</a></p>
1
2008-11-06T09:38:47Z
[ "python", "apache", "egg", "python-egg-cache" ]
apache user can not write to .python-eggs
268,015
<p>I have read that I need to set the <code>PYTHON_EGG_CACHE</code> environment variable, or install the python library as an uncompressed .egg</p> <p>Which do you suggest?</p>
3
2008-11-06T09:11:07Z
268,106
<p>I got it working by uncompressing the .egg so it did not require the cache directory:</p> <p><a href="http://stackoverflow.com/questions/268025/install-mysqldb-for-python-as-non-compressed-egg">http://stackoverflow.com/questions/268025/install-mysqldb-for-python-as-non-compressed-egg</a></p>
2
2008-11-06T09:46:05Z
[ "python", "apache", "egg", "python-egg-cache" ]
apache user can not write to .python-eggs
268,015
<p>I have read that I need to set the <code>PYTHON_EGG_CACHE</code> environment variable, or install the python library as an uncompressed .egg</p> <p>Which do you suggest?</p>
3
2008-11-06T09:11:07Z
268,110
<p>If you are talking about Trac then the issue you are having is <a href="http://stackoverflow.com/questions/215267/how-do-you-fix-a-trac-installation-that-begins-giving-errors-relating-to-python">this one</a>. It should be solved in trac 0.11.1.</p>
0
2008-11-06T09:47:32Z
[ "python", "apache", "egg", "python-egg-cache" ]
Install MySQLdb (for python) as non-compressed egg
268,025
<p>The install instructions are:</p> <pre><code>$ python setup.py build $ sudo python setup.py install # or su first </code></pre> <p>This gives me an .egg file. How do I tell the install to dump the files as a normal, uncompressed library?</p> <p>Thanks!</p>
4
2008-11-06T09:15:21Z
268,054
<p>From the <a href="http://peak.telecommunity.com/DevCenter/EasyInstall#command-line-options" rel="nofollow">EasyInstall</a> doc, command line options:</p> <blockquote> <p>--always-unzip, -Z</p> <p>Don't install any packages as zip files, even if the packages are marked as safe for running as a zipfile. </p> </blockquote> <p>Can you use <em>easyinstall</em> instead of calling setup.py ? </p> <p>calling <code>easy_install -Z mysql_python</code> from the command prompt, finds the egg on the net and installs it.</p>
3
2008-11-06T09:26:17Z
[ "python", "install", "mysql", "egg" ]
Install MySQLdb (for python) as non-compressed egg
268,025
<p>The install instructions are:</p> <pre><code>$ python setup.py build $ sudo python setup.py install # or su first </code></pre> <p>This gives me an .egg file. How do I tell the install to dump the files as a normal, uncompressed library?</p> <p>Thanks!</p>
4
2008-11-06T09:15:21Z
268,101
<p>OK, I hate to answer my own question, but:</p> <p>find your python site-packages (mine is /usr/local/lib/python2.5/site-packages )</p> <p>then:</p> <pre><code>$ unzip MySQL_python-1.2.2-py2.5-linux-i686.egg </code></pre> <p>This worked fine for me</p>
7
2008-11-06T09:44:54Z
[ "python", "install", "mysql", "egg" ]
Install MySQLdb (for python) as non-compressed egg
268,025
<p>The install instructions are:</p> <pre><code>$ python setup.py build $ sudo python setup.py install # or su first </code></pre> <p>This gives me an .egg file. How do I tell the install to dump the files as a normal, uncompressed library?</p> <p>Thanks!</p>
4
2008-11-06T09:15:21Z
268,111
<p>This will tell setuptools to not zip it up:</p> <pre><code>sudo python setup.py install --single-version-externally-managed </code></pre>
1
2008-11-06T09:47:56Z
[ "python", "install", "mysql", "egg" ]
Install MySQLdb (for python) as non-compressed egg
268,025
<p>The install instructions are:</p> <pre><code>$ python setup.py build $ sudo python setup.py install # or su first </code></pre> <p>This gives me an .egg file. How do I tell the install to dump the files as a normal, uncompressed library?</p> <p>Thanks!</p>
4
2008-11-06T09:15:21Z
1,460,602
<p>I'm a little late to this party, but here's a way to do it that seems to work great:</p> <pre><code>sudo python setup.py install --single-version-externally-managed --root=/ </code></pre> <p>And then you don't use a .python-egg, any *.pth files etc.</p>
4
2009-09-22T14:57:28Z
[ "python", "install", "mysql", "egg" ]
Multiple database support in django
268,089
<p>From some forum I came to know that Multiple database support is added in Django at lower level, but the higher level apis are not added yet.</p> <p>Can anyone please tell me how one can achieve multiple database connections in Django.</p> <p>Does anyone have any idea by when Django will fully/officially support Multiple database connections.</p>
9
2008-11-06T09:39:20Z
268,369
<p>The most recent discussion I've seen on it was in the <a href="http://groups.google.com/group/django-developers/browse_thread/thread/9f0353fe0682b73" rel="nofollow">Proposal: user-friendly API for multi-database support</a> django-developers thread, which also has an example of one way to use multiple databases using Managers in the original message.</p>
4
2008-11-06T11:35:55Z
[ "python", "django", "database-connection" ]
Multiple database support in django
268,089
<p>From some forum I came to know that Multiple database support is added in Django at lower level, but the higher level apis are not added yet.</p> <p>Can anyone please tell me how one can achieve multiple database connections in Django.</p> <p>Does anyone have any idea by when Django will fully/officially support Multiple database connections.</p>
9
2008-11-06T09:39:20Z
271,220
<p>I think you will have to resort to "raw sql" .. kinda thing .. <br> look here: <a href="http://docs.djangoproject.com/en/dev/topics/db/sql/" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/db/sql/</a></p> <p>you need a "connection" to your other database, if you look at <code>django/db/__init__.py</code> around line 39 (in my version ..)</p> <p><code> connection = backend.DatabaseWrapper(**settings.DATABASE_OPTIONS) </code></p> <p>try to take it from there ..<br> P.S. I haven't really tried this or anything .. just trying to point in the general direction of what I think might solve your problem.</p>
0
2008-11-07T04:08:19Z
[ "python", "django", "database-connection" ]
Multiple database support in django
268,089
<p>From some forum I came to know that Multiple database support is added in Django at lower level, but the higher level apis are not added yet.</p> <p>Can anyone please tell me how one can achieve multiple database connections in Django.</p> <p>Does anyone have any idea by when Django will fully/officially support Multiple database connections.</p>
9
2008-11-06T09:39:20Z
272,522
<p>If you read a few of the many (<em>many</em>) threads on this subject in django-dev, you will see that what <em>looks</em> straightforward, isn't. If you pick a single use case, then it looks easy, but as soon as you start to generalize in any way you start to run into trouble.</p> <p>To use the above-referenced thread as an example, when you say "multiple databases", which of the following are you talking about?</p> <ul> <li>All DB on the same machine under the same engine.</li> <li>All DB on same machine, different engines (E.g. MySQL + PostgreSQL)</li> <li>One Master DB with N read-only slaves on different machines.</li> <li>Sharding of tables across multiple DB servers.</li> </ul> <p>Will you need:</p> <ul> <li>Foreign keys across DBs</li> <li>JOINs across machines and/or engines</li> <li>etc. etc.</li> </ul> <p>One of the problems with a slick ORM like Django's is that it hides all of those messy details under a nice paint job. To continue to do that, but to then add in any of the above, is Not Easy (tm).</p>
3
2008-11-07T15:54:37Z
[ "python", "django", "database-connection" ]
Multiple database support in django
268,089
<p>From some forum I came to know that Multiple database support is added in Django at lower level, but the higher level apis are not added yet.</p> <p>Can anyone please tell me how one can achieve multiple database connections in Django.</p> <p>Does anyone have any idea by when Django will fully/officially support Multiple database connections.</p>
9
2008-11-06T09:39:20Z
997,136
<p>Eric Florenzano wrote a very good blog post that allows you some multiple database support at: <a href="http://www.eflorenzano.com/blog/post/easy-multi-database-support-django/" rel="nofollow">Easy MultipleDatabase Support for Django</a>.</p> <p>It starts by creating a new custom manager that allows you to specify the database settings.</p>
2
2009-06-15T16:46:56Z
[ "python", "django", "database-connection" ]
Multiple database support in django
268,089
<p>From some forum I came to know that Multiple database support is added in Django at lower level, but the higher level apis are not added yet.</p> <p>Can anyone please tell me how one can achieve multiple database connections in Django.</p> <p>Does anyone have any idea by when Django will fully/officially support Multiple database connections.</p>
9
2008-11-06T09:39:20Z
1,287,729
<p>Eric Florenzano's approach works well if all your databases use the same engine. If you have different engines (Postgres and MSSQL in my case) you will run into many issues deep in the ORM code (such as models/sql/where.py using the default connection's SQL syntax).</p> <p>If you need this to work, you should wait for Alex Gaynor's MultiDB project which is planned for <a href="http://code.djangoproject.com/wiki/Version1.2Features" rel="nofollow">Django 1.2</a></p>
0
2009-08-17T12:37:13Z
[ "python", "django", "database-connection" ]
Multiple database support in django
268,089
<p>From some forum I came to know that Multiple database support is added in Django at lower level, but the higher level apis are not added yet.</p> <p>Can anyone please tell me how one can achieve multiple database connections in Django.</p> <p>Does anyone have any idea by when Django will fully/officially support Multiple database connections.</p>
9
2008-11-06T09:39:20Z
1,836,058
<p>If you simply need multiple connections, you can do something like this:</p> <pre><code>from django.db import load_backend myBackend = load_backend('postgresql_psycopg2') # or 'mysql', 'sqlite3', 'oracle' myConnection = myBackend.DatabaseWrapper({ 'DATABASE_HOST': '192.168.1.1', 'DATABASE_NAME': 'my_database', 'DATABASE_OPTIONS': {}, 'DATABASE_PASSWORD': "", 'DATABASE_PORT': "", 'DATABASE_USER': "my_user", 'TIME_ZONE': "America/New_York",}) # Now we can do all the standard raw sql stuff with myConnection. myCursor = myConnection.cursor() myCursor.execute("SELECT COUNT(1) FROM my_table;") myCursor.fetchone() </code></pre>
9
2009-12-02T21:49:37Z
[ "python", "django", "database-connection" ]
Multiple database support in django
268,089
<p>From some forum I came to know that Multiple database support is added in Django at lower level, but the higher level apis are not added yet.</p> <p>Can anyone please tell me how one can achieve multiple database connections in Django.</p> <p>Does anyone have any idea by when Django will fully/officially support Multiple database connections.</p>
9
2008-11-06T09:39:20Z
2,277,593
<p>This will be in Django 1.2.</p> <p>See <a href="http://docs.djangoproject.com/en/dev/topics/db/multi-db/">http://docs.djangoproject.com/en/dev/topics/db/multi-db/</a></p>
6
2010-02-17T00:52:00Z
[ "python", "django", "database-connection" ]
Multiple database support in django
268,089
<p>From some forum I came to know that Multiple database support is added in Django at lower level, but the higher level apis are not added yet.</p> <p>Can anyone please tell me how one can achieve multiple database connections in Django.</p> <p>Does anyone have any idea by when Django will fully/officially support Multiple database connections.</p>
9
2008-11-06T09:39:20Z
2,583,949
<p>From Django 1.2, it will support multiple databases. See: <a href="http://docs.djangoproject.com/en/dev/topics/db/multi-db/" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/db/multi-db/</a> Version 1.2 is now in beta</p>
0
2010-04-06T10:00:48Z
[ "python", "django", "database-connection" ]
Multiple database support in django
268,089
<p>From some forum I came to know that Multiple database support is added in Django at lower level, but the higher level apis are not added yet.</p> <p>Can anyone please tell me how one can achieve multiple database connections in Django.</p> <p>Does anyone have any idea by when Django will fully/officially support Multiple database connections.</p>
9
2008-11-06T09:39:20Z
8,539,232
<p>There is a "using" directive for queries,saves, and deletes</p> <p><a href="https://docs.djangoproject.com/en/dev/topics/db/multi-db/#manually-selecting-a-database" rel="nofollow">https://docs.djangoproject.com/en/dev/topics/db/multi-db/#manually-selecting-a-database</a></p>
1
2011-12-16T19:33:51Z
[ "python", "django", "database-connection" ]
Multiple database support in django
268,089
<p>From some forum I came to know that Multiple database support is added in Django at lower level, but the higher level apis are not added yet.</p> <p>Can anyone please tell me how one can achieve multiple database connections in Django.</p> <p>Does anyone have any idea by when Django will fully/officially support Multiple database connections.</p>
9
2008-11-06T09:39:20Z
14,604,432
<p>Multiple database to choose from </p> <p>We always need one named default, the names of the rest are up to you.</p> <pre><code>DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mupltiple_datab_app1', 'USER': 'root', 'PASSWORD': 'admin', 'HOST': "", 'PORT': "", }, 'user1':{ 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mupltiple_datab_app2', 'USER': 'root', 'PASSWORD': 'admin', 'HOST': "", 'PORT': "", }, 'user2':{ 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mupltiple_datab_app3', 'USER': 'root', 'PASSWORD': 'admin', 'HOST':"" , 'PORT': "" , } } </code></pre> <p>for sync to one particular database</p> <pre><code>manage.py syncdb --database=user1 </code></pre>
1
2013-01-30T12:49:34Z
[ "python", "django", "database-connection" ]
Getting key with maximum value in dictionary?
268,272
<p>I have a <code>dictionary</code>: keys are strings, values are integers.</p> <p>Example: </p> <pre><code>stats = {'a':1000, 'b':3000, 'c': 100} </code></pre> <p>I'd like to get <code>'b'</code> as an answer, since it's the key with a higher value.</p> <p>I did the following, using an intermediate list with reversed key-value tuples:</p> <pre><code>inverse = [(value, key) for key, value in stats.items()] print max(inverse)[1] </code></pre> <p>Is that one the better (or even more elegant) approach?</p>
302
2008-11-06T10:49:58Z
268,285
<p>You can use <code>operator.itemgetter</code> for that:</p> <pre><code>import operator stats = {'a':1000, 'b':3000, 'c': 100} max(stats.iteritems(), key=operator.itemgetter(1))[0] </code></pre> <p>And instead of building a new list in memory use <code>stats.iteritems()</code>. The <code>key</code> parameter to the <code>max()</code> function is a function that computes a key that is used to determine how to rank items.</p> <p>Please note that if you were to have another key-value pair 'd': 3000 that this method will only return <strong>one</strong> of the <strong>two</strong> even though they both have the maximum value. </p> <pre><code>&gt;&gt;&gt; import operator &gt;&gt;&gt; stats = {'a':1000, 'b':3000, 'c': 100, 'd':3000} &gt;&gt;&gt; max(stats.iteritems(), key=operator.itemgetter(1))[0] 'b' </code></pre>
253
2008-11-06T10:58:45Z
[ "python", "dictionary", "max" ]
Getting key with maximum value in dictionary?
268,272
<p>I have a <code>dictionary</code>: keys are strings, values are integers.</p> <p>Example: </p> <pre><code>stats = {'a':1000, 'b':3000, 'c': 100} </code></pre> <p>I'd like to get <code>'b'</code> as an answer, since it's the key with a higher value.</p> <p>I did the following, using an intermediate list with reversed key-value tuples:</p> <pre><code>inverse = [(value, key) for key, value in stats.items()] print max(inverse)[1] </code></pre> <p>Is that one the better (or even more elegant) approach?</p>
302
2008-11-06T10:49:58Z
268,303
<p>Thanks, very elegant, I didn't remember that max allows a "key" parameter.</p> <p>BTW, to get the right answer ('b') it has to be:</p> <pre><code>import operator stats = {'a':1000, 'b':3000, 'c': 100} max(stats.iteritems(), key=operator.itemgetter(1))[0] </code></pre>
3
2008-11-06T11:04:28Z
[ "python", "dictionary", "max" ]
Getting key with maximum value in dictionary?
268,272
<p>I have a <code>dictionary</code>: keys are strings, values are integers.</p> <p>Example: </p> <pre><code>stats = {'a':1000, 'b':3000, 'c': 100} </code></pre> <p>I'd like to get <code>'b'</code> as an answer, since it's the key with a higher value.</p> <p>I did the following, using an intermediate list with reversed key-value tuples:</p> <pre><code>inverse = [(value, key) for key, value in stats.items()] print max(inverse)[1] </code></pre> <p>Is that one the better (or even more elegant) approach?</p>
302
2008-11-06T10:49:58Z
268,350
<p>Here is another one:</p> <pre><code>stats = {'a':1000, 'b':3000, 'c': 100} max(stats.iterkeys(), key=lambda k: stats[k]) </code></pre> <p>The function <code>key</code> simply returns the value that should be used for ranking and <code>max()</code> returns the demanded element right away.</p>
24
2008-11-06T11:28:56Z
[ "python", "dictionary", "max" ]
Getting key with maximum value in dictionary?
268,272
<p>I have a <code>dictionary</code>: keys are strings, values are integers.</p> <p>Example: </p> <pre><code>stats = {'a':1000, 'b':3000, 'c': 100} </code></pre> <p>I'd like to get <code>'b'</code> as an answer, since it's the key with a higher value.</p> <p>I did the following, using an intermediate list with reversed key-value tuples:</p> <pre><code>inverse = [(value, key) for key, value in stats.items()] print max(inverse)[1] </code></pre> <p>Is that one the better (or even more elegant) approach?</p>
302
2008-11-06T10:49:58Z
272,269
<pre><code>key, value = max(stats.iteritems(), key=lambda x:x[1]) </code></pre> <p>If you don't care about value (I'd be surprised, but) you can do:</p> <pre><code>key, _ = max(stats.iteritems(), key=lambda x:x[1]) </code></pre> <p>I like the tuple unpacking better than a [0] subscript at the end of the expression. I never like the readability of lambda expressions very much, but find this one better than the operator.itemgetter(1) IMHO.</p>
18
2008-11-07T14:41:33Z
[ "python", "dictionary", "max" ]
Getting key with maximum value in dictionary?
268,272
<p>I have a <code>dictionary</code>: keys are strings, values are integers.</p> <p>Example: </p> <pre><code>stats = {'a':1000, 'b':3000, 'c': 100} </code></pre> <p>I'd like to get <code>'b'</code> as an answer, since it's the key with a higher value.</p> <p>I did the following, using an intermediate list with reversed key-value tuples:</p> <pre><code>inverse = [(value, key) for key, value in stats.items()] print max(inverse)[1] </code></pre> <p>Is that one the better (or even more elegant) approach?</p>
302
2008-11-06T10:49:58Z
280,156
<pre><code>max(stats, key=stats.get) </code></pre>
299
2008-11-11T06:24:30Z
[ "python", "dictionary", "max" ]
Getting key with maximum value in dictionary?
268,272
<p>I have a <code>dictionary</code>: keys are strings, values are integers.</p> <p>Example: </p> <pre><code>stats = {'a':1000, 'b':3000, 'c': 100} </code></pre> <p>I'd like to get <code>'b'</code> as an answer, since it's the key with a higher value.</p> <p>I did the following, using an intermediate list with reversed key-value tuples:</p> <pre><code>inverse = [(value, key) for key, value in stats.items()] print max(inverse)[1] </code></pre> <p>Is that one the better (or even more elegant) approach?</p>
302
2008-11-06T10:49:58Z
12,343,826
<p>I have tested MANY variants, and this is the fastest way to return the key of dict with the max value:</p> <pre><code>def keywithmaxval(d): """ a) create a list of the dict's keys and values; b) return the key with the max value""" v=list(d.values()) k=list(d.keys()) return k[v.index(max(v))] </code></pre> <p>To give you an idea, here are some candidate methods:</p> <pre><code>def f1(): v=list(d1.values()) k=list(d1.keys()) return k[v.index(max(v))] def f2(): d3={v:k for k,v in d1.items()} return d3[max(d3)] def f3(): return list(filter(lambda t: t[1]==max(d1.values()), d1.items()))[0][0] def f3b(): # same as f3 but remove the call to max from the lambda m=max(d1.values()) return list(filter(lambda t: t[1]==m, d1.items()))[0][0] def f4(): return [k for k,v in d1.items() if v==max(d1.values())][0] def f4b(): # same as f4 but remove the max from the comprehension m=max(d1.values()) return [k for k,v in d1.items() if v==m][0] def f5(): return max(d1.items(), key=operator.itemgetter(1))[0] def f6(): return max(d1,key=d1.get) def f7(): """ a) create a list of the dict's keys and values; b) return the key with the max value""" v=list(d1.values()) return list(d1.keys())[v.index(max(v))] def f8(): return max(d1, key=lambda k: d1[k]) tl=[f1,f2, f3b, f4b, f5, f6, f7, f8, f4,f3] cmpthese.cmpthese(tl,c=100) </code></pre> <p>The test dictionary:</p> <pre><code>d1={1: 1, 2: 2, 3: 8, 4: 3, 5: 6, 6: 9, 7: 17, 8: 4, 9: 20, 10: 7, 11: 15, 12: 10, 13: 10, 14: 18, 15: 18, 16: 5, 17: 13, 18: 21, 19: 21, 20: 8, 21: 8, 22: 16, 23: 16, 24: 11, 25: 24, 26: 11, 27: 112, 28: 19, 29: 19, 30: 19, 3077: 36, 32: 6, 33: 27, 34: 14, 35: 14, 36: 22, 4102: 39, 38: 22, 39: 35, 40: 9, 41: 110, 42: 9, 43: 30, 44: 17, 45: 17, 46: 17, 47: 105, 48: 12, 49: 25, 50: 25, 51: 25, 52: 12, 53: 12, 54: 113, 1079: 50, 56: 20, 57: 33, 58: 20, 59: 33, 60: 20, 61: 20, 62: 108, 63: 108, 64: 7, 65: 28, 66: 28, 67: 28, 68: 15, 69: 15, 70: 15, 71: 103, 72: 23, 73: 116, 74: 23, 75: 15, 76: 23, 77: 23, 78: 36, 79: 36, 80: 10, 81: 23, 82: 111, 83: 111, 84: 10, 85: 10, 86: 31, 87: 31, 88: 18, 89: 31, 90: 18, 91: 93, 92: 18, 93: 18, 94: 106, 95: 106, 96: 13, 9232: 35, 98: 26, 99: 26, 100: 26, 101: 26, 103: 88, 104: 13, 106: 13, 107: 101, 1132: 63, 2158: 51, 112: 21, 113: 13, 116: 21, 118: 34, 119: 34, 7288: 45, 121: 96, 122: 21, 124: 109, 125: 109, 128: 8, 1154: 32, 131: 29, 134: 29, 136: 16, 137: 91, 140: 16, 142: 104, 143: 104, 146: 117, 148: 24, 149: 24, 152: 24, 154: 24, 155: 86, 160: 11, 161: 99, 1186: 76, 3238: 49, 167: 68, 170: 11, 172: 32, 175: 81, 178: 32, 179: 32, 182: 94, 184: 19, 31: 107, 188: 107, 190: 107, 196: 27, 197: 27, 202: 27, 206: 89, 208: 14, 214: 102, 215: 102, 220: 115, 37: 22, 224: 22, 226: 14, 232: 22, 233: 84, 238: 35, 242: 97, 244: 22, 250: 110, 251: 66, 1276: 58, 256: 9, 2308: 33, 262: 30, 263: 79, 268: 30, 269: 30, 274: 92, 1300: 27, 280: 17, 283: 61, 286: 105, 292: 118, 296: 25, 298: 25, 304: 25, 310: 87, 1336: 71, 319: 56, 322: 100, 323: 100, 325: 25, 55: 113, 334: 69, 340: 12, 1367: 40, 350: 82, 358: 33, 364: 95, 376: 108, 377: 64, 2429: 46, 394: 28, 395: 77, 404: 28, 412: 90, 1438: 53, 425: 59, 430: 103, 1456: 97, 433: 28, 445: 72, 448: 23, 466: 85, 479: 54, 484: 98, 485: 98, 488: 23, 6154: 37, 502: 67, 4616: 34, 526: 80, 538: 31, 566: 62, 3644: 44, 577: 31, 97: 119, 592: 26, 593: 75, 1619: 48, 638: 57, 646: 101, 650: 26, 110: 114, 668: 70, 2734: 41, 700: 83, 1732: 30, 719: 52, 728: 96, 754: 65, 1780: 74, 4858: 47, 130: 29, 790: 78, 1822: 43, 2051: 38, 808: 29, 850: 60, 866: 29, 890: 73, 911: 42, 958: 55, 970: 99, 976: 24, 166: 112} </code></pre> <p>And the test results under Python 3.2:</p> <pre><code> rate/sec f4 f3 f3b f8 f5 f2 f4b f6 f7 f1 f4 454 -- -2.5% -96.9% -97.5% -98.6% -98.6% -98.7% -98.7% -98.9% -99.0% f3 466 2.6% -- -96.8% -97.4% -98.6% -98.6% -98.6% -98.7% -98.9% -99.0% f3b 14,715 3138.9% 3057.4% -- -18.6% -55.5% -56.0% -56.4% -58.3% -63.8% -68.4% f8 18,070 3877.3% 3777.3% 22.8% -- -45.4% -45.9% -46.5% -48.8% -55.5% -61.2% f5 33,091 7183.7% 7000.5% 124.9% 83.1% -- -1.0% -2.0% -6.3% -18.6% -29.0% f2 33,423 7256.8% 7071.8% 127.1% 85.0% 1.0% -- -1.0% -5.3% -17.7% -28.3% f4b 33,762 7331.4% 7144.6% 129.4% 86.8% 2.0% 1.0% -- -4.4% -16.9% -27.5% f6 35,300 7669.8% 7474.4% 139.9% 95.4% 6.7% 5.6% 4.6% -- -13.1% -24.2% f7 40,631 8843.2% 8618.3% 176.1% 124.9% 22.8% 21.6% 20.3% 15.1% -- -12.8% f1 46,598 10156.7% 9898.8% 216.7% 157.9% 40.8% 39.4% 38.0% 32.0% 14.7% -- </code></pre> <p>And under Python 2.7:</p> <pre><code> rate/sec f3 f4 f8 f3b f6 f5 f2 f4b f7 f1 f3 384 -- -2.6% -97.1% -97.2% -97.9% -97.9% -98.0% -98.2% -98.5% -99.2% f4 394 2.6% -- -97.0% -97.2% -97.8% -97.9% -98.0% -98.1% -98.5% -99.1% f8 13,079 3303.3% 3216.1% -- -5.6% -28.6% -29.9% -32.8% -38.3% -49.7% -71.2% f3b 13,852 3504.5% 3412.1% 5.9% -- -24.4% -25.8% -28.9% -34.6% -46.7% -69.5% f6 18,325 4668.4% 4546.2% 40.1% 32.3% -- -1.8% -5.9% -13.5% -29.5% -59.6% f5 18,664 4756.5% 4632.0% 42.7% 34.7% 1.8% -- -4.1% -11.9% -28.2% -58.8% f2 19,470 4966.4% 4836.5% 48.9% 40.6% 6.2% 4.3% -- -8.1% -25.1% -57.1% f4b 21,187 5413.0% 5271.7% 62.0% 52.9% 15.6% 13.5% 8.8% -- -18.5% -53.3% f7 26,002 6665.8% 6492.4% 98.8% 87.7% 41.9% 39.3% 33.5% 22.7% -- -42.7% f1 45,354 11701.5% 11399.0% 246.8% 227.4% 147.5% 143.0% 132.9% 114.1% 74.4% -- </code></pre> <p>You can see that <code>f1</code> is the fastest under Python 3.2 and 2.7 (or, more completely, <code>keywithmaxval</code> at the top of this post)</p>
104
2012-09-09T23:30:37Z
[ "python", "dictionary", "max" ]
Getting key with maximum value in dictionary?
268,272
<p>I have a <code>dictionary</code>: keys are strings, values are integers.</p> <p>Example: </p> <pre><code>stats = {'a':1000, 'b':3000, 'c': 100} </code></pre> <p>I'd like to get <code>'b'</code> as an answer, since it's the key with a higher value.</p> <p>I did the following, using an intermediate list with reversed key-value tuples:</p> <pre><code>inverse = [(value, key) for key, value in stats.items()] print max(inverse)[1] </code></pre> <p>Is that one the better (or even more elegant) approach?</p>
302
2008-11-06T10:49:58Z
17,217,820
<pre><code>Counter = 0 for word in stats.keys(): if stats[word]&gt; counter: Counter = stats [word] print Counter </code></pre>
0
2013-06-20T15:32:51Z
[ "python", "dictionary", "max" ]
Getting key with maximum value in dictionary?
268,272
<p>I have a <code>dictionary</code>: keys are strings, values are integers.</p> <p>Example: </p> <pre><code>stats = {'a':1000, 'b':3000, 'c': 100} </code></pre> <p>I'd like to get <code>'b'</code> as an answer, since it's the key with a higher value.</p> <p>I did the following, using an intermediate list with reversed key-value tuples:</p> <pre><code>inverse = [(value, key) for key, value in stats.items()] print max(inverse)[1] </code></pre> <p>Is that one the better (or even more elegant) approach?</p>
302
2008-11-06T10:49:58Z
23,428,922
<p>Given that more than one entry my have the max value. I would make a list of the keys that have the max value as their value.</p> <pre><code>&gt;&gt;&gt; stats = {'a':1000, 'b':3000, 'c': 100, 'd':3000} &gt;&gt;&gt; [key for key,val in stats.iteritems() if val == max(stats.values())] ['b', 'd'] </code></pre> <p>This will give you 'b' and any other max key as well.</p>
10
2014-05-02T13:07:23Z
[ "python", "dictionary", "max" ]
Getting key with maximum value in dictionary?
268,272
<p>I have a <code>dictionary</code>: keys are strings, values are integers.</p> <p>Example: </p> <pre><code>stats = {'a':1000, 'b':3000, 'c': 100} </code></pre> <p>I'd like to get <code>'b'</code> as an answer, since it's the key with a higher value.</p> <p>I did the following, using an intermediate list with reversed key-value tuples:</p> <pre><code>inverse = [(value, key) for key, value in stats.items()] print max(inverse)[1] </code></pre> <p>Is that one the better (or even more elegant) approach?</p>
302
2008-11-06T10:49:58Z
30,043,094
<p>Per the iterated solutions via comments in the selected answer... </p> <p>In Python 3:</p> <pre><code>max(stats.keys(), key=(lambda k: stats[k])) </code></pre> <p>In Python 2:</p> <pre><code>max(stats.iterkeys(), key=(lambda k: stats[k])) </code></pre>
5
2015-05-05T02:03:11Z
[ "python", "dictionary", "max" ]
Getting key with maximum value in dictionary?
268,272
<p>I have a <code>dictionary</code>: keys are strings, values are integers.</p> <p>Example: </p> <pre><code>stats = {'a':1000, 'b':3000, 'c': 100} </code></pre> <p>I'd like to get <code>'b'</code> as an answer, since it's the key with a higher value.</p> <p>I did the following, using an intermediate list with reversed key-value tuples:</p> <pre><code>inverse = [(value, key) for key, value in stats.items()] print max(inverse)[1] </code></pre> <p>Is that one the better (or even more elegant) approach?</p>
302
2008-11-06T10:49:58Z
35,256,685
<p>If you need to know only a key with the max value you can do it without <code>iterkeys</code> or <code>iteritems</code> because iteration through a dictionary on Python is just an iteration through a dictionary keys.</p> <pre><code>ddd = {'a': 3, 'b': 1} max_key = max(ddd, key=lambda k: ddd[k]) </code></pre>
11
2016-02-07T17:31:32Z
[ "python", "dictionary", "max" ]
Getting key with maximum value in dictionary?
268,272
<p>I have a <code>dictionary</code>: keys are strings, values are integers.</p> <p>Example: </p> <pre><code>stats = {'a':1000, 'b':3000, 'c': 100} </code></pre> <p>I'd like to get <code>'b'</code> as an answer, since it's the key with a higher value.</p> <p>I did the following, using an intermediate list with reversed key-value tuples:</p> <pre><code>inverse = [(value, key) for key, value in stats.items()] print max(inverse)[1] </code></pre> <p>Is that one the better (or even more elegant) approach?</p>
302
2008-11-06T10:49:58Z
35,585,900
<p>With <code>collections.Counter</code> you could do</p> <pre><code>&gt;&gt;&gt; import collections &gt;&gt;&gt; stats = {'a':1000, 'b':3000, 'c': 100} &gt;&gt;&gt; stats = collections.Counter(stats) &gt;&gt;&gt; stats.most_common(1) [('b', 3000)] </code></pre> <p>If appropriate, you could simply start with an empty <code>collections.Counter</code> and add to it</p> <pre><code>&gt;&gt;&gt; stats = collections.Counter() &gt;&gt;&gt; stats['a'] += 1 : etc. </code></pre>
4
2016-02-23T18:58:38Z
[ "python", "dictionary", "max" ]
How to stop BaseHTTPServer.serve_forever() in a BaseHTTPRequestHandler subclass?
268,629
<p>I am running my <code>HTTPServer</code> in a separate thread (using the threading module which has no way to stop threads...) and want to stop serving requests when the main thread also shuts down.</p> <p>The Python documentation states that <code>BaseHTTPServer.HTTPServer</code> is a subclass of <code>SocketServer.TCPServer</code>, which supports a <code>shutdown</code> method, but it is missing in <code>HTTPServer</code>.</p> <p>The whole <code>BaseHTTPServer</code> module has very little documentation :(</p>
22
2008-11-06T13:10:54Z
268,660
<p>I should start by saying that "I probably wouldn't do this myself, but I have in the past". The serve_forever (from SocketServer.py) method looks like this:</p> <pre><code>def serve_forever(self): """Handle one request at a time until doomsday.""" while 1: self.handle_request() </code></pre> <p>You could replace (in subclass) <code>while 1</code> with <code>while self.should_be_running</code>, and modify that value from a different thread. Something like:</p> <pre><code>def stop_serving_forever(self): """Stop handling requests""" self.should_be_running = 0 # Make a fake request to the server, to really force it to stop. # Otherwise it will just stop on the next request. # (Exercise for the reader.) self.make_a_fake_request_to_myself() </code></pre> <p>Edit: I dug up the actual code I used at the time:</p> <pre><code>class StoppableRPCServer(SimpleXMLRPCServer.SimpleXMLRPCServer): stopped = False allow_reuse_address = True def __init__(self, *args, **kw): SimpleXMLRPCServer.SimpleXMLRPCServer.__init__(self, *args, **kw) self.register_function(lambda: 'OK', 'ping') def serve_forever(self): while not self.stopped: self.handle_request() def force_stop(self): self.server_close() self.stopped = True self.create_dummy_request() def create_dummy_request(self): server = xmlrpclib.Server('http://%s:%s' % self.server_address) server.ping() </code></pre>
15
2008-11-06T13:21:35Z
[ "python", "http", "basehttpserver" ]
How to stop BaseHTTPServer.serve_forever() in a BaseHTTPRequestHandler subclass?
268,629
<p>I am running my <code>HTTPServer</code> in a separate thread (using the threading module which has no way to stop threads...) and want to stop serving requests when the main thread also shuts down.</p> <p>The Python documentation states that <code>BaseHTTPServer.HTTPServer</code> is a subclass of <code>SocketServer.TCPServer</code>, which supports a <code>shutdown</code> method, but it is missing in <code>HTTPServer</code>.</p> <p>The whole <code>BaseHTTPServer</code> module has very little documentation :(</p>
22
2008-11-06T13:10:54Z
268,686
<p>In my python 2.6 installation, I can call it on the underlying TCPServer - it still there inside your <code>HTTPServer</code>:</p> <pre><code>TCPServer.shutdown &gt;&gt;&gt; import BaseHTTPServer &gt;&gt;&gt; h=BaseHTTPServer.HTTPServer(('',5555), BaseHTTPServer.BaseHTTPRequestHandler) &gt;&gt;&gt; h.shutdown &lt;bound method HTTPServer.shutdown of &lt;BaseHTTPServer.HTTPServer instance at 0x0100D800&gt;&gt; &gt;&gt;&gt; </code></pre>
15
2008-11-06T13:30:25Z
[ "python", "http", "basehttpserver" ]
How to stop BaseHTTPServer.serve_forever() in a BaseHTTPRequestHandler subclass?
268,629
<p>I am running my <code>HTTPServer</code> in a separate thread (using the threading module which has no way to stop threads...) and want to stop serving requests when the main thread also shuts down.</p> <p>The Python documentation states that <code>BaseHTTPServer.HTTPServer</code> is a subclass of <code>SocketServer.TCPServer</code>, which supports a <code>shutdown</code> method, but it is missing in <code>HTTPServer</code>.</p> <p>The whole <code>BaseHTTPServer</code> module has very little documentation :(</p>
22
2008-11-06T13:10:54Z
4,020,093
<p>I think you can use <code>[serverName].socket.close()</code></p>
8
2010-10-26T01:38:35Z
[ "python", "http", "basehttpserver" ]
How to stop BaseHTTPServer.serve_forever() in a BaseHTTPRequestHandler subclass?
268,629
<p>I am running my <code>HTTPServer</code> in a separate thread (using the threading module which has no way to stop threads...) and want to stop serving requests when the main thread also shuts down.</p> <p>The Python documentation states that <code>BaseHTTPServer.HTTPServer</code> is a subclass of <code>SocketServer.TCPServer</code>, which supports a <code>shutdown</code> method, but it is missing in <code>HTTPServer</code>.</p> <p>The whole <code>BaseHTTPServer</code> module has very little documentation :(</p>
22
2008-11-06T13:10:54Z
19,211,760
<p>Another way to do it, based on <a href="http://docs.python.org/2/library/basehttpserver.html#more-examples">http://docs.python.org/2/library/basehttpserver.html#more-examples</a>, is: instead of serve_forever(), keep serving as long as a condition is met, with the server checking the condition before and after each request. For example:</p> <pre><code>import CGIHTTPServer import BaseHTTPServer KEEP_RUNNING = True def keep_running(): return KEEP_RUNNING class Handler(CGIHTTPServer.CGIHTTPRequestHandler): cgi_directories = ["/cgi-bin"] httpd = BaseHTTPServer.HTTPServer(("", 8000), Handler) while keep_running(): httpd.handle_request() </code></pre>
5
2013-10-06T17:32:17Z
[ "python", "http", "basehttpserver" ]
How to stop BaseHTTPServer.serve_forever() in a BaseHTTPRequestHandler subclass?
268,629
<p>I am running my <code>HTTPServer</code> in a separate thread (using the threading module which has no way to stop threads...) and want to stop serving requests when the main thread also shuts down.</p> <p>The Python documentation states that <code>BaseHTTPServer.HTTPServer</code> is a subclass of <code>SocketServer.TCPServer</code>, which supports a <code>shutdown</code> method, but it is missing in <code>HTTPServer</code>.</p> <p>The whole <code>BaseHTTPServer</code> module has very little documentation :(</p>
22
2008-11-06T13:10:54Z
22,493,362
<p>In python 2.7, calling shutdown() works but only if you are serving via serve_forever, because it uses async select and a polling loop. Running your own loop with handle_request() ironically excludes this functionality because it implies a dumb blocking call.</p> <p>From SocketServer.py's BaseServer:</p> <pre><code>def serve_forever(self, poll_interval=0.5): """Handle one request at a time until shutdown. Polls for shutdown every poll_interval seconds. Ignores self.timeout. If you need to do periodic tasks, do them in another thread. """ self.__is_shut_down.clear() try: while not self.__shutdown_request: # XXX: Consider using another file descriptor or # connecting to the socket to wake this up instead of # polling. Polling reduces our responsiveness to a # shutdown request and wastes cpu at all other times. r, w, e = select.select([self], [], [], poll_interval) if self in r: self._handle_request_noblock() finally: self.__shutdown_request = False self.__is_shut_down.set() </code></pre> <p>Heres part of my code for doing a blocking shutdown from another thread, using an event to wait for completion:</p> <pre><code>class MockWebServerFixture(object): def start_webserver(self): """ start the web server on a new thread """ self._webserver_died = threading.Event() self._webserver_thread = threading.Thread( target=self._run_webserver_thread) self._webserver_thread.start() def _run_webserver_thread(self): self.webserver.serve_forever() self._webserver_died.set() def _kill_webserver(self): if not self._webserver_thread: return self.webserver.shutdown() # wait for thread to die for a bit, then give up raising an exception. if not self._webserver_died.wait(5): raise ValueError("couldn't kill webserver") </code></pre>
7
2014-03-18T23:38:21Z
[ "python", "http", "basehttpserver" ]
How to stop BaseHTTPServer.serve_forever() in a BaseHTTPRequestHandler subclass?
268,629
<p>I am running my <code>HTTPServer</code> in a separate thread (using the threading module which has no way to stop threads...) and want to stop serving requests when the main thread also shuts down.</p> <p>The Python documentation states that <code>BaseHTTPServer.HTTPServer</code> is a subclass of <code>SocketServer.TCPServer</code>, which supports a <code>shutdown</code> method, but it is missing in <code>HTTPServer</code>.</p> <p>The whole <code>BaseHTTPServer</code> module has very little documentation :(</p>
22
2008-11-06T13:10:54Z
35,358,134
<p>I tried all above possible solution and ended up with having a "sometime" issue - somehow it did not really do it - so I ended up making a dirty solution that worked all the time for me:</p> <p>If all above fails, then brute force kill your thread using something like this:</p> <pre><code>import subprocess cmdkill = "kill $(ps aux|grep '&lt;name of your thread&gt; true'|grep -v 'grep'|awk '{print $2}') 2&gt; /dev/null" subprocess.Popen(cmdkill, stdout=subprocess.PIPE, shell=True) </code></pre>
0
2016-02-12T08:41:21Z
[ "python", "http", "basehttpserver" ]
How to stop BaseHTTPServer.serve_forever() in a BaseHTTPRequestHandler subclass?
268,629
<p>I am running my <code>HTTPServer</code> in a separate thread (using the threading module which has no way to stop threads...) and want to stop serving requests when the main thread also shuts down.</p> <p>The Python documentation states that <code>BaseHTTPServer.HTTPServer</code> is a subclass of <code>SocketServer.TCPServer</code>, which supports a <code>shutdown</code> method, but it is missing in <code>HTTPServer</code>.</p> <p>The whole <code>BaseHTTPServer</code> module has very little documentation :(</p>
22
2008-11-06T13:10:54Z
35,576,127
<p>The event-loops ends on SIGTERM, <kbd>Ctrl</kbd>+<kbd>C</kbd> or when <code>shutdown()</code> is called.</p> <p><code>server_close()</code> must be called after <code>server_forever()</code> to close the listening socket.</p> <pre class="lang-py prettyprint-override"><code>import http.server class StoppableHTTPServer(http.server.HTTPServer): def run(self): try: self.serve_forever() except KeyboardInterrupt: pass finally: # Clean-up server (close socket, etc.) self.server_close() </code></pre> <p>Simple server stoppable with user action (SIGTERM, <kbd>Ctrl</kbd>+<kbd>C</kbd>, ...):</p> <pre class="lang-py prettyprint-override"><code>server = StoppableHTTPServer(("127.0.0.1", 8080), http.server.BaseHTTPRequestHandler) server.run() </code></pre> <p>Server running in a thread:</p> <pre class="lang-py prettyprint-override"><code>import threading server = StoppableHTTPServer(("127.0.0.1", 8080), http.server.BaseHTTPRequestHandler) # Start processing requests thread = threading.Thread(None, server.run) thread.start() # ... do things ... # Shutdown server server.shutdown() thread.join() </code></pre>
1
2016-02-23T11:18:35Z
[ "python", "http", "basehttpserver" ]
Replacing multiple occurrences in nested arrays
268,891
<p>I've got this python dictionary "mydict", containing arrays, here's what it looks like :</p> <pre><code>mydict = dict( one=['foo', 'bar', 'foobar', 'barfoo', 'example'], two=['bar', 'example', 'foobar'], three=['foo', 'example']) </code></pre> <p>i'd like to replace all the occurrences of "example" by "someotherword". </p> <p>While I can already think of a few ways to do it, is there a most "pythonic" method to achieve this ?</p>
3
2008-11-06T14:36:01Z
269,043
<pre><code>for arr in mydict.values(): for i, s in enumerate(arr): if s == 'example': arr[i] = 'someotherword' </code></pre>
2
2008-11-06T15:13:48Z
[ "python", "arrays", "dictionary", "replace" ]
Replacing multiple occurrences in nested arrays
268,891
<p>I've got this python dictionary "mydict", containing arrays, here's what it looks like :</p> <pre><code>mydict = dict( one=['foo', 'bar', 'foobar', 'barfoo', 'example'], two=['bar', 'example', 'foobar'], three=['foo', 'example']) </code></pre> <p>i'd like to replace all the occurrences of "example" by "someotherword". </p> <p>While I can already think of a few ways to do it, is there a most "pythonic" method to achieve this ?</p>
3
2008-11-06T14:36:01Z
270,535
<p>If you want to leave the original untouched, and just return a new dictionary with the modifications applied, you can use:</p> <pre><code>replacements = {'example' : 'someotherword'} newdict = dict((k, [replacements.get(x,x) for x in v]) for (k,v) in mydict.iteritems()) </code></pre> <p>This also has the advantage that its easy to extend with new words just by adding them to the replacements dict. If you want to mutate an existing dict in place, you can use the same approach:</p> <pre><code>for l in mydict.values(): l[:]=[replacements.get(x,x) for x in l] </code></pre> <p>However it's probably going to be slower than <a href="http://stackoverflow.com/questions/268891/replacing-multiple-occurrences-in-nested-arrays#269043">J.F Sebastian's</a> solution, as it rebuilds the whole list rather than just modifying the changed elements in place.</p>
2
2008-11-06T22:15:59Z
[ "python", "arrays", "dictionary", "replace" ]
Replacing multiple occurrences in nested arrays
268,891
<p>I've got this python dictionary "mydict", containing arrays, here's what it looks like :</p> <pre><code>mydict = dict( one=['foo', 'bar', 'foobar', 'barfoo', 'example'], two=['bar', 'example', 'foobar'], three=['foo', 'example']) </code></pre> <p>i'd like to replace all the occurrences of "example" by "someotherword". </p> <p>While I can already think of a few ways to do it, is there a most "pythonic" method to achieve this ?</p>
3
2008-11-06T14:36:01Z
271,294
<p>Here's another take:</p> <pre><code>for key, val in mydict.items(): mydict[key] = ["someotherword" if x == "example" else x for x in val] </code></pre> <p>I've found that building lists is <strong>very</strong> fast, but of course profile if performance is important.</p>
1
2008-11-07T05:18:17Z
[ "python", "arrays", "dictionary", "replace" ]
How can you emulate a mailing list in Django?
268,930
<p>I'm on a project which is trying to write what amounts to a Mailing List app in Django, and we're running into a couple of problems/questions.</p> <p>The code we have so far doesn't set various List headers, and re-sets the To header to be the person we're sending it to, instead of the list address.</p> <p>Now, we can work our way through all these fiddly little details, but I was wondering if anyone had any code which already did this sort of thing that we could crib from, so that we don't have to go through all the trial-and-error ourselves. Specific sections of RFCs that showed us what we should be sending would also be useful.</p> <p>Thanks,<br/> Blake.</p>
3
2008-11-06T14:45:37Z
269,377
<p>Did you take a look at <a href="http://www.greatcircle.com/majordomo/" rel="nofollow">majordomo</a>, or <a href="http://www.gnu.org/software/mailman/index.html" rel="nofollow">mailman</a>?</p>
1
2008-11-06T16:42:00Z
[ "python", "django", "mailing-list" ]
How can you emulate a mailing list in Django?
268,930
<p>I'm on a project which is trying to write what amounts to a Mailing List app in Django, and we're running into a couple of problems/questions.</p> <p>The code we have so far doesn't set various List headers, and re-sets the To header to be the person we're sending it to, instead of the list address.</p> <p>Now, we can work our way through all these fiddly little details, but I was wondering if anyone had any code which already did this sort of thing that we could crib from, so that we don't have to go through all the trial-and-error ourselves. Specific sections of RFCs that showed us what we should be sending would also be useful.</p> <p>Thanks,<br/> Blake.</p>
3
2008-11-06T14:45:37Z
269,379
<p><a href="http://www.apps.ietf.org/rfc/rfc2919.html" rel="nofollow">RFC 2919</a> has some info and more references on this.</p>
2
2008-11-06T16:42:10Z
[ "python", "django", "mailing-list" ]
How can you emulate a mailing list in Django?
268,930
<p>I'm on a project which is trying to write what amounts to a Mailing List app in Django, and we're running into a couple of problems/questions.</p> <p>The code we have so far doesn't set various List headers, and re-sets the To header to be the person we're sending it to, instead of the list address.</p> <p>Now, we can work our way through all these fiddly little details, but I was wondering if anyone had any code which already did this sort of thing that we could crib from, so that we don't have to go through all the trial-and-error ourselves. Specific sections of RFCs that showed us what we should be sending would also be useful.</p> <p>Thanks,<br/> Blake.</p>
3
2008-11-06T14:45:37Z
6,985,535
<p>What about <a href="http://labs.freehackers.org/projects/colibri/wiki" rel="nofollow">http://labs.freehackers.org/projects/colibri/wiki</a> It seems to do what you want: a mailing list manager with a django frontend.</p>
3
2011-08-08T16:47:09Z
[ "python", "django", "mailing-list" ]
Is there a Python library function which attempts to guess the character-encoding of some bytes?
269,060
<p>I'm writing some mail-processing software in Python that is encountering strange bytes in header fields. I suspect this is just malformed mail; the message itself claims to be us-ascii, so I don't think there is a true encoding, but I'd like to get out a unicode string approximating the original one without throwing a <code>UnicodeDecodeError </code>.</p> <p>So, I'm looking for a function that takes a <code>str</code> and optionally some hints and does its darndest to give me back a <code>unicode</code>. I could write one of course, but if such a function exists its author has probably thought a bit deeper about the best way to go about this.</p> <p>I also know that Python's design prefers explicit to implicit and that the standard library is designed to avoid implicit magic in decoding text. I just want to explicitly say "go ahead and guess".</p>
14
2008-11-06T15:18:20Z
269,105
<p>You may be interested in <a href="http://pypi.python.org/pypi/chardet">Universal Encoding Detector</a>.</p>
19
2008-11-06T15:26:25Z
[ "python", "email", "character-encoding", "invalid-characters" ]
Is there a Python library function which attempts to guess the character-encoding of some bytes?
269,060
<p>I'm writing some mail-processing software in Python that is encountering strange bytes in header fields. I suspect this is just malformed mail; the message itself claims to be us-ascii, so I don't think there is a true encoding, but I'd like to get out a unicode string approximating the original one without throwing a <code>UnicodeDecodeError </code>.</p> <p>So, I'm looking for a function that takes a <code>str</code> and optionally some hints and does its darndest to give me back a <code>unicode</code>. I could write one of course, but if such a function exists its author has probably thought a bit deeper about the best way to go about this.</p> <p>I also know that Python's design prefers explicit to implicit and that the standard library is designed to avoid implicit magic in decoding text. I just want to explicitly say "go ahead and guess".</p>
14
2008-11-06T15:18:20Z
269,276
<p>+1 for the <a href="http://web.archive.org/web/20110709171259/http://chardet.feedparser.org/docs/faq.html">chardet</a> module (suggested by <a href="http://stackoverflow.com/questions/269060/is-there-a-python-library-function-which-attempts-to-guess-the-character-encoding/269105#269105"><code>@insin</code></a>).</p> <p>It is not in the standard library, but you can easily install it with the following command:</p> <pre><code>$ pip install chardet </code></pre> <p><a href="http://web.archive.org/web/20111003070626/http://chardet.feedparser.org/">Example</a>:</p> <pre><code>&gt;&gt;&gt; import chardet &gt;&gt;&gt; import urllib &gt;&gt;&gt; detect = lambda url: chardet.detect(urllib.urlopen(url).read()) &gt;&gt;&gt; detect('http://stackoverflow.com') {'confidence': 0.85663169917190185, 'encoding': 'ISO-8859-2'} &gt;&gt;&gt; detect('http://stackoverflow.com/questions/269060/is-there-a-python-lib') {'confidence': 0.98999999999999999, 'encoding': 'utf-8'} </code></pre> <p>See <a href="http://guide.python-distribute.org/installation.html#installing-pip">Installing Pip</a> if you don't have one.</p>
15
2008-11-06T16:13:29Z
[ "python", "email", "character-encoding", "invalid-characters" ]
Is there a Python library function which attempts to guess the character-encoding of some bytes?
269,060
<p>I'm writing some mail-processing software in Python that is encountering strange bytes in header fields. I suspect this is just malformed mail; the message itself claims to be us-ascii, so I don't think there is a true encoding, but I'd like to get out a unicode string approximating the original one without throwing a <code>UnicodeDecodeError </code>.</p> <p>So, I'm looking for a function that takes a <code>str</code> and optionally some hints and does its darndest to give me back a <code>unicode</code>. I could write one of course, but if such a function exists its author has probably thought a bit deeper about the best way to go about this.</p> <p>I also know that Python's design prefers explicit to implicit and that the standard library is designed to avoid implicit magic in decoding text. I just want to explicitly say "go ahead and guess".</p>
14
2008-11-06T15:18:20Z
271,058
<p>The best way to do this that I've found is to iteratively try decoding a prospective with each of the most common encodings inside of a try except block.</p>
1
2008-11-07T02:31:26Z
[ "python", "email", "character-encoding", "invalid-characters" ]
Is there a Python library function which attempts to guess the character-encoding of some bytes?
269,060
<p>I'm writing some mail-processing software in Python that is encountering strange bytes in header fields. I suspect this is just malformed mail; the message itself claims to be us-ascii, so I don't think there is a true encoding, but I'd like to get out a unicode string approximating the original one without throwing a <code>UnicodeDecodeError </code>.</p> <p>So, I'm looking for a function that takes a <code>str</code> and optionally some hints and does its darndest to give me back a <code>unicode</code>. I could write one of course, but if such a function exists its author has probably thought a bit deeper about the best way to go about this.</p> <p>I also know that Python's design prefers explicit to implicit and that the standard library is designed to avoid implicit magic in decoding text. I just want to explicitly say "go ahead and guess".</p>
14
2008-11-06T15:18:20Z
273,631
<p>As far as I can tell, the standard library doesn't have a function, though it's not too difficult to write one as suggested above. I think the real thing I was looking for was a way to decode a string and guarantee that it wouldn't throw an exception. The errors parameter to string.decode does that.</p> <pre><code>def decode(s, encodings=('ascii', 'utf8', 'latin1')): for encoding in encodings: try: return s.decode(encoding) except UnicodeDecodeError: pass return s.decode('ascii', 'ignore') </code></pre>
9
2008-11-07T21:03:20Z
[ "python", "email", "character-encoding", "invalid-characters" ]
What mime-type should I return for a python string
269,292
<p>I have a web API that returns python dictionaries or lists as a response that I eval() in python scripts that use the API, for completness I wanted to set a proper content-type but not sure what would be best to use "text/x-python" or maybe "application/python", or something else? </p> <p>[edit] I'm also outputting JSON, I'm doing Python as an option mainly for internal use.[/edit]</p>
3
2008-11-06T16:19:58Z
269,364
<p>I doubt there's an established MIME type. Have you considered using JSON instead, it is almost the same as a Python dict, and has a better established culture of tools and techniques.</p>
8
2008-11-06T16:38:35Z
[ "python", "http", "mime-types" ]
What mime-type should I return for a python string
269,292
<p>I have a web API that returns python dictionaries or lists as a response that I eval() in python scripts that use the API, for completness I wanted to set a proper content-type but not sure what would be best to use "text/x-python" or maybe "application/python", or something else? </p> <p>[edit] I'm also outputting JSON, I'm doing Python as an option mainly for internal use.[/edit]</p>
3
2008-11-06T16:19:58Z
271,988
<p>The authoritative registry is <a href="http://www.iana.org/assignments/media-types/" rel="nofollow">at IANA</a> and, no, there is no standard subtype for Python. So, do not use type like "application/python" but you may use private subtypes such as "text/x-python" (the one I find in the mime-support package on my Debian).</p>
3
2008-11-07T12:59:35Z
[ "python", "http", "mime-types" ]
How can I Cause a Deadlock in MySQL for Testing Purposes
269,676
<p>I want to make my Python library working with MySQLdb be able to detect deadlocks and try again. I believe I've coded a good solution, and now I want to test it.</p> <p>Any ideas for the simplest queries I could run using MySQLdb to create a deadlock condition would be?</p> <p>system info:</p> <ul> <li>MySQL 5.0.19 </li> <li>Client 5.1.11 </li> <li>Windows XP</li> <li>Python 2.4 / MySQLdb 1.2.1 p2</li> </ul>
8
2008-11-06T18:06:13Z
270,449
<p>you can always run LOCK TABLE tablename from another session (mysql CLI for instance). That might do the trick.</p> <p>It will remain locked until you release it or disconnect the session.</p>
1
2008-11-06T21:51:06Z
[ "python", "mysql", "database", "deadlock" ]
How can I Cause a Deadlock in MySQL for Testing Purposes
269,676
<p>I want to make my Python library working with MySQLdb be able to detect deadlocks and try again. I believe I've coded a good solution, and now I want to test it.</p> <p>Any ideas for the simplest queries I could run using MySQLdb to create a deadlock condition would be?</p> <p>system info:</p> <ul> <li>MySQL 5.0.19 </li> <li>Client 5.1.11 </li> <li>Windows XP</li> <li>Python 2.4 / MySQLdb 1.2.1 p2</li> </ul>
8
2008-11-06T18:06:13Z
270,492
<p>I'm not familar with Python, so excuse my incorrect language If I'm saying this wrong... but open two sessions (in separate windows, or from separate Python processes - from separate boxes would work ... ) Then ... </p> <p>. In Session A:</p> <pre><code> Begin Transaction Insert TableA() Values()... </code></pre> <p>. Then In Session B:</p> <pre><code>Begin Transaction Insert TableB() Values()... Insert TableA() Values() ... </code></pre> <p>. Then go back to session A</p> <pre><code> Insert TableB() Values () ... </code></pre> <p>You'll get a deadlock... </p>
1
2008-11-06T22:01:53Z
[ "python", "mysql", "database", "deadlock" ]
How can I Cause a Deadlock in MySQL for Testing Purposes
269,676
<p>I want to make my Python library working with MySQLdb be able to detect deadlocks and try again. I believe I've coded a good solution, and now I want to test it.</p> <p>Any ideas for the simplest queries I could run using MySQLdb to create a deadlock condition would be?</p> <p>system info:</p> <ul> <li>MySQL 5.0.19 </li> <li>Client 5.1.11 </li> <li>Windows XP</li> <li>Python 2.4 / MySQLdb 1.2.1 p2</li> </ul>
8
2008-11-06T18:06:13Z
271,789
<p>You want something along the following lines.</p> <p><strong>parent.py</strong></p> <pre><code>import subprocess c1= subprocess.Popen( ["python", "child.py", "1"], stdin=subprocess.PIPE, stdout=subprocess.PIPE ) c2= subprocess.Popen( ["python", "child.py", "2"], stdin=subprocess.PIPE, stdout=subprocess.PIPE ) out1, err1= c1.communicate( "to 1: hit it!" ) print " 1:", repr(out1) print "*1:", repr(err1) out2, err2= c2.communicate( "to 2: ready, set, go!" ) print " 2:", repr(out2) print "*2:", repr(err2) out1, err1= c1.communicate() print " 1:", repr(out1) print "*1:", repr(err1) out2, err2= c2.communicate() print " 2:", repr(out2) print "*2:", repr(err2) c1.wait() c2.wait() </code></pre> <p><strong>child.py</strong></p> <pre><code>import yourDBconnection as dbapi2 def child1(): print "Child 1 start" conn= dbapi2.connect( ... ) c1= conn.cursor() conn.begin() # turn off autocommit, start a transaction ra= c1.execute( "UPDATE A SET AC1='Achgd' WHERE AC1='AC1-1'" ) print ra print "Child1", raw_input() rb= c1.execute( "UPDATE B SET BC1='Bchgd' WHERE BC1='BC1-1'" ) print rb c1.close() print "Child 1 finished" def child2(): print "Child 2 start" conn= dbapi2.connect( ... ) c1= conn.cursor() conn.begin() # turn off autocommit, start a transaction rb= c1.execute( "UPDATE B SET BC1='Bchgd' WHERE BC1='BC1-1'" ) print rb print "Child2", raw_input() ra= c1.execute( "UPDATE A SET AC1='Achgd' WHERE AC1='AC1-1'" ) print ta c1.close() print "Child 2 finish" try: if sys.argv[1] == "1": child1() else: child2() except Exception, e: print repr(e) </code></pre> <p>Note the symmetry. Each child starts out holding one resource. Then they attempt to get someone else's held resource. You can, for fun, have 3 children and 3 resources for a really vicious circle.</p> <p>Note that difficulty in contriving a situation in which deadlock occurs. If your transactions are short -- and consistent -- deadlock is very difficult to achieve. Deadlock requires (a) transaction which hold locks for a long time AND (b) transactions which acquire locks in an inconsistent order. I have found it easiest to prevent deadlocks by keeping my transactions short and consistent.</p> <p>Also note the non-determinism. You can't predict which child will die with a deadlock and which will continue after the other died. Only one of the two need to die to release needed resources for the other. Some RDBMS's claim that there's a rule based on number of resources held blah blah blah, but in general, you'll never know how the victim was chosen.</p> <p>Because of the two writes being in a specific order, you sort of expect child 1 to die first. However, you can't guarantee that. It's not deadlock until child 2 tries to get child 1's resources -- the sequence of who acquired first may not determine who dies.</p> <p>Also note that these are processes, not threads. Threads -- because of the Python GIL -- might be inadvertently synchronized and would require lots of calls to <code>time.sleep( 0.001 )</code> to give the other thread a chance to catch up. Processes -- for this -- are slightly simpler because they're fully independent.</p>
1
2008-11-07T11:12:14Z
[ "python", "mysql", "database", "deadlock" ]
How can I Cause a Deadlock in MySQL for Testing Purposes
269,676
<p>I want to make my Python library working with MySQLdb be able to detect deadlocks and try again. I believe I've coded a good solution, and now I want to test it.</p> <p>Any ideas for the simplest queries I could run using MySQLdb to create a deadlock condition would be?</p> <p>system info:</p> <ul> <li>MySQL 5.0.19 </li> <li>Client 5.1.11 </li> <li>Windows XP</li> <li>Python 2.4 / MySQLdb 1.2.1 p2</li> </ul>
8
2008-11-06T18:06:13Z
1,468,676
<p>Not sure if either above is correct. Check out this:</p> <p><a href="http://www.xaprb.com/blog/2006/08/08/how-to-deliberately-cause-a-deadlock-in-mysql/" rel="nofollow">http://www.xaprb.com/blog/2006/08/08/how-to-deliberately-cause-a-deadlock-in-mysql/</a></p>
1
2009-09-23T21:42:49Z
[ "python", "mysql", "database", "deadlock" ]
How can I Cause a Deadlock in MySQL for Testing Purposes
269,676
<p>I want to make my Python library working with MySQLdb be able to detect deadlocks and try again. I believe I've coded a good solution, and now I want to test it.</p> <p>Any ideas for the simplest queries I could run using MySQLdb to create a deadlock condition would be?</p> <p>system info:</p> <ul> <li>MySQL 5.0.19 </li> <li>Client 5.1.11 </li> <li>Windows XP</li> <li>Python 2.4 / MySQLdb 1.2.1 p2</li> </ul>
8
2008-11-06T18:06:13Z
8,100,573
<p>Here's some pseudocode for how i do it in PHP:</p> <p>Script 1:</p> <pre><code>START TRANSACTION; INSERT INTO table &lt;anything you want&gt;; SLEEP(5); UPDATE table SET field = 'foo'; COMMIT; </code></pre> <p>Script 2:</p> <pre><code>START TRANSACTION; UPDATE table SET field = 'foo'; SLEEP(5); INSERT INTO table &lt;anything you want&gt;; COMMIT; </code></pre> <p>Execute script 1 and then immediately execute script 2 in another terminal. You'll get a deadlock if the database table already has some data in it (In other words, it starts deadlocking after the second time you try this).</p> <p>Note that if mysql won't honor the SLEEP() command, use Python's equivalent in the application itself.</p>
1
2011-11-11T22:09:50Z
[ "python", "mysql", "database", "deadlock" ]
Using Python to authenticate against raw username, hash, salt in DB created by ASP.NET roles/membership
269,713
<p>We have a current application where user login credentials are stored in a SQL Server DB. These are, basically, stored as a plain text username, a password hash, and an associated salt for this hash.</p> <p>These were all created by built in functions in ASP.NET's membership/role system. Here's a row for a user named 'joe' and a password of 'password':</p> <blockquote> <p>joe,kDP0Py2QwEdJYtUX9cJABg==,OJF6H4KdxFLgLu+oTDNFodCEfMA=</p> </blockquote> <p>I've dumped this stuff into a CSV file and I'm attempting to get it into a usable format for Django which stores its passwords in this format:</p> <p>[algo]$[salt]$[hash]</p> <p>Where the salt is a plain string and the hash is the hex digest of an SHA1 hash.</p> <p>So far I've been able to ascertain that ASP is storing these hashes and salts in a base64 format. Those values above decode into binary strings.</p> <p>We've used reflector to glean how ASP authenticates against these values:</p> <pre><code>internal string EncodePassword(string pass, int passwordFormat, string salt) { if (passwordFormat == 0) { return pass; } byte[] bytes = Encoding.Unicode.GetBytes(pass); byte[] src = Convert.FromBase64String(salt); byte[] dst = new byte[src.Length + bytes.Length]; byte[] inArray = null; Buffer.BlockCopy(src, 0, dst, 0, src.Length); Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length); if (passwordFormat == 1) { HashAlgorithm algorithm = HashAlgorithm.Create(Membership.HashAlgorithmType); if ((algorithm == null) &amp;&amp; Membership.IsHashAlgorithmFromMembershipConfig) { RuntimeConfig.GetAppConfig().Membership.ThrowHashAlgorithmException(); } inArray = algorithm.ComputeHash(dst); } else { inArray = this.EncryptPassword(dst); } return Convert.ToBase64String(inArray); } </code></pre> <p>Eseentially, pulls in the salt from the DB and b64 decodes it into a binary representation. It does a "GetBytes" on the raw password and then it concatinates them, salt first.</p> <p>It then runs the SHA1 algorithm on this new string, base64 encodes it, and compares it against the value stored in the database.</p> <p>I've attempted to write some code to try and reproduce these hashes in Python and I'm failing. I won't be able to use them in Django until I can figure out how this translates over. Here's how I'm testing:</p> <pre><code>import hashlib from base64 import b64decode, b64encode b64salt = "kDP0Py2QwEdJYtUX9cJABg==" b64hash = "OJF6H4KdxFLgLu+oTDNFodCEfMA=" binsalt = b64decode(b64salt) password_string = 'password' m1 = hashlib.sha1() # Pass in salt m1.update(binsalt) # Pass in password m1.update(password_string) # B64 encode the binary digest if b64encode(m1.digest()) == b64hash: print "Logged in!" else: print "Didn't match" print b64hash print b64encode(m1.digest()) </code></pre> <p>I'm wondering if anyone can see any flaws in my approach or can suggest an alternate method. Perhaps you can take the algorithms above and the known password and salt above and produce the hash on your system?</p>
6
2008-11-06T18:14:45Z
269,888
<p>Two thoughts as to what could be going wrong.</p> <p>First the code from the reflection has three paths:</p> <ul> <li>If passwordFormat is 0 it returns the password as is.</li> <li>If passwordFormat is 1 it creates the hash as your python code does.</li> <li>If passwordFormat is anything other than 0 or 1 it calls this.EncryptPassword()</li> </ul> <p>How do you know you are hashing the password, and not encrypting the password with this.EncryptPassword()? You may need to reverse the EncryptPassword() member function and replicate that. That is unless you have some information which ensures that you are hashing the password and not encrypting it.</p> <p>Second if it is indeed hashing the password you may want to see what the Encoding.Unicode.GetBytes() function returns for the string "password", as you may be getting something back like:</p> <pre><code>0x00 0x70 0x00 0x61 0x00 0x73 0x00 0x73 0x00 0x77 0x00 0x6F 0x00 0x72 0x00 0x64 </code></pre> <p>instead of:</p> <pre><code>0x70 0x61 0x73 0x73 0x77 0x6F 0x72 0x64 </code></pre> <p>I hope this helps.</p>
0
2008-11-06T19:06:58Z
[ "asp.net", "python", "hash", "passwords" ]
Using Python to authenticate against raw username, hash, salt in DB created by ASP.NET roles/membership
269,713
<p>We have a current application where user login credentials are stored in a SQL Server DB. These are, basically, stored as a plain text username, a password hash, and an associated salt for this hash.</p> <p>These were all created by built in functions in ASP.NET's membership/role system. Here's a row for a user named 'joe' and a password of 'password':</p> <blockquote> <p>joe,kDP0Py2QwEdJYtUX9cJABg==,OJF6H4KdxFLgLu+oTDNFodCEfMA=</p> </blockquote> <p>I've dumped this stuff into a CSV file and I'm attempting to get it into a usable format for Django which stores its passwords in this format:</p> <p>[algo]$[salt]$[hash]</p> <p>Where the salt is a plain string and the hash is the hex digest of an SHA1 hash.</p> <p>So far I've been able to ascertain that ASP is storing these hashes and salts in a base64 format. Those values above decode into binary strings.</p> <p>We've used reflector to glean how ASP authenticates against these values:</p> <pre><code>internal string EncodePassword(string pass, int passwordFormat, string salt) { if (passwordFormat == 0) { return pass; } byte[] bytes = Encoding.Unicode.GetBytes(pass); byte[] src = Convert.FromBase64String(salt); byte[] dst = new byte[src.Length + bytes.Length]; byte[] inArray = null; Buffer.BlockCopy(src, 0, dst, 0, src.Length); Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length); if (passwordFormat == 1) { HashAlgorithm algorithm = HashAlgorithm.Create(Membership.HashAlgorithmType); if ((algorithm == null) &amp;&amp; Membership.IsHashAlgorithmFromMembershipConfig) { RuntimeConfig.GetAppConfig().Membership.ThrowHashAlgorithmException(); } inArray = algorithm.ComputeHash(dst); } else { inArray = this.EncryptPassword(dst); } return Convert.ToBase64String(inArray); } </code></pre> <p>Eseentially, pulls in the salt from the DB and b64 decodes it into a binary representation. It does a "GetBytes" on the raw password and then it concatinates them, salt first.</p> <p>It then runs the SHA1 algorithm on this new string, base64 encodes it, and compares it against the value stored in the database.</p> <p>I've attempted to write some code to try and reproduce these hashes in Python and I'm failing. I won't be able to use them in Django until I can figure out how this translates over. Here's how I'm testing:</p> <pre><code>import hashlib from base64 import b64decode, b64encode b64salt = "kDP0Py2QwEdJYtUX9cJABg==" b64hash = "OJF6H4KdxFLgLu+oTDNFodCEfMA=" binsalt = b64decode(b64salt) password_string = 'password' m1 = hashlib.sha1() # Pass in salt m1.update(binsalt) # Pass in password m1.update(password_string) # B64 encode the binary digest if b64encode(m1.digest()) == b64hash: print "Logged in!" else: print "Didn't match" print b64hash print b64encode(m1.digest()) </code></pre> <p>I'm wondering if anyone can see any flaws in my approach or can suggest an alternate method. Perhaps you can take the algorithms above and the known password and salt above and produce the hash on your system?</p>
6
2008-11-06T18:14:45Z
270,670
<p>It appears python is inserting a byte order marker when you convert a UTF16 string to binary. The .NET byte array contains no BOM, so I did some ghetto python that turns the UTF16 into hex, removes the first 4 characters, then decodes it to binary.</p> <p>There may be a better way to rip out the BOM, but this works for me!</p> <p>Here's one that passes:</p> <pre><code>import hashlib from base64 import b64decode, b64encode def utf16tobin(s): return s.encode('hex')[4:].decode('hex') b64salt = "kDP0Py2QwEdJYtUX9cJABg==" b64hash = "OJF6H4KdxFLgLu+oTDNFodCEfMA=" binsalt = b64decode(b64salt) password_string = 'password'.encode("utf16") password_string = utf16tobin(password_string) m1 = hashlib.sha1() # Pass in salt m1.update(binsalt + password_string) # Pass in password # B64 encode the binary digest if b64encode(m1.digest()) == b64hash: print "Logged in!" else: print "Didn't match" print b64hash print b64encode(m1.digest()) </code></pre>
8
2008-11-06T22:57:12Z
[ "asp.net", "python", "hash", "passwords" ]
How do I find the location of Python module sources?
269,795
<p>How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux?</p> <p>I'm trying to look for the source of the <code>datetime</code> module in particular, but I'm interested in a more general answer as well.</p>
261
2008-11-06T18:36:52Z
269,803
<p>The <code>sys.path</code> list contains the list of directories which will be searched for modules at runtime:</p> <pre><code>python -v &gt;&gt;&gt; import sys &gt;&gt;&gt; sys.path ['', '/usr/local/lib/python25.zip', '/usr/local/lib/python2.5', ... ] </code></pre>
25
2008-11-06T18:39:52Z
[ "python", "module" ]
How do I find the location of Python module sources?
269,795
<p>How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux?</p> <p>I'm trying to look for the source of the <code>datetime</code> module in particular, but I'm interested in a more general answer as well.</p>
261
2008-11-06T18:36:52Z
269,806
<p>Running <code>python -v</code> from the command line should tell you what is being imported and from where. This works for me on Windows and Mac OS X.</p> <pre><code>C:\&gt;python -v # installing zipimport hook import zipimport # builtin # installed zipimport hook # C:\Python24\lib\site.pyc has bad mtime import site # from C:\Python24\lib\site.py # wrote C:\Python24\lib\site.pyc # C:\Python24\lib\os.pyc has bad mtime import os # from C:\Python24\lib\os.py # wrote C:\Python24\lib\os.pyc import nt # builtin # C:\Python24\lib\ntpath.pyc has bad mtime ... </code></pre> <p>I'm not sure what those bad mtime's are on my install!</p>
136
2008-11-06T18:40:27Z
[ "python", "module" ]
How do I find the location of Python module sources?
269,795
<p>How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux?</p> <p>I'm trying to look for the source of the <code>datetime</code> module in particular, but I'm interested in a more general answer as well.</p>
261
2008-11-06T18:36:52Z
269,810
<p><code>datetime</code> is a builtin module, so there is no (Python) source file.</p> <p>For modules coming from <code>.py</code> (or <code>.pyc</code>) files, you can use <code>mymodule.__file__</code>, e.g.</p> <pre><code>&gt; import random &gt; random.__file__ 'C:\\Python25\\lib\\random.pyc' </code></pre>
25
2008-11-06T18:41:56Z
[ "python", "module" ]
How do I find the location of Python module sources?
269,795
<p>How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux?</p> <p>I'm trying to look for the source of the <code>datetime</code> module in particular, but I'm interested in a more general answer as well.</p>
261
2008-11-06T18:36:52Z
269,814
<p>Not all python modules are written in python. Datetime happens to be one of them that is not, and (on linux) is datetime.so.</p> <p>You would have to download the source code to the python standard library to get at it.</p>
0
2008-11-06T18:43:03Z
[ "python", "module" ]
How do I find the location of Python module sources?
269,795
<p>How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux?</p> <p>I'm trying to look for the source of the <code>datetime</code> module in particular, but I'm interested in a more general answer as well.</p>
261
2008-11-06T18:36:52Z
269,825
<p>For a pure python module you can find the source by looking at <code>themodule.__file__</code>. The datetime module, however, is written in C, and therefore <code>datetime.__file__</code> points to a .so file (there is no <code>datetime.__file__</code> on Windows), and therefore, you can't see the source.</p> <p>If you download a python source tarball and extract it, the modules' code can be found in the <strong>Modules</strong> subdirectory.</p> <p>For example, if you want to find the datetime code for python 2.6, you can look at</p> <pre><code>Python-2.6/Modules/datetimemodule.c </code></pre> <p>You can also find the latest Mercurial version on the web at <a href="https://hg.python.org/cpython/file/tip/Modules/_datetimemodule.c">https://hg.python.org/cpython/file/tip/Modules/_datetimemodule.c</a></p>
211
2008-11-06T18:45:33Z
[ "python", "module" ]
How do I find the location of Python module sources?
269,795
<p>How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux?</p> <p>I'm trying to look for the source of the <code>datetime</code> module in particular, but I'm interested in a more general answer as well.</p>
261
2008-11-06T18:36:52Z
2,723,437
<p>Check out this <a href="http://chris-lamb.co.uk/2010/04/22/locating-source-any-python-module/" rel="nofollow">nifty "cdp" command</a> to cd to the directory containing the source for the indicated Python module:</p> <pre><code>cdp () { cd "$(python -c "import os.path as _, ${1}; \ print _.dirname(_.realpath(${1}.__file__[:-1]))" )" } </code></pre>
7
2010-04-27T17:22:07Z
[ "python", "module" ]
How do I find the location of Python module sources?
269,795
<p>How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux?</p> <p>I'm trying to look for the source of the <code>datetime</code> module in particular, but I'm interested in a more general answer as well.</p>
261
2008-11-06T18:36:52Z
5,089,930
<p>New in Python 3.2, you can now use e.g. <code>code_info()</code> from the dis module: <a href="http://docs.python.org/dev/whatsnew/3.2.html#dis">http://docs.python.org/dev/whatsnew/3.2.html#dis</a></p>
10
2011-02-23T10:56:12Z
[ "python", "module" ]
How do I find the location of Python module sources?
269,795
<p>How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux?</p> <p>I'm trying to look for the source of the <code>datetime</code> module in particular, but I'm interested in a more general answer as well.</p>
261
2008-11-06T18:36:52Z
5,740,458
<p>In the python interpreter you could import the particular module and then type help(module). This gives details such as Name, File, Module Docs, Description et al.</p> <p>Ex:</p> <pre><code>import os help(os) Help on module os: NAME os - OS routines for Mac, NT, or Posix depending on what system we're on. FILE /usr/lib/python2.6/os.py MODULE DOCS http://docs.python.org/library/os DESCRIPTION This exports: - all functions from posix, nt, os2, or ce, e.g. unlink, stat, etc. - os.path is one of the modules posixpath, or ntpath - os.name is 'posix', 'nt', 'os2', 'ce' or 'riscos' </code></pre> <p>et al</p>
8
2011-04-21T06:39:13Z
[ "python", "module" ]
How do I find the location of Python module sources?
269,795
<p>How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux?</p> <p>I'm trying to look for the source of the <code>datetime</code> module in particular, but I'm interested in a more general answer as well.</p>
261
2008-11-06T18:36:52Z
13,888,157
<p>I realize this answer is 4 years late, but the existing answers are misleading people.</p> <p>The right way to do this is never <code>__file__</code>, or trying to walk through <code>sys.path</code> and search for yourself, etc. (unless you need to be backward compatible beyond 2.1).</p> <p>It's the <a href="http://docs.python.org/library/inspect.html"><code>inspect</code></a> module—in particular, <code>getfile</code> or <code>getsourcefile</code>.</p> <p>Unless you want to learn and implement the rules (which are documented, but painful, for CPython 2.x, and not documented at all for other implementations, or 3.x) for mapping <code>.pyc</code> to <code>.py</code> files; dealing with .zip archives, eggs, and module packages; trying different ways to get the path to <code>.so</code>/<code>.pyd</code> files that don't support <code>__file__</code>; figuring out what Jython/IronPython/PyPy do; etc. In which case, go for it.</p> <p>Meanwhile, every Python version's source from 2.0+ is available online at <code>http://hg.python.org/cpython/file/X.Y/</code> (e.g., <a href="http://hg.python.org/cpython/file/2.7/">2.7</a> or <a href="http://hg.python.org/cpython/file/3.3/">3.3</a>). So, once you discover that <code>inspect.getfile(datetime)</code> is a <code>.so</code> or <code>.pyd</code> file like <code>/usr/local/lib/python2.7/lib-dynload/datetime.so</code>, you can look it up inside the Modules directory. Strictly speaking, there's no way to be sure of which file defines which module, but nearly all of them are either <code>foo.c</code> or <code>foomodule.c</code>, so it shouldn't be hard to guess that <a href="http://hg.python.org/cpython/file/2.7/Modules/datetimemodule.c">datetimemodule.c</a> is what you want.</p>
77
2012-12-15T00:31:15Z
[ "python", "module" ]
How do I find the location of Python module sources?
269,795
<p>How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux?</p> <p>I'm trying to look for the source of the <code>datetime</code> module in particular, but I'm interested in a more general answer as well.</p>
261
2008-11-06T18:36:52Z
15,211,581
<p>Here's a one-liner to get the filename for a module, suitable for shell aliasing:</p> <pre><code>echo 'import sys; t=__import__(sys.argv[1],fromlist=[\".\"]); print(t.__file__)' | python - </code></pre> <p>Set up as an alias:</p> <pre><code>alias getpmpath="echo 'import sys; t=__import__(sys.argv[1],fromlist=[\".\"]); print(t.__file__)' | python - " </code></pre> <p>To use:</p> <pre><code>[buildbot@domU-12-31-39-0A-9C-B8 ~]$ getpmpath twisted /usr/lib64/python2.6/site-packages/twisted/__init__.pyc [buildbot@domU-12-31-39-0A-9C-B8 ~]$ getpmpath twisted.web /usr/lib64/python2.6/site-packages/twisted/web/__init__.pyc </code></pre>
4
2013-03-04T21:35:24Z
[ "python", "module" ]
How do I find the location of Python module sources?
269,795
<p>How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux?</p> <p>I'm trying to look for the source of the <code>datetime</code> module in particular, but I'm interested in a more general answer as well.</p>
261
2008-11-06T18:36:52Z
16,370,057
<p>from the standard library try <a href="http://docs.python.org/2/library/imp.html#imp.find_module">imp.find_module</a></p> <pre><code>&gt;&gt;&gt; import imp &gt;&gt;&gt; imp.find_module('fontTools') (None, 'C:\\Python27\\lib\\site-packages\\FontTools\\fontTools', ('', '', 5)) &gt;&gt;&gt; imp.find_module('datetime') (None, 'datetime', ('', '', 6)) </code></pre>
17
2013-05-04T02:40:30Z
[ "python", "module" ]
How do I find the location of Python module sources?
269,795
<p>How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux?</p> <p>I'm trying to look for the source of the <code>datetime</code> module in particular, but I'm interested in a more general answer as well.</p>
261
2008-11-06T18:36:52Z
24,117,914
<p>On windows you can find the location of the python module as shown below:i.e find rest_framework module <img src="http://i.stack.imgur.com/TsWpv.png" alt="enter image description here"></p>
2
2014-06-09T10:04:36Z
[ "python", "module" ]
How do I find the location of Python module sources?
269,795
<p>How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux?</p> <p>I'm trying to look for the source of the <code>datetime</code> module in particular, but I'm interested in a more general answer as well.</p>
261
2008-11-06T18:36:52Z
27,230,006
<p>For those who prefer a GUI solution: if you're using a gui such as Spyder (part of the Anaconda installation) you can just right-click the module name (such as "csv" in "import csv") and select "go to definition" - this will open the file, but also on the top you can see the exact file location ("C:....csv.py") </p>
0
2014-12-01T14:00:13Z
[ "python", "module" ]
How do I find the location of Python module sources?
269,795
<p>How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux?</p> <p>I'm trying to look for the source of the <code>datetime</code> module in particular, but I'm interested in a more general answer as well.</p>
261
2008-11-06T18:36:52Z
32,784,452
<p>If you're using pip to install your modules, just <code>pip show $module</code> the location is returned.</p>
9
2015-09-25T14:27:58Z
[ "python", "module" ]
How do I find the location of Python module sources?
269,795
<p>How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux?</p> <p>I'm trying to look for the source of the <code>datetime</code> module in particular, but I'm interested in a more general answer as well.</p>
261
2008-11-06T18:36:52Z
37,970,790
<p>On Ubuntu 12.04, for example numpy package for python2, can be found at:</p> <pre><code>/usr/lib/python2.7/dist-packages/numpy </code></pre> <p>Of course, this is not generic answer</p>
0
2016-06-22T14:18:30Z
[ "python", "module" ]
C++ string diff (a la Python's difflib)
269,918
<p>I'm trying to diff two strings to determine whether or not they solely vary in one numerical subset of the string structure; for example,</p> <pre><code>varies_in_single_number_field('foo7bar', 'foo123bar') # Returns True, because 7 != 123, and there's only one varying # number region between the two strings. </code></pre> <p>In Python I can use the <code>difflib</code> to accomplish this:</p> <pre><code>import difflib, doctest def varies_in_single_number_field(str1, str2): """ A typical use case is as follows: &gt;&gt;&gt; varies_in_single_number_field('foo7bar00', 'foo123bar00') True Numerical variation in two dimensions is no good: &gt;&gt;&gt; varies_in_single_number_field('foo7bar00', 'foo123bar01') False Varying in a nonexistent field is okay: &gt;&gt;&gt; varies_in_single_number_field('foobar00', 'foo123bar00') True Identical strings don't *vary* in any number field: &gt;&gt;&gt; varies_in_single_number_field('foobar00', 'foobar00') False """ in_differing_substring = False passed_differing_substring = False # There should be only one. differ = difflib.Differ() for letter_diff in differ.compare(str1, str2): letter = letter_diff[2:] if letter_diff.startswith(('-', '+')): if passed_differing_substring: # Already saw a varying field. return False in_differing_substring = True if not letter.isdigit(): return False # Non-digit diff character. elif in_differing_substring: # Diff character not found - end of diff. in_differing_substring = False passed_differing_substring = True return passed_differing_substring # No variation if no diff was passed. if __name__ == '__main__': doctest.testmod() </code></pre> <p>But I have no idea how to find something like <code>difflib</code> for C++. Alternative approaches welcome. :)</p>
3
2008-11-06T19:16:12Z
270,006
<p>It's probably a bit of overkill, but you could use boost to interface to python. At the worst, difflib is implemented in pure python, and it's not too long. It should be possible to port from python to C...</p>
1
2008-11-06T19:46:23Z
[ "c++", "python", "algorithm", "diff" ]
C++ string diff (a la Python's difflib)
269,918
<p>I'm trying to diff two strings to determine whether or not they solely vary in one numerical subset of the string structure; for example,</p> <pre><code>varies_in_single_number_field('foo7bar', 'foo123bar') # Returns True, because 7 != 123, and there's only one varying # number region between the two strings. </code></pre> <p>In Python I can use the <code>difflib</code> to accomplish this:</p> <pre><code>import difflib, doctest def varies_in_single_number_field(str1, str2): """ A typical use case is as follows: &gt;&gt;&gt; varies_in_single_number_field('foo7bar00', 'foo123bar00') True Numerical variation in two dimensions is no good: &gt;&gt;&gt; varies_in_single_number_field('foo7bar00', 'foo123bar01') False Varying in a nonexistent field is okay: &gt;&gt;&gt; varies_in_single_number_field('foobar00', 'foo123bar00') True Identical strings don't *vary* in any number field: &gt;&gt;&gt; varies_in_single_number_field('foobar00', 'foobar00') False """ in_differing_substring = False passed_differing_substring = False # There should be only one. differ = difflib.Differ() for letter_diff in differ.compare(str1, str2): letter = letter_diff[2:] if letter_diff.startswith(('-', '+')): if passed_differing_substring: # Already saw a varying field. return False in_differing_substring = True if not letter.isdigit(): return False # Non-digit diff character. elif in_differing_substring: # Diff character not found - end of diff. in_differing_substring = False passed_differing_substring = True return passed_differing_substring # No variation if no diff was passed. if __name__ == '__main__': doctest.testmod() </code></pre> <p>But I have no idea how to find something like <code>difflib</code> for C++. Alternative approaches welcome. :)</p>
3
2008-11-06T19:16:12Z
270,143
<p>This might work, it at least passes your demonstration test: EDIT: I've made some modifications to deal with some string indexing issues. I believe it should be good now.</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;vector&gt; #include &lt;algorithm&gt; #include &lt;cctype&gt; bool starts_with(const std::string &amp;s1, const std::string &amp;s2) { return (s1.length() &lt;= s2.length()) &amp;&amp; (s2.substr(0, s1.length()) == s1); } bool ends_with(const std::string &amp;s1, const std::string &amp;s2) { return (s1.length() &lt;= s2.length()) &amp;&amp; (s2.substr(s2.length() - s1.length()) == s1); } bool is_numeric(const std::string &amp;s) { for(std::string::const_iterator it = s.begin(); it != s.end(); ++it) { if(!std::isdigit(*it)) { return false; } } return true; } bool varies_in_single_number_field(std::string s1, std::string s2) { size_t index1 = 0; size_t index2 = s1.length() - 1; if(s1 == s2) { return false; } if((s1.empty() &amp;&amp; is_numeric(s2)) || (s2.empty() &amp;&amp; is_numeric(s1))) { return true; } if(s1.length() &lt; s2.length()) { s1.swap(s2); } while(index1 &lt; s1.length() &amp;&amp; starts_with(s1.substr(0, index1), s2)) { index1++; } while(ends_with(s1.substr(index2), s2)) { index2--; } return is_numeric(s1.substr(index1 - 1, (index2 + 1) - (index1 - 1))); } int main() { std::cout &lt;&lt; std::boolalpha &lt;&lt; varies_in_single_number_field("foo7bar00", "foo123bar00") &lt;&lt; std::endl; std::cout &lt;&lt; std::boolalpha &lt;&lt; varies_in_single_number_field("foo7bar00", "foo123bar01") &lt;&lt; std::endl; std::cout &lt;&lt; std::boolalpha &lt;&lt; varies_in_single_number_field("foobar00", "foo123bar00") &lt;&lt; std::endl; std::cout &lt;&lt; std::boolalpha &lt;&lt; varies_in_single_number_field("foobar00", "foobar00") &lt;&lt; std::endl; std::cout &lt;&lt; std::boolalpha &lt;&lt; varies_in_single_number_field("7aaa", "aaa") &lt;&lt; std::endl; std::cout &lt;&lt; std::boolalpha &lt;&lt; varies_in_single_number_field("aaa7", "aaa") &lt;&lt; std::endl; std::cout &lt;&lt; std::boolalpha &lt;&lt; varies_in_single_number_field("aaa", "7aaa") &lt;&lt; std::endl; std::cout &lt;&lt; std::boolalpha &lt;&lt; varies_in_single_number_field("aaa", "aaa7") &lt;&lt; std::endl; } </code></pre> <p>Basically, it looks for a string which has 3 parts, string2 begins with part1, string2 ends with part3 and part2 is only digits.</p>
2
2008-11-06T20:33:58Z
[ "c++", "python", "algorithm", "diff" ]
C++ string diff (a la Python's difflib)
269,918
<p>I'm trying to diff two strings to determine whether or not they solely vary in one numerical subset of the string structure; for example,</p> <pre><code>varies_in_single_number_field('foo7bar', 'foo123bar') # Returns True, because 7 != 123, and there's only one varying # number region between the two strings. </code></pre> <p>In Python I can use the <code>difflib</code> to accomplish this:</p> <pre><code>import difflib, doctest def varies_in_single_number_field(str1, str2): """ A typical use case is as follows: &gt;&gt;&gt; varies_in_single_number_field('foo7bar00', 'foo123bar00') True Numerical variation in two dimensions is no good: &gt;&gt;&gt; varies_in_single_number_field('foo7bar00', 'foo123bar01') False Varying in a nonexistent field is okay: &gt;&gt;&gt; varies_in_single_number_field('foobar00', 'foo123bar00') True Identical strings don't *vary* in any number field: &gt;&gt;&gt; varies_in_single_number_field('foobar00', 'foobar00') False """ in_differing_substring = False passed_differing_substring = False # There should be only one. differ = difflib.Differ() for letter_diff in differ.compare(str1, str2): letter = letter_diff[2:] if letter_diff.startswith(('-', '+')): if passed_differing_substring: # Already saw a varying field. return False in_differing_substring = True if not letter.isdigit(): return False # Non-digit diff character. elif in_differing_substring: # Diff character not found - end of diff. in_differing_substring = False passed_differing_substring = True return passed_differing_substring # No variation if no diff was passed. if __name__ == '__main__': doctest.testmod() </code></pre> <p>But I have no idea how to find something like <code>difflib</code> for C++. Alternative approaches welcome. :)</p>
3
2008-11-06T19:16:12Z
270,155
<p>You could do an ad hoc approach: You're looking to match strings s and s', where s=abc and s'=ab'c, and the b and b' should be two distinct numbers (possible empty). So:</p> <ol> <li>Compare the strings from the left, char by char, until you hit different characters, and then stop. You </li> <li>Similarly, compare the strings from the right until you hit different characters, OR hit that left marker.</li> <li>Then check the remainders in the middle to see if they're both numbers.</li> </ol>
1
2008-11-06T20:36:24Z
[ "c++", "python", "algorithm", "diff" ]
C++ string diff (a la Python's difflib)
269,918
<p>I'm trying to diff two strings to determine whether or not they solely vary in one numerical subset of the string structure; for example,</p> <pre><code>varies_in_single_number_field('foo7bar', 'foo123bar') # Returns True, because 7 != 123, and there's only one varying # number region between the two strings. </code></pre> <p>In Python I can use the <code>difflib</code> to accomplish this:</p> <pre><code>import difflib, doctest def varies_in_single_number_field(str1, str2): """ A typical use case is as follows: &gt;&gt;&gt; varies_in_single_number_field('foo7bar00', 'foo123bar00') True Numerical variation in two dimensions is no good: &gt;&gt;&gt; varies_in_single_number_field('foo7bar00', 'foo123bar01') False Varying in a nonexistent field is okay: &gt;&gt;&gt; varies_in_single_number_field('foobar00', 'foo123bar00') True Identical strings don't *vary* in any number field: &gt;&gt;&gt; varies_in_single_number_field('foobar00', 'foobar00') False """ in_differing_substring = False passed_differing_substring = False # There should be only one. differ = difflib.Differ() for letter_diff in differ.compare(str1, str2): letter = letter_diff[2:] if letter_diff.startswith(('-', '+')): if passed_differing_substring: # Already saw a varying field. return False in_differing_substring = True if not letter.isdigit(): return False # Non-digit diff character. elif in_differing_substring: # Diff character not found - end of diff. in_differing_substring = False passed_differing_substring = True return passed_differing_substring # No variation if no diff was passed. if __name__ == '__main__': doctest.testmod() </code></pre> <p>But I have no idea how to find something like <code>difflib</code> for C++. Alternative approaches welcome. :)</p>
3
2008-11-06T19:16:12Z
270,241
<p>@Evan Teran: looks like we did this in parallel -- I have a markedly less readable O(n) implementation:</p> <pre><code>#include &lt;cassert&gt; #include &lt;cctype&gt; #include &lt;string&gt; #include &lt;sstream&gt; #include &lt;iostream&gt; using namespace std; ostringstream debug; const bool DEBUG = true; bool varies_in_single_number_field(const string &amp;str1, const string &amp;str2) { bool in_difference = false; bool passed_difference = false; string str1_digits, str2_digits; size_t str1_iter = 0, str2_iter = 0; while (str1_iter &lt; str1.size() &amp;&amp; str2_iter &lt; str2.size()) { const char &amp;str1_char = str1.at(str1_iter); const char &amp;str2_char = str2.at(str2_iter); debug &lt;&lt; "str1: " &lt;&lt; str1_char &lt;&lt; "; str2: " &lt;&lt; str2_char &lt;&lt; endl; if (str1_char == str2_char) { if (in_difference) { in_difference = false; passed_difference = true; } ++str1_iter, ++str2_iter; continue; } in_difference = true; if (passed_difference) { /* Already passed a difference. */ debug &lt;&lt; "Already passed a difference." &lt;&lt; endl; return false; } bool str1_char_is_digit = isdigit(str1_char); bool str2_char_is_digit = isdigit(str2_char); if (str1_char_is_digit &amp;&amp; !str2_char_is_digit) { ++str1_iter; str1_digits.push_back(str1_char); } else if (!str1_char_is_digit &amp;&amp; str2_char_is_digit) { ++str2_iter; str2_digits.push_back(str2_char); } else if (str1_char_is_digit &amp;&amp; str2_char_is_digit) { ++str1_iter, ++str2_iter; str1_digits.push_back(str1_char); str2_digits.push_back(str2_char); } else { /* Both are non-digits and they're different. */ return false; } } if (in_difference) { in_difference = false; passed_difference = true; } string str1_remainder = str1.substr(str1_iter); string str2_remainder = str2.substr(str2_iter); debug &lt;&lt; "Got to exit point; passed difference: " &lt;&lt; passed_difference &lt;&lt; "; str1 digits: " &lt;&lt; str1_digits &lt;&lt; "; str2 digits: " &lt;&lt; str2_digits &lt;&lt; "; str1 remainder: " &lt;&lt; str1_remainder &lt;&lt; "; str2 remainder: " &lt;&lt; str2_remainder &lt;&lt; endl; return passed_difference &amp;&amp; (str1_digits != str2_digits) &amp;&amp; (str1_remainder == str2_remainder); } int main() { assert(varies_in_single_number_field("foo7bar00", "foo123bar00") == true); assert(varies_in_single_number_field("foo7bar00", "foo123bar01") == false); assert(varies_in_single_number_field("foobar00", "foo123bar00") == true); assert(varies_in_single_number_field("foobar00", "foobar00") == false); assert(varies_in_single_number_field("foobar00", "foobaz00") == false); assert(varies_in_single_number_field("foo00bar", "foo01barz") == false); assert(varies_in_single_number_field("foo01barz", "foo00bar") == false); if (DEBUG) { cout &lt;&lt; debug.str(); } return 0; } </code></pre>
0
2008-11-06T20:56:26Z
[ "c++", "python", "algorithm", "diff" ]
C++ string diff (a la Python's difflib)
269,918
<p>I'm trying to diff two strings to determine whether or not they solely vary in one numerical subset of the string structure; for example,</p> <pre><code>varies_in_single_number_field('foo7bar', 'foo123bar') # Returns True, because 7 != 123, and there's only one varying # number region between the two strings. </code></pre> <p>In Python I can use the <code>difflib</code> to accomplish this:</p> <pre><code>import difflib, doctest def varies_in_single_number_field(str1, str2): """ A typical use case is as follows: &gt;&gt;&gt; varies_in_single_number_field('foo7bar00', 'foo123bar00') True Numerical variation in two dimensions is no good: &gt;&gt;&gt; varies_in_single_number_field('foo7bar00', 'foo123bar01') False Varying in a nonexistent field is okay: &gt;&gt;&gt; varies_in_single_number_field('foobar00', 'foo123bar00') True Identical strings don't *vary* in any number field: &gt;&gt;&gt; varies_in_single_number_field('foobar00', 'foobar00') False """ in_differing_substring = False passed_differing_substring = False # There should be only one. differ = difflib.Differ() for letter_diff in differ.compare(str1, str2): letter = letter_diff[2:] if letter_diff.startswith(('-', '+')): if passed_differing_substring: # Already saw a varying field. return False in_differing_substring = True if not letter.isdigit(): return False # Non-digit diff character. elif in_differing_substring: # Diff character not found - end of diff. in_differing_substring = False passed_differing_substring = True return passed_differing_substring # No variation if no diff was passed. if __name__ == '__main__': doctest.testmod() </code></pre> <p>But I have no idea how to find something like <code>difflib</code> for C++. Alternative approaches welcome. :)</p>
3
2008-11-06T19:16:12Z
270,251
<p>How about using something like boost::regex?</p> <pre> // pseudo code, may or may not compile bool match_except_numbers(const std::string& s1, const std::string& s2) { static const boost::regex fooNumberBar("foo\\d+bar"); return boost::match(s1, fooNumberBar) && boost::match(s2, fooNumberBar); } </pre>
0
2008-11-06T20:58:45Z
[ "c++", "python", "algorithm", "diff" ]
Tkinter: invoke event in main loop
270,648
<p>How do you invoke a tkinter <code>event</code> from a separate object? </p> <p>I'm looking for something like wxWidgets <code>wx.CallAfter</code>. For example, If I create an object, and pass to it my <code>Tk</code> root instance, and then try to call a method of that root window from my object, my app locks up.</p> <p>The best I can come up with is to use the the <code>after</code> method and check the status from my separate object, but that seems wasteful.</p>
14
2008-11-06T22:49:44Z
276,069
<p>To answer your specific question of "How do you invoke a TkInter event from a separate object", use the <code>event_generate</code> command. It allows you to inject events into the event queue of the root window. Combined with Tk's powerful virtual event mechanism it becomes a handy message passing mechanism. </p> <p>For example:</p> <pre><code>from tkinter import * def doFoo(*args): print("Hello, world") root = Tk() root.bind("&lt;&lt;Foo&gt;&gt;", doFoo) # some time later, inject the "&lt;&lt;Foo&gt;&gt;" virtual event at the # tail of the event queue root.event_generate("&lt;&lt;Foo&gt;&gt;", when="tail") </code></pre> <p>Note that the <code>event_generate</code> call will return immediately. It's not clear if that's what you want or not. Generally speaking you don't want an event based program to block waiting for a response to a specific event because it will <em>freeze the GUI</em>. </p> <p>I'm not sure if this solves your problem though; without seeing your code I'm not sure what your real problem is. I can, for example, access methods of root in the constructor of an object where the root is passed in without the app locking up. This tells me there's something else going on in your code.</p> <p>Here's an example of successfully accessing methods on a root window from some other object:</p> <pre><code>from tkinter import * class myClass: def __init__(self, root): print("root background is %s" % root.cget("background")) root = Tk() newObj = myClass(root) </code></pre>
21
2008-11-09T16:26:28Z
[ "python", "user-interface", "communication", "tkinter" ]
Tkinter: invoke event in main loop
270,648
<p>How do you invoke a tkinter <code>event</code> from a separate object? </p> <p>I'm looking for something like wxWidgets <code>wx.CallAfter</code>. For example, If I create an object, and pass to it my <code>Tk</code> root instance, and then try to call a method of that root window from my object, my app locks up.</p> <p>The best I can come up with is to use the the <code>after</code> method and check the status from my separate object, but that seems wasteful.</p>
14
2008-11-06T22:49:44Z
36,778,730
<p>Here below just some doc and link to better understand Bryan's answer above. </p> <p>function description from <a href="http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/universal.html" rel="nofollow">New Mexico Tech</a> :</p> <p><code>w.event_generate(sequence, **kw)</code></p> <blockquote> <p>This method causes an event to trigger without any external stimulus. The handling of the event is the same as if it had been triggered by an external stimulus. The sequence argument describes the event to be triggered. You can set values for selected fields in the Event object by providing keyword=value arguments, where the keyword specifies the name of a field in the Event object.</p> </blockquote> <p>list and description of tcl/tk event attributes <a href="https://www.tcl.tk/man/tcl/TkCmd/event.htm" rel="nofollow">here</a></p>
3
2016-04-21T19:25:28Z
[ "python", "user-interface", "communication", "tkinter" ]
How do I determine all of my IP addresses when I have multiple NICs?
270,745
<p>I have multiple Network Interface Cards on my computer, each with its own IP address.</p> <p>When I use <code>gethostbyname(gethostname())</code> from Python's (built-in) <code>socket</code> module, it will only return one of them. How do I get the others?</p>
24
2008-11-06T23:20:28Z
270,777
<p>You should directly obtain all IP configured IP addresses, e.g. by running ifconfig and parsing its output (it's also possible to do what <a href="http://pypi.python.org/pypi/netifaces/0.3" rel="nofollow">ifconfig does directly in Python</a>, <a href="http://stackoverflow.com/questions/259389/finding-an-ip-from-an-interface-name">see how it is done in C</a>). If you want host names, use gethostbyaddr.</p>
0
2008-11-06T23:32:44Z
[ "python", "sockets", "ip-address" ]
How do I determine all of my IP addresses when I have multiple NICs?
270,745
<p>I have multiple Network Interface Cards on my computer, each with its own IP address.</p> <p>When I use <code>gethostbyname(gethostname())</code> from Python's (built-in) <code>socket</code> module, it will only return one of them. How do I get the others?</p>
24
2008-11-06T23:20:28Z
273,112
<p>It's linux only, but there's a very simple recipe here <a href="http://code.activestate.com/recipes/439094/" rel="nofollow">http://code.activestate.com/recipes/439094/</a> </p> <p>It probably uses similar code to the <a href="http://pypi.python.org/pypi/netifaces/" rel="nofollow">netifaces package</a> mentioned in another answer (but current version linked here)</p> <p>The socket.getaddrinfo() doesn't actually return the bound ip address for the device. If your hosts file contains a line with "127.0.1.1 yourhost.example.com yourhost", which is a common configuration, getaddrinfo is only going to return 127.0.1.1.</p>
1
2008-11-07T18:36:31Z
[ "python", "sockets", "ip-address" ]
How do I determine all of my IP addresses when I have multiple NICs?
270,745
<p>I have multiple Network Interface Cards on my computer, each with its own IP address.</p> <p>When I use <code>gethostbyname(gethostname())</code> from Python's (built-in) <code>socket</code> module, it will only return one of them. How do I get the others?</p>
24
2008-11-06T23:20:28Z
274,644
<p>Use the <a href="http://alastairs-place.net/netifaces/"><code>netifaces</code></a> module. Because networking is complex, using netifaces can be a little tricky, but here's how to do what you want:</p> <pre><code>&gt;&gt;&gt; import netifaces &gt;&gt;&gt; netifaces.interfaces() ['lo', 'eth0'] &gt;&gt;&gt; netifaces.ifaddresses('eth0') {17: [{'broadcast': 'ff:ff:ff:ff:ff:ff', 'addr': '00:11:2f:32:63:45'}], 2: [{'broadcast': '10.0.0.255', 'netmask': '255.255.255.0', 'addr': '10.0.0.2'}], 10: [{'netmask': 'ffff:ffff:ffff:ffff::', 'addr': 'fe80::211:2fff:fe32:6345%eth0'}]} &gt;&gt;&gt; for interface in netifaces.interfaces(): ... print netifaces.ifaddresses(interface)[netifaces.AF_INET] ... [{'peer': '127.0.0.1', 'netmask': '255.0.0.0', 'addr': '127.0.0.1'}] [{'broadcast': '10.0.0.255', 'netmask': '255.255.255.0', 'addr': '10.0.0.2'}] &gt;&gt;&gt; for interface in netifaces.interfaces(): ... for link in netifaces.ifaddresses(interface)[netifaces.AF_INET]: ... print link['addr'] ... 127.0.0.1 10.0.0.2 </code></pre> <p>This can be made a little more readable like this:</p> <pre><code>from netifaces import interfaces, ifaddresses, AF_INET def ip4_addresses(): ip_list = [] for interface in interfaces(): for link in ifaddresses(interface)[AF_INET]: ip_list.append(link['addr']) return ip_list </code></pre> <p>If you want IPv6 addresses, use <code>AF_INET6</code> instead of <code>AF_INET</code>. If you're wondering why <code>netifaces</code> uses lists and dictionaries all over the place, it's because a single computer can have multiple NICs, and each NIC can have multiple addresses, and each address has its own set of options.</p>
30
2008-11-08T11:43:25Z
[ "python", "sockets", "ip-address" ]
How do I determine all of my IP addresses when I have multiple NICs?
270,745
<p>I have multiple Network Interface Cards on my computer, each with its own IP address.</p> <p>When I use <code>gethostbyname(gethostname())</code> from Python's (built-in) <code>socket</code> module, it will only return one of them. How do I get the others?</p>
24
2008-11-06T23:20:28Z
1,491,617
<p>Here is a routine for finding all IPv4 and IPv6 interfaces. As a previous poster pointed out, socket.gethostbyname_ex() does not work for IPv6, and the Python documentation recommends one use <a href="http://docs.python.org/library/socket.html#socket.getaddrinfo" rel="nofollow">socket.getaddressinfo()</a> instead.</p> <p>This routine adds the callback IPv4 interface (127.0.0.1), and if there are any IPv6 interfaces then it also adds the callback IPv6 interface (::1). On my machine, socket.getaddrinfo() will give me one or both of these but only if I have no other interfaces available.</p> <p>For my needs, I wanted to try to open a UDP socket on a specified port on each of my available interfaces, which is why the code has "port" and socket.SOCK_DGRAM in it. It is safe to change those, e.g. if you don't have a port in mind.</p> <pre><code>addrinfo_ipv4 = socket.getaddrinfo(hostname,port,socket.AF_INET,socket.SOCK_DGRAM) addrinfo_ipv6 = [] try: addrinfo_ipv6 = socket.getaddrinfo(hostname,port,socket.AF_INET6,socket.SOCK_DGRAM) except socket.gaierror: pass addrinfo = [(f,t,a) for f,t,p,cn,a in addrinfo_ipv4+addrinfo_ipv6] addrinfo_local = [(socket.AF_INET,socket.SOCK_DGRAM,('127.0.0.1',port))] if addrinfo_ipv6: addrinfo_local.append( (socket.AF_INET6,socket.SOCK_DGRAM,('::1',port)) ) [addrinfo.append(ai) for ai in addrinfo_local if ai not in addrinfo] </code></pre>
1
2009-09-29T09:59:20Z
[ "python", "sockets", "ip-address" ]
How do I determine all of my IP addresses when I have multiple NICs?
270,745
<p>I have multiple Network Interface Cards on my computer, each with its own IP address.</p> <p>When I use <code>gethostbyname(gethostname())</code> from Python's (built-in) <code>socket</code> module, it will only return one of them. How do I get the others?</p>
24
2008-11-06T23:20:28Z
16,412,986
<pre><code>import socket [i[4][0] for i in socket.getaddrinfo(socket.gethostname(), None)] </code></pre>
3
2013-05-07T06:56:09Z
[ "python", "sockets", "ip-address" ]
How do I determine all of my IP addresses when I have multiple NICs?
270,745
<p>I have multiple Network Interface Cards on my computer, each with its own IP address.</p> <p>When I use <code>gethostbyname(gethostname())</code> from Python's (built-in) <code>socket</code> module, it will only return one of them. How do I get the others?</p>
24
2008-11-06T23:20:28Z
27,494,105
<p><a href="https://docs.python.org/3.4/library/socket.html#socket.if_nameindex" rel="nofollow">https://docs.python.org/3.4/library/socket.html#socket.if_nameindex</a></p> <p>socket.if_nameindex()</p> <p>Return a list of network interface information (index int, name string) tuples. OSError if the system call fails.</p> <p>Availability: Unix.</p> <p><strong>New in version 3.3.</strong></p> <hr> <p>made this code that is runable on Python 3.4, UNIX / Linux</p> <pre><code>#!/env/python3.4 import socket import fcntl import struct def active_nic_addresses(): """ Return a list of IPv4 addresses that are active on the computer. """ addresses = [ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][:1] return addresses def get_ip_address( NICname ): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa(fcntl.ioctl( s.fileno(), 0x8915, # SIOCGIFADDR struct.pack('256s', NICname[:15].encode("UTF-8")) )[20:24]) def nic_info(): """ Return a list with tuples containing NIC and IPv4 """ nic = [] for ix in socket.if_nameindex(): name = ix[1] ip = get_ip_address( name ) nic.append( (name, ip) ) return nic if __name__ == "__main__": print( active_nic_addresses() ) print( nic_info() ) </code></pre> <hr> <p>Will print something like:</p> <pre><code>['192.168.0.2'] [('lo', '127.0.0.1'), ('enp3s0', '192.168.0.2')] </code></pre>
1
2014-12-15T22:11:42Z
[ "python", "sockets", "ip-address" ]
How do I determine all of my IP addresses when I have multiple NICs?
270,745
<p>I have multiple Network Interface Cards on my computer, each with its own IP address.</p> <p>When I use <code>gethostbyname(gethostname())</code> from Python's (built-in) <code>socket</code> module, it will only return one of them. How do I get the others?</p>
24
2008-11-06T23:20:28Z
33,946,251
<p>All addresses in one line with the help of the <code>netifaces</code> module:</p> <pre><code>[netifaces.ifaddresses(iface)[netifaces.AF_INET][0]['addr'] for iface in netifaces.interfaces() if netifaces.AF_INET in netifaces.ifaddresses(iface)] </code></pre>
4
2015-11-26T20:05:35Z
[ "python", "sockets", "ip-address" ]
How do I determine all of my IP addresses when I have multiple NICs?
270,745
<p>I have multiple Network Interface Cards on my computer, each with its own IP address.</p> <p>When I use <code>gethostbyname(gethostname())</code> from Python's (built-in) <code>socket</code> module, it will only return one of them. How do I get the others?</p>
24
2008-11-06T23:20:28Z
35,776,008
<p>You can do it fairly easily like this:</p> <pre><code>import netifaces for interface in netifaces.interfaces(): print netifaces.ifaddresses(interface) </code></pre> <p>For more information you can look up the <a href="https://pypi.python.org/pypi/netifaces" rel="nofollow">netifaces documentation</a>.</p>
0
2016-03-03T15:17:34Z
[ "python", "sockets", "ip-address" ]
How do I determine all of my IP addresses when I have multiple NICs?
270,745
<p>I have multiple Network Interface Cards on my computer, each with its own IP address.</p> <p>When I use <code>gethostbyname(gethostname())</code> from Python's (built-in) <code>socket</code> module, it will only return one of them. How do I get the others?</p>
24
2008-11-06T23:20:28Z
39,951,087
<p>This snippet will give a list of all available IPV4 addresses in the system.</p> <pre><code>import itertools from netifaces import interfaces, ifaddresses, AF_INET links = filter(None, (ifaddresses(x).get(AF_INET) for x in interfaces())) links = itertools.chain(*links) ip_addresses = [x['addr'] for x in links] </code></pre>
0
2016-10-10T03:53:27Z
[ "python", "sockets", "ip-address" ]
Efficiently updating database using SQLAlchemy ORM
270,879
<p>I'm starting a new application and looking at using an ORM -- in particular, SQLAlchemy.</p> <p>Say I've got a column 'foo' in my database and I want to increment it. In straight sqlite, this is easy:</p> <pre><code>db = sqlite3.connect('mydata.sqlitedb') cur = db.cursor() cur.execute('update table stuff set foo = foo + 1') </code></pre> <p>I figured out the SQLAlchemy SQL-builder equivalent:</p> <pre><code>engine = sqlalchemy.create_engine('sqlite:///mydata.sqlitedb') md = sqlalchemy.MetaData(engine) table = sqlalchemy.Table('stuff', md, autoload=True) upd = table.update(values={table.c.foo:table.c.foo+1}) engine.execute(upd) </code></pre> <p>This is slightly slower, but there's not much in it.</p> <p>Here's my best guess for a SQLAlchemy ORM approach:</p> <pre><code># snip definition of Stuff class made using declarative_base # snip creation of session object for c in session.query(Stuff): c.foo = c.foo + 1 session.flush() session.commit() </code></pre> <p>This does the right thing, but it takes just under fifty times as long as the other two approaches. I presume that's because it has to bring all the data into memory before it can work with it.</p> <p>Is there any way to generate the efficient SQL using SQLAlchemy's ORM? Or using any other python ORM? Or should I just go back to writing the SQL by hand?</p>
62
2008-11-07T00:24:04Z
270,891
<p>Withough testing, I'd try:</p> <pre><code>for c in session.query(Stuff).all(): c.foo = c.foo+1 session.commit() </code></pre> <p>(IIRC, commit() works without flush()).</p> <p>I've found that at times doing a large query and then iterating in python can be up to 2 orders of magnitude faster than lots of queries. I assume that iterating over the query object is less efficient than iterating over a list generated by the all() method of the query object.</p> <p>[Please note comment below - this did not speed things up at all].</p>
0
2008-11-07T00:35:19Z
[ "python", "orm", "sqlalchemy" ]
Efficiently updating database using SQLAlchemy ORM
270,879
<p>I'm starting a new application and looking at using an ORM -- in particular, SQLAlchemy.</p> <p>Say I've got a column 'foo' in my database and I want to increment it. In straight sqlite, this is easy:</p> <pre><code>db = sqlite3.connect('mydata.sqlitedb') cur = db.cursor() cur.execute('update table stuff set foo = foo + 1') </code></pre> <p>I figured out the SQLAlchemy SQL-builder equivalent:</p> <pre><code>engine = sqlalchemy.create_engine('sqlite:///mydata.sqlitedb') md = sqlalchemy.MetaData(engine) table = sqlalchemy.Table('stuff', md, autoload=True) upd = table.update(values={table.c.foo:table.c.foo+1}) engine.execute(upd) </code></pre> <p>This is slightly slower, but there's not much in it.</p> <p>Here's my best guess for a SQLAlchemy ORM approach:</p> <pre><code># snip definition of Stuff class made using declarative_base # snip creation of session object for c in session.query(Stuff): c.foo = c.foo + 1 session.flush() session.commit() </code></pre> <p>This does the right thing, but it takes just under fifty times as long as the other two approaches. I presume that's because it has to bring all the data into memory before it can work with it.</p> <p>Is there any way to generate the efficient SQL using SQLAlchemy's ORM? Or using any other python ORM? Or should I just go back to writing the SQL by hand?</p>
62
2008-11-07T00:24:04Z
270,942
<p>If it is because of the overhead in terms of creating objects, then it probably can't be sped up at all with SA.</p> <p>If it is because it is loading up related objects, then you might be able to do something with lazy loading. Are there lots of objects being created due to references? (IE, getting a Company object also gets all of the related People objects).</p>
0
2008-11-07T01:08:04Z
[ "python", "orm", "sqlalchemy" ]
Efficiently updating database using SQLAlchemy ORM
270,879
<p>I'm starting a new application and looking at using an ORM -- in particular, SQLAlchemy.</p> <p>Say I've got a column 'foo' in my database and I want to increment it. In straight sqlite, this is easy:</p> <pre><code>db = sqlite3.connect('mydata.sqlitedb') cur = db.cursor() cur.execute('update table stuff set foo = foo + 1') </code></pre> <p>I figured out the SQLAlchemy SQL-builder equivalent:</p> <pre><code>engine = sqlalchemy.create_engine('sqlite:///mydata.sqlitedb') md = sqlalchemy.MetaData(engine) table = sqlalchemy.Table('stuff', md, autoload=True) upd = table.update(values={table.c.foo:table.c.foo+1}) engine.execute(upd) </code></pre> <p>This is slightly slower, but there's not much in it.</p> <p>Here's my best guess for a SQLAlchemy ORM approach:</p> <pre><code># snip definition of Stuff class made using declarative_base # snip creation of session object for c in session.query(Stuff): c.foo = c.foo + 1 session.flush() session.commit() </code></pre> <p>This does the right thing, but it takes just under fifty times as long as the other two approaches. I presume that's because it has to bring all the data into memory before it can work with it.</p> <p>Is there any way to generate the efficient SQL using SQLAlchemy's ORM? Or using any other python ORM? Or should I just go back to writing the SQL by hand?</p>
62
2008-11-07T00:24:04Z
278,606
<p>SQLAlchemy's ORM is meant to be used together with the SQL layer, not hide it. But you do have to keep one or two things in mind when using the ORM and plain SQL in the same transaction. Basically, from one side, ORM data modifications will only hit the database when you flush the changes from your session. From the other side, SQL data manipulation statements don't affect the objects that are in your session.</p> <p>So if you say</p> <pre><code>for c in session.query(Stuff).all(): c.foo = c.foo+1 session.commit() </code></pre> <p>it will do what it says, go fetch all the objects from the database, modify all the objects and then when it's time to flush the changes to the database, update the rows one by one.</p> <p>Instead you should do this:</p> <pre><code>session.execute(update(stuff_table, values={stuff_table.c.foo: stuff_table.c.foo + 1})) session.commit() </code></pre> <p>This will execute as one query as you would expect, and because atleast the default session configuration expires all data in the session on commit you don't have any stale data issues.</p> <p>In the almost-released 0.5 series you could also use this method for updating:</p> <pre><code>session.query(Stuff).update({Stuff.foo: Stuff.foo + 1}) session.commit() </code></pre> <p>That will basically run the same SQL statement as the previous snippet, but also select the changed rows and expire any stale data in the session. If you know you aren't using any session data after the update you could also add synchronize_session=False to the update statement and get rid of that select.</p>
99
2008-11-10T17:40:42Z
[ "python", "orm", "sqlalchemy" ]
Efficiently updating database using SQLAlchemy ORM
270,879
<p>I'm starting a new application and looking at using an ORM -- in particular, SQLAlchemy.</p> <p>Say I've got a column 'foo' in my database and I want to increment it. In straight sqlite, this is easy:</p> <pre><code>db = sqlite3.connect('mydata.sqlitedb') cur = db.cursor() cur.execute('update table stuff set foo = foo + 1') </code></pre> <p>I figured out the SQLAlchemy SQL-builder equivalent:</p> <pre><code>engine = sqlalchemy.create_engine('sqlite:///mydata.sqlitedb') md = sqlalchemy.MetaData(engine) table = sqlalchemy.Table('stuff', md, autoload=True) upd = table.update(values={table.c.foo:table.c.foo+1}) engine.execute(upd) </code></pre> <p>This is slightly slower, but there's not much in it.</p> <p>Here's my best guess for a SQLAlchemy ORM approach:</p> <pre><code># snip definition of Stuff class made using declarative_base # snip creation of session object for c in session.query(Stuff): c.foo = c.foo + 1 session.flush() session.commit() </code></pre> <p>This does the right thing, but it takes just under fifty times as long as the other two approaches. I presume that's because it has to bring all the data into memory before it can work with it.</p> <p>Is there any way to generate the efficient SQL using SQLAlchemy's ORM? Or using any other python ORM? Or should I just go back to writing the SQL by hand?</p>
62
2008-11-07T00:24:04Z
4,540,110
<pre><code>session.query(Clients).filter(Clients.id == client_id_list).update({'status': status}) session.commit() </code></pre> <p>Try this =)</p>
45
2010-12-27T16:28:03Z
[ "python", "orm", "sqlalchemy" ]
Efficiently updating database using SQLAlchemy ORM
270,879
<p>I'm starting a new application and looking at using an ORM -- in particular, SQLAlchemy.</p> <p>Say I've got a column 'foo' in my database and I want to increment it. In straight sqlite, this is easy:</p> <pre><code>db = sqlite3.connect('mydata.sqlitedb') cur = db.cursor() cur.execute('update table stuff set foo = foo + 1') </code></pre> <p>I figured out the SQLAlchemy SQL-builder equivalent:</p> <pre><code>engine = sqlalchemy.create_engine('sqlite:///mydata.sqlitedb') md = sqlalchemy.MetaData(engine) table = sqlalchemy.Table('stuff', md, autoload=True) upd = table.update(values={table.c.foo:table.c.foo+1}) engine.execute(upd) </code></pre> <p>This is slightly slower, but there's not much in it.</p> <p>Here's my best guess for a SQLAlchemy ORM approach:</p> <pre><code># snip definition of Stuff class made using declarative_base # snip creation of session object for c in session.query(Stuff): c.foo = c.foo + 1 session.flush() session.commit() </code></pre> <p>This does the right thing, but it takes just under fifty times as long as the other two approaches. I presume that's because it has to bring all the data into memory before it can work with it.</p> <p>Is there any way to generate the efficient SQL using SQLAlchemy's ORM? Or using any other python ORM? Or should I just go back to writing the SQL by hand?</p>
62
2008-11-07T00:24:04Z
32,447,458
<p>Here's an example of how to solve the same problem without having to map the fields manually:</p> <pre><code>from sqlalchemy import Column, ForeignKey, Integer, String, Date, DateTime, text, create_engine from sqlalchemy.exc import IntegrityError from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from sqlalchemy.orm.attributes import InstrumentedAttribute engine = create_engine('postgres://postgres@localhost:5432/database') session = sessionmaker() session.configure(bind=engine) Base = declarative_base() class Media(Base): __tablename__ = 'media' id = Column(Integer, primary_key=True) title = Column(String, nullable=False) slug = Column(String, nullable=False) type = Column(String, nullable=False) def update(self): s = session() mapped_values = {} for item in Media.__dict__.iteritems(): field_name = item[0] field_type = item[1] is_column = isinstance(field_type, InstrumentedAttribute) if is_column: mapped_values[field_name] = getattr(self, field_name) s.query(Media).filter(Media.id == self.id).update(mapped_values) s.commit() </code></pre> <p>So to update a Media instance, you can do something like this:</p> <pre><code>media = Media(id=123, title="Titular Line", slug="titular-line", type="movie") media.update() </code></pre>
0
2015-09-08T00:10:34Z
[ "python", "orm", "sqlalchemy" ]
Efficiently updating database using SQLAlchemy ORM
270,879
<p>I'm starting a new application and looking at using an ORM -- in particular, SQLAlchemy.</p> <p>Say I've got a column 'foo' in my database and I want to increment it. In straight sqlite, this is easy:</p> <pre><code>db = sqlite3.connect('mydata.sqlitedb') cur = db.cursor() cur.execute('update table stuff set foo = foo + 1') </code></pre> <p>I figured out the SQLAlchemy SQL-builder equivalent:</p> <pre><code>engine = sqlalchemy.create_engine('sqlite:///mydata.sqlitedb') md = sqlalchemy.MetaData(engine) table = sqlalchemy.Table('stuff', md, autoload=True) upd = table.update(values={table.c.foo:table.c.foo+1}) engine.execute(upd) </code></pre> <p>This is slightly slower, but there's not much in it.</p> <p>Here's my best guess for a SQLAlchemy ORM approach:</p> <pre><code># snip definition of Stuff class made using declarative_base # snip creation of session object for c in session.query(Stuff): c.foo = c.foo + 1 session.flush() session.commit() </code></pre> <p>This does the right thing, but it takes just under fifty times as long as the other two approaches. I presume that's because it has to bring all the data into memory before it can work with it.</p> <p>Is there any way to generate the efficient SQL using SQLAlchemy's ORM? Or using any other python ORM? Or should I just go back to writing the SQL by hand?</p>
62
2008-11-07T00:24:04Z
33,638,391
<p>There are several ways to UPDATE using sqlalchemy</p> <pre><code>1) for c in session.query(Stuff).all(): c.foo += 1 session.commit() 2) session.query().\ update({"foo": (Stuff.foo + 1)}) session.commit() 3) conn = engine.connect() stmt = Stuff.update().\ values(Stuff.foo = (Stuff.foo + 1)) conn.execute(stmt) </code></pre>
3
2015-11-10T19:53:27Z
[ "python", "orm", "sqlalchemy" ]
How can I apply authenticated proxy exceptions to an opener using urllib2?
270,983
<p>When using urllib2 (and maybe urllib) on windows python seems to magically pick up the authenticated proxy setting applied to InternetExplorer. However, it doesn't seem to check and process the Advance setting "Exceptions" list.</p> <p>Is there a way I can get it to process the exceptions list? Or, ignore the IE proxy setting and apply my own proxy opener to address this issue?</p> <p>I played with creating a proxy opener before, but couldn't get it to work. Here's what I managed to dig out, but I still don't see how/where to apply any exceptions and I'm not even sure if this is right:</p> <pre><code>proxy_info = { 'host':'myproxy.com', 'user':Username, 'pass':Password, 'port':1080 } http_str = "http://%(user)s:%(pass)s@%(host)s:%(port)d" % proxy_info authInfo = urllib2.HTTPBasicAuthHandler() authInfo.add_password() proxy_dict = {'http':http_str} proxyHandler = urllib2.ProxyHandler(proxy_dict) # apply the handler to an opener proxy_opener = urllib2.build_opener(proxyHandler, urllib2.HTTPHandler) urllib2.install_opener(proxy_opener) </code></pre>
4
2008-11-07T01:29:14Z
271,023
<p>By default <code>urllib2</code> gets the proxy settings from the environment variable, which is why it is using the IE settings. This is very handy, because you don't need to setup authentication yourself.</p> <p>You can't apply exceptions like you want to, the easiest way to do this would be to have two <code>opener</code>s and decide which one to use depending on whether the domain is in your exception list or not.</p> <p>Use the default <code>opener</code> for when you want to use the proxy, and one without a proxy for when you don't need it:</p> <pre><code>&gt;&gt;&gt; no_proxy = urllib2.ProxyHandler({}) &gt;&gt;&gt; opener = urllib2.build_opener(no_proxy) &gt;&gt;&gt; urllib2.install_opener(opener) </code></pre> <p>From <a href="http://docs.python.org/howto/urllib2.html?highlight=proxyhandler#proxies" rel="nofollow">here</a>.</p> <p><strong>Edit:</strong></p> <p>Here's how I'd do it:</p> <pre><code>exclusion_list = ['http://www.google.com/', 'http://localhost/'] no_proxy = urllib2.ProxyHandler({}) no_proxy_opener = urllib2.build_opener(no_proxy) default_proxy_opener = urllib2.build_opener() url = 'http://www.example.com/' if url in exclusion_list: opener = no_proxy_opener else: opener = default_proxy_opener page = opener.open(url) print page </code></pre> <p>Your biggest problem will be matching the url to the exclusion list, but that's a whole new question.</p>
2
2008-11-07T01:58:09Z
[ "python", "windows", "proxy" ]