Python

  1. Home
  2. Computing & Technology
  3. Python

Python Blog

From Al Lukaszewski, for About.com

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
To affect the first, the best known solution is to use SWIG (Simplified Wrapper and Interface Generator). The latter can be affected with the 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.

Comments

No comments yet. Leave a Comment

Leave a Comment

Line and paragraph breaks are automatic. Some HTML allowed: <a href="" title="">, <b>, <i>, <strike>

Explore Python

About.com Special Features

Python

  1. Home
  2. Computing & Technology
  3. Python

©2009 About.com, a part of The New York Times Company.

All rights reserved.