python - 在 python 脚本中调用 bash 函数

标签 python bash macos subprocess

我有一个 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/

相关文章:

python Constraints——限制数量

python - 如何从列表中删除特定单词?

linux - Unix Bash 脚本导致 git clone 无法工作

linux - Unix 查找命令目录提示

macos - Fluid.app 将控制台日志放在哪里?

python - Django 打印声明安全性

javascript - 使用 jQuery 和变量的问题

bash - 继续从 tcp 服务器读取数据,直到收到特定消息

xcode - 远程运行 Xcode 构建并获取结果以在本地运行项目或显示构建问题

ios - Mac 催化剂版本