python - 如何将所有被调用的函数参数变成一个(Python 3)

标签 python function python-3.x arguments simulator

我正在用 Python 构建一个终端模拟器,并且我将命令存储在参数中,例如:

def ls(a):
    for item in os.listdir():
        print item

a = input('Command: ')
a = a.split()

终端的工作方式如下:

  1. 要求用户输入
  2. 拆分输入
  3. 使用输入的第一部分在局部变量中搜索函数
  4. 如果有,则使用输入的其余部分作为参数
  5. 调用函数

我的 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/

相关文章:

python - 用Python发送邮件主题

python - 文件未在 python 中发布

python - 如何通过仅指定某些列来添加两个数据框

C - 指针、函数和递归

C++问题在类之间传递对象

ios - 你可以在 Objective C 中将函数存储在数组中吗?

Python Eclipse 类型转换智能感知解决方法

python - 根据 lambda 表达式定义命名函数和使用 `def` 之间有区别吗?

Python 3 : Lists and loops

python - python3多线程写入文件