技术小黑屋

Read Output From Shell

Python provides a lot of method to read output from a just executed shell. However many of them has been deprecated(Not recommened). But subprocess works at present compared to other methods.

1
2
3
4
5
6
7
8
9
10
11
12
from subprocess import Popen,PIPE,STDOUT

def readFromCommand(command) :
    p = Popen(command, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
    result = p.stdout.read().strip()
    return result

print readFromCommand('ls')
#result
#0001-.patch
#0001-.patch.zip
#0001-Replace-app_name-into-Browser.patch

A detailed description about subprocess has been written down here. http://docs.python.org/2/library/subprocess.html

Others





快来解锁最新版 Typora,新用户券后仅需 84 元!
如何便宜的购买 office 365 ?
新版赤友 NTFS 助手来袭,正版超低价