尝试用exec捕获

时间:2018-01-20 07:00:26

标签: python python-3.x exception exception-handling exec

我正在尝试运行生成python代码的遗传算法。换句话说,我正在变形天网。

我遇到了SyntaxError的问题,我认为这是在except区块中发现的。

from random import sample
from time import time

TEST_INPUTS = 100

def sortedness(l=[], fraction=1.00):
    fraction = 1.00 - fraction
    # random * percent does not make percent sorted.
    for p in range(int(len(l)*fraction)):
        i, j = sample(l, 2)
        l[i], l[j] = l[j], l[i]

class CodeGene(Gene):
    def mate(self, gene):

        # this slight improvement over the last version should allow mating between 
        # differently sized codes. 

        self_middle = int(floor(len(self.code)/2))
        gene_middle = int(floor(len(gene.code)/2))

        return [
            Gene(self.code[:self_middle] + gene.code[gene_middle:]),
            Gene(gene.code[:gene_middle] + self.code[self_middle:])
       ]

    def calc_cost(self, target):
        score = 100

        context = {
            'unsorted': sortedness(list(range(TEST_INPUTS)), 0.0)
        }

        start = time()
        i = self.code.find('import')
        while i > -1:
            self.code = self.code[i:] + self.code[:i+len('import')]
            i = self.code.find('import')
        exec self.code in context 
        end = time()
        t = end - start()

        if 'sort' in context:
            score -= (TEST_INPUTS + 100)
        try:
            # only run this code in a virtual machine
            exec "sorted = sort(unsorted)" in context 
            score -= (TEST_INPUTS + 100)

            for i in range(TEST_INPUTS):
                if context['sorted'][i] == i:
                    score -= TEST_INPUTS
        except(SyntaxError):
            score += (TEST_INPUTS + 100)

class CodePopulation(Population):
    def __init__(self, target=sorted, size=100, log_costs=False):
        self.target = target
        self.members = []
        for i in range(size):
            gene = CodeGene('')
            gene.random(len(self.target.code))
            self.members.append(gene)
        self.generationNumber = 0

        self.log_costs = log_costs
        if self.log_costs:
            self.cost_log = [] # logs the cost of the highest ranking member

0 个答案:

没有答案