【发布时间】:2022-01-09 06:34:57
【问题描述】:
我正在尝试创建一个命令行,但是当我使用 split 函数并打印它时,它返回 [],当我将它放入一个 if 语句中说 IndexError: list index out of range 时它返回一个错误。
这是我的代码:
rep = "repeat"
cmd = ""
errorColor = "\033[1;31;47m "
splitCmd = []
def cmdIn():
cmd = input(">>")
splitCmd = cmd.split()
cmdLen = len(cmd)
while True:
cmdIn()
print(splitCmd)
if cmd == None:
print("Error: no command entered")
if splitCmd[0] == rep:
cmdArgs = ""
for x in splitCmd:
if splitCmd[1] == rep:
print()
else:
cmdArgs += x+" "
else:
print("Unknown error")
谢谢,NDev
【问题讨论】:
-
你必须从
splitCmd函数返回splitCmd,否则......你将一无所有...... -
您实际上有 两个 名为
splitCmd的独立变量。一种是全局的,一种是cmdIn()函数的本地。它们彼此没有影响。 -
^^
cmd也是如此。 -
@John Gordon - 它已经是公开的,它是在开头声明的
-
cmdIn()中的变量是局部变量,因为 1)您分配给它,并且 2)您没有明确声明它是全局的。这就是 Python 的工作原理。
标签: python string list cmd split