Search code examples
pythonmongodbpython-3.xcmdmongoimport

Python: navigate to directory, and insert command line on cmd window inside Python


I've read the documentations that other stackoverflow posts provided, but I couldn't understand what they are saying.

Here is what I want to achieve: I want to navigate to a specific directory that contains a specific executable file, and insert a command line.

So,

.\> cd C:\Program Files\MongoDB\Server\3.4\bin
C:\Program Files\MongoDB\Server\3.4\bin> mongoimport -h <IP_ADDRESS> -d <DB> -c <COLLECTION> -u <USER> -p <PASSWORD> --drop --file C:\data.txt  

I need a code will perform the two lines of code above inside Python. In .\3.4\bin directory, there is an executable file called 'mongoimport.exe'. And on the SAME LINE, I need to insert additional sentences to specify the external server I want to access.

How can this be done?


Solution

  • You can use subprocess like:

    from subprocess import run
    
    run(["C:\\Program Files\\MongoDB\\Server\\3.4\\bin\\mongoimport.exe",  "-h", "<IP_ADDRESS>", "-d", "<DB>", "-c", "<COLLECTION>", "-u", "<USER>", "-p", "<PASSWORD>", "--drop", "--file", "C:\data.txt" ])
    

    It will execute only exe file, if for example you need execute a python file add the executable:

    run(["python.exe", "your_python_file"])
    

    More information