0

I'm really new to python, it's the first time I'm writing it actually. And I'm creating a program that gets the number of views on a Twitch.tv stream, but I'm getting an error Expected string or buffer Python when I'm calling this function

 def getURL():
  output = subprocess.Popen(["livestreamer", "twitch.tv/streamname", "-j"], stdout=subprocess.PIPE).communicate()[1]
  return json.loads(output)["streams"]["worst"]["url"]

I'm calling the function from here:

urls = []

urls.append(getURL())

What am I doing wrong? I've been trying to figure this one out for ages... And if anybody knows how to fix this, I'd be the happiest man alive ;)

Thanks in advance.

EDIT:

This is all the code I have.

import requests
import subprocess
import json
import sys
import threading
import time

urls = []
urlsUsed = []

def getURL():
output = subprocess.Popen(["livestreamer", "twitch.tv/hemzk", "-j"],       stdout=subprocess.PIPE).communicate()[1]
return json.loads(output)["streams"]["worst"]["url"]

def build():

global numberOfViewers

  urls.append(getURL())

And I'm getting the error at return json.loads(output)["streams"]["worst"]["url"]

2
  • Post the full code sample and error message and I'll take a look. Commented Nov 24, 2013 at 12:19
  • At least say which line the error refers to. Commented Nov 24, 2013 at 12:22

1 Answer 1

0

Change

output = subprocess.Popen(["livestreamer", "twitch.tv/streamname", "-j"],
                          stdout=subprocess.PIPE).communicate()[1] 

to

output = subprocess.Popen(["livestreamer", "twitch.tv/streamname", "-j"],
                          stdout=subprocess.PIPE).communicate()[0] 

(Change 1 to 0).

More detailed explanation of your problem follows. Popen.communicate returns a tuple stdout, stderr. Here, it looks like you are interested in stdout (index 0), but you are picking out stderr (index 1). stderr is None here because you have not attached a pipe to it. You then try to parse None using json.loads() which expected a str or a buffer object.

If you want stderr output, you must add stderr=subprocess.PIPE to your Popen constructor call.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! That worked. But I'm still getting an error on the same line, but this time, it's a Can't use a string pattern on a bytes-like object
Are you using Python 3+? If so, you must explicitly convert the bytes object (your stdout) into a string. For instance: json.loads(stdout.decode(encoding='UTF-8')).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.