【问题标题】:Execute a custom bash function within python在 python 中执行自定义 bash 函数
【发布时间】:2018-04-22 07:00:55
【问题描述】:

这个问题是this question 的简单版本。

简单来说,我在~/.bash_profile 上定义了一个自定义bash 函数my_func,并在同一环境中使用了另外两个定义的bash 函数。

另外,my_func 接受两个参数,比如说ab。 my_func 所做的是连接到远程服务器并发送一些文件(这些文件由ab 确定)。

如果我在bash shell 上输入: . my_func a b 一切正常,我在屏幕上看到了一些打印语句。

但是,如果我包括: subprocess.call(['#!/bin/bash . my_func a b'], shell=True) 似乎什么也没发生。

我尝试通过以下方式导出my_func 使用的所有 bash 函数:

subprocess.call(['#!/bin/bash export -f my_func'], shell=True) 我对my_func 使用的其余函数做了同样的事情。

编辑:

如果我使用subprocess.call(['bash', '-c' ,'my_func a b], shell=True),bash shell 将变为bash-3.2$

【问题讨论】:

    标签: python bash macos shell subprocess


    【解决方案1】:

    你需要在启动python程序之前导出函数

    export -f my_func
    python foo.py
    

    好吧,如果系统的默认 shell (/bin/sh) 不是 bash,则上面的示例可能不起作用。为了避免这种情况,您可以像这样使用子进程调用:

    $ function foo() { echo "bar" ; }
    $ export -f foo
    $ cat foo.py
    import subprocess
    subprocess.call(['bash', '-c', 'foo'])
    $ python foo.py
    bar
    

    替代方案:

    我会将函数放入一个 lib 文件中,比如说:

    # /usr/share/my_lib/my_lib.sh
    
    function my_func() {
        # do something
    }
    

    然后我将通过 PATH 中的脚本公开该函数:

    #!/bin/bash
    # /usr/local/bin/my_prog
    
    source /usr/lib/my_lib/my_lib.sh
    my_func "$1" "$2"
    

    在 Python 中,您只需:

    subprocess.call(['/usr/local/bin/my_prog', 'a', 'b'])
    

    顺便说一句:如果您在其他地方不需要该功能,您可以直接将其放入/usr/local/bin/my_prog

    【讨论】:

    • 感谢您的回答。我试图这样做,但它似乎没有任何效果。
    • 仔细看例子。我使用shell=True
    • 如果我不这样做,我会遇到很多错误,比如ssh: command not found, basename:commnand not found, rsync: command not found e.t.c。所有这些命令都包含在my_func的定义中。
    • 很难在没有看到功能的情况下重现。愚蠢的问题,你为什么不简单地把那个函数放到一个脚本中,比如说/usr/local/bin/my_script,然后调用那个脚本?会不会简单很多?
    • 太好了,这似乎不那么复杂。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2016-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-27
    • 2016-03-11
    相关资源
    最近更新 更多