简体   繁体   中英

What is the most acceptable way to manage (i.e. properly terminate) the MongoDB daemon in Python?

I am using a local ("community") version of MongoDB, Python 3, and pymongo.

First, I had been manually starting the MongoDB daemon ( mongod ) in a separate shell and then running my Python script. This script uses pymongo to successfully instantiate the MongoDB client ( mongo ) and interact with my database. When my script terminated, I would manually terminate the daemon by sending the kill command to its PID.

While this is all fine and dandy, the goal of this script is to automate as much as possible. As such, I want to incorporate the starting and terminating of the daemon via script, but it must be asynchronous so as to not keep the main code from running. I tried using subprocess.Popen() , and then a Thread class with the daemon attribute set to true -- yet I still see the mongod process up and running when I call ps after my entire program exits.

Below is the Thread class:

class MongoDaemonThread(object):
    def __init__(self):
        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True
        thread.start()

    def run(self):
        mongo_daemon = subprocess.Popen('/Users/<me>/.mongodb/bin/mongod')
        return mongo_daemon

And here is the function in which I interact with the database:

def db_write(report_list, args):
    # ...
    client = MongoClient()
    db = client.cbf
    # ...
    reports = db.reports
    for report in report_list:
        report_id = reports.insert_one(report).inserted_id
    # ...

What I'm looking to do is the following, all through Python (be it one script or multiple):

  1. enter code
  2. start mongod (asynchronously to rest of code/in background and let it listen for connections from a Mongo client) ( #TODO )
  3. create a Mongo client
  4. interface with my database through said client
  5. terminate the Mongo daemon ( #TODO )
  6. exit code/terminate program

Is threading the right way to do this? If so, what am I doing wrong? If threading is not the answer, what method might you suggest I use instead?

First of all, you shouldn't start the mongod process from python. mongod should be started and stopped from shell. Because database must always be ready for connections. But IF you really want to do it from python, you can still use:

from subprocess import call
call(["mongod","&"])

to start the mongod process.

To end the process:

from subprocess import call
call(["pkill", "mongod","&"])

这个答案 -使用p = Popen() p.terminate()然后使用p.terminate() -似乎正是我想要的。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM