【问题标题】: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 脚本中使用 python 文件中存在的常量?
【发布时间】:2021-07-05 21:40:28
【问题描述】:

我想在 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'

感谢您的帮助!

【问题讨论】:

  • 只运行一个 Python 脚本来完成这个任务不是更容易吗?
  • 所以它像配置?将常量值存储在 JSON 文件中怎么样,然后您可以使用jq 在 python 和 shell 脚本中读取?
  • @TimRoberts 不,这只是代码的一部分,shell 脚本也在执行许多其他操作
  • @MarcinOrlowski 我没有使用 JSON 的经验。你能告诉我怎么做吗

标签: python python-3.x shell raspberry-pi sh


【解决方案1】:

您可以将 shell 脚本中的 ash 替换为唯一的格式化字符串(例如 {}),您可以使用 Python 代码中的 replace 函数将该格式化字符串的任何出现替换为所需的主机名( a 变量)将 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中获取变量名并输出到标准输出,然后你可以将输出存储在一个变量中,比如a,你可以在sed命令中使用它

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

【讨论】:

    猜你喜欢
    • 2018-05-19
    • 1970-01-01
    • 1970-01-01
    • 2023-01-06
    • 2017-03-12
    • 1970-01-01
    • 2015-08-18
    • 2018-05-07
    • 1970-01-01
    相关资源
    最近更新 更多