有什么方法可以在 shell 脚本中导入 python 文件并在 shell 脚本中使用 python 文件中存在的常量?

Is there any way to import a python file inside a shell script and use the constants present in python file inside shell script?

我想在 shell script.Have 共享两个文件代码中使用 python 文件中的常量。 我正在尝试使用 shell script.But 将 raspberry pi 的主机名从 'raspberry' 更改为 'ash' 我不想在 shell script.I 有一个 constants.py 文件,我想在其中存储所有常量。

.sh

sed -i 's/raspberry/ash/' hostname
sed -i 's/raspberry/ash/' hosts

constants.py

a = "ash"

我想在 shell 脚本中使用此 'a' 而不是 'ash'

感谢您的帮助!

您可以将 shell 脚本中的 ash 替换为您可以在 [=31] 中使用 replace 函数的唯一格式化字符串(例如 {}) =] 代码,在将 shell 脚本的内容读入 Python 字符串时,用所需的主机名(a 变量)替换任何出现的格式化字符串。阅读 shell 脚本的字符串并将其替换为所需的主机名后,您可以使用更新后的字符串

覆盖脚本

Shell 脚本 (test.sh):

sed -i 's/raspberry/{}/' hostname
sed -i 's/raspberry/{}/' hosts

Python 脚本:

a = "ash"

filename = "test.sh" # shell script to replace hostname
# Read file content into string and replace the formatted string with the desired hostname
with open(filename, 'r') as fl:
    content = fl.read().replace('{}', a)

# Overwrite the shell script with the updated string
with open(filename, 'w') as fl:
    fl.write(content)

编辑:或者,如果您知道变量存储在与shell脚本相同目录的constants.py脚本中,您可以使用命令python3 -c "import constants; print(constants.<variable>)"来获取constants.py 中的变量名并将其输出到标准输出,然后您可以将输出存储在一个变量中,比如 a,您可以在 sed 命令中使用

a=$(python3 -c "import constants; print(constants.a)")
sed -i "s/raspberry/$a/" hostname
sed -i "s/raspberry/$a/" hosts