X-Git-Url: https://git.ucc.asn.au/?a=blobdiff_plain;f=src%2Flink%2FexternAgent.py;h=0680f33146c544662da9639b7c573896059d09e2;hb=e9f0debda3ab1209ece73fd4edaaefe755b6ab2a;hp=6112482fac8da3de59d794b200d7bb9e055bbdf0;hpb=edf8e5b569e75692d61a44f2c3241fb6410e4fbd;p=progcomp10.git diff --git a/src/link/externAgent.py b/src/link/externAgent.py index 6112482..0680f33 100644 --- a/src/link/externAgent.py +++ b/src/link/externAgent.py @@ -16,11 +16,13 @@ class externAgent (BaseAgent): BaseAgent.__init__(self) try: self.process = subprocess.Popen(externName, stdin=subprocess.PIPE, - stdout=subprocess.PIPE, stderr=subprocess.PIPE, + stdout=subprocess.PIPE, universal_newlines=True) except Exception, e: print ("Error spawning \"%s\": " % externName), e - + + self.process.stdin.write ( ' '.join( ["HI", repr(self.GetID()), "\r\n"] ) ) + def stringToItem( self, str ): if str == "Rock": return Rock @@ -73,7 +75,7 @@ class externAgent (BaseAgent): return attack, bluff except: #agent is insane - print "Agent is insane:", self + print "Agent is insane:", self, self.GetID() pass def Defend (self, foe, bluff ): @@ -85,7 +87,7 @@ class externAgent (BaseAgent): return defence except: #agent is insane - print "Agent is insane:", self + print "Agent is insane:", self, self.GetID() pass def Results (self, foe, isInstigatedByYou, winner, attItem, defItem, bluffItem, pointDelta): @@ -110,13 +112,30 @@ class externAgent (BaseAgent): self.process.stdin.write ( string ) self.process.stdout.readline() # read and discard (should be "OK") + # we kill off the process here because otherwise the class doesn't get + # destroyed until the end of the iteration. This causes us to hold more + # than MAX_TOTAL_AGENTS open for a period of time, which is a bad thing. + if self.IsDead(): + try: + self.process.communicate( "BYE\r\n" ) + except Exception, e: + print "Error in BYE:", self, ":", e + + try: + self.process.kill() + except: + None + + def __del__(self): - try: - self.process.communicate( "BYE\r\n" ) - except Exception, e: - print "Error in BYE:", self, ":", e + #unless we're being deleted unexpectedly, this is a no-op. + if self.process.poll() == None: + try: + self.process.communicate( "BYE\r\n" ) + except Exception, e: + print "Error in BYE:", self, ":", e - try: - self.process.kill() - except: - None \ No newline at end of file + try: + self.process.kill() + except: + None