【问题标题】:Standard Output python piping标准输出 python 管道
【发布时间】:2015-08-04 02:05:10
【问题描述】:

我正在尝试使用 BeautifulSoup 制作一个程序,从 Google Finance 获取当前比特币价格。这是我的代码:

from sys import stdout
import requests
from bs4 import BeautifulSoup

src = requests.get('https://www.google.com/finance/\
converter?a=1&from=BTC&to=USD&meta=ei\%3DawPAVfG8JYHpmAGevavICw').text
soup = BeautifulSoup(src, 'html.parser')
target = soup.find('span', {'class': 'bld'})
stdout.write(target.string)

我想将比特币价格作为标准输出输出,这样我就可以将它通过管道传输到我的 Linux 机器上的其他命令中,如下所示:

python bitcoin.py | echo

当我尝试使用 stdout.write() 来实现它时,它给了我错误:

Exception ignored in: <_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>
BrokenPipeError: [Errno 32] Broken pipe

我需要这样做的原因是我可以将它添加到我的 bash_profile 中,以便在每次 bash 启动时打印当前的比特币价格。

【问题讨论】:

    标签: python-3.x pipe stdout


    【解决方案1】:

    管道坏了,因为echo 没有接受任何输入。我承认,错误消息有点令人困惑:

    $ use_bs.py | echo
    
    Exception ignored in: <_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>
    BrokenPipeError: [Errno 32] Broken pipe
    
    $ use_bs.py | cat
    286.0200 USD$ 
    

    请注意,USD 和下一个提示之间没有空格,因为您没有添加换行符。您可以改为打印 - 默认情况下会添加一个换行符,但如果您使用管道,您可能不希望这样做。

    【讨论】:

    • 谢谢!我是 bash 新手,我刚刚知道您使用 cat 来读取标准输出。