我想你知道你喜歡修改哪個集合。如果你這樣做,你可以添加集合作爲你的命令的另一個參數:
之後,你可以通過使用sys.argv或專門編寫用於解析命令行參數的庫來獲取命令行參數。 python 3標準庫包含argpase(https://docs.python.org/3/library/argparse.html)。不過,我建議使用點擊(http://click.pocoo.org/5/)。
另存爲cli.py以下
import click
from pymongo import MongoClient
MONGOHOST = 'localhost'
MONGOPORT = 27017
@click.command()
@click.option('--db', help='Database', required=True)
@click.option('--col', help='Collection', required=True)
@click.option('--build_type', help='Build Type', required=True)
@click.option('--status', help='Status', required=True)
def update(db, col, build_type, status):
mongocol = MongoClient(MONGOHOST, MONGOPORT)[db][col]
mongocol.insert_one({'build_type': build_type, 'status': status})
# You could also do: mongocol.find_and_modify() or whatever...
if __name__ == '__main__':
update()
然後運行像這樣的命令:
python cli.py --db=test --col=test --build_type=staging --sta
tus=finished
請確保您有pymongo並點擊安裝:
pip install pymongo click
感謝的人。得到它的工作。 – user3504250