在python中执行自定义bash函数
这是一个更简单的问题 简单地说,我在在python中执行自定义bash函数,python,bash,macos,shell,subprocess,Python,Bash,Macos,Shell,Subprocess,这是一个更简单的问题 简单地说,我在~/.bash_profile上定义了一个自定义bash函数my_func,并使用了在同一环境中定义的另外两个bash函数 另外,my_func接受两个参数,比如a和b。my_func所做的是连接到远程服务器并发送一些文件(这些文件由a和b确定) 如果我在bashshell上键入: 。我的_func a b一切正常,我在屏幕上看到一些打印语句 但是,如果我包括: subprocess.call(['#!/bin/bash.my#func a b'],shell
~/.bash_profile
上定义了一个自定义bash函数my_func
,并使用了在同一环境中定义的另外两个bash函数
另外,my_func
接受两个参数,比如a
和b
。my_func所做的是连接到远程服务器并发送一些文件(这些文件由a
和b
确定)
如果我在bash
shell上键入:
。我的_func a b
一切正常,我在屏幕上看到一些打印语句
但是,如果我包括:
subprocess.call(['#!/bin/bash.my#func a b'],shell=True)
我尝试导出my_func
使用的所有bash函数,方法包括:
subprocess.call(['#!/bin/bash export-f my#u func'],shell=True)
我对my#func
使用的其余函数也做了同样的操作
编辑:
如果我使用
subprocess.call(['bash','-c','my_func a b],shell=True)
bash shell将变为bash-3.2$
启动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
}
然后,我将通过路径中的脚本公开该函数:
#!/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:command-not-found、rsync:command-not-found
e.t.c。所有这些命令都包含在my_-func
的定义中。没有看到函数很难复制。愚蠢的问题,你为什么不干脆把这个函数放到一个脚本中,比如说/usr/local/bin/my_script
,然后调用这个脚本呢?这不是更简单吗?太好了,这似乎不那么复杂。谢谢