python - 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
解决方案
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
推荐阅读
- reactjs - React Native,Redux:获取更多/加载更多
- java - 从 .jar 到可导入包...如何?
- c# - 如何自定义 ASP.Net Core 模型绑定错误?
- javascript - 带有 microsoft graph javascript sdk 的多部分 HTTP 请求
- c# - UWP XAML NavigationMenu 更改行为
- spring-boot - cloud.aws.jdbc.datasource 抛出断言错误:Spring Boot 应用程序的密码不能为空
- postgresql - postgres \copy 命令给出错误:错误:“到”处或附近的语法错误
- python - Openpyxl 将字典写入电子表格
- apache - 停止 httpd 但 localhost 仍然绑定到 0.0.0.0:80
- yocto - 如何让“HelloWorld - BitBake Style”在更新版本的 Yocto 上工作?