赞
踩
在解决一个实时获取命令行输出的问题时,通过查找资料,发现一个从subprocess运行的子进程中实时获取输出的方法,程序如下:
- import shlex
- import subprocess
-
- if __name__ == '__main__':
- shell_cmd = 'ping www.baidu.com'
- cmd = shlex.split(shell_cmd)
- p = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
- while p.poll() is None:
- line = p.stdout.readline()
- line = line.strip()
- if line:
- print(line)
- if p.returncode == 0:
- print('Subprogram success')
- else:
- print('Subprogram failed')
在命令行输入“ping www.baidu.com”会得到如下输出信息:
但该程序运行的输出却是这样的:
也就是这里输出的是bytes类型的数据,而我们想要的是含有汉字的str类型的数据,bytes转str有以下两种方法:
s1 = str(line, encoding='utf-8')
s2 = line.decode('utf-8')
但是,改过之后运行程序时却报错了:
- Traceback (most recent call last):
- File "E:/PycharmProjects/Video_Crack/test.py", line 13, in <module>
- s1 = str(line, encoding='utf-8')
- UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd5 in position 0: invalid continuation byte
- Process finished with exit code 1
翻到了一篇博客,里面有这么一段话:
如果python中所要处理的字符串中包含中文,那么最好要搞懂所用字符的编码,是gbk/gb2312/gb18030,还是utf-8,否则容易出现乱码,以及此处的语法错误。
尝试将编码方式改为“gbk”或者“gb2312”以及“gb18030”之后,输出就正常了,这说明原来的中文字符是采用gbk/gb2312/gb18030编码的。
- import shlex
- import subprocess
-
- if __name__ == '__main__':
- shell_cmd = 'ping www.baidu.com'
- cmd = shlex.split(shell_cmd)
- p = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
- while p.poll() is None:
- line = p.stdout.readline()
- line = line.strip()
- if line:
- s1 = str(line, encoding='gbk')
- print(s1)
- if p.returncode == 0:
- print('Subprogram success')
- else:
- print('Subprogram failed')
参考博文:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。