首页 新闻 会员 周边

使用subprocess处理复杂的多个管道符的shell命令时,异常

0
[已关闭问题] 关闭于 2020-12-25 09:43

代码如下:

import subprocess
cmd1=['ifconfig','-a']
cmd2=['grep','inet']
cmd3=['grep', '-v', '127.0.0.1']
cmd4=['grep', '-v', 'inet6']
cmd5=['awk','{print $2}']
cmd6=['tr','-d','addr:']
cmd7=['head','-n','1']

def exec_cmd(*args):
    for index,cmd in enumerate(args):
        if index == 0:
            p=subprocess.Popen(cmd,stderr=subprocess.PIPE,stdout=subprocess.PIPE,
                   shell=False)
        else:
            p=subprocess.Popen(cmd,stdin=p.stdout,stderr=subprocess.PIPE,
                               stdout=subprocess.PIPE,shell=False)
    ret = p.communicate()[0]
    print(ret.decode())


exec_cmd(cmd1,cmd2,cmd3,cmd4,cmd5)

我的预期是要得到本机的ip地址,上面的代码执行后获取不到,在执行第一个subprocess后会卡在那里,请问怎么解决!

松风新雪初霁的主页 松风新雪初霁 | 菜鸟二级 | 园豆:202
提问于:2020-12-25 09:38
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册