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):
- enter code
- start
mongod
(asynchronously to rest of code/in background and let it listen for connections from a Mongo client) (#TODO
) - create a Mongo client
- interface with my database through said client
- terminate the Mongo daemon (
#TODO
) - 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?