python learning - use subprocess to get command line output

  Version used here: Python2 >= 2.7

  For getting the output in the command line window python has a nice module: subprocess

  Two simple examples:

  1. Get the output of the ping command:

from subprocess import *

host = raw_input('Enter a host address:')

p = Popen(['ping', '-c5', host],
          stdin=PIPE,
          stdout=PIPE,
          )
p.wait()
out = p.stdout.read()

print out

   Here's what I've been using before:

p = Popen(['ping', '-c5', host],
          stdin=PIPE,
          stdout=PIPE,
          stderr=PIPE,
          shell=True
          )

   But I can't get any output when I write it like this:

  The reason is the official reminder: If shell is True, the specified command will be executed through the shell.

  So just remove it:

  2. Get disk information:

# -*- coding:utf-8 -*-

from subprocess import *

p = Popen('df -Th',
          stdout=PIPE,
          stderr=PIPE,
          shell=True
          )
p.wait()
out = p.stdout.read()

print out

   You can see that shell=Ture is used again. If it is not used here, an error will be reported. The example comes from: https://www.cnblogs.com/yyds/p/7288916.html

  References:

    1.https://docs.python.org/2/library/subprocess.html

    2.https: //www.cnblogs.com/yyds/p/7288916.html

    3.https://blog.csdn.net/sophia_slr/article/details/44450739

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326217998&siteId=291194637