我正在用python编写一个类似命令提示符的程序,用户在其中键入一个命令,一个字典找到相关的方法,然后访问另一个包含所有方法的文件,然后运行用户请求的文件。你知道吗
但是,当我尝试运行其中任何一个方法时,它首先从所有方法中打印出“return”语句之外的任何内容,然后执行所请求的方法。你知道吗
这是我运行的主文件。(rcmd.py公司)你知道吗
from commands import *
def get_input():
user = input("Guppy\RACHEAL> ")
return user
def command_line():
# LOOP DETERMINATION VARIABLE
exit = False
while exit == False:
user_input = get_input()
if user_input == "exit":
exit = True
break
elif user_input == "":
get_input()
else:
e = commands.execute(user_input)
print("FINISHED --> " + str(e))
# PROGRAM START LOOP
#
#
command_line()
这是使用字典执行方法的文件(命令.py)你知道吗
from modules import *
class commands(object):
def execute(user_input):
# DICTIONARY OF COMMANDS
COMMANDS = {
# || GENERAL || #
"help" : modules.help(),
# || FIND || #
"find- time" : modules.find_time(user),
"find- date" : modules.find_date(),
# || INPUT || #
"input- log: new" : modules.input_new_log()
}
try:
execution = COMMANDS[user_input]
return execution
except KeyError:
return "ERROR --> No such command"
这是包含所有方法的文件 导入日期时间
class modules(object):
# -- || GENERAL MODULES || --- #
def help():
return "Action terms:\n'find'\n'input'" + "\n__________\n"
# --- || 'FIND' MODULES || --- #
def find_time():
print("Nothing")
return datetime.datetime.now().time()
def find_date():
return datetime.datetime.now().date()
# --- || 'INPUT' MODULES || --- #
def input_new_log():
new_user_log = input("> ")
path = 'C:\\Users\\Guppy\\Projects\\RACHEAL\\RACHEALs Databases\\user_log.txt'
with open(path, 'w') as log:
log.write(new_user_log)
input_new_log_exit_code = 1
return "EXIT CODE = " + str(input_new_log_exit_code)
这是我得到的结果
Guppy\RACHEAL> find- date
Guppy\RACHEAL> Nothing
>
FINISHED --> 2017-31-12
我应该去哪里
Guppy\RACHEAL> find- date
FINISHED --> 2017-31-12
如果有人知道为什么这不能正常工作,或者我做错了什么,我会非常感激。你知道吗
问题是在
commands.py
中定义COMMANDS
:这里您将每个值设置为函数的输出,而不是函数本身。它应该更像这样:
您还必须将
execution = COMMANDS[user_input]
行更改为execution = COMMANDS[user_input]()
。这将为您提供所需的输出。你知道吗问题在于构造要调用的函数字典的方式。你知道吗
对于字典中的每个条目,调用函数,并将调用函数的结果赋给条目。您需要做的是为函数指定一个引用。注意没有括号。你知道吗
然后需要在字典中查找后调用函数m:
请注意导致在此处调用函数的额外括号。你知道吗
而且,与
find_time()
不一致。在dictionary构造函数中,您传递的是一个参数,但函数似乎并不期望这样。你知道吗相关问题 更多 >
编程相关推荐