我的python代码出错

时间:2017-07-08 18:08:03

标签: python python-3.x syntax-error

我的python cod一直给我一些错误,如缩进和语法,我一直在修复它们但无济于事。所以这里是我正在使用的代码我仍然不确定我在这里做错了什么(顺便说一句,这只是因为与朋友争论我不能做的事情)

import requests
import subprocess
import json
import sys
import threading
import time
from Queue import Queue

numberOfViewers = int(sys.argv[1])
builderThreads = int(sys.argv[2])
startTime = time.time()
numberOfSockets = 0
concurrent = 25
urls = []
urlsUsed = []

def getURL(): # Get tokens
  output = subprocess.Popen(["livestreamer", "twitch.tv/CHANNEL_NAME", "-j"], stdout=subprocess.PIPE).communicate()[0]
        return json.loads(output)['streams']['worst']['url'] # Parse json and return the URL parameter

def build(): # Builds a set of tokens, aka viewers
        global numberOfSockets
        global numberOfViewers
        while True:
                if numberOfSockets < numberOfViewers:
                        numberOfSockets += 1
                        print "Building viewers " + str(numberOfSockets) + "/" + str(numberOfViewers)
                        urls.append(getURL())

def view(): # Opens connections to send views
        global numberOfSockets
        while True:
                url=q.get()
                requests.head(url)
                if (url in urlsUsed):
                        urls.remove(url)
                        urlsUsed.remove(url)
                        numberOfSockets -= 1
                else:
                        urlsUsed.append(url)
                q.task_done()

if __name__ == '__main__':
        for i in range(0, builderThreads):
                threading.Thread(target = build).start()

        while True:
                while (numberOfViewers != numberOfSockets): # Wait until sockets are built
                        time.sleep(1)

                q=Queue(concurrent*2)
                for i in range(concurrent):
                        try:
                                t=threading.Thread(target=view)
                                t.daemon=True
                                t.start()
                        except:
                                print 'thread error'
                try:
                        for url in urls:
                                print url
                                q.put(url.strip())
                                q.join()
                except KeyboardInterrupt:
                        sys.exit(1)

3 个答案:

答案 0 :(得分:1)

您需要缩进代码。当你这样做时,Python不喜欢它:

def main():
print "Hello World!"

Python想要缩进(我认为它是4个空格)

def main():
    print "Hello World!"

您有语法和缩进错误的行号是什么?顺便问一下?

答案 1 :(得分:1)

Python使用缩进来定义块而不是{}。

此外,您应该在所有文档中继续使用第一个缩进格式。这意味着如果您从制表符开始,即使空格在视觉上看起来相同,也必须始终使用制表符,如果您使用4个空格,则无法在代码中更改标签或更多空格。

您提到的错误通常是因为您从互联网上粘贴了代码并且正在使用标签而您正在使用空格,反之亦然。

我建议重新修改整个代码,因为它很短。

答案 2 :(得分:0)

您的代码中有一些错误:

1: print: 如果您使用的是Python3 -

  

print语句已替换为print()函数   关键字参数替换旧的大多数特殊语法   打印声明

了解更多information about whats new in python 3

2:缩进: 如果您收到此错误: IndentationError: expected an indented block 这意味着你有不正确的缩进。作为一种解释性语言,适当的缩进对于Python来说是必要且重要的:

  

在逻辑开头引出空格(空格和制表符)   line用于计算行的缩进级别   turn用于确定语句的分组。

有关详细信息,请查看Python reference manual for Indentation

修正代码示例:

我为你修正了这些错误,下面是它的样子:

import requests
import subprocess
import json
import sys
import threading
import time
from Queue import Queue

numberOfViewers = int(sys.argv[1])
builderThreads = int(sys.argv[2])
startTime = time.time()
numberOfSockets = 0
concurrent = 25
urls = []
urlsUsed = []

def getURL(): # Get tokens
  output = subprocess.Popen(["livestreamer", "twitch.tv/CHANNEL_NAME", "-j"],
  stdout=subprocess.PIPE).communicate()[0]
  return json.loads(output)['streams']['worst']['url'] # Parse json and return the URL parameter

def build(): # Builds a set of tokens, aka viewers
  global numberOfSockets
  global numberOfViewers
  while True:
    if numberOfSockets < numberOfViewers:
      numberOfSockets += 1
      print ("Building viewers " + str(numberOfSockets) + "/" + str(numberOfViewers))
      urls.append(getURL())

def view(): # Opens connections to send views
  global numberOfSockets
  while True:
    url=q.get()
    requests.head(url)
    if (url in urlsUsed):
      urls.remove(url)
      urlsUsed.remove(url)
      numberOfSockets -= 1
    else:
      urlsUsed.append(url)
      q.task_done()

      if __name__ == '__main__':
        for i in range(0, builderThreads):
          threading.Thread(target = build).start()

          while True:
            while (numberOfViewers != numberOfSockets): # Wait until sockets are built
              time.sleep(1)

              q=Queue(concurrent*2)
              for i in range(concurrent):
                try:
                  t=threading.Thread(target=view)
                  t.daemon=True
                  t.start()
                except:
                  print ('thread error')
                  try:
                    for url in urls:
                      print (url)
                      q.put(url.strip())
                      q.join()
                  except KeyboardInterrupt:
                    sys.exit(1)

3. ImportError:没有名为&#39;的模块&#39;

这意味着您的模块请求丢失。如果您有Windows,请使用命令行安装它,如果您有Mac,则使用终端安装。

$ sudo pip install requests --upgrade