实时捕获python模块的终端输出

Capture a terminal output in real time of an python module

python 'yfinance' 模块在 pandas 数据框中下载许多金融证券的报价,同时在控制台中显示进度条。这样:

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

我想实时抓取控制台进度条,代码应该是这样的:

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()

我把子进程搞得一团糟。我需要你的帮助!谢谢。 我已经看到了所有与此主题有关的链接,但无法解决我的问题。

您需要两个 python 文件来执行您想要的操作。

一个是 yf_download.py 第二个是 run.py

文件代码是这样的,你可以运行通过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()