如何从python运行命令行

2024-04-26 12:28:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我在终端中运行以下命令:

mongoexport --db database_name --collection agents --type=csv --fieldFile agFieldsTest.txt --out file/path/agTestInfo.csv

我试着用:

>>> import subprocess
>>> subprocess.call(["mongoexport --db database_name --collection agents --type=csv --fieldFile agFieldsTest.txt --out file/path/agTestInfo.csv"])

我得到以下错误:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 524, in call
return Popen(*popenargs, **kwargs).wait()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 711, in __init__
errread, errwrite)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1308, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory

Tags: csvinpyliblinelibraryframeworkcall
1条回答
网友
1楼 · 发布于 2024-04-26 12:28:22

最好的方法是将命令分解为单独的“单词”:

>>> subprocess.call(["mongoexport", " db", "database_name", " collection", "agents", " type=csv", " fieldFile", "agFieldsTest.txt", " out", "file/path/agTestInfo.csv"])

或者,您可以使用shell=True让shell为您执行以下操作:

>>> subprocess.call(["mongoexport  db database_name  collection agents  type=csv  fieldFile agFieldsTest.txt  out file/path/agTestInfo.csv"], shell=True)

相关问题 更多 >