-1

So lets say I open CMD or PowerShell and enter

ping google.com -t

I will get a constant stream of pings. (I could obviously also write a script that gets pings within python but that is not the problem, I just want to know how to do this in theory.) What i want to do now is write a python script that gets those outputs from the CMD and prints them out, live. Is this even possible?

Example: I am running a server which prints logs into a command line and I want to read and save them (i know the save part, just the retrieve is my problem)

Example2: I am running my monero wallet (not the gui, the command line version) and want a script that notifies me when money is sent in

Summed up: an external program of which the UI is a Command line or whose logs are printed into CMD or similar programs is running, and i want to get all the things this program prints out.

  • 1
    Possible duplicate of [Retrieving the output of subprocess.call()](https://stackoverflow.com/questions/1996518/retrieving-the-output-of-subprocess-call) – SiHa Mar 07 '19 at 16:55
  • @SiHa as far as i understand it I need to call the program from within python for it to work. If possible I just want to enter the PID from task manager and read the output of an already running program which is running in the command line (like the command line monero wallet) or something like that –  Mar 07 '19 at 17:04
  • What operating system? – MarkReedZ Mar 07 '19 at 17:13
  • @MarkReedZ Windows for now, I will later on also need Ubuntu, but I think once I know how it works on one I can figure the rest out (if you know linux though you can also tell me) –  Mar 07 '19 at 17:16

1 Answers1

2

On linux this is the simplest way. 9590 is the pid of the process and -s says write out 500 characters from each output line (otherwise it truncates).

import os
stream = os.popen("strace -ewrite -p 9590 -s 500")
while 1:
  print( stream.readline() )

You need to use sudo with strace

sudo python grab_output.py

Output with ping google is:

write(1, "64 bytes from 108.177.122.138 (108.177.122.138): icmp_seq=125 ttl=44 time=40.3 ms\n", 82) = 82
write(1, "64 bytes from 108.177.122.138 (108.177.122.138): icmp_seq=126 ttl=44 time=32.5 ms\n", 82) = 82

So you'd have to clean it up a bit.

MarkReedZ
  • 1,421
  • 4
  • 10
  • Is the following what you want or are you asking to run the ping outside of python and attach to that process's output? – MarkReedZ Mar 07 '19 at 16:56
  • the latter i think. run ping in cmd without python and the tell python to read the output of that command line –  Mar 07 '19 at 17:18
  • I've updated the answer. What you are asking to do is "Use python to attach to the stdout of a running process". Using a debugger like gdb would also work. – MarkReedZ Mar 07 '19 at 17:18
  • Perfect, thanks. Is there a similar way to do it on Windows? I need both but I think linux will suffice for now. Anyway, thank you! –  Mar 07 '19 at 17:21