Search code examples
pythonwindowscommand-linemongoimport

How do I pass command to mongoimport using python os.system()? upsertFields has spaces


I am trying to import file into mongoDb.

Python 3.7, mongoimport, windows. It works perfectly with fields without space.

command = '"D:\\Program Files\\bin\\mongoimport.exe" -c _ --mode=merge --upsertFields="Current url",Title -d _  --file="D:\\folder\\folder\\temp.json" --jsonArray'
os.system(command)

Result: 'D:\Program' is not recognized as an internal or external command,

I think it can be related to escaping but don't know exactly.

I've tried

c2 = ["D:\\Program Files\\bin\\mongoimport.exe", '-c _ --mode=merge --upsertFields="Current url",Title -d _ --file="D:\\audiotorah\\audiotorah\\temp.json" --jsonArray']

import subprocess
subprocess.Popen(c2,stdin=subprocess.PIPE,stdout=subprocess.PIPE, bufsize =0)

But it never stops.


Solution

  • To avoid escaping, append an r before the string to make it a raw string.

    Using os.system:

    import os
    
    command = r'"D:\Program Files\bin\mongoimport.exe" -c _ --mode=merge --upsertFields="Current url",Title -d _ --file="D:\folder\folder\temp.json" --jsonArray'
    os.system(command)
    

    Using subprocess.Popen:

    import subprocess, shlex
    
    command = r'"D:\Program Files\bin\mongoimport.exe" -c _ --mode=merge --upsertFields="Current url",Title -d _ --file="D:\audiotorah\audiotorah\temp.json" --jsonArray'
    subprocess.Popen(shlex.split(command), stdin=subprocess.PIPE, stdout=subprocess.PIPE)