![](/img/trans.png)
[英]What is the best way to modify a class attribute (self) using an external/helper file (i.e. module) in Python?
[英]What is the most acceptable way to manage (i.e. properly terminate) the MongoDB daemon in Python?
我正在使用MongoDB,Python 3和pymongo的本地(“社區”)版本。
首先,我一直在一個單獨的shell中手動啟動MongoDB守護程序( mongod
),然后運行我的Python腳本。 該腳本使用pymongo成功實例化MongoDB客戶端( mongo
)並與我的數據庫進行交互。 當腳本終止時,我可以通過將kill
命令發送到其PID來手動終止該守護程序。
盡管這一切都很好,但此腳本的目標是盡可能地自動化。 因此,我想通過腳本合並守護程序的啟動和終止,但是它必須是異步的,以免使主代碼無法運行。 我嘗試使用subprocess.Popen()
,然后使用daemon屬性設置為true
的Thread
類-但是,當我在整個程序退出后調用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(無論是一個腳本還是多個腳本)進行以下操作:
mongod
(與其余代碼異步/在后台,讓它偵聽來自Mongo客戶端的連接)( #TODO
) #TODO
) 穿線是正確的方法嗎? 如果是這樣,我在做什么錯? 如果無法解決線程問題,您可能會建議我使用哪種方法代替?
首先,您不應該從python啟動mongod
進程。 mongod
應該從shell啟動和停止。 因為數據庫必須始終准備好進行連接。 但是,如果您真的想從python做到這一點,仍然可以使用:
from subprocess import call
call(["mongod","&"])
開始mongod
進程。
要結束該過程:
from subprocess import call
call(["pkill", "mongod","&"])
這個答案 -使用p = Popen()
p.terminate()
然后使用p.terminate()
-似乎正是我想要的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.