Why use Python's os module methods instead of executing shell commands directly?
It's faster,
os.system
andsubprocess.call
create new processes which is unnecessary for something this simple. In fact,os.system
andsubprocess.call
with theshell
argument usually create at least two new processes: the first one being the shell, and the second one being the command that you're running (if it's not a shell built-in liketest
).Some commands are useless in a separate process. For example, if you run
os.spawn("cd dir/")
, it will change the current working directory of the child process, but not of the Python process. You need to useos.chdir
for that.You don't have to worry about special characters interpreted by the shell.
os.chmod(path, mode)
will work no matter what the filename is, whereasos.spawn("chmod 777 " + path)
will fail horribly if the filename is something like; rm -rf ~
. (Note that you can work around this if you usesubprocess.call
without theshell
argument.)You don't have to worry about filenames that begin with a dash.
os.chmod("--quiet", mode)
will change the permissions of the file named--quiet
, butos.spawn("chmod 777 --quiet")
will fail, as--quiet
is interpreted as an argument. This is true even forsubprocess.call(["chmod", "777", "--quiet"])
.You have fewer cross-platform and cross-shell concerns, as Python's standard library is supposed to deal with that for you. Does your system have
chmod
command? Is it installed? Does it support the parameters that you expect it to support? Theos
module will try to be as cross-platform as possible and documents when that it's not possible.If the command you're running has output that you care about, you need to parse it, which is trickier than it sounds, as you may forget about corner-cases (filenames with spaces, tabs and newlines in them), even when you don't care about portability.
It is safer. To give you an idea here is an example script
import os
file = raw_input("Please enter a file: ")
os.system("chmod 777 " + file)
If the input from the user was test; rm -rf ~
this would then delete the home directory.
This is why it is safer to use the built in function.
Hence why you should use subprocess instead of system too.