首页 > 解决方案 > How to get readable command outputs from terminal

问题描述

I'm running into a problem whit this script and I don't know how to describe it. Here is the code:

import subprocess
while True:
    imp = input(">>> ")
    proc = subprocess.Popen(imp, shell=True, stdout=subprocess.PIPE,)
    output = proc.communicate()[0]
    print(output)

If you write ping 192.168.0.1 as input it will output a binary number I think but the .decode("utf-8") function doesn't work

标签: pythonshell

解决方案


You need to use decode the output you get when you run a command, that is. Note that since the OP is using hungarian, the encoding is ISO-8859-2 and not utf-8

import subprocess
while True:
    imp = input(">>> ")
    proc = subprocess.Popen(imp, shell=True, stdout=subprocess.PIPE,)
    output = proc.communicate()[0]
    #Decode the binary string 
    print(output.decode('ISO-8859-2'))

A sample output will be

>>> ping -c 1 127.0.0.1
PING 127.0.0.1 (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.045 ms

--- 127.0.0.1 ping statistics ---
1 packets transmitted, 1 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 0.045/0.045/0.045/0.000 ms

>>> 

The new encoding works with the OP's example output

s = b'\r\n192.168.0.1 pingel\x82se - 32 b\xa0jtnyi adattal:\r\nV\xa0lasz 192.168.0.1: b\xa0jt=32 id\x8b<10 ezredmp. TTL=64\r\nV\xa0lasz 192.168.0.1: b\xa0jt=32 id\x8b<10 ezredmp. TTL=64\r\nV\xa0lasz 192.168.0.1: b\xa0jt=32 id\x8b<10 ezredmp. TTL=64\r\nV\xa0lasz 192.168.0.1: b\xa0jt=32 id\x8b<10 ezredmp. TTL=64\r\n\r\n192.168.0.1 ping-statisztik\xa0ja:\r\n Csomagok: k\x81ld\x94tt = 4, fogadott = 4, elveszett = 0\r\n (0% vesztes\x82g),\r\nOda-vissza \xa3t ideje k\x94zel\xa1t\x8blegesen, milliszekundumban:\r\n minimum = 0ms, maximum = 0ms, \xa0tlag = 0ms\r\n'
print(s.decode('ISO-8859-2'))

The output is

192.168.0.1 pingelse - 32 b jtnyi adattal:
V lasz 192.168.0.1: b jt=32 id<10 ezredmp. TTL=64
V lasz 192.168.0.1: b jt=32 id<10 ezredmp. TTL=64
V lasz 192.168.0.1: b jt=32 id<10 ezredmp. TTL=64
V lasz 192.168.0.1: b jt=32 id<10 ezredmp. TTL=64

192.168.0.1 ping-statisztik ja:
 Csomagok: kldtt = 4, fogadott = 4, elveszett = 0
 (0% vesztesg),
Oda-vissza Łt ideje kzelĄtlegesen, milliszekundumban:
 minimum = 0ms, maximum = 0ms,  tlag = 0ms

推荐阅读