How to Get Output From a Shell Command in Python

The Python programming language comes with an extensive library of modules. You can use the "subprocess" module and its included functions to send shell commands to the operating system, and gather the output for use in your Python script.

Instructions

    • 1

      Import the "subprocess" module into your script:

      >>>import subprocess

    • 2

      Create a command string to give to the "Popen" function. The command string may consist of a single command within a single string. It can consist of a list of strings representing a command an a series of arguments:

      >>>command = 'ps'

    • 3

      Call the "Popen" function and assign its output to a variable. The Popen function will take the command, run it in a command shell, and return the results to the Python script:

      >>>p = subprocess.Popen(command) //runs the shell command to display active processes
      20744 ttys000 0:00.01 -bash
      20747 ttys000 0:00.16 python

Related Searches:

References

Comments

Related Ads

Featured