如何调用名称存储在txt文件中的函数?

问题描述 投票:0回答:2

(对不起,有任何错误,这是我经过数小时的寻找解决方案后的第一篇帖子!)

我将函数名称及其参数存储在txt文件中,并要求调用执行某些命令的函数。

到目前为止我所做的:

def main():
    global Pen
    filename = input("Please  enter the name of the file: ")
    plt.axis('square')
    plt.axis([-400, 400, -400, 400])
    Pen = (0, 0, False, 0)
    file = open(filename)
    commands = []
    for data in file:
        data = data.split(',')
        cs = data[0]
        ca = (data[1].rstrip('\n'))
        command = (cs, ca)
        commands.append(command)
    print(commands)
    for i in commands:
        i[0](i[1])

这给了我一个typeError:'str'对象不可调用。

如何使用字符串调用函数?还有其他方法吗?(工作表要求我阅读存储在txt指令文件中的命令)

所有上下文代码:

from matplotlib import pyplot as plt
import math
from math import *


Pen = (0, 0, False, 0)

def main():
    global Pen
    filename = input("Please  enter the name of the file: ")
    plt.axis('square')
    plt.axis([-400, 400, -400, 400])
    Pen = (0, 0, False, 0)
    file = open(filename)
    commands = []
    for data in file:
        data = data.split(',')
        cs = data[0]
        ca = (data[1].rstrip('\n'))
        command = (cs, ca)
        commands.append(command)
    print(commands)
    for i in commands:
        i[0](i[1])


def rotate(angle):
    global Pen
    Pen = list(Pen)
    Pen[3] = Pen[3] - angle
    Pen = tuple(Pen)


def forward(distance):
    global Pen
    Pen = list(Pen)
    x = [Pen[0]]
    y = [Pen[1]]
    a = Pen[0] + (cos(radians(Pen[3])) * distance)
    b = Pen[1] + (sin(radians(Pen[3])) * distance)
    Pen[0] = a
    Pen[1] = b
    Pen = tuple(Pen)
    if Pen[2]:
        x.append(a)
        y.append(b)
        plt.plot(x, y, 'b-')


def pen(state):
    global Pen
    Pen = list(Pen)
    Pen[2] = state
    Pen = tuple(Pen)

main()

print(Pen)
plt.show()

python
2个回答
0
投票

当遍历命令元组以调用它的项时,您可能只需要检查一下i[0]是否等于函数的字符串名,然后在相等性为true时调用该函数即可。

for i in commands:
    if i[0] == 'functionName':
        functionName(i[1])

0
投票

按照此模板,使函数稍有不同,就可以从字符串中调用它们。

© www.soinside.com 2019 - 2024. All rights reserved.