1

I have the following command I run in terminal:

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

I tried to run it using:

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

I get the following error:

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

1 Answer 1

2

The best way is to break up the command into individual "words":

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

Alternatively, you can use shell=True to have the shell do that for you:

>>> subprocess.call(["mongoexport --db database_name --collection agents --type=csv --fieldFile agFieldsTest.txt --out file/path/agTestInfo.csv"], shell=True)
Sign up to request clarification or add additional context in comments.

3 Comments

...with the very important caveats about shell=True being a security risk. See the docs: docs.python.org/2/library/…
Indeed. For the above case where the command line is constant, the security risks are not really exposed.
...but on SO it's always worth making sure those issues are clear, right, both for other users down the road, and in the event that the OP simplified their example (which doesn't appear to be the case here, but...)?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.