简体   繁体   中英

How to catch streaming output (file in c++) from terminal to a file in python without changing the c++ file?

This is the python code which is to be edited

import os    
while True:
    command=input("Entre Command:")
    if command==1:
            os.system("sudo python led_test.py")
    elif command==2:
            os.system("sudo /home/abhi/rpi_x4driver_Final/rpi_x4driver/Runme")
    elif command==3:
            os.system("aplay /home/abhi/C_music.wav")

.The Output is coming from Command==2 Which needs to be saved in files(Dynamic names) each containing 200 lines.This means that i want to make batches of outputs coming from

os.system("sudo /home/abhi/rpi_x4driver_Final/rpi_x4driver/Runme")

and save them in files with dynamic names.

i have tried this code but it doesn't work

command=input("Entre Command:")
if command==1:
    sys.exit()
elif command==2:
proc = 
subprocess.Popen(["sudo/home/abhi/rpi_x4driver_Final/rpi_x4driver/Runme"], 
stdout=subprocess.PIPE)

while True:
    line = proc.stdout.readline()
    if line != '':
        # save to a file instead of printing
        print "test:", line.rstrip()
    else:
        break
  1. If you want to extract a part of the output from the stream and then save it, consider using subprocess.check_out as follow:

     import subprocess s = subprocess.check_out(['path/to/the/executable','-option']) s.decode('utf-8') 
  2. If you don't care about extracting, consider using the shell redirection as suggested by @Someprogrammerdude with the > redirection in the shell. More details here : http://www.tldp.org/LDP/abs/html/io-redirection.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM