1

I'm relatively new in python, but I'm trying to learn hard. For the last couple of days tried to solve an error on this script :

import requests
import subprocess
import json
import sys
import multiprocessing
import time
import random

channel_url = "gaming.youtube.com/game/"
processes = [5]


def get_channel():
    # Reading the channel name - passed as an argument to this script
    if len(sys.argv) >= 2:
        global channel_url
        channel_url += sys.argv[1]
    else:
        print "An error has occurred while trying to read arguments. Did you specify the channel?"
        sys.exit(1)


def get_proxies():
    # Reading the list of proxies
    try:
        lines = [line.rstrip("\n") for line in open("proxylist.txt")]
    except IOError as e:
        print "An error has occurred while trying to read the list of proxies: %s" % e.strerror
        sys.exit(1)

    return lines


def get_url():
    # Getting the json with all data regarding the stream
    try:
        response = subprocess.Popen(
            ["livestreamer.exe", "--http-header", "Client-ID=ewvlchtxgqq88ru9gmfp1gmyt6h2b93", 
            channel_url, "-j"], stdout=subprocess.PIPE).communicate()[0]
    except subprocess.CalledProcessError:
        print "An error has occurred while trying to get the stream data. Is the channel online? Is the channel name correct?"
        sys.exit(1)
    except OSError:
        print "An error has occurred while trying to use livestreamer package. Is it installed? Do you have Python in your PATH variable?"

    # Decoding the url to the worst quality of the stream
    try:
        url = json.loads(response)['streams']['audio_only']['url']
    except:
        try:
            url = json.loads(response)['streams']['worst']['url']
        except (ValueError, KeyError):
            print "An error has occurred while trying to get the stream data. Is the channel online? Is the channel name correct?"
            sys.exit(1)

    return url


def open_url(url, proxy):
    # Sending HEAD requests
    while True:
        try:
            with requests.Session() as s:
                response = s.head(url, proxies=proxy)
            print "Sent HEAD request with %s" % proxy["http"]
            time.sleep(20)
        except requests.exceptions.Timeout:
            print "  Timeout error for %s" % proxy["http"]
        except requests.exceptions.ConnectionError:
            print "  Connection error for %s" % proxy["http"]


def prepare_processes():
    global processes
    proxies = get_proxies()
    n = 0

    if len(proxies) < 1:
        print "An error has occurred while preparing the process: Not enough proxy servers. Need at least 1 to function."
        sys.exit(1)

    for proxy in proxies:
        # Preparing the process and giving it its own proxy
        processes.append(
            multiprocessing.Process(
                target=open_url, kwargs={
                    "url": get_url(), "proxy": {
                        "http": proxy}}))

        print '.',

    print ''

if __name__ == "__main__":
    print "Obtaining the channel..."
    get_channel()
    print "Obtained the channel"
    print "Preparing the processes..."
    prepare_processes()
    print "Prepared the processes"
    print "Booting up the processes..."

    # Timer multiplier
    n = 8

    # Starting up the processes
    for process in processes:
        time.sleep(random.randint(1, 5) * n)
        process.daemon = True
        process.start()
        if n > 1:
            n -= 1

    # Running infinitely
    while True:
        time.sleep(1)

ERROR :

python test999.py UCbadKBJT1bE14AtfBnsw27g
Obtaining the channel...
Obtained the channel
Preparing the processes...
An error has occurred while trying to use livestreamer package. Is it installed? Do you have Python in your PATH variable?
Traceback (most recent call last):
  File "test999.py", line 115, in <module>
    prepare_processes()
  File "test999.py", line 103, in prepare_processes
    "url": get_url(), "proxy": {
  File "test999.py", line 67, in get_url
    url = json.loads(response)['streams']['worst']['url']
UnboundLocalError: local variable 'response' referenced before assignment
  1. I had tried on windows, installed all modules (and updated them ) livestreamer, rtmdump, dlls and other needed binary files.
  2. On linux : installed livestreamer, requests, json and all neede modules. Still can't resolve it. Please help !
Graziel
  • 11
  • 1
  • This is nothing to do with your OS or libraries. You have `response = subprocess.Popen()` inside a `try` block. If `Popen()` _fails_, then `response` never comes into existence. All of your code that subsequently tries to reference `response` will fail. You need to define `response` inside the first `except` block to some meaningful value (`None`?) and configure subsequent code to handle that situation. – roganjosh Sep 09 '17 at 08:02
  • hmm...let's see – Graziel Sep 09 '17 at 08:03
  • That's precisely what `UnboundLocalError: local variable 'response' referenced before assignment` is telling you. You're trying to use a "variable" that does not exist. This error comes from Python itself, not a library. – roganjosh Sep 09 '17 at 08:04
  • Trying to execute a EXE file on linux mint? How is it supposed to work? – Frederik.L Sep 09 '17 at 08:08
  • You likely want to `sys.exit` in your second except block (`except OSError:`) just as you do in the first. Without that, this exception makes perfect sense given the program flow shown in your stack trace. – jedwards Sep 09 '17 at 08:08
  • Daaamn !!! I was so bliiind !!! :)) – Graziel Sep 09 '17 at 08:10
  • @roganjosh @jedwards @Frederik.L Guys, solved first part of my problem. Now I have another error : `[ File "test999.py", line 109, in d.daemon = True AttributeError: 'int' object has no attribute 'daemon'` This simply messed up my brain !! tried also this : `for d in processes: time.sleep(random.randint(1, 5) * n) d.daemon = True d.start() if n > 1: n -= 1` – Graziel Sep 09 '17 at 09:05
  • You need to understand how "scope" works in Python. `get_channel()` under `if __name__ == '__main__` does not add anything into the global scope. You call the function, but do not assign the `return`ed value to some name in the global namespace. Thus, `processes` remains what you defined it as - `processes = [5]`, so `for process in processes:` gives you `5`, an integer, which you then try to call a method on. `5.daemon` and `5.start()` don't make sense and that's what the error is telling you. – roganjosh Sep 09 '17 at 09:21

1 Answers1

-2

response = subprocess.Popen() in try clause. When it fails, no response lkocal variable. You should assign response before try,and process None that subporcess.Popen() may return.

Coder.Yyy
  • 11
  • 1