我正在用 Python 构建一个终端模拟器,并且我将命令存储在参数中,例如:
def ls(a):
for item in os.listdir():
print item
a = input('Command: ')
a = a.split()
终端的工作方式如下:
- 要求用户输入
- 拆分输入
- 使用输入的第一部分在局部变量中搜索函数
- 如果有,则使用输入的其余部分作为参数
- 调用函数
我的 cd 命令有问题。
def cd(a):
if a == None:
print('cd')
print('Change directories')
else:
os.chdir(os.getcwd() + '/' + a())
当你让它进入一个没有空格的文件夹时,它会起作用,比如当你输入cd Windows
时在提示中,它有效。但是,当您尝试进入其中包含空格的文件夹时,问题就开始了。例如,当我输入cd Documents Copy
时,它要么进入 Documents 文件夹(如果有),要么崩溃。
我该如何修复它?我曾想过将所有被调用的函数参数变成一个,但我不知道该怎么做,可能还有其他方法。
最佳答案
您需要一个更复杂的 split()
函数 - 请参阅 Split a string by spaces — preserving quoted substrings answer寻找潜在的解决方案。
更新
如果你有一个名为“thedog”的子目录,其中有一个空格,那么在你的解释器中你可以这样做:
Command: cd "the dog"
代码修改大致如下:
import shlex
import os
def ls(a):
for item in os.listdir():
print(item)
def cd(a):
if a == None:
print('cd')
print('Change directories')
else:
os.chdir(os.getcwd() + '/' + a)
a = input('Command: ')
a = shlex.split(a)
if len(a) > 1:
locals()[a[0]](a[1][:99])
print()
else:
locals()[a[0]](None)
print()
关于python - 如何将所有被调用的函数参数变成一个(Python 3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37170585/