MongoDB 服务器上的数据加载来自 jupyter notebook 但不是来自脚本

Data loading on MongoDB server works from jupyter notebook but not from script

我有一个数据集存储在 json 文件中,我需要将其上传到 MongoDB 服务器。如果我使用 Jupyter notebook 上传数据,一切正常,但如果我使用 python 脚本,则一切正常。代码完全一样。你建议如何解决这个问题?

代码如下:

import pandas as pd
import pymongo
from pymongo import MongoClient
import json
import DNS

# Function to upload the dialogue lines to MongoDB Server
def prepare_dataframe():
    dialogue_edited = pd.read_json("5lines1response_random100from880_cleaned.json")
    dialogue_edited.reset_index(inplace=True)
    data_dict = dialogue_edited.to_dict("records")# Insert collection
    # To communicate with the MongoDB Server
    cluster = MongoClient()
    db = cluster['DebuggingSystem']
    collection = db['MCS_dialogue']
    collection.insert_many(data_dict)
    return collection

if __name__ == '__main__':
    collection = prepare_dataframe()

这是 python 脚本和 jupyter notebook 的屏幕截图。我是 运行 使用 Visual Studio 的笔记本。

替换

if __name__ == '__main__':
    collection = prepare_dataframe()

collection = prepare_dataframe()

并尝试运行您的脚本。 __main__ 解释得很好 here