-1

My python cod keeps giving me errors like indention and syntax which I keep fixing them but to no avail. So here is the code I'm using I'm still not sure what I'm doing wrong here (BTW this is just due to an argument with a friend about what I can't do)

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)
1
  • Hi @flamelier welcome to StackOverflow. Please post your error to improve your post. That way fellow programmers can better help you debug your error/program. Commented Jul 8, 2017 at 18:15

3 Answers 3

1

You need to indent your code. Python doesn't like it when you do this for example:

def main():
print "Hello World!"

Python wants indents (I think it's 4 spaces)

def main():
    print "Hello World!"

What line number is it where you have syntax and indent errors? by the way?

Sign up to request clarification or add additional context in comments.

Comments

1

Python uses indentation for defining blocks instead of {}.

Also you should keep using the first indentation formating during all document. It means if you start with tabs you have to always use tabs even if spaces look the same visually and if you are using 4 space you can't change later in the code for tabs or more space.

The error you mentioned usually occurs because you pasted code from the internet and it is using tabs and you are using spaces or vice versa.

I recommend to re-indend the whole code as it's short.

Comments

0

You have a couple error in your code:

1: print: If you are using Python3 -

The print statement has been replaced with a print() function, with keyword arguments to replace most of the special syntax of the old print statement

for more information about whats new in python 3

2: Indentation: If you are getting this error: IndentationError: expected an indented block that means you have improper indentations. As an interpreted language proper indentation is necessary and important for Python:

Leading whitespace (spaces and tabs) at the beginning of a logical line is used to compute the indentation level of the line, which in turn is used to determine the grouping of statements.

for more information look at Python reference manual for Indentation

Fixed code example:

I fixed these error for you and below is how it should look like:

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: No module named 'requests'

This means your module request is missing. Simply install it with using Command line if you have Windows or Terminal if you have a Mac.

$ sudo pip install requests --upgrade

2 Comments

So i used the code you had there and here is what it is telling me: raceback (most recent call last): File "C:\Users\flamelier\Desktop\Twitch.py", line 1, in <module> import requests ImportError: No module named 'requests'
That is a completely different error. Usually, I would suggest you ask it in a new a question. but I will edit my answer to accommodate your new error

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.