将独立代码转换为函数

2024-03-29 09:50:58 发布

您现在位置:Python中文网/ 问答频道 /正文

免责声明:拿起编码几个月前,往往比没有我倾向于使用不正确的语言,提前道歉。你知道吗

我正在编写一个函数,它可以将sbml模型(.xml文件)转换为更可读的latex文件(转换为.tex文件)。你知道吗

将独立代码转换为函数时遇到问题。我最好的猜测是,问题出在一个嵌套函数中(转移后)listfiller。你知道吗

我从sbml模型中获取信息的主要方法是将代码预写到一个列表中(在函数中称为Commands),这些基本上是对libSBML库中的函数的调用,这些函数提取一些信息[字符串,整数,etc]),listfiller根据我传入嵌套函数的任何对象(称为obj)进行计算。你知道吗

出于某种原因,一旦我将整个代码移到一个函数中,listfiller就再也看不到对象了。此外,它确实看到了字面上命名为obj的:

试图用*args**kwargs代替obj都没有用

将所有事物命名为“obj”是不可能的(即非常麻烦)

下面是函数本身(需要tellurium library运行:pip install tellurium)和libSBML的任何.xml文件,如this

def xml2tex(name):
    import tesbml

    def listfiller(Commands , obj,  tofill = [], twoD = 1):
            '''
            Uses a dismal method of evaluating a piece of code 
            from 'Commands' to fit a specific string into 'tofill' 
            takes in a libsbml object as obj

            if twoD = 0, then does not fill 'tofill' with the templin as one element
            but returns the compiled templin as 1-D list
            '''
            l = len(Commands)
            templin = [None]*l
            for i in range(l):
                templin[i] = eval(Commands[i])
            if twoD == 1:
                tofill.append(templin)
                return tofill
            elif twoD == 0:
                return templin


    reader = tesbml.SBMLReader()
    mod = reader.readSBML(name)
    Reactions = []
    l = mod.model.getNumReactions()
    Rlist = ['R.getId()','R.getReversible()','R.getFast()']
    for x in range(0,l):
        R = mod.model.getReaction(x)
        RL = listfiller(Rlist, R, twoD=0) #starting the element of common matrix/list to append at the end

        Reactions.append(RL);
    return Reactions

错误:

Traceback (most recent call last):

  File "<ipython-input-56-48f48283afb5>", line 1, in <module>
    xml2tex('model.xml')

  File "/Users/sergejczan/Desktop/Lab/untitled1.py", line 38, in xml2tex
    RL = listfiller(Rlist, obj = R, twoD=0) #starting the element of common matrix/list to append at the end

  File "/Users/sergejczan/Desktop/Lab/untitled1.py", line 23, in listfiller
    templin[i] = eval(Commands[i])

  File "<string>", line 1, in <module>
NameError: name 'R' is not defined

Tags: 文件ofthe函数inobjlinexml