zoukankan      html  css  js  c++  java
  • subprocess之check_out用法

    在python3中使用subprocess的check_out方法时,因为该输出为byte类型,所以如果要查看具体的内容时需要进行转码,如果转码不对话,会影响内容输出的可读性,如下:

    #1,输出解码不带参数

     1 # -*- coding:utf-8 -*-
     2 
     3 import subprocess
     4 cmd = r"ping www.baidu.com"
     5 result = subprocess.check_output(cmd)
     6 print(result.decode())  # decode中不带参数,默认是以utf-8解码
     7 
     8 
     9 输出报错:
    10 Traceback (most recent call last):
    11   File "E:/debug.py", line 12, in <module>
    12     print(result.decode())  # decode中不带参数
    13 UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd5 in position 2: invalid continuation byte
    14 
    15 Process finished with exit code 1

    #2,输出解码带上 unicode_escape 参数,会显示乱码

     1 # -*- coding:utf-8 -*-
     2 
     3 import subprocess
     4 cmd = r"ping www.baidu.com"
     5 result = subprocess.check_output(cmd)
     6 print(result.decode("unicode_escape"))  # decode中带参数 unicode_escape
     7 
     8 
     9 输出显示乱码如下:
    10 ÕýÔÚ Ping www.a.shifen.com [14.215.177.39] ¾ßÓÐ 32 ×Ö½ÚµÄÊý¾Ý:
    11 À´×Ô 14.215.177.39 µÄ»Ø¸´: ×Ö½Ú=32 ʱ¼ä=6ms TTL=47
    12 À´×Ô 14.215.177.39 µÄ»Ø¸´: ×Ö½Ú=32 ʱ¼ä=6ms TTL=47
    13 À´×Ô 14.215.177.39 µÄ»Ø¸´: ×Ö½Ú=32 ʱ¼ä=6ms TTL=47
    14 À´×Ô 14.215.177.39 µÄ»Ø¸´: ×Ö½Ú=32 ʱ¼ä=6ms TTL=47
    15 
    16 14.215.177.39 µÄ Ping ͳ¼ÆÐÅÏ¢:
    17     Êý¾Ý°ü: ÒÑ·¢ËÍ = 4£¬ÒѽÓÊÕ = 4£¬¶ªÊ§ = 0 (0% ¶ªÊ§)£¬
    18 Íù·µÐг̵ĹÀ¼Æʱ¼ä(ÒÔºÁÃëΪµ¥Î»):
    19     ×î¶Ì = 6ms£¬× = 6ms£¬Æ½¾ù = 6ms
    20 
    21 
    22 Process finished with exit code 0

    #3、输出解码带上 gbk 参数,显示正常

     1 # -*- coding:utf-8 -*-
     2 
     3 import subprocess
     4 cmd = r"ping www.baidu.com"
     5 result = subprocess.check_output(cmd)
     6 print(result.decode("gbk"))  # decode中带参数 gbk
     7 
     8 
     9 输出显示正常如下:
    10 正在 Ping www.a.shifen.com [14.215.177.39] 具有 32 字节的数据:
    11 来自 14.215.177.39 的回复: 字节=32 时间=7ms TTL=47
    12 来自 14.215.177.39 的回复: 字节=32 时间=6ms TTL=47
    13 来自 14.215.177.39 的回复: 字节=32 时间=7ms TTL=47
    14 来自 14.215.177.39 的回复: 字节=32 时间=7ms TTL=47
    15 
    16 14.215.177.39 的 Ping 统计信息:
    17     数据包: 已发送 = 4,已接收 = 4,丢失 = 0 (0% 丢失),
    18 往返行程的估计时间(以毫秒为单位):
    19     最短 = 6ms,最长 = 7ms,平均 = 6ms
    20 
    21 
    22 Process finished with exit code 0
  • 相关阅读:
    网卡
    java调用函数参数的传递机制及java内存管理
    zookeeper安装遇到的问题
    tcp/ip,http,socket mysql底层技术原理
    前台页面
    权限模块设计及使用
    spring security学习,使用过程
    mybatis处理集合、循环、数组和in等语句的使用
    sql语句的一些学习
    java 实现获取当天,当周,当月,当季,当年的时间段
  • 原文地址:https://www.cnblogs.com/aziji/p/12029063.html
Copyright © 2011-2022 走看看