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

Tokfrans
  • 1,939
  • 2
  • 24
  • 56

1 Answers1

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.

Max
  • 3,384
  • 2
  • 27
  • 26
  • 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 http://stackoverflow.com/questions/14010551/how-to-convert-between-bytes-and-strings-in-python-3 for more details – Max Nov 24 '13 at 12:33