Tuesday, April 15, 2008

Executing a Command in a Subshell

In Python 2.5, executing a command in a sub-shell is easy. Import the os module and use the function system. Here is an example, assuming we are in a Linux environment:

import os

os.system('ls')


The output will be the file and directory listing from the ls command.


This can also be used to execute another python script, assuming the script calling the os.system function is in the same directory as the python script that will be called.

import os

os.system('python example.py')


The script example.py will execute as if it was called on the command line.