Search code examples
python-3.xmodulesubprocessreal-timeyfinance

Capture a terminal output in real time of an python module


The python 'yfinance' module downloads the quotes of many Financial Securities in a pandas dataframe and in the meanwhile it displays a progress bar in the console. In this way:

import yfinance as yf
Tickerlist = ["AAPL","GOOG","MSFT"]
quote = yf.download(tickers=Tickerlist,period='max',interval='1d',group_by='ticker')

I would like to capture the console progress bar in real time, and the code should be this:

import sys
import subprocesss
process = subprocess.Popen(["yf.download","tickers=Tickerlist","period='max'","interval='1d'","group_by='ticker'"],stdout=quote)
while True:
    out = process.stdout.read(1)
    sys.stdout.write(out)
    sys.stdout.flush()

I make a big mess with subprocess. I need your help! Thanks. I have already seen all the links that deal with this topic but without being able to solve my problem.


Solution

  • You need two python files to do what you want.

    one is yf_download.py and second is run.py

    The file code looks like this and you can run it through run.py

    python run.py

    yf_download.py

    import sys
    import yfinance as yf
    
    Tickerlist = ["AAPL","GOOG","MSFT"]
    
    def run(period):
        yf.download(tickers=Tickerlist, period=period,interval='1d',group_by='ticker')
    
    if __name__ == '__main__':
        period = sys.argv[1]
        run(period)
    
    

    run.py

    import sys
    import subprocess
    
    process = subprocess.Popen(["python", "yf_download.py", "max"],stdout=subprocess.PIPE)
    
    while True:
        out = process.stdout.read(1)
        if process.poll() is not None:
            break
        if out != '':
            sys.stdout.buffer.write(out)
            sys.stdout.flush()