python怎么把输出结果保存为变量_如何在python中将os.system()输出存储在变量或列表中...

要添加到Paul的答案(使用subprocess.check_output):

我稍微重写了一下,以便更容易地处理可能抛出错误的命令(例如,在非g it目录中调用“git status”将抛出返回代码128和CalledProcessError)

下面是我的工作Python 2.7示例:import subprocess

class MyProcessHandler( object ):

# *********** constructor

def __init__( self ):

# return code saving

self.retcode = 0

# ************ modified copy of subprocess.check_output()

def check_output2( self, *popenargs, **kwargs ):

# open process and get returns, remember return code

pipe = subprocess.PIPE

process = subprocess.Popen( stdout = pipe, stderr = pipe, *popenargs, **kwargs )

output, unused_err = process.communicate( )

retcode = process.poll( )

self.retcode = retcode

# return standard output or error output

if retcode == 0:

return output

else:

return unused_err

# call it like this

my_call = "git status"

mph = MyProcessHandler( )

out = mph.check_output2( my_call )

print "process returned code", mph.retcode

print "output:"

print out

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值