xonsh:有没有办法将函数调用为带有可选参数的命令?

xonsh: Is there a way to call a function as a command that takes optional arguments?

我在 Xonsh 中有一个函数,我想像命令一样使用它(即:没有括号)。该函数应该有选择地接受参数,但是每当我调用不带参数的函数时,我只会得到函数地址。如何调用带有可选参数的函数?

示例如下:

def _up(args, stdin=None):
    # go up any number of directories
    if not args or len(args) < 1:
        args[0] = 1
    balloons = ('../' * int(args[0]))
    # echo @(balloons)
    cd @(balloons)
aliases['up'] = _up

当我调用不带参数的 up 时,我得到 <function __main__.up>。当我这样称呼它时,它起作用了:up 2.

我可以做一个像这样的函数,但如果不使用括号(即:作为命令)我就不能调用它,这是我更喜欢的:

def up(dirs=1):
    # go up any number of directories
    balloons = ('../' * dirs)
    # echo @(balloons)
    cd @(balloons)

调用 up()up(2) 都是这样工作的,但比只调用 upup 2 更麻烦。在 Xonsh 中完成我想做的事情的正确方法是什么?

我不确定为什么你在没有传递参数时得到函数 repr,但是你的函数的一个调整版本可以工作:

def _up(args):  # don't need stdin
    # go up any number of directories
    if not args or len(args) < 1:
        args = [1]  # if args is None you can't index to it
    balloons = ('../' * int(args[0]))
    # echo @(balloons)
    cd @(balloons)
aliases['up'] = _up

xonsh 的当前 main @ c2f862df 这只需要一个 up 就可以上升一个级别,或者您可以使用 [= 指定多个级别16=],等等