运行shell命令并捕获输出我想编写一个函数,它将执行shell命令并返回其输出。如一串不管是错误还是成功的信息。我只想得到与命令行相同的结果。什么样的代码示例会做这样的事情呢?例如:def run_command(cmd):
# ??????print run_command('mysqladmin create test -uroot -pmysqladmin12')# Should output something like:# mysqladmin:
CREATE DATABASE failed; error: 'Can't create database 'test'; database exists'
4 回答
子衿沉夜
TA贡献1828条经验 获得超3个赞
import commandsprint commands.getstatusoutput('wc -l file')
python2.7
python3
subprocess
import subprocess output=subprocess.Popen(["date"],stdout=PIPE)response=output.communicate()print response
繁花如伊
TA贡献2012条经验 获得超12个赞
def runProcess(exe): p = subprocess.Popen(exe, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) while(True): # returns None while subprocess is running retcode = p.poll() line = p.stdout.readline() yield line if retcode is not None: break
for line in runProcess('mysqladmin create test -uroot -pmysqladmin12'.split()): print line,
回首忆惘然
TA贡献1847条经验 获得超11个赞
def run_command(command): p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) return iter(p.stdout.readline, b'')
command = 'mysqladmin create test -uroot -pmysqladmin12'.split()for line in run_command(command): print(line)
添加回答
举报
0/150
提交
取消