标准输出python管道

时间:2015-08-04 02:05:11

标签: python-3.x pipe stdout

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

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开始时打印当前的比特币价格。

1 个答案:

答案 0 :(得分: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$ 

请注意,美元和下一个提示之间没有空格,因为您没有添加换行符。您可以改为打印 - 默认情况下会添加换行符,但如果您正在使用换行符,则可能不需要它。