Get Output of A Function in Python In a variable

Viewed 416

My python script downloads youtube videos using the youtube-dl library. It only prints progress and does not return progress value. I have to pump the progress to my HTML page. Using return() only gives code as 0 or none. JavaScript is configured to get return value and add it to a textarea. It is not possible to configure the library as it is huge.

stream.download(quiet=False, filepath=outfilepath)

This calls a module pafy which further calls youtube-dl.

 16,498,967.0 Bytes [100.00%] received. Rate: [5446 KB/s].  ETA: [0 secs]

This output does not go to HTML but is printed in python shell. How to get this output in my HTML page?

1 Answers

One possible solution is overriding the builtin sys.stdout.write method which is being used by pafy to print to console. You can make it also log the print statements into a data structure.

In the following code, I used a list to store all strings passed to sys.stdout.write function. This will log all your download progress prints into this list. You can always access your latest log from the list.

import pafy
import sys

#List for logging required printed strings
myPrintLogs=[]

def write(text):
    """Overloaded sys.stdout.write function"""
    myPrintLogs.append(text) #Adding text into Logs List
    if len(text) == 0:
        return
    old_sys_write(text + '\n') #Calling the actual method for printing text

old_sys_write=sys.stdout.write 
sys.stdout.write=write

Add your download code after initializing this. You'll have all the console output in the list myPrintLogs. You should call the method for download in a new thread so that you can monitor the logs in main thread.

Related