2

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?

Nilanka Manoj
  • 3,527
  • 4
  • 17
  • 48
Bhavya Gupta
  • 186
  • 2
  • 12

1 Answers1

0

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.

Hamza Khurshid
  • 765
  • 7
  • 18
  • @Hamza-Kurshid ```Error - return ("Latest Progress: ",myPrintLogs[-1]) IndexError: list index out of range``` – Bhavya Gupta Apr 01 '20 at 11:36
  • @BhavyaGupta Make sure you define the method before everything else. And then access the list myPrintLogs after you are sure the required print statements have been executed. – Hamza Khurshid Apr 01 '20 at 12:02
  • Yes, I did it the exact way. Still it is blank. the print command is not given in my script. It is originating from some imported module. – Bhavya Gupta Apr 01 '20 at 12:11
  • The module `pafy` doesn't use `print` in its implementation. It uses `sys.stdout.write` instead. So I updated the code to override this method instead. You can try this one! – Hamza Khurshid Apr 01 '20 at 17:17
  • You are great! It works like charm. But now, I am having SSL Error from python. Can you help me in that too? – Bhavya Gupta Apr 02 '20 at 06:50
  • Please share complete stack trace. – Hamza Khurshid Apr 02 '20 at 10:49