Python Forum
Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Invalid Syntax Error
#1
I am trying to monitor usage of Solstice Pods using the Python script. I was given an example python application that polls Solstice Pods for usage and then saves the data into a spreadsheet for viewing. When I do it, I get a syntax error in this part of the program, error at the comma:

except urllib2.URLError, e:

I'm attaching what I got below in case anyone can help take a look. Thanks!


#
# UsageCaptureExample.py
#
# Solstice Usage Capture 
#
# An OpenControl Protocol Example.
#
# This application monitors a Solstice Pod deployment for a given amount of time and
# saves connection count information for each Pod to a comma-separated datafile that can easilly be imported
# into Excel or another tool to visualize usage statistics over time.
#
# Usage:   solsticeUsageCapture <Solstice Host File> <OutputFile (comma separated)> [-time] <time in seconds>
#
# The arguments are:
#
# <hostFile.txt>:  A textfile that contains, on each line, a display name and it's corresponding IPAddress.  This file 
#   contains the set of Solstice Hosts that will be monitored.
#
# <outputFile.txt>: The resulting output textfile.  This file will be written throughout the monitoring process and closed 
#   when the program terminates.  The format of this file is a CSV where each line contains the number of users connected
#   at the sample for each host.
#
# <Time (in minutes) to monitor the program>
#
# This application uses the OpenControl protocol to establish a connection and download utilization information.
#
# (c) Mersive Technologies, 2016
#
# Author: Christopher Jaynes
# 	  CTO & Founder, Mersive
#
# --------------- LICENSE - LGPL -----------------------------------------------
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# -------------------------------------------------------------------------------
import argparse	
import sys
import urllib
import time
import os

import urllib2

# Solstice OpenControl is based on JSON records, you can parse by hand or use existing libraries (like I do here)
# 
import json


#
# I use the argparse library to quickly parse the command line for arguments and marshall them into each component
#
argumentParser = argparse.ArgumentParser(description='Solstice Usage Capture, Command Line Arguments.')
argumentParser.add_argument('HostFile', metavar='<hostfile.txt>', type=str, help='Solstice Host Text File: [Name] [IPAddr] [Port] per line')
argumentParser.add_argument('OutputFile', metavar='<outputFile.txt>', type=str, help='Output File for Usage Data')
argumentParser.add_argument('Time', metavar='<Time in Minutes>', type=int, help='Length of Capture in Minutes')

gHostConnectionInfo = []
gHostCount = 0

#
# This variable defines how often to poll user count for all hosts in the hostFile.txt file

gSampleIntervalInSeconds = 5

#
# OpenControl users several different URLs based on the type of information you are reading/writing (control, stats, config)
# This program will be reading statistics information (users connected), so we will be using the "stats" URL 
#
gSolstice_Stats_URL = "/api/stats"



#
#
# DEFINE loadHostFile.  A simple function to load a text file with hostname and IPAddr and load each line to the the
# gHostConnectionInfo array for processing later.
#
def loadHostFile(aHostFile):

	whiteSpaceRegEx = "\\s"

	#
	# First test if the file exists, then open and read until no more data exists.
	# 
	if (os.path.isfile(aHostFile)) :
		with open(aHostFile, 'r') as file:
			index = 0
			for line in file:
				gHostConnectionInfo.append(line.split())
				index = index+1

		return index
	else:
		print(aHostFile+" does not appear to exist or cannot be opened.")
		exit()
	

#
#
# DEFINE getUserCountFromHost.  Given an IPAddress, poll the number of users currently connected at that Solstice IPAddress.
#	If there is a problem (i.e. there is no Solstice host at that IPAddress, or it cannot be reached, set to zero.
#
def getUserCountFromHost( aIPAddr ):

	# This function users the url2lib for processing communicating to the socket and waiting on a response.  
	#
	# NOTE: This example assumes that the admin password is not set for all the endpoints.  If the admin password 
	# has been set.  The OpenControl protocol will use https and not http as shown below.  Additionally
 	# the urlStr would have to be appended with "?password=<your admin password>" so that the current admin password is
	# transmitted as an argument to the Solstice Host as part of the URL get request.

	urlStr = "http://192.168.1.5"+aIPAddr+gSolstice_Stats_URL


	try:
		urlRequestResult = urllib2.urlopen( urlStr , timeout=1 )
	except urllib2.URLError, e:
		return(0)

	hostValuesStr = urlRequestResult.read()


	statsTopLevelRecord = json.loads( hostValuesStr );
	##
	## Parse out the Statistics SubRecord and Return User Count
	##
	if 'm_statistics' in statsTopLevelRecord:
		displayInformation = statsTopLevelRecord[ 'm_statistics' ]
		return( displayInformation['m_connectedUsers'] )
	else:
		return( 0 )



