subprocess.Popen()

从的python2.4版本开始,可以用子这个模块来产生子进程,并连接到子进程的标准输入/输出/错误中去,还可以得到子进程的返回值。子意在替代其他几个老的模块或函数,例如:os.system,os.spawn *,os.popen *,popen2。,命令。subprocess模块可用于执行复杂的系统命令,包括os.popen()不适用的交互模式的场景,例如python

相互场景

import subprocessobj = subprocess.Popen(['python'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)obj.stdin.write('print('hello world')')obj.stdin.write('\n')obj.stdin.write('print('hello python')')obj.stdin.close()cmd_out = obj.stdout.read()obj.stdout.close()cmd_error = obj.stderr.read()obj.stderr.close()print(cmd_out)print(cmd_error) # 程序没有异常,只输出空行

执行结果:hello worldhello python

非共有场景

p = subprocess.Popen('ipconfig', shell=True, stdout=subprocess.PIPE)out, err = p.communicate()for line in out.splitlines(): print(line.decode('gbk', 'ignore'))

注:如果子进程输出到数据到stdout或stderr的管道,并达到了系统pipe的缓存大小的话,子进程会等待父进程转换管道,而父进程此时正wait着着话,将会产生传说中的死锁。建议使用communication()来避免这种情况的发生。

Popen.communicate(input = None)和子进程交互:发送数据到stdin,并从stdout和stderr读数据,直到收到EOF。等待子进程结束。可选的输入如有有话,要为字符串类型。此函数返回一个元组:(stdoutdata,stderrdata),元素类型为,需要进行转码,上面的代码——line.decode(“ gbk”,“ ignore”)

实践案例下面的演示根据系统命令config,获取本机MAC地址和IP地址的代码以网上的代码为基础修改def get_mac_and_ip(): ''' # 获取本机MAC地址和IP地址 :return: (MAC地址,IP地址) ''' # 使用with,不需要显式的写pipe.close() with os.popen('ipconfig -all') as pipe: str_config = pipe.read() # print('完整配置信息:', str_config) # 利用正则表达式和re模块检索结果 mac_re_compile = re.compile(r'物理地址[\. ]+: ([\w-]+)') ip_re_compile = re.compile(r'IPv4 地址[\. ]+: ([\.\d]+)') mac = mac_re_compile.findall(str_config)[0] # 找到MAC ip = ip_re_compile.findall(str_config)[0] # 找到IP # print('MAC=%s, IP=%s' % (mac, ip)) return mac, ipresult = get_mac_and_ip()print('MAC: %s\n IP: %s' % result)

执行结果

MAC: 26-0A-64-A7-68-84 IP: 192.168.1.103

MAC: 26-0A-64-A7-68-84 IP: 192.168.1.103
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值