Answer the question
In order to leave comments, you need to log in
How to intercept information from the console?
How to intercept information from the console in Python?
I need to run os.system('ping -c 1 ya.ru') and intercept the information line by line (yes, everything that is written there and then analyzed, but that's another question) from the console.
Exitcode does not quite suit me in this case according to the result of ping, I need exactly information like:
PING 8.8.8.8 (8.8.8.8): 56 data bytes
64 bytes from 8.8.8.8: icmp_seq=0 ttl=108 time=64.503 ms
64 bytes from 8.8.8.8: icmp_seq=1 ttl=108 time=57.064 ms
Answer the question
In order to leave comments, you need to log in
from subprocess import Popen, PIPE
def get_ping():
args = ["ping", "-n", "4", "www.ya.ru"] # -n требуются права Администратора
process = Popen(args, stdout=PIPE)
"""
# Построчное чтение данных
for line in process.stdout:
print("stdout:", line.decode('cp866'))
"""
data, error = process.communicate() # Распаковка кортежа
print(error)
return data.decode(encoding='cp866') # cp866 для Windows
def main():
print(get_ping())
input()
if __name__ == '__main__':
main()
from subprocess import Popen, PIPE
# запускаем команду, вывод перенаправляем в PIPE
proc = Popen('cmd /c ping 8.8.8.8', stdout=PIPE)
# по завершении работы proc, прочитать данные из
# stdout (и отправить ввод, если надо), результат не декодирован (bytes)
res = proc.communicate()[0] # <- communicate возвращает кортеж (stdout_data, stderr_data)
print(res.decode('cp866')) # выводим на печать декодированные данные
Beware, bastard
import os
from threading import Thread
def listen(filename, count):
# запускаем в отдельном потоке команду
t = Thread(target=os.system, args=((f'ping -c {count} yandex.ru > {filename}'),))
t.start()
# ждем начала работы потока, после чего открываем файл
while not os.path.exists(filename):
pass
else:
f = open(filename, 'r')
i = 0
while i <= count:
data = f.read()
if data:
print(data)
i += 1
listen('out', 5)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question