我有一个 python
脚本(例如 test.py
)和一个 commands.txt
文件,其中包含自定义 bash
函数(例如 my_func
)及其参数,例如
my_func arg1 arv2; my_func arg3 arg4; my_func arg5 arg6;
该函数包含在~/.bash_profile
中。
我尝试做的是:
subprocess.call(['.', path/to/commands.txt], shell=True)
就将 shell 参数设置为 True 而言,我知道这不是最好的情况,但即使以这种方式我似乎也无法实现它。运行 test.py 时得到的结果是:
my_func:找不到命令
最佳答案
您需要直接调用 bash,并指示它处理这两个文件。
在命令行中,这是:
bash -c '. ~/.bash_profile; . commands.txt'
用 python 包装它:
subprocess.call(['bash', '-c', '. ~/.bash_profile; . commands.txt'])
您还可以在commands.txt 顶部获取~/.bash_profile。然后您就可以运行单个文件。
将函数提取到单独的文件中可能是有意义的,因为 .bash_profile 旨在由登录 shell 使用,而不是像这样。
关于python - 在 python 脚本中调用 bash 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47184031/