Arun Kamath
Arun Kamath

Reputation: 1

'mongoexport' not working when trying to run the command in a Python script

My requirement is to execute the 'mongoexport' command to get the data in mongo db into a csv and then compare it against another csv to identify any exceptions/discrepancies. I am trying to implement this using python 3.6 but am getting "'mongoexport' is not recognized as an internal or external command, operable program or batch file" error.

Below is my code snippet:

import os
import pymongo as mng
import subprocess


connected = False

#Open DB connection
try:
    connection = mng.MongoClient('localhost', 27017)
    db = connection['foo']
    print("I am connected to Mongo DB")
    connected = True
except:
    print("I am not able to connect to Mongo DB")

tgt_count = db.restaurants.count()
path = subprocess.call("dir",shell=True)
subprocess.call("mongoexport --db foo --collection restaurants --type=csv --fieldFile D:/my_mongo/fldlist.txt --out D:/my_mongo/outfile.csv", shell=True)

enter image description here

Note: I am getting this while trying to run in Pycharm IDE.

You can see I have confirmed the location from which the command is running to (path = subprocess.call("dir",shell=True)). After ensuring the dir location I manually ran the same mongoexport command in the Windows command prompt and it worked fine - so the environment variable not being updated properly should not be the issue. Also the call function seems to work as well - Any pointers to what I am doing wrong/missing would be of great help...Please

Upvotes: 0

Views: 2942

Answers (1)

user7818749
user7818749

Reputation:

Put dir in single quotes. Also if you are using the arguments in list form, then remove shell=true. If they are in string form, you can add shell=true

import os
import pymongo as mng
import subprocess


connected = False

#Open DB connection
try:
    connection = mng.MongoClient('localhost', 27017)
    db = connection['foo']
    print("I am connected to Mongo DB")
    connected = True
except:
    print("I am not able to connect to Mongo DB")

tgt_count = db.restaurants.count()
path = subprocess.call('dir',shell=True)
subprocess.call("mongoexport --db foo --collection restaurants --type=csv --fieldFile D:/my_mongo/fldlist.txt --out D:/my_mongo/outfile.csv")

Upvotes: 3

Related Questions