Saturday, December 13, 2014

Pylint Broken on install: "control_pragmas = {'disable', 'enable'}"

So, wanting better Python code and having used pychecker for years and years, I was recently pointed to pylint again as a tool-of-choice.

Installing it was simple:

$ sudo pip install pylint
Downloading/unpacking pylint
Downloading pylint-1.4.0-py2.py3-none-any.whl (412kB): 412kB downloaded
Downloading/unpacking astroid>=1.3.2 (from pylint)
Downloading astroid-1.3.2-py2.py3-none-any.whl (163kB): 163kB downloaded
Downloading/unpacking six (from pylint)
Downloading six-1.8.0-py2.py3-none-any.whl
Downloading/unpacking logilab-common>=0.53.0 (from pylint)
Downloading logilab-common-0.63.2.tar.gz (196kB): 196kB downloaded
Running (path:/tmp/pip_build_root/logilab-common/ egg_info for package logilab-common
/usr/lib64/python2.6/distutils/ UserWarning: Unknown distribution option: 'test_require'
package init file './test/' not found (or not a regular file)
Downloading/unpacking unittest2>=0.5.1 (from logilab-common>=0.53.0->pylint)
Downloading unittest2-0.8.0-py2.py3-none-any.whl (94kB): 94kB downloaded
Downloading/unpacking argparse (from unittest2>=0.5.1->logilab-common>=0.53.0->pylint)
Downloading argparse-1.2.2-py2.py3-none-any.whl
Installing collected packages: pylint, astroid, six, logilab-common, unittest2, argparse
Compiling /tmp/pip_build_root/pylint/pylint/ ...
SyntaxError: ('invalid syntax', ('/tmp/pip_build_root/pylint/pylint/', 585, 37, " control_pragmas = {'disable', 'enable'}\n"))

Compiling /tmp/pip_build_root/pylint/pylint/reporters/ ...
SyntaxError: ('invalid syntax', ('/tmp/pip_build_root/pylint/pylint/reporters/', 136, 18, " for attr in ('msg', 'symbol', 'category', 'C')})\n"))

Compiling /tmp/pip_build_root/pylint/pylint/test/functional/ ...
SyntaxError: ('invalid syntax', ('/tmp/pip_build_root/pylint/pylint/test/functional/', 6, 31, 'class Parent(object, metaclass=abc.ABCMeta):\n'))

Compiling /tmp/pip_build_root/pylint/pylint/test/functional/ ...
SyntaxError: ('invalid syntax', ('/tmp/pip_build_root/pylint/pylint/test/functional/', 15, 34, 'class GoodClass(object, metaclass=abc.ABCMeta):\n'))

Compiling /tmp/pip_build_root/pylint/pylint/test/functional/ ...
SyntaxError: ('invalid syntax', ('/tmp/pip_build_root/pylint/pylint/test/functional/', 14, 34, 'class GoodClass(object, metaclass=abc.ABCMeta):\n'))

Compiling /tmp/pip_build_root/pylint/pylint/test/functional/ ...
SyntaxError: ('invalid syntax', ('/tmp/pip_build_root/pylint/pylint/test/functional/', 34, 38, 'class TestMetaclass(object, metaclass=ABCMeta):\n'))

Compiling /tmp/pip_build_root/pylint/pylint/test/functional/ ...
SyntaxError: ('invalid syntax', ('/tmp/pip_build_root/pylint/pylint/test/functional/', 34, 38, 'class TestMetaclass(object, metaclass=ABCMeta):\n'))

Compiling /tmp/pip_build_root/pylint/pylint/test/functional/ ...
SyntaxError: ('invalid syntax', ('/tmp/pip_build_root/pylint/pylint/test/functional/', 29, 20, "with open('f') as f, open( as g:\n"))

Compiling /tmp/pip_build_root/pylint/pylint/test/functional/ ...
SyntaxError: ('invalid syntax', ('/tmp/pip_build_root/pylint/pylint/test/functional/', 15, 26, "print('hello world', file=sys.stdout)\n"))

Compiling /tmp/pip_build_root/pylint/pylint/test/functional/ ...
SyntaxError: ('invalid syntax', ('/tmp/pip_build_root/pylint/pylint/test/functional/', 10, 29, 'class NotOldStyle2(metaclass=type):\n'))

Compiling /tmp/pip_build_root/pylint/pylint/test/functional/ ...
SyntaxError: ('invalid syntax', ('/tmp/pip_build_root/pylint/pylint/test/functional/', 9, 20, ' first, second, *last = (1, 2, 3, 4)\n'))

Compiling /tmp/pip_build_root/pylint/pylint/test/functional/ ...
SyntaxError: ('invalid syntax', ('/tmp/pip_build_root/pylint/pylint/test/functional/', 8, 19, ' def test(self)->Undefined: # [undefined-variable]\n'))

Compiling /tmp/pip_build_root/pylint/pylint/test/functional/ ...
SyntaxError: ("'yield' outside function", ('/tmp/pip_build_root/pylint/pylint/test/functional/', 2, None, 'yield 1 # [yield-outside-function]\n'))

/tmp/pip_build_root/pylint/pylint/test/input/ SyntaxWarning: assertion is always true, perhaps remove parentheses?
assert (1 == 1, 2 == 2), "no error"
/tmp/pip_build_root/pylint/pylint/test/input/ SyntaxWarning: assertion is always true, perhaps remove parentheses?
assert (1 == 1, 2 == 2) #this should generate a warning
/tmp/pip_build_root/pylint/pylint/test/input/ SyntaxWarning: assertion is always true, perhaps remove parentheses?
assert (1 == 1, ), "no error"
/tmp/pip_build_root/pylint/pylint/test/input/ SyntaxWarning: assertion is always true, perhaps remove parentheses?
assert (1 == 1, )
/tmp/pip_build_root/pylint/pylint/test/input/ SyntaxWarning: assertion is always true, perhaps remove parentheses?
assert (1 == 1, 2 == 2, 3 == 5), "no error"
/tmp/pip_build_root/pylint/pylint/test/input/ SyntaxWarning: assertion is always true, perhaps remove parentheses?
assert (True, 'error msg') #this should generate a warning
Compiling /tmp/pip_build_root/pylint/pylint/test/input/ ...
SyntaxError: ('invalid syntax', ('/tmp/pip_build_root/pylint/pylint/test/input/', 8, 9, ' for x in range(3)}\n'))

Compiling /tmp/pip_build_root/pylint/pylint/test/input/ ...
SyntaxError: ('invalid syntax', ('/tmp/pip_build_root/pylint/pylint/test/input/', 14, 25, ' raise IndexError from 1\n'))

Compiling /tmp/pip_build_root/pylint/pylint/test/input/ ...
SyntaxError: ("'continue' not properly in loop", ('/tmp/pip_build_root/pylint/pylint/test/input/', 8, None, 'continue\n'))

Compiling /tmp/pip_build_root/pylint/pylint/test/input/ ...
SyntaxError: ("duplicate argument '_' in function definition",)

Compiling /tmp/pip_build_root/pylint/pylint/test/input/ ...
SyntaxError: ('invalid syntax', ('/tmp/pip_build_root/pylint/pylint/test/input/', 6, 22, "exec('a = 1', globals={})\n"))

Compiling /tmp/pip_build_root/pylint/pylint/test/input/ ...
SyntaxError: ('keyword argument repeated', ('/tmp/pip_build_root/pylint/pylint/test/input/', 8, None, 'function_default_arg(two=5, two=7)\n'))

Compiling /tmp/pip_build_root/pylint/pylint/test/input/ ...
SyntaxError: ('invalid syntax', ('/tmp/pip_build_root/pylint/pylint/test/input/', 3, 15, 'def function(*, foo):\n'))

Compiling /tmp/pip_build_root/pylint/pylint/test/input/ ...
SyntaxError: ('invalid syntax', ('/tmp/pip_build_root/pylint/pylint/test/input/', 8, 28, ' return {x: lambda: x for x in range(10)}\n'))

Compiling /tmp/pip_build_root/pylint/pylint/test/input/ ...
SyntaxError: ('invalid syntax', ('/tmp/pip_build_root/pylint/pylint/test/input/', 14, 29, 'class Test(object, metaclass=Meta):\n'))

Compiling /tmp/pip_build_root/pylint/pylint/test/input/ ...
SyntaxError: ('invalid syntax', ('/tmp/pip_build_root/pylint/pylint/test/input/', 12, 21, ' nonlocal attr\n'))

Compiling /tmp/pip_build_root/pylint/pylint/test/input/ ...
SyntaxError: ("'return' outside function", ('/tmp/pip_build_root/pylint/pylint/test/input/', 3, None, 'return\n'))

Compiling /tmp/pip_build_root/pylint/pylint/test/input/ ...
SyntaxError: ("'return' with argument inside generator",)

Compiling /tmp/pip_build_root/pylint/pylint/test/input/ ...
SyntaxError: ('invalid syntax', ('/tmp/pip_build_root/pylint/pylint/test/input/', 5, 23, 'def function1(value={1}):\n'))

Compiling /tmp/pip_build_root/pylint/pylint/test/input/ ...
SyntaxError: ('invalid syntax', ('/tmp/pip_build_root/pylint/pylint/test/input/', 1, 9, 'def toto\n'))

Compiling /tmp/pip_build_root/pylint/pylint/test/input/ ...
SyntaxError: ('invalid syntax', ('/tmp/pip_build_root/pylint/pylint/test/input/', 8, 20, 'class Bad(metaclass=ABCMet):\n'))

Compiling /tmp/pip_build_root/pylint/pylint/test/input/ ...
SyntaxError: ('invalid syntax', ('/tmp/pip_build_root/pylint/pylint/test/input/', 10, 21, 'class Meta(metaclass=abc.ABCMeta):\n'))

Compiling /tmp/pip_build_root/pylint/pylint/test/input/ ...
SyntaxError: ('invalid syntax', ('/tmp/pip_build_root/pylint/pylint/test/input/', 10, 20, ' nonlocal cnt\n'))

Compiling /tmp/pip_build_root/pylint/pylint/test/input/ ...
SyntaxError: ("default 'except:' must be last", ('/tmp/pip_build_root/pylint/pylint/test/input/', 28, None, '__revision__ += 1\n'))

Compiling /tmp/pip_build_root/pylint/pylint/test/input/ ...
Sorry: IndentationError: ('expected an indented block', ('/tmp/pip_build_root/pylint/pylint/test/input/', 2, 5, "print('hop')\n"))
Compiling /tmp/pip_build_root/pylint/pylint/ ...
SyntaxError: ('invalid syntax', ('/tmp/pip_build_root/pylint/pylint/', 59, 26, 'MSG_TYPES_LONG = {v: k for k, v in six.iteritems(MSG_TYPES)}\n'))

Compiling /tmp/pip_build_root/astroid/astroid/tests/testdata/python3/data/ ...
SyntaxError: ('invalid syntax', ('/tmp/pip_build_root/astroid/astroid/tests/testdata/python3/data/', 55, 32, " print('yo', end=' ')\n"))

Compiling /tmp/pip_build_root/astroid/astroid/tests/testdata/python3/data/ ...
SyntaxError: ('invalid syntax', ('/tmp/pip_build_root/astroid/astroid/tests/testdata/python3/data/', 100, 22, "print('bonjour', file=stream)\n"))

Compiling /tmp/pip_build_root/astroid/astroid/tests/ ...
SyntaxError: ('invalid syntax', ('/tmp/pip_build_root/astroid/astroid/tests/', 71, 33, ' self.assertSetEqual({"a", "b", "c"}, set(base.instance_attrs))\n'))

Compiling /tmp/pip_build_root/astroid/astroid/tests/ ...
SyntaxError: ('invalid syntax', ('/tmp/pip_build_root/astroid/astroid/tests/', 492, 44, ' self.assertSetEqual({n.__class__ for n in xxx.infered()},\n'))

Compiling /tmp/pip_build_root/astroid/astroid/tests/ ...
SyntaxError: ('invalid syntax', ('/tmp/pip_build_root/astroid/astroid/tests/', 248, 41, " {os.path.join(package, x) for x in ['', '', '', '', '']})\n"))

Compiling /tmp/pip_build_root/astroid/astroid/tests/ ...
SyntaxError: ('invalid syntax', ('/tmp/pip_build_root/astroid/astroid/tests/', 556, 39, " expected_methods = {'__init__', 'class_method', 'method', 'static_method'}\n"))

Running install for logilab-common
/usr/lib64/python2.6/distutils/ UserWarning: Unknown distribution option: 'test_require'
package init file './test/' not found (or not a regular file)
package init file './test/' not found (or not a regular file)
changing mode of build/scripts-2.6/pytest from 644 to 755
package init file './test/' not found (or not a regular file)
Installing /usr/lib/python2.6/site-packages/logilab_common-0.63.2-py2.6-nspkg.pth
changing mode of /usr/bin/pytest to 755
package init file './test/' not found (or not a regular file)
Successfully installed pylint astroid six logilab-common unittest2 argparse
Cleaning up...
krice4@graph301p:~$ dir
Thinking this would be good, I did the normal first-use invocation:

[esm@graph301p:bin]$ pylint
Traceback (most recent call last):
  File "/usr/bin/pylint", line 11, in
  File "/usr/lib/python2.6/site-packages/pylint/", line 22, in run_pylint
    from pylint.lint import Run
  File "/usr/lib/python2.6/site-packages/pylint/", line 585
    control_pragmas = {'disable', 'enable'}
SyntaxError: invalid syntax
[esm@graph301p:bin]$ dir

No joy.  Thinking my install failed, I turned to the intertubewebs and found that the Pylint people decided to not support Python 2.6 anymore.  It's apparently a Python 2.7 game only now.

I found out from here:

Not to worry, though, pychecker still works.

Sunday, November 30, 2014

Python Coding Best Practice Guide - Practical Goodness (prevent over-smart show-offs from killing your project)

Over the last 8? 9? years of coding in Python, I've had to deal with code written by a variety of people:

  • Some of these people were very good at coding so I could quickly understand what they were doing and modify it as needed.
  • Some of these people were very smart.
  • These two groups overlapped only haphazardly.

My definition of good code is stuff that the average joe programmer, maybe 2 years out of a C.S. degree or so (or the equivalent industry experience), can understand quickly and modify to meet the business-demand of the moment.

Bad code is that which has to be read, re-read, analyzed, tried out interactively to see how parts work, analyzed again, and drawn out with data-flow diagrams because it requires a lot of brainpower to hold all of the parts in your head at once.

Maybe I'm not that smart. Maybe I am. I like to think I'm smart. But, when it's 2 am and I have to figure something out Right Now to make it work before I can go back to sleep, or if I'm really working on a giant project and I only have an hour or so to make a small mod someone wants - that's not when I want to be analyzing something to trace back where the problem is.

Back 15 years ago, when I was full-time coding in C (or C++, somewhat rarely), I had a whole list of things that I thought the designers of C, Kernigan and Richie, got wrong. I still remember some of that list. But, the important part is the adage:

Just because you CAN do a thing doesn't mean you SHOULD do a thing.

In C, the verboten (or at least things I avoided) included:

  • extensive use of #define and #ifdef for things other than constants and MAX functions. Smart people show off and write complex crap.
  • unions. Yes, unions. You could declare a struct that has an alternate layout as a union, and switch between the two. It's ripe for stupidity.
  • lots of mallocs and frees. I put everything I could on the stack because if there was an exit path I missed, that memory wasn't getting freed anytime soon.
  • ...etc.

Some of this translates below into Python. I think the corollary to IFDEF in Python is decorators. You're doing the same thing - putting all sorts of logic into a wrapper. That is, you have to figure out the wrapper before they can figure out your code. if it's simple, great, go ahead. If not, you're shooting the person who comes after you.

Some decorators are golden - @property and @classmethod are great, no problem there because you can create getters/setters quickly and singletons, etc. But, a frequent example is something like, @deprecated which writes a lot message with the call stack before turning around and calling the function. BUT, it's just as easy to insert a function call at the top of the function, something like, GlobalCallDeprecated() which does the same thing. When a function works, why use a decorator? People like to show off how smart they are. Whup-tee-do, great, you're smart, so am I, get over it and write something I don't have to spend time figuring out.

With that in mind: Below is the list we're using here at (Large.Fortune-50.Company.Infrastructure.Dept.). This department generates graphs, thus the references to 'graph' boxes.

1.  pep-8
2.  use 4-space indentation.  Anyone touching code should use reindent to fix this.
    There is a program called 'reindent' available on all graph boxes.  it rewrites the file with 4 space indent.
3.  spacing (pep-8) is important, once space around equals in assignment, but none in calls:
    a = 5
    self.runThis(5, 6, abc=12)
4.  run pychecker on all code
        * alias pychecker="pychecker --limit=9999"
        * some unused vars are okay
5.  MOST except the shortest sets of code should be in classes that do nothing but can be invoked from a test.
    MOST outer scope routines should contain try/except blocks.
    When creating something that produces multiple outputs (measurements, for example), each set of measurements
      should be created in a separate try/except block, so a failure in one area does not lead to total failure.
    MOST classes should start with a capital letter, e.g., CamelCase.
    MOST modules should start with a lowercase letter, e.g.,
    MOST module globals should be all caps with underscores, e.g., ALL_CAPS
    MOST methods should be lowercase first letter, e.g., camelCase() or camel_case()
    Slight preference for camelCase vs. under_scored var and method names, but both are okay.
    VERY FEW global variables should be used, if any, and all should be at the top of a file.
    Globals should be used in the init so they can be overriden by tests and other code.
    Filenames and/or explicit paths should be at the top, as globals, so they can be found / changed easily.

    import this
    import traceback


    class Something(object):

        def __init__(self, logger=None):
            if logger:
                self.log = logger
            self.var1 = 'c'
            self.var2 = 'ff'
            self.veryFewGlobals = VERY_FEW_GLOBALS

        def blah1(self, instr):
            instr += 'a'
            self.var1 = instr

        def blah2(self, instr):
            instr += 'b'
            self.var1 = instr

        def main(self):
  "starting.")  #whatever
                x = 'abc'
                self.var2 = self.blah2(x)
                self.var1 = str(self.var1) + ''
            except Exception, e:
                tb = traceback.format_exc()
                self.log.error("Something.main(): Exception: e: %s, tb: %s" % (e, tb))

    if __name__ == '__main__':
        s = Something()

