python - 如何调用名称存储在 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()
解决方案
当您遍历命令元组以调用它的项目时,您可能只想检查您i[0]
是否等于函数的字符串名称,然后如果相等则调用该函数。
for i in commands:
if i[0] == 'functionName':
functionName(i[1])
推荐阅读
- jenkins - 无法在詹金斯中安装部署到容器插件
- exception - GWT 异常处理
- jquery - 从对象jquery中删除某个索引处的元素
- python - 在 AWS ec2 Ubuntu 实例上使用 pickle 加载对象
- r - 在子集向量中使用第二个 & 时的 R 函数错误
- spotfire - 如何从周数中获取天数
- dart - Dart 中是否有基本的过期地图?
- math - 线性规划优化和梯度下降优化有什么区别?
- php - 如何在不丢失 SQL 请求时间/服务器内存的情况下使用 PHP/MySQL 实现良好的 MVC 模式?(良好做法)
- html - 如何设置我的设计,每 3 个控件显示在一行中,每个控件上方都有标签?