如何避免从 Bash 脚本中多次调用 Python 解释器?
How can I avoid calling Python interpreter many times from a Bash script?
我正在从事一个涉及两个主要组件的项目,一个具有 Bash 命令行界面,另一个具有 Python API。出于这个问题的目的,假设这些组件都不能修改为使用不同的界面语言。
我现在需要编写一些使用这两个组件的功能的脚本。我有两种可能的方法:(a) 编写 Bash 脚本调用 Python 解释器来与 Python 组件交互,或者,(b) 编写 Python 脚本使用调用 os.system
或类似的东西,允许 运行 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,都将用于单元测试,因此可读性、可维护性和可扩展性比单纯的速度更重要。此外,为了保持一致性,所有这些都应使用相同的语言编写。
我希望有人能指导我找到解决这个问题的最优雅的方法。提前致谢!
您可以在 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
发送命令。
我正在从事一个涉及两个主要组件的项目,一个具有 Bash 命令行界面,另一个具有 Python API。出于这个问题的目的,假设这些组件都不能修改为使用不同的界面语言。
我现在需要编写一些使用这两个组件的功能的脚本。我有两种可能的方法:(a) 编写 Bash 脚本调用 Python 解释器来与 Python 组件交互,或者,(b) 编写 Python 脚本使用调用 os.system
或类似的东西,允许 运行 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,都将用于单元测试,因此可读性、可维护性和可扩展性比单纯的速度更重要。此外,为了保持一致性,所有这些都应使用相同的语言编写。
我希望有人能指导我找到解决这个问题的最优雅的方法。提前致谢!
您可以在 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
发送命令。