title: Get mongod rs.status() results from a python script
body: <p>For monitoring purposees I try to get the output of the following shell commands but from a python script</p>
  
  <pre><code>:mongo --port 27040
  -&gt; enters mongodb shell
  :rs.status()
  </code></pre>
  
  <p>see image
  <a href="https://i.stack.imgur.com/ee3Rq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ee3Rq.png" alt="mongo command"></a></p>
  
  <p>The result of the command is json that I want to access outside the mongo shell to write it to a file, I can run other command in python using pymongo like:</p>
  
  <pre><code>import json, os  
  # load mongo library
  current_dir = os.path.dirname(os.path.realpath(__file__))
  os.sys.path.append(os.path.join(current_dir, 'pymongo-3.7.1-cp27-cp27m-manylinux1_x86_64.whl'))
  
  from bson import json_util
  from pymongo import MongoClient
  from pymongo.errors import OperationFailure, ConnectionFailure
  
  #connection settings
  port = 27040
  hostname = "localhost"
  #default database used by mongodb
  database = "test"
  
  try:
      # connect to the database
      client = MongoClient(hostname,int(port))
      db = client[database] # select the database
      serverstats = db.command("serverStatus")
      serialized_serverstats = json.dumps(serverstats, default=json_util.default)
      print serialized_serverstats
  except Exception as e:
      print("Unhandled Error is %s" % e)
  </code></pre>
  
  <p>This runs something equal to running db.serverStatus() in the mongo shell.
  But how do I run rs.status() form inside a python script?</p>