Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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"]

share|improve this question
    
Post the full code sample and error message and I'll take a look. –  Allan McLemore Nov 24 '13 at 12:19
    
At least say which line the error refers to. –  Scott Hunter Nov 24 '13 at 12:22

1 Answer 1

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.

share|improve this answer
    
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 –  Tokfrans Nov 24 '13 at 12:29
    
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')). –  Max Nov 24 '13 at 12:32
    
See stackoverflow.com/questions/14010551/… for more details –  Max Nov 24 '13 at 12:33

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.