Python:导航到目录,并在 Python 内的 cmd window 上插入命令行

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

我已经阅读了其他 Whosebug 帖子提供的文档,但我无法理解他们在说什么。

这是我想要实现的:我想导航到包含特定可执行文件的特定目录,然后插入命令行。

所以,

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

我需要一个代码来执行上面两行代码Python。 在.\3.4\bin 目录下,有一个名为'mongoimport.exe' 的可执行文件。并且在同一条线上,我需要插入额外的句子来指定我想要访问的外部服务器。

如何做到这一点?

您可以像这样使用subprocess

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" ])

它只会执行exe文件,例如如果你需要执行一个python文件添加可执行文件:

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

More information