I am writing a script to automate HvZ games at my college and have run into this strange frustrating syntax error:
File "HvZGameMaster.py", line 53
class players(object):
^
SyntaxError: invalid syntax
Here is the offending code
class mailMan(object):
"""mailMan manages player interactions such as tags reported via text messages or emails"""
def __init__(self, playerManager):
super(mailMan, self).__init__()
self.mail = imaplib.IMAP4_SSL('imap.gmail.com')
self.mail.login(args.username,args.password)
self.mail.list()
# Out: list of "folders" aka labels in gmail.
self.mail.select("inbox") #connect to inbox.
def getBody(self, emailMessage):
maintype = emailMessage.get_content_maintype()
if maintype == 'multipart':
for part in emailMessage.get_payload():
if part.get_content_maintype() == 'text':
return part.get_payload()
elif maintype == 'text':
return emailMessage.get_payload()
def getUnread(self):
self.mail.select("inbox") # Select inbox or default namespace
(retcode, messages) = self.mail.search(None, '(UNSEEN)')
if retcode == 'OK':
retlist = []
for num in messages[0].split(' '):
print 'Processing :', messages
typ, data = self.mail.fetch(num,'(RFC822)')
msg = email.message_from_string(data[0][1])
typ, data = self.mail.store(num,'-FLAGS','\\Seen')
if retcode == 'OK':
for item in str(msg).split('\n'):
#finds who sent the message
if re.match("From: *",item):
print (item[6:], self.getBody(msg))
retlist.append((item[6:], self.getBody(msg).rstrip())
#print (item, self.getBody(msg).rstrip())
class players(object): #<-the problem happens here
"""manages the player"""
def __init__(self, pDict):
super(players, self).__init__()
self.pDict = pDict
#makes a partucular player a zombie
def makeZombie(self, pID):
self.pDict[pID].zombie = True
#makes a partucular player a zombie
def makeHuman(self, pID):
self.pDict[pID].zombie = False
As far as I can tell what I have written is correct and I have checked to make sure it is all tabs and not spaces I have made sure i don't have any erroneous \r's or \n's floating around (all \n's are where the should be at the end of the line and I'm not using any \r's)
You can find all my code for this project here if you would like to try running it yourself
There is an unbalanced (missing) parenthesis on the line above the line raising the error:
retlist.append((item[6:], self.getBody(msg).rstrip())
Note that some editors have matching parenthesis highlighting, and key combinations for moving back and forth across matched parentheses. Using an editor with these features can help cut down on these errors.
Related
I have a basic electricity system model that I have built in Pyomo and has been working well. I'm now looking to make it a bit more sophisticated, adding in some additional variables, such as start costs for individual generators.
I pasted below some of the code I have added - I can provide more contextual code if required, but it is only these lines that have been added to trigger this error. The error thrown back by Pyomo is shown in quotes in the header to this query. I have deliberately left in some commenting out of lines, where I simplified the code to try to identify where the issue is. To no avail: I still get an error with the commenting out shown below:
model.StartFuelCost = Param(model.GeneratorName, model.Resource, default=0)
model.GeneratorCommitted = Var(model.GeneratorName, model.Hour, domain=Boolean, initialize=0)
model.GeneratorStart = Var(model.GeneratorName, model.Hour, domain=Boolean, initialize=0)
model.StartFuelCostByGenerator = Var(model.GeneratorName, model.Resource, model.Hour, domain=NonNegativeReals, initialize=0.0)
model.StartFuelCostTotal = Var(model.Resource, model. Hour, domain.NonNegativeReals, initialize=0.0)
...
def GeneratorCommitted_rule(model,g,h):
# if model.Generation[g,h] > 0:
return model.GeneratorCommitted[g,h] == 1
# else:
# return model.GeneratorCommitted[g,h] == 0
model.SupplyDemand_Calc2 = Constraint(model.GeneratorName, model.Hour, rule=GeneratorCommitted_rule)
# ISSUE: Either need to remove conditionality or pass info from the last time step
def GeneratorStart_rule(model,g,h):
# if model.Hour > 1:
# return max(0, model.GeneratorCommitted[g,h] - model.GeneratorCommitted[g,h-1]) == model.GeneratorStart[g,h]
# else:
return model.GeneratorCommitted[g,h] == model.GeneratorStart[g,h]
model.SupplyDemand_Calc3 = Constraint(model.GeneratorName, model.Hour, rule=GeneratorStart_rule)
def StartFuelCostByGenerator_rule(model,g,r,h):
return model.StartFuelCost[g,r] * model.ResourcePrice[r] * model.GeneratorStart[g,h] == model.StartFuelCostByGenerator[g,r,h]
model.Costing_Calc5 = Constraint(model.GeneratorName, model.Resource, model.Hour, rule=StartFuelCostByGenerator_rule)
def StartFuelCostTotal_rule(model,r,h):
return sum(model.StartFuelCostByGenerator[g,r,h] for g in model.GeneratorName) == model.StartFuelCostTotal[r,h]
model.Costing_Calc6 = Constraint(model.Resource, model.Hour, rule=StartFuelCostTotal_rule)
This is your problem:
model.StartFuelCostTotal = Var(model.Resource, model. Hour, domain.NonNegativeReals, initialize=0.0)
You have "." (dot) notation there with domain, so it is trying to figure out what this thing is that you call domain... You want to change that to an =.
In the future, it is much easier (and you are more likely) to get help if you post the actual code with the error trace which says which line contains the error.
I'm very new to Python and I was trying to use a nice library (audiotools) to play an mp3 playlist, just as an exercise.
This is the class to play the tracklist (loosely based on THIS, once I discovered there is a "callback function with no arguments which is called by the player when the current track is finished" (*) ):
class Trackplay:
def __init__(self,
track_list,
audio_output=audiotools.player.open_output('ALSA'),
replay_gain=audiotools.player.RG_NO_REPLAYGAIN):
self.track_index = INDEX - 1
self.track_list = track_list
self.player = audiotools.player.Player(
audio_output,
replay_gain,
self.next_track())
def next_track(self):
try:
self.track_index += 1
current_track = self.track_list[self.track_index]
print str(current_track)
audio_file = audiotools.open(current_track)
self.player.open(audio_file) # <---------- error
self.player.play()
except IndexError:
print('playing finished')
Then I'm calling:
tp = Trackplay(get_track_list(PATH))
where get_track_list is a method returning a list of mp3s from the dir PATH.
The error I get (at the line marked with the "error" comment) is:
AttributeError: Trackplay instance has no attribute 'player'
I don't understand what's happening ...but reading all the AttributeError questions here, must be something stupid...
player seems to me exactly a Trackplay's attribute. Other attributes, as track_index and track_list seems OK, since the line print str(current_track) prints the current track.
Thanks for any help.
See this code here?
self.player = audiotools.player.Player(
audio_output,
replay_gain,
self.next_track())
As part of creating the Player you're going to assign to self.player, you call self.next_track(). self.next_track tries to use self.player, before self.player exists!
def next_track(self):
try:
self.track_index += 1
current_track = self.track_list[self.track_index]
print str(current_track)
audio_file = audiotools.open(current_track)
self.player.open(audio_file)
self.player.play()
except IndexError:
print('playing finished')
next_track doesn't even return anything, so it's baffling why you're trying to pass self.next_track() as an argument to Player.
Was that supposed to be a callback? If so, you should pass self.next_track to Player without calling it.
self.player = audiotools.player.Player(
audio_output,
replay_gain,
self.next_track)
# ^ no call parentheses
I am a newbie to programming. Learning from Udacity. In unit 2, I studied the following code to fetch links from a particular url:
import urllib2
def get_page(url):
return urllib2.urlopen(url).read()
def get_next_target(page):
start_link = page.find('<a href=')
if start_link == -1:
return None, 0
start_quote = page.find('"', start_link)
end_quote = page.find('"', start_quote + 1)
url = page[start_quote + 1:end_quote]
return url, end_quote
def print_all_links(page):
while True:
url, endpos = get_next_target(page)
if url:
print url
page = page[endpos:]
else:
break
print_all_links(get_page('http://en.wikipedia.org'))
It worked perfectly. Today I wanted to modify this code so the script could crawl for a particular word in a webpage rather than URLs. Here is what I came up with:
import urllib2
def get_web(url):
return urllib2.urlopen(url).read()
def get_links_from(page):
start_at = page.find('america')
if start_at == -1:
return None, 0
start_word = page.find('a', start_at)
end_word = page.find('a', start_word + 1)
word = page[start_word + 1:end_word]
return word, end_word
def print_words_from(page):
while True:
word, endlet = get_links_from(page)
if word:
print word
page = page[endlet:]
else:
break
print_words_from(get_web('http://en.wikipedia.org/wiki/America'))
When I run the above, I get no errors, but nothing prints out either. So I added the print keyword -
print print_words_from(get_web('http://en.wikipedia.org/wiki/America'))
When I run, I get None as result. I am unable to understand where am I going wrong. My code probably is messed up, but because there is no error coming up, I am unable to figure out where it is messed up.
Seeking help.
I understand this as you are trying to get it to print the word America for every instance of the word on the Wikipedia page.
You are searching for "america" but the word is written "America". "a" is not equal to "A" which is causing you to find no results.
Also, start_word is searing for 'a', so I adjusted that to search for 'A' instead.
At this point, it was printing 'meric' over and over. I edited your 'word' to begin at 'start_word' rather than 'start_word + 1'. I also adjusted your 'end_word' to be 'end_word+1' so that it prints that last letter.
It is now working on my machine. Let me know if you need any clarification.
def get_web(url):
return urllib2.urlopen(url).read()
def get_links_from(page):
start_at = page.find('America')
if start_at == -1:
return None, 0
start_word = page.find('A', start_at)
end_word = page.find('a', start_word + 1)
word = page[start_word:end_word+1]
return word, end_word
def print_words_from(page):
while True:
word, endlet = get_links_from(page)
if word:
print word
page = page[endlet:]
else:
break
print_words_from(get_web('http://en.wikipedia.org/wiki/America'))
This is a code snippet written in python to receive sms via a usb modem. When I run the program all I get is a status message "OK"., but nothing else.How do I fix the issue to print the messages I am receiving?
import serial
class HuaweiModem(object):
def __init__(self):
self.open()
def open(self):
self.ser = serial.Serial('/dev/ttyUSB_utps_modem', 115200, timeout=1)
self.SendCommand('ATZ\r')
self.SendCommand('AT+CMGF=1\r')
def SendCommand(self,command, getline=True):
self.ser.write(command)
data = ''
if getline:
data=self.ReadLine()
return data
def ReadLine(self):
data = self.ser.readline()
print data
return data
def GetAllSMS(self):
self.ser.flushInput()
self.ser.flushOutput()
command = 'AT+CMGL="all"\r'
print self.SendCommand(command,getline=False)
self.ser.timeout = 2
data = self.ser.readline()
print data
while data !='':
data = self.ser.readline()
if data.find('+cmgl')>0:
print data
h = HuaweiModem()
h.GetAllSMS()
In GetAllSMS there are two things I notice:
1) You are using self.ser.readline and not self.Readline so GetAllSMS will not try to print anything (except the first response line) before the OK final response is received, and at that point data.find('+cmgl')>0 will never match.
Is that just the problem?
2) Will print self.SendCommand(command,getline=False) call the function just as it were written as self.SendCommand(command,getline=False)? (Just checking since I do not write python myself)
In any case, you should rework your AT parsing a bit.
def SendCommand(self,command, getline=True):
The getline parameter here is not a very good abstraction. Leave out reading responses from the SendCommand function. You should rather implement proper parsing of the responses given back by the modem and handle that outside. In the general case something like
self.SendCommand('AT+CSOMECMD\r')
data = self.ser.readline()
while ! IsFinalResult(data):
data = self.ser.readline()
print data # or do whatever you want with each line
For commands without any explicit processing of the responses, you can implement a SendCommandAndWaitForFinalResponse function that does the above.
See this answer for more information about a IsFinalResult function.
where you are having problems is here in your GetAllSMS function. Now replace my GeTALLSMS function with yours and see what happens
def GetAllSMS(self):
self.ser.flushInput()
self.ser.flushOutput()
command = 'AT+CMGL="all"\r' #to get all messages both read and unread
print self.SendCommand(command,getline=False)
while 1:
self.ser.timeout = 2
data = self.ser.readline()
print data
or this
def GetAllSMS(self):
self.ser.flushInput()
self.ser.flushOutput()
command = 'AT+CMGL="all"\r' #to get all messages both read and unread
print self.SendCommand(command,getline=False)
self.ser.timeout = 2
data = self.ser.readall() #you can also u read(10000000)
print data
thats all...
somewhere in my views.py,I have
def loadFcs(request):
r = requests.get('a url')
res = json.loads(r.text)
#Do other stuff
return HttpResponse('some response')
Now when I call this from my javascript, loadFcs gets called, and probably requests.get gets called asynchronously. So I end up seeing ' TypeError at /loadFcs expected string or buffer' and the trace points to the line with
res = json.loads(r.text)
I also modified my code to check whats the problem, and
def loadFcs(request):
r = requests.get('a url')
res = json.loads(r.text)
if r == None:
print 'r is none'
if r.text == None:
print 'text is None'
#Do other stuff
return HttpResponse('some response')
and noticed that 'text is none'. So I think I need to adjust code so that request.get is synchronous. I think the method execution continues and the return statement is hit even before r.text has some value.
Suggestions?
okay, so I tried the same thing with python command line and it worked BUT not with the same code in my server.
So what was the problem?
apparently, response.text is in some encoding ( UTF8) which my server was not set to receive, so it was just throwing it away and hence null.
Solution: use response.content ( which is raw binary)