CALLING AN EXTERNAL COMMAND IN PYTHON

Andrew Watson

Total Post:39

Points:273
Posted by  Andrew Watson
Python 
 738  View(s)
Ratings:
Rate this:
How can I call an external command (as if I'd typed it at the Unix shell or Windows command prompt) from within a Python script?
  1. Mayank Tripathi

    Post:397

    Points:3117
    Re: Calling an external command in Python

    Look at the subprocess module in the stdlib:

    from subprocess import call
    call(["ls", "-l"])

    The advantage of subprocess vs system is that it is more flexible (you can get the stdout, stderr, the "real" status code, better error handling, etc...). I think os.system is deprecated, too, or will be:

    http://docs.python.org/library/subprocess.html#replacing-older-functions-with-the-subprocess-module

    For quick/dirty/one time scripts, os.system is enough, though

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!