python3
代码语言:javascript复制import subprocess
def cmd(cmdstr):
return subprocess.check_output(cmdstr, shell=True)
python2
代码语言:javascript复制import commands
commands.getoutput('ls /bin/ls')
如果需要实时看进度(比如ping):
代码语言:javascript复制import subprocess
def cmd(cmdstr):
ps = subprocess.Popen(cmdstr, stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
while True:
data = ps.stdout.readline()
if data == b'':
if ps.poll() is not None:
break
else:
# print("libos output: {}".format(data.decode()))
yield data.decode()