Does python's `os.system` ever throw an exception?
Might the esteemed os.system
of Python fame开发者_StackOverflow throw an exception? If so, which ones?
Short answer: yes:
>>> import os
>>> os.system(None)
TypeError ...
Long answer: look here http://docs.python.org/library/subprocess.html#subprocess-replacements to see how to avoid using os.system
.
On POSIX systems it appears to be a straight pass-through to system()
(listing from Python 2.7.1's posixmodule.c):
static PyObject *
posix_system(PyObject *self, PyObject *args)
{
char *command;
long sts;
if (!PyArg_ParseTuple(args, "s:system", &command))
return NULL;
Py_BEGIN_ALLOW_THREADS
sts = system(command);
Py_END_ALLOW_THREADS
return PyInt_FromLong(sts);
}
os.system
throws a TypeError
if there is not exactly one string argument. If the fork
fails due to resource or ulimit restrictions, it will return -1
. If the argument is not valid in some way (like non-existing command), it will return a high error code. Apart from the aforementioned TypeError
, os.system
does not throw any exceptions.
If you're asking whether it throws an exception when the process you're calling ends with an error, the answer is no, you can call a program with os.system()
, have it error out, and you will never know.
That's why you should use the subprocess
module.
精彩评论