Issuing System Commands Within Python
Saturday March 22, 2008
In Python, any other Python program is able to be imported as a module into another Python program - regardless of whether the module being imported is part of the Python library or your own code. As such, it is usually very simple to import pre-written Python code into a new application and not re-invent the wheel. Working with other languages is a bit more challenging, however. Depending on what you need to do, two options are available:
- Interface with the internals of the target language
- Call the other program with the necessary incantation (or flags) to execute it as desired
os module's system function as follows:
>>> import os
>>> os.system('kcalc')
kbuildsycoca running...
Note that this will call kcalc, the KDE calculator program, and will execute it in the foreground -- effectively causing the Python program (here the Python shell) to wait until the program is closed to continue. Naturally, if this is not desired, simply pass it to the background:
os.system('kcalc &')
Then control will return to the Python interpreter once the call is made.