def main():


	# Parse command line arguments
	args = argumentParser.parse_args()

	#Load Host file into the gConnectionInfo structure that holds hostname/IP/Port
	gHostCount = loadHostFile( args.HostFile )





	# Start the timer and begin collecting usage information from all hosts.
	# At the end of each loop, append the result to the CSV output file.
	#
	timeStart = time.time()
	timeEnd = timeStart + (60*args.Time)


	#
	# Open output file.
	# and begin collecting data.
	#
	try:
		lOutputFile = open(args.OutputFile, "w")

		# Output HEADER Info
		lOutputFile.write("Time, ")
		for  gHostNumber in xrange(0,gHostCount):
			lOutputFile.write(gHostConnectionInfo[gHostNumber][0]+", ")
		lOutputFile.write("Total\n")


		while (time.time() < timeEnd):
			accumulatedUserCount = 0
			lOutputFile.write("%.0f" % (time.time() - timeStart))
			# Get number of users Connected for each display.
			for hostNumber in xrange(0,gHostCount):
				lNumUsers = getUserCountFromHost( gHostConnectionInfo[hostNumber][1]);
				accumulatedUserCount += lNumUsers
			
				lOutputFile.write(", "+str( lNumUsers ) )
			lOutputFile.write(", "+str(accumulatedUserCount)+"\n")
			lOutputFile.flush()
			time.sleep( gSampleIntervalInSeconds )

		close(lOutputFile)

	except IOError:
		print(args.OutputFile+" could not be opened.  Exiting.")
		exit()


main()
Reply
#2
If you are using Python3, therein lies your problem. There is no urllib2 in Python3. Try importing urllib.error instead.
Reply
#3
Yes, I was using version 3 but I deleted it, installed version 2.7.14 and ran the program, but now I'm getting a different error message - see below. Any ideas?


Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:25:58) [MSC v.1500 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> 
========= RESTART: C:\Users\Desktop\UsageCaptureExample.py =========
usage: UsageCaptureExample.py [-h]
                              <hostfile.txt> <outputFile.txt> <Time in
                              Minutes>
UsageCaptureExample.py: error: too few arguments
>>> 
Reply
#4
I think it means when you run UsageCaptureExample.py you need to append the args.
e.g. UsageCaptureExample.py hostfile outputfile time

I'm a noob to python and programming so it's just a best guess.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Syntax error for "root = Tk()" dlwaddel 15 1,178 Jan-29-2024, 12:07 AM
Last Post: dlwaddel
Photo SYNTAX ERROR Yannko 3 380 Jan-19-2024, 01:20 PM
Last Post: rob101
  error: invalid command 'egg_info' TimTu 0 957 Jul-27-2023, 07:30 AM
Last Post: TimTu
  Syntax error while executing the Python code in Linux DivAsh 8 1,584 Jul-19-2023, 06:27 PM
Last Post: Lahearle
  Code is returning the incorrect values. syntax error 007sonic 6 1,227 Jun-19-2023, 03:35 AM
Last Post: 007sonic
  print(data) is suddenly invalid syntax db042190 6 1,196 Jun-14-2023, 02:55 PM
Last Post: deanhystad
  syntax error question - string mgallotti 5 1,316 Feb-03-2023, 05:10 PM
Last Post: mgallotti
  Syntax error? I don't see it KenHorse 4 1,256 Jan-15-2023, 07:49 PM
Last Post: Gribouillis
  [ERROR] ParamValidationError: Parameter validation failed: Invalid type for parameter gdbengo 3 11,024 Dec-26-2022, 08:48 AM
Last Post: ibreeden
  Syntax error tibbj001 2 891 Dec-05-2022, 06:38 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020