Shell command

Donn Cave donn at
Tue Feb 12 18:31:58 CET 2002

Quoth "DelPiccolo Ivano" <ivano.delpiccolo at>:
| How can I do to launch a command in my python script ?
| example : I want to launch the command : rm test.txt

The handful of people who have already recommended
os.system('rm test.txt') are correct, and os.unlink('test.txt')
too.  But if you really wanted to execute something more like
'rm %s' % file - in other words, your command parameters are
determined partly at run time - then there's a grave risk with
os.system(), and you should consider os.spawnv() instead.

The problem is that os.system invokes the UNIX shell, which
interprets the command, and any shell punctuation that happens
to get into your data can radically change the command.  This
is particularly important when the data comes from some external
source, such as user input.

exitcode = os.spawnv(os.P_WAIT, '/bin/rm', ['rm', 'text.txt',])

Another advantage is that you'll get the exit code's integer
value, instead of a bit mask that has to be analyzed to get
that value.  0 is success, anything else is failure (and a
negative number is the terminating signal.)  And it doesn't
invoke the shell, so it ought to be more efficient.

	Donn Cave, donn at

More information about the Python-list mailing list