coder guy
coder guy

Reputation: 589

Standard Output python piping

I am trying to use BeautifulSoup to make a program that gets the current bitcoin price from Google finance. Here is my code:

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)

I want to output the bitcoin price as the standard output so that I can pipe it into other commands on my Linux machine like this:

python bitcoin.py | echo

When I tried to implement this using stdout.write() it gave me errors:

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

The reason I need to do this is so that I can add this to my bash_profile to print the current bitcoin price every time bash starts.

Upvotes: 1

Views: 577

Answers (1)

Patrick Maupin
Patrick Maupin

Reputation: 8127

The pipe is broken because echo doesn't take any input. The error message is sort of confusing, I admit:

$ 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$ 

Note that there is no space between USD and the next prompt because you did not add a newline. You could do print instead -- that would add a newline by default, but if you are piping it, you may not want that.

Upvotes: 1

Related Questions