在python中创建自定义命令

时间:2018-10-19 12:07:47

标签: python

我正在尝试在Python中创建一些命令,它将从文本文件中读取。

假设文件名为commands.txt

ADD 5 4
SUBSTRACT 6 5

输出:-

9
1

我们将像这样传递文本输入文件,

python myfile.pycommands.txt

我可以在Python中添加或减去,但是如何从文本文件中读取和使用命令,

myfile.py:-

sum = 5+4
print sum
substract = 6-5
print substract 

2 个答案:

答案 0 :(得分:2)

这类事情很快就会变得复杂,一个非常简单/幼稚的解决方案会做出很多假设,就像这样:

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))

答案 1 :(得分:2)

尝试以下代码。假设您有一个名为commands.txt的文件,其中包含问题中提到的内容。确保您没有写SUB S TRACT,而是SUBTRACT:

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!')