[英]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 脚本中使用 python 文件中存在的常量。已共享两个文件代码。 我正在尝试使用 shell 脚本将树莓派的主机名从“raspberry”更改为“ash”。但我不想在 shell 脚本中对名称进行硬编码。我有一个我想要的 constants.py 文件存储所有常量。
.sh
sed -i 's/raspberry/ash/' hostname
sed -i 's/raspberry/ash/' hosts
常量.py
a = "ash"
我想在 shell 脚本中使用这个 'a' 而不是 'ash'
谢谢您的帮助!
You can replace ash
in the shell script with a unique formatted string (for example {}
) that you can use the replace
function in Python code to replace any occurrences of that formatted string with the desired hostname ( a
variable) when reading the content of将 shell 脚本转换为 Python 字符串。 在您阅读 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 和 output 的变量名将其存储到标准输出,然后您可以将 output 存储在变量中,例如a
,您可以在sed
命令中使用
a=$(python3 -c "import constants; print(constants.a)")
sed -i "s/raspberry/$a/" hostname
sed -i "s/raspberry/$a/" hosts
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.