M
M
Morrowind2020-08-10 18:01:12
Python
Morrowind, 2020-08-10 18:01:12

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


So far, I see only an attempt to import information into txt and then from there get the same Python lines and parse what you need.
Is there an easier option?
Google on this about import io - but the suggested examples are not quite clear to me.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander, 2020-08-10
@hekkaaa

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()

B
bbkmzzzz, 2020-08-10
@bbkmzzzz

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')) # выводим на печать декодированные данные

M
Miit, 2020-08-10
@Miit

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 question

Ask a Question

731 491 924 answers to any question