SimPy yield hold的语法错误

时间:2015-03-18 11:43:39

标签: python syntax generator yield simpy

我是Simpy的初学者。我只是按照手册的第一步(http://simpy.sourceforge.net/old/SimPy_Manual/Manuals/Manual.html)并将其调整到我想做的事情。 我的代码

# -*- coding: utf-8 -*-
#from mpl_toolkits.mplot3d import Axes3D
#from matplotlib import cm
#import matplotlib.pyplot as plt
import numpy as np
import random as rd
import math
from SimPy.Simulation import Process, activate, hold, initialize, simulate
import sys

class Agent(Process):
    def __init__(self,i,x,y,u,v,state):
        Process.__init__(self, name='Agent' + str(i))
        self.i = i
        self.x = x
        self.y = y
        self.u = u
        self.v = v
        self.st = state

    def go(self):
        dt=1.0/math.sqrt(self.u**2+self.v**2)
        print('%s starts at %s' %(self.i,now())
        yield hold, self, dt
        print('%s changed place at %s' %(self.i,now())

initialize()
a = Agent('nano',9,0,0,1,0)
#b = Agent(1,9,0,0,1,0)
activate(a,a.go(),at=0.0)
#activate(b,b.go(),at=5.0)
simulate(until=100.0)

引发以下错误:

hcecilia@helcecil:~/BRL$ python agent_sim.py 
  File "agent_sim.py", line 24
    yield hold, self, dt
        ^
SyntaxError: invalid syntax

但是,当我尝试手册的确切代码时,即:

from SimPy.Simulation import Process, activate, initialize, hold, now, simulate


class Message(Process):
    """A simple Process"""
    def __init__(self, i, len):
        Process.__init__(self, name='Message' + str(i))
        self.i = i
        self.len = len

    def go(self):
        print('%s %s %s' % (now(), self.i, 'Starting'))
        yield hold, self, 100.0
        print('%s %s %s' % (now(), self.i, 'Arrived'))


initialize()
p1 = Message(1, 203)   # new message
activate(p1, p1.go())  # activate it
p2 = Message(2, 33)
activate(p2, p2.go(), at=6.0)
simulate(until=200)
print('Current time is %s' % now())  # will print 106.0

工作正常。我看不出两者之间有什么区别。如果您有任何想法......

1 个答案:

答案 0 :(得分:1)

您错过了前一行的结束)括号:

print('%s starts at %s' %(self.i,now())
#    1                   2          332?

括号对1未关闭。

在Python中,逻辑行仅在所有括号,括号和大括号都关闭时结束;没有右括号yield被视为print()函数调用的一部分,并且该语法无效。