【问题标题】:What is the most acceptable way to manage (i.e. properly terminate) the MongoDB daemon in Python?在 Python 中管理(即正确终止)MongoDB 守护进程的最可接受的方法是什么?
【发布时间】:2018-12-22 05:13:54
【问题描述】:

我正在使用本地(“社区”)版本的 MongoDB、Python 3 和 pymongo。

首先,我在单独的 shell 中手动启动 MongoDB 守护程序 (mongod),然后运行我的 Python 脚本。此脚本使用 pymongo 成功实例化 MongoDB 客户端 (mongo) 并与我的数据库交互。当我的脚本终止时,我会通过将kill 命令发送到它的PID 来手动终止守护进程。

虽然这一切都很好,但这个脚本的目标是尽可能地自动化。因此,我想通过脚本合并守护进程的启动和终止,但它必须是异步的,以免主代码无法运行。我尝试使用subprocess.Popen(),然后使用Thread 类,其守护程序属性设置为true——但当我在整个程序退出后调用ps 时,我仍然看到mongod 进程启动并运行。

下面是Thread 类:

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

这是我与数据库交互的函数:

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
    # ...

我希望通过 Python 执行以下操作(无论是一个脚本还是多个):

  1. 输入代码
  2. 启动 mongod(异步到其余代码/在后台,让它监听来自 Mongo 客户端的连接)(#TODO)
  3. 创建一个 Mongo 客户端
  4. 通过所述客户端与我的数据库交互
  5. 终止 Mongo 守护进程 (#TODO)
  6. 退出代码/终止程序

线程是正确的方法吗?如果是这样,我做错了什么?如果线程不是答案,您建议我改用什么方法?

【问题讨论】:

    标签: python multithreading mongodb pymongo daemon


    【解决方案1】:

    首先,你不应该从 python 启动mongod 进程。 mongod 应该从 shell 启动和停止。因为数据库必须始终准备好连接。但是如果你真的想用 python 来做,你仍然可以使用:

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

    启动mongod 进程。

    结束进程:

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

    【讨论】:

    • 在未来,我们将把守护进程的启动迁移到别处,但是对于这个“模拟”任务,因为数据库是为这个唯一的目的而创建的,并且只能通过这个进行交互一个程序,我想把所有东西都捆绑在 Python 中。 (我想我可以编写一个包含所有内容的 bash 脚本,但我已经有一个 Python 脚本可以调用我多次讨论过的脚本,我觉得我让事情变得不必要地复杂了。)那据说...使用call(["mongod"])和call(["pkill", "mongod"])返回错误。
    • 另外,根据this SO post ...subprocess.call()会“运行args描述的命令,等待命令完成,然后返回returncode属性。”我确实不想等待命令完成。
    • @jiccan 我忘了在每个命令后加上&amp;。已更正。
    【解决方案2】:

    This answer -- 使用p = Popen() 然后p.terminate() -- 似乎正是我想要的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-09
      • 2017-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多