1

저는 파이썬으로는 비교적 새로운 것이지만, 열심히 공부하려고합니다.Python 2.7.13 Livestreamer 나를 미치게 만드는 오류

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. 나는 창에 시도 모든 모듈을 설치 (및 업데이트)했다 livestreamer, rtmdump 지난 며칠를 들어이 스크립트에 오류를 해결하기 위해 시도 , dll 및 기타 필요한 바이너리 파일.
  2. 리눅스에서 : 설치된 라이브 스트리머, 요청, json 및 모든 필수 모듈. 여전히 해결할 수는 없습니다. 도와주세요 !
+0

이것은 운영체제 또는 라이브러리와 관련이 없습니다. 'try' 블록 안에'response = subprocess.Popen()'이 있습니다. 'Popen()'_fails_의 경우,'response'는 결코 존재하지 않습니다. 이후에'response'를 참조하려고하는 모든 코드는 실패합니다. 첫 번째'except' 블록 안에'response'를 의미있는 값 ('None'?)으로 정의하고 그 상황을 처리 할 후속 코드를 구성해야합니다. – roganjosh

+0

흠 ... – Graziel

+0

을 보자. 정확히 'UnboundLocalError : 할당 전에 참조 된 로컬 변수'응답 '이 무엇을 말하고 있는지. 존재하지 않는 "변수"를 사용하려고합니다. 이 오류는 Python 자체에서 가져온 것이지 라이브러리에서 가져온 것입니다. – roganjosh

답변

-2

응답은 try 절의 subprocess.Popen()입니다. 실패 할 경우 lkocal 변수가 없으므로 response입니다. 시도하기 전에 응답을 지정하고 subporcess.Popen()이 반환 할 수있는 None을 처리해야합니다.

+0

이게별로 의미가 없네요. 서식을 정리하고 예제를 제공하는 것이 좋습니다. – roganjosh

+0

. 그것은 매우 간단했습니다. 나는 장님이고 livestreamer.exe :)로 불려왔다.))) – Graziel