Sign Up

Sign In

Forget Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

You must login to ask question.

Calling an external command from Python

  • 0

How do you call an external command (as if I’d typed it at the Unix shell or Windows command prompt) from within a Python script?

Click to rate this post!
[Total: 0 Average: 0]
Share This Post
Share
  1. Look at the subprocess module in the standard library:

    import subprocess
    subprocess.run(["ls", "-l"])

    The advantage of subprocess vs. system is that it is more flexible (you can get the stdoutstderr, the “real” status code, better error handling, etc…).

    The official documentation recommends the subprocess module over the alternative os.system():

    The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function [os.system()].

    The Replacing Older Functions with the subprocess Module section in the subprocess documentation may have some helpful recipes.

    For versions of Python before 3.5, use call:

    import subprocess
    subprocess.call(["ls", "-l"])
    • 0
Leave an answer

Leave an answer

Browse

close