标准输出 python 管道
Standard Output python piping
我正在尝试使用 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 开始时打印当前比特币价格。
管道坏了,因为 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和下一个提示之间没有space,因为你没有加换行符。您可以改为打印——默认情况下会添加一个换行符,但如果您正在管道化它,您可能不希望那样。
我正在尝试使用 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 开始时打印当前比特币价格。
管道坏了,因为 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和下一个提示之间没有space,因为你没有加换行符。您可以改为打印——默认情况下会添加一个换行符,但如果您正在管道化它,您可能不希望那样。