在python中创建自定义命令
我正在尝试用Python创建一些命令,它将从文本文件中读取 假设文件名为在python中创建自定义命令,python,Python,我正在尝试用Python创建一些命令,它将从文本文件中读取 假设文件名为commands.txt ADD 5 4 SUBSTRACT 6 5 输出:- 9 1 我们将像这样传递文本输入文件 python myfile.py commands.txt 我可以在Python中添加或删除命令,但是如何从文本文件中读取和使用命令 myfile.py:- sum = 5+4 print sum substract = 6-5 print substract 这类事情可能会很快变得复杂,一个非常简单
commands.txt
ADD 5 4
SUBSTRACT 6 5
输出:-
9
1
我们将像这样传递文本输入文件
python myfile.py commands.txt
我可以在Python中添加或删除命令,但是如何从文本文件中读取和使用命令
myfile.py:-
sum = 5+4
print sum
substract = 6-5
print substract
这类事情可能会很快变得复杂,一个非常简单/幼稚的解决方案会做出很多假设,比如:
def do_add(a, b):
return float(a) + float(b)
def do_subtract(a, b):
return float(a) - float(b)
cmds = {
'ADD': do_add,
'SUBSTRACT': do_subtract,
}
def process(line):
cmd, *args = line.split()
return cmds[cmd](*args)
with open('input.txt') as fd:
for line in fd:
print(process(line))
请尝试以下代码。它假设您有一个名为
commands.txt
的文件,其中包含问题中提到的内容。确保不写SUBSTRACT,而是减去:
def subtract(args):
return int(args[0]) - int(args[1])
def add(args):
return int(args[0]) + int(args[1])
FN_LOOKUP = {
'ADD': add,
'SUBTRACT': subtract,
}
with open('commands.txt') as f:
for line in f.readlines():
# Remove whitespace/linebreaks
line = line.strip()
# Command is the first string before a whitespace
cmd = line.split(' ')[0]
# Arguments are everything after that, separated by whitespaces
args = line.split(' ')[1:]
if cmd in FN_LOOKUP:
# If the command is in the dict, execute it with its args
result = FN_LOOKUP[cmd](args)
args_str = ', '.join(args)
print(f'{cmd}({args_str}) = {result}')
else:
# If not, raise an error
raise ValueError(f'{cmd} is not a valid command!')
您的代码:不读取文件,不分割读取文件中的行,不尝试基于从文件中分割的内容使用任何类型的数学。您的代码:使用本地值9覆盖内置的
sum()
函数(这很糟糕)。请展示你的努力和你在任务设置上的具体问题-否则这只是一个“为我做我的工作”的问题,将被否决并很快关闭。如果你想编辑你的问题,请删除它(这样在你将其内容提高到标准时没有人否决它),然后取消删除它。通过一种简单的方式,你可以打开文件,在循环中逐行读取它,将每一行拆分为its字符串元素,然后根据第一行字符串调用相应的函数,并将同一行中的剩余字符串作为参数传递给它。我建议您先尝试一下,然后编辑您的问题以向我们展示您的代码。基本的算术运算也在操作符
模块-->{'ADD':operator.ADD,…}
中。