首页 > 解决方案 > 如何调用名称存储在 txt 文件中的函数?

问题描述

(抱歉有任何错误,这是我在寻找解决方案数小时后的第一篇文章!!)

我已将函数名称及其参数存储在一个 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' object is not callable。

如何使用字符串调用函数?有没有其他方法可以做到这一点?(工作表要求我读取存储在 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

解决方案


当您遍历命令元组以调用它的项目时,您可能只想检查您i[0]是否等于函数的字符串名称,然后如果相等则调用该函数。

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

推荐阅读