6.  All code should have at least two tests: a trivial test, and an instantiation test.
    Tests should be in a file named in a subdirectory tests.
    Monkey-patch / duck-punch methods to reduce and simplify the test.

    # for one test, run:  nosetests metricType:TestMetricType.test_simpleRetrieve
    class TestSomething(unittest.TestCase):

       def test_trivial(self):
           return True

       def test_instantiate(self):
           s = Something()
           assert s

       def test_blah1(self):
           s = Something()
           s.var1 = 'ddd'
           assert s.var1 == 'abcab'

       def myroutine(self, instr):
           something = {
               'metricType'  : 'poweriq',
               'metric'      : metricName,
               'timestamp'   : timestamp,
               'value'       : value,
               'context'     : context,

3.  Function calls with lots of parameters should not be indented to the max level - it makes for
    lots of whitespace, all the code on the right side of the screen, too-long lines, etc.

    # BAD - discouraged.
    someVarNameHere = self.callingFunctionNowHere(exceptionallyLongVarName=1,
    someVarNameHere = self.callingFunctionNowHere(

    someVarNameHere = self.callingFunctionNowHere(exceptionallyLongVarName=1,
        additionallyLongExceptionallyLongVarName=4, somethihng=5 )

14. Comments added to the end of multiple lines are discouraged:

    # BAD - Discouraged
    var1 = self.callingSomethingHere(12)   # ESOC-123334
    var2 = self.callingSomethingHere(14)   # ESOC-123334

    # Preferred:

    # added for ESOC-123334:
    var1 = self.callingSomethingHere(12)
    var2 = self.callingSomethingHere(14)

15. Exceptionally long quotes should use the triple-quote concept to prevent problems with
    escaping quotes:

    x = ''' very long
        lines go here and
        continue at indentations
        presuming that's not a problem.

16.  It is generally quite possible to avoid line-continuation characters.
     Generally, long lines end up being inside a list.
     As with the above function calls with many params, just open the paren
     and keep adding variables.

17.  Line length limits of 80 or even 120 characters are far less than the width of our
     modern screens.  However, some limit should apply since the eye has a hard time aligning
     to very, very long lines.
     There's no hard/fast limit, it's up to us individually, but 150 characters is probably a good limit
     except in very unusual circumstances.

18.  Logging lines should start with the name of the routine, so we know where the line came from."someRoutine():  started routine to figure out blah.")

19.  Libraries incorporated into other programs should have the class name also."sendReconEvent.connect(): connected to %s" % (pformat(self.destination)))

20.  Getting command line options should always be its own routine.
     This is because test cases cannot parse or understand parseOptions.  Example:

     # pulled out so can be overridden in test routines, e.g., m.getOptionParser = lambda x: None
     def getOptionParser(self):
         return OptionParser()

     def getOptions(self):
         parser = self.getOptionParser()
         parser.add_option("-d", "--debug",   action="store_true", dest="debug",   default=False, help="debug mode for this program, writes debug messages to logfile." )
         parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=False, help="verbose mode for this program, prints a lot to stdout." )
         parser.add_option("-p", "--processes", action="store", type="int", dest="processes", default=10, help="number of processes to run.")
         (options, args)             = parser.parse_args()
         self.verbose                = options.verbose
         self.debug                  = options.debug
         self.numProcesses           = options.processes
         if (self.verbose):
             print "verbose=%s, debug=%s, processes=%s" % (self.verbose, self.debug, self.numProcesses)

21.  Except in test routines and sorts, the use of lambda functions is strongly discouraged.  Example:
     return [lambda x, i=i : i * x for i in range(5)]   # WTF? What does it do? Tested: [x(2)for x in f]=>[0,2,4,6,8] Why? Dafuq?

22.  In general, the use of yield is troublesome and should be avoided except when strongly needed.
     Especially grievous is the use of multiple yield statements in one method / function, since tracing
     code execution paths with this is vastly nasty.

23.  In code, avoid the use of 'from blah import *' for many, many, many reasons.  Most proximate:  pychecker can't check the code now.

24.  Decorators:
     * Writing custom decorators is strongly discouraged as it obfuscates code.  
     * Generally acceptable decorators are ones that are included in standard libraries (incl. Django)
     * Decorators should be used as tools, not as weapons of mass confusion.

25.  Any but the most simplistic use should be avoided of the following:
        * getattr and setattr methods

26.  The overall architectural goal of all scripts should be SIMPLICITY of code readability by zombies (the on-call guy at 3 am). 
     This is versus other considerations like execution speed, code size, 'elegance', etc.

27.  No file or class should be named the same as any standard library method.

28.  No variables anywhere should be named with reserved words or the names of standard libraries.  Examples:
     type = 'a'
     resource = 'Something'
     int = 7
     long = True
     path = 'blah/blah1'   # os.path is common, sometimes people do 'from os import path' and then you're in trouble.

29.  The use of **args is discouraged.  It is way too easy to mess up.  It has to be called exactly correctly and used
     within a method exactly correctly.  That is, calls with foo(context) are bad but easy, must do foo(**context) instead,
     but you will not get an error message

     #So, instead of:
     context = { foo: 7, bar: 8, baz: 10 }
     someClassInstance.funcOne(baz=6, **context)
     def funcOne(baz=8, bar=9, **args):
         # magic happened, baz is 6 or 10, but probably not 8.  Good luck.

     # do this, it's utterly obvious even at a glance:
     miscVals = { foo: 7, bar: 8 }
     someClassInstance.funcOne(baz=8, context=miscVals)
     def funcOne(baz=8, bar=9, context={}):
         if baz != 8 and context.get('baz', None):  print "WHICH ONE?"
         baz = context.get('baz', None) or baz
         bar = context.get('bar', None) or bar

30.  To close db handles, instead of __del__ use atexit.register() as in:

     import mysql
     import atexit
     class Bar(object):
         def __init__(self):
             self.dbHandle = mysql.openConnection(...) # or something
         def cleanup(self):
                 print "db handle closed."
                 print "FYI, db close failed."

31.  Additional rules:
     with the exception of using lambdas, map, and filter.

32.  In a perfect world, we clean up our code to bring it to clarity and obviousness right away.
     Short of that, we should endeavor to clean up our code any time we touch it.
     This includes making scripts use classes and adding a file with a couple of tests in it.
     Before committing, we should always run pychecker.

33.  Functions and methods should not be absurdly long.  
     If they are too long, they should be broken up.
     A handy library for reducing method size is counterStats which allows obj=CounterStats(['x']); obj.x = 5 coding.

Thursday, September 04, 2014

SOLVED: MongoDB - Pymongo ConnectionFailure: function takes at most 4 arguments (5 given)

I was getting this odd message, leading to pymongo fail the Connection() and MongoClient() instantiation.  No connection?  Really?  Getting this message:

[user@boxnamehere:logs]$ python
Python 2.6.6 (r266:84292, Jul 20 2011, 10:22:43)
[GCC 4.4.5 20110214 (Red Hat 4.4.5-6)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from pymongo import MongoClient
>>> mc = MongoClient('', 11222)
Traceback (most recent call last):
  File "", line 1, in
  File "/usr/lib64/python2.6/site-packages/pymongo/", line 369, in __init__
    raise ConnectionFailure(str(e))
pymongo.errors.ConnectionFailure: function takes at most 4 arguments (5 given)

So, what's wrong?  It's tough to find out.  I went in, backed-up and modified the files in the lib64/python2.6/site-packages/pymongo and bson/ dirs.  I imported traceback, added tb=format_exc() to each level of the try/except needed.  This gave me a really long traceback but at least I could see what was happening.

Once modified, my test program now produces:

user@boxname:~$ ./
Traceback (most recent call last):
  File "./", line 5, in
    mc = MC(host='', port=11222, socketTimeoutMS=15000)
  File "/usr/lib64/python2.6/site-packages/pymongo/", line 373, in __init__
    raise ConnectionFailure(msg)
pymongo.errors.ConnectionFailure: function takes at most 4 arguments (5 given) Traceback (most recent call last):
  File "/usr/lib64/python2.6/site-packages/pymongo/", line 867, in __find_node
    member, nodes = self.__try_node(candidate)
  File "/usr/lib64/python2.6/site-packages/pymongo/", line 714, in __try_node
    {'ismaster': 1})
  File "/usr/lib64/python2.6/site-packages/pymongo/", line 695, in __simple_command
    response = helpers._unpack_response(response)['data'][0]
  File "/usr/lib64/python2.6/site-packages/pymongo/", line 117, in _unpack_response
TypeError: function takes at most 4 arguments (5 given)
, Traceback (most recent call last):
  File "/usr/lib64/python2.6/site-packages/pymongo/", line 367, in __init__
  File "/usr/lib64/python2.6/site-packages/pymongo/", line 936, in _ensure_connected
  File "/usr/lib64/python2.6/site-packages/pymongo/", line 807, in __ensure_member
    member, nodes = self.__find_node()
  File "/usr/lib64/python2.6/site-packages/pymongo/", line 900, in __find_node
    raise AutoReconnect(', '.join(errors))
AutoReconnect: function takes at most 4 arguments (5 given) Traceback (most recent call last):
  File "/usr/lib64/python2.6/site-packages/pymongo/", line 867, in __find_node
    member, nodes = self.__try_node(candidate)
  File "/usr/lib64/python2.6/site-packages/pymongo/", line 714, in __try_node
    {'ismaster': 1})
  File "/usr/lib64/python2.6/site-packages/pymongo/", line 695, in __simple_command
    response = helpers._unpack_response(response)['data'][0]
  File "/usr/lib64/python2.6/site-packages/pymongo/", line 117, in _unpack_response
TypeError: function takes at most 4 arguments (5 given)

So, we see the problem is that the Pymongo version is calling, at about line 85 of /usr/lib64/python2.6/site-packages/pymongo/

result["data"] = bson.decode_all(response[20:],
                                  as_class, tz_aware, uuid_subtype,

But, when I go into /usr/lib64/python2.6/site-packages/bson/ I see function defined differently:

def decode_all(data, as_class=dict,
               tz_aware=True, uuid_subtype=OLD_UUID_SUBTYPE):
    """Decode BSON data to multiple documents.

So, I could fix this in the bson code, by adding an optional param.

Instead, though, I'm going to just remove the extraneous param since I'm thinking I don't need it.

Changeset: One file modified: /usr/lib64/python2.6/site-packages/pymongo/

[user@server:pymongo]$ diff
<                                      as_class, tz_aware, uuid_subtype
<                                     )
>                                      as_class, tz_aware, uuid_subtype,
>                                      compile_re)


Turns out, the problem isn't  with the code in pymongo.  It's that MongoDB Corp. has chosen to bundle their own version of the 'bson' package in with pymongo, and that version doesn't engage in happy-kindergarden-play with the pypy version of bson.

So, to fix this, do the following (omitting the $ prompts so you can cut and paste).  Note important steps of NOT BELIEVING PIP that it really uninstalled everything:

sudo pip uninstall bson
sudo pip uninstall pymongo
cd /usr/lib64/python2.6/site-packages
# Now, remove old versions of pymongo and bson.  Pip doesn't delete everything, dammit.
sudo rm -rf bson pymongo*
sudo pip install pymongo

Done!  Pymongo installs its own, proper version of bson.

Restart your processes and re-run your tests, it should work now.  Pymongo will connect to your mongo cluster properly, etc.

Note that the above problem occurs especially frequently if the box is under heavy load because (as we noted above) the initial connection raised an AutoReconnect. 

Enjoy your newfound powers in peace and with goodwill towards all.

Tuesday, September 02, 2014

SOLVED: Skype crashes on startup on Ubuntu 14.04

Just had a problem with Skype crashing immediately upon startup on my Ubuntu 14.04 box (as of Sept. 2, 2014).  This was an unexpected, sudden, and seemingly a random failure.

Skype would startup with the blue skype starting screen, open the contacts window for several seconds, then the window would close with no message.

Needing a message, I invoked from the command line and saw messages:

me@boxname:~/.Skype$ skype
Gtk-Message: Failed to load module "overlay-scrollbar"
Gtk-Message: Failed to load module "unity-gtk-module"
(skype:3825): Gtk-WARNING **: Unable to locate theme engine in module_path: "murrine",
(skype:3825): Gtk-WARNING **: Unable to locate theme engine in module_path: "murrine",
... bunch of these ...

(skype:3825): Gtk-WARNING **: Unable to locate theme engine in module_path: "murrine",
(skype:3825): Gtk-WARNING **: Unable to locate theme engine in module_path: "murrine",
Gtk-Message: Failed to load module "canberra-gtk-module"
Corrupt JPEG data: 3014 extraneous bytes before marker 0xd9
Aborted (core dumped)

Found this set of directions:

Worked perfectly.

me@boxname:~$  cd
me@boxname:~$ tar -czf ~/.Skype
me@boxname:~$ sqlite3 ~/.Skype/
SQLite version 3.8.2 2013-12-06 14:53:30
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> select * from Messages where type = 68;
... bunch of crap here ...

sqlite> select count(*) from Messages where type = 68;
sqlite> quit
me@boxname:~$ skype
... same error messages as above, without the last one about 'Aborted (core dumped)'.

Thursday, August 28, 2014

SOLVED: diff 2 files, get results without markup

So, I want do a logrotate and remove files that are old, keeping only the latest 3 files.  So, script starts with:

$ fullLoglist="/tmp/full_loglist"
$ keepLoglist="/tmp/keep_loglist"
$ rmLoglist="/tmp/rm_loglist"

$ ls -lrt ${d}/rs*log* > ${fullLoglist}

First, I create a file with all the files listed:

$ cat ${fullLoglist}

I only want the top 3 files, though, and to rm the older ones.  So, I extract the ones I want to keep:

$ cat ${fullLoglist} | head -3 > $keepLoglist
$ cat $keepLoglistgraphdb_1j/rs-47-a/rs-47-a.log

Now, I need to get a diff of the rest of them so I know what to call rm on.  But how?  If I just do a diff, I get:

$ diff /tmp/full_loglist /tmp/keep_loglist
< graphdb_1j/rs-47-a/rs-47-a.log.2014-08-27T14-48-44
< graphdb_1j/rs-47-a/rs-47-a.log.2014-08-27T15-14-35
< graphdb_1j/rs-47-a/rs-47-a.log.2014-08-27T15-35-11
< graphdb_1j/rs-47-a/rs-47-a.log.2014-08-27T19-48-56
< graphdb_1j/rs-47-a/rs-47-a.log.2014-08-28T13-44-21

I DON'T WANT the extra markup.  I want diff without markup.  I try to google:

linux diff without markup
linux diff without greater-than less-than
linux diff line format markup
linux diff supress markup
linux diff only different lines

I try various options, like:

$ diff --line-format "%L" --suppress-common-lines /tmp/full_loglist /tmp/keep_loglist

This is WRONG, it prints all the lines, not just the different ones. Ug. 

SOLUTION ONE:  comm -3

I found two solutions.  The first is to use comm, and pass a -3 option.  This prints just the different lines.  I hadn't ever heard of comm before, but it's nice:

$ comm -3 /tmp/full_loglist /tmp/keep_loglist

SOLUTION TWO:  sort | uniq -u

I don't care about the ordering of these things.  So, I can use the simple solution of sort and uniq -u.  The uniq command normally prints all unique lines, removing duplicates.  But, an option is -u, which only prints lines that occur once-and-only-once.

$ cat /tmp/full_loglist /tmp/keep_loglist | sort  | uniq -u

SOLVED!   No >, no < signs with diff and no line number markup.

Script to implement this process, for your edification:


cd /opt/storage
dirlist=`ls -d graphdb_[1234][ij]/rs-*`

for d in $dirlist
  echo "---------------------------"
  echo "dir: ${d}"
  ls ${d}/rs*log* > ${fullLoglist}
  ls -al ${fullLoglist}
  echo "full files: `cat ${fullLoglist}`"
  cat ${fullLoglist} | head -3 > $keepLoglist
  echo "keep files: `cat ${keepLoglist}`"
  cat $keepLoglist $fullLoglist | sort | uniq -u > $rmLoglist
  echo "rm   files: `cat ${rmLoglist}`"
  if [ -s $rmLoglist ]
        echo "Removing files...."
        cat $rmLoglist | xargs rm -v
        echo "No files to remove this time."


Tuesday, August 26, 2014

SOLVED: Multiprocess updates of shared dict-of-dicts

Earlier, I posted the following:

I've run into my very first bug in Python.  It's a known, existing bug, but it's still the first time I've actually encountered one spontaneously.

I should caveat that I occassionally forget things, and I've been using Python 8 years, so it could be this has happened before but I've forgotten it.

The problem is as follows:

* I'm working in multiple processes, so I'm sharing a data structure across processes.  it's a dict.  So, I do

from multiprocessing import manager
d = manager.dict()

and share the sucker around.  Then, I do:

self.ddict.setdefault(mname, {})
#self.ddict[mname][ts] = val
self.log.error("updating mname: %s w/ ts: %s, val: %s" % (mname, ts, val))
self.log.error("ddict %s, mname at %s" % (self.ddict, self.ddict[mname]))


2014-08-26 11:20:57,221 MainThread ERROR updating mname: a.b.c.d w/ ts: 1409070057, val: 1.0
2014-08-26 11:20:57,221 MainThread ERROR ddict {'a.b.c.d': {}}, mname at {}
2014-08-26 11:20:57,222 MainThread ERROR ddict: {'a.b.c.d' {}}

According to, this is a known bug.  I'm using Python2.6 and cannot upgrade. 

Damnit.  Looking for a workaround.


Problem is that the shared memory 'watcher' manages the data structure and shares around updates to everyone using it. This means that this manager has to know when the data struct is updated in one process and tell the other processes to pull in the updates.

If you're using a dict-of-dicts DOD, the inner dict just looks like a blob that process A changes by direct access to the object, without informing DOD of the change. So, to fix this do:

dod = Manager.dict()
process ONE: dod['a'] = { 'x' : 12 }
# process TWO sees this update of a = x:12
process TWO: dod['a']['x'] = 13
# process ONE has no idea this happened, manager doesn't bring in the update.
# to fix:
process TWO: y=dod['a'];y['x']=13;dod=y
# this informs manager that dod is different.

Wednesday, January 15, 2014

WANTED: Complete List of WhiteHouse.Gov Petitions

I've created a petition on to modify copyright law to prevent copyright of any law enacted in the United States at the Federal, State, and Local level.  This prevents jerk corporations from claiming copyright when someone tries to put the code/law/edict on a webpage.

But, there aren't enough signatures yet.  So I tried advertising to my FB friends.  I have to get to 150 before the petition is visible on the list of open petitions on the website.

That got me thinking:  how do I find all the other petitions that aren't available for viewing yet due to being not-advertised enough?

They provide a short-URL for these petitions.  This shortener probably is incremental.  Mine is  PLEASE SIGN IT and I figure the other petitions might have urls near it.

So, here's my program to find them:



nums1 = [x for x in range(65, 90)]
nums2 = [x for x in range(97, 122)]
nums = []
print nums

with open("/tmp/urls.wh", "w") as OFH:
    for i in nums:
        for j in nums:
            for k in nums:
                for m in nums:
                    OFH.write("\n" % (i, j, k, m))

# wget -a out.log -t 1 --read-timeout=3 --max-redirect 1  --save-headers

No luck yet, it takes a long time to run.

Tuesday, January 07, 2014

Solved: How to install Python ibm_db DB2 driver on RHEL

Solved:  Installing Python's DB2 module (ibm_db) on Linux

Problem 1 I kept getting a message about not having include files installed.  First, I had to get a sysadmin to install the files.  But, he didn't finish the job, quite.  I had to soft link it myself.  That is, the include files are installed by default in /opt/ibm/db2/V10.1, but linked to from /opt/db2inst/sqllib.  So:
$ sudo ln -s /opt/ibm/db2/V10.1/include /opt/db2inst/sqllib/include
That solved the include problem.

Problem 2I was installing IBM's DB2 python driver on a RHEL 6.2 linux box, but I kept getting the message:
Detected 64-bit Python
Environment variable IBM_DB_HOME is not set. Set it to your DB2/IBM_Data_Server_Driver installation directory and retry ibm_db module install.
This was despite executing the userprofile script in /opt/db2inst/sqllib/userprofile, which set the environment vars properly: 
xxxxx@xxxxxx:~/making/ibm_db-$ env | egrep -i ibm
Dammit!  I couldn't get past this.  I tried both
  • sudo easy_install ibm_db 
  • sudo pip install ibm_db
This was to no avail.  I even tried putting the whole thing in a bash script and doing the export IBM_DB_LIB stuff there.  Again, failure.

Finally, I downloaded the source and did the python build, which worked, so I was halfway there.  Then, I had to do the sudo install (since it was to be installed in system directories):  Failure (with above message about missing IBM_DB_HOME environment variable).  But, I could do the env and see the vars there!  So, since I'm doing this from source, I edited and put a pprint in, showing the os.envoron.  This made it obvious.  It showed I was executing as sudo, so as root, and root didn't have the userprofile being executed, so not var was being set.

Quick:  "man sudo" !!

SOLUTION:  It shows that to do this right, you must invoke sudo with -E to keep the environment variables from the current environment.
$ sudo -E python install
Hurray!  Installed!