【发布时间】:2015-06-26 09:10:17
【问题描述】:
有很多关于如何从 python 运行 shell 命令的文献,但我有兴趣做相反的事情。我有一个 python 模块 mycommands.py,其中包含如下函数
def command(arg1, arg2):
pass
def command1(arg1, arg2, arg3):
pass
函数参数都是字符串。目标是能够从 bash 中运行这些函数,如下所示
$ command arg1 arg2
$ command1 arg1 arg2 arg3
到目前为止,我在 .bash_profile 中有以下蛮力设置,我必须手动为每个 python 函数提供 bash 绑定
function command() {
python -c "import mycommand as m; out=m.command('$1', '$2'); print(out)"
}
function command1() {
python -c "import mycommand as m; out=m.command1('$1', '$2', '$3'); print(out)"
}
如果能有一个像这样的 bash 命令就好了
$ import_python mycommands.py
它会自动将模块中的所有 python 函数导入为 bash 命令。是否存在实现此类命令的库?
【问题讨论】:
-
你为什么要这样做?
-
只需使用Click。
-
@tzaman Click 并没有为一个模块中的不同功能提供多个调度,但是,这是大部分问题所在。除此之外,只需导入
argparse并为不同的函数编写解析器。 -
@Dzhelil 为什么不直接启动
python解释器并直接调用您的函数? -
我想要这样做的一个原因是因为 shell 具有出色的文件名完成支持,而 python 解释器没有。从 shell 调用对文件进行操作的函数比从 python 解释器调用要容易得多。