如何将库的Python函数作为Bash命令提供?

2024-05-15 15:21:04 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个大型的Python函数库,我希望这些函数(或其中的一些函数)可以作为Bash中的命令使用。你知道吗

首先,不考虑Bash命令选项和参数,如何获得一个Python文件的函数,该文件包含许多要使用单个单词Bash命令运行的函数?我不想通过命令“suite”的命令使用这些功能。因此,假设我在这个Python文件中有一个名为zappo的函数(例如,名为library1.py)。我想用一个单词Bash命令调用这个函数,比如zappo而不是library1 zappo。你知道吗

第二,如何处理选项和参数?我在想一个很好的方法是捕获Bash命令的所有选项和参数,然后在Python函数中使用docopt解析*在函数级使用它们。你知道吗


Tags: 文件方法函数py命令功能bash参数
1条回答
网友
1楼 · 发布于 2024-05-15 15:21:04

是的,但答案可能不像你希望的那么简单。无论您做什么,您都必须在bashshell中为要运行的每个函数创建一些内容。但是,可以让Python脚本生成存储在源文件中的别名。你知道吗

基本思路如下:

#!/usr/bin/python

import sys
import __main__ #<  This allows us to call methods in __main__
import inspect #<  This allows us to look at methods in __main__

########### Function/Class.Method Section ##############
# Update this with functions you want in your shell    #
########################################################
def takesargs():
    #Just an example that reads args
    print(str(sys.argv))
    return

def noargs():
    #and an example that doesn't
    print("doesn't take args")
    return
########################################################

#Make sure there's at least 1 arg (since arg 0 will always be this file)
if len(sys.argv) > 1:
    #This fetches the function info we need to call it
    func = getattr(__main__, str(sys.argv[1]), None)
    if callable(func):
        #Actually call the function with the name we received
        func()
    else:
        print("No such function")
else:
    #If no args were passed to this function, just output a list of aliases for this script that can be appended to .bashrc or similar.
    funcs = inspect.getmembers(__main__, predicate=inspect.isfunction)
    for func in funcs:
        print("alias {0}='./suite.py {0}'".format(func[0]))

显然,如果您在类中使用方法而不是main中的函数,请将引用从__main__更改为类,并将inspect中的谓词更改为inspect.ismethod。另外,您可能希望对别名使用绝对路径等

样本输出:

~ ./suite.py
alias noargs='./suite.py noargs'
alias takesargs='./suite.py takesargs'

~ ./suite.py > ~/pyliases

~ echo ". ~/pyliases" >> ~/.bashrc

~ . ~/.bashrc

~ noargs
doesn't take args

~ takesargs blah
['./suite.py', 'takesargs', 'blah']

如果使用我上面建议的方法,实际上可以在.bashrc从文件中获取别名之前运行~/suite.py > ~/pyliases。然后,每次登录/启动新的终端会话时,您的环境都会得到更新。只需编辑python函数文件,然后. ~/.bashrc这些函数就可以使用了。你知道吗

相关问题 更多 >