【问题标题】:How can I avoid calling Python interpreter many times from a Bash script?如何避免从 Bash 脚本中多次调用 Python 解释器?
【发布时间】:2017-03-09 04:15:56
【问题描述】:

我正在处理一个涉及两个主要组件的项目,一个带有 Bash 命令行界面,另一个带有 Python API。出于本问题的目的,假设这些组件都不能被修改为使用不同的界面语言。

我现在需要编写一些脚本来使用这两个组件的特性。我想到了两种可能的方法:(a) 编写调用 Python 解释器的 Bash 脚本以与 Python 组件交互,或者,(b) 使用对 os.system 或类似的调用来编写 Python 脚本,这允许一个人运行 Bash 命令.

编写 Bash 脚本的问题是我经常需要在循环内从 Python 组件调用函数,如下所示:

while read -r line ; do
    echo "Now handling the next line of the file."
    python -c "from my_module import *; my_function('${line}')"
    # some bash commands
done < some_file.txt

我不喜欢这么多次调用 Python 解释器的开销,而且还经常执行相同的导入。有没有办法启动解释器并导入模块一次,然后在该上下文中动态调用其他函数?请记住,我将在 Python 函数调用之间使用其他 Bash 命令。

编写 Python 脚本的问题在于,任何时候我们需要使用命令行界面访问组件,我们都必须调用 os.system 或类似的东西。一些脚本只包括对命令行界面的调用,这意味着我会有一个 Python 脚本,每一行都使用os.system。我也不喜欢这个。

这些脚本,无论是用 Python 还是 Bash 编写的,都将用于单元测试,因此可读性、可维护性和可扩展性比纯粹的速度更重要。此外,为了保持一致性,所有这些都应该用相同的语言编写。

我希望有人可以指导我找到解决此问题的最优雅的解决方案。提前致谢!

【问题讨论】:

  • python 复制?将标准输入发送到 repl?
  • @AlexanderMills 我希望能够做这样的事情,但我以前没有见过命名管道。迭戈的回答向我展示了如何做到这一点。不过感谢您的建议!

标签: python bash language-interoperability


【解决方案1】:

你可以在bash

mkfifo in out
python -ic 'from my_module import *'  <in >out & exec 3> in 4< out
while read -r line ; do
    echo "Now handling the next line of the file."
    echo "my_function('$line')" >&3
    # read the result of my_function
    read r <&4; echo $r
    # some bash commands
done < some_file.txt
exec 3>&-
exec 4<&-
rm in out

您可以在继续执行bash 命令的同时向python 发送命令。

【讨论】:

  • 这正是我所希望的!谢谢!
猜你喜欢
  • 1970-01-01
  • 2016-01-17
  • 1970-01-01
  • 2021-10-16
  • 1970-01-01
  • 1970-01-01
  • 2020-01-09
  • 2011-09-06
  • 2020-07-17
相关资源
最近更新 更多