【问题标题】:Writing multiple lines of python code in a single line in shell script在 shell 脚本的一行中编写多行 python 代码
【发布时间】:2017-03-14 19:56:24
【问题描述】:

我正在尝试使用 shell 脚本而不使用 jq 来编辑 json 文件。我找到了必要的 python 代码,Python read JSON file and modify,但是当我尝试在 shell 中的一行中执行所有这些代码时,我收到了一个语法错误。 我写了以下命令:

export data = `python -c "import json;import os;filename='test.json';with open(filename, 'r') as f:data = json.load(f) data['id'] = 'abc';os.remove(filename);with open(filename, 'w') as f:json.dump(data, f, indent=4)"`

有什么建议吗?

【问题讨论】:

  • 你为什么不把你的代码放在一个单独的python脚本中,你可以在shell中用一行代码调用它? python yourscript.py。你也可以让你的脚本接受你需要的任何参数。
  • 为什么不直接创建一个.py 文件并运行它?
  • 我正在尝试通过 shell 运行 jenkins 作业,我需要其中一个 jenkins 参数,用于修改 json 中的数据。这就是为什么我需要在单个命令中执行修改操作。
  • 确保= 周围没有空格。还要考虑$() 替换反引号,导致export data=$(python ...)
  • 我尝试执行:export data=(python -c "import json;import os;filename='test.json';with open(filename, 'r') as f:data = json .load(f) data['id'] = 'abc';os.remove(filename);with open(filename, 'w') as f:json.dump(data, f, indent=4)") 。我在“with”处看到语法错误。

标签: python json shell


【解决方案1】:

得到答案:

$(python -c "import json;import os;filename='test.json';f=open(filename, 'r');data=json.load(f);data['id']="abc";os.remove(filename);f=open(filename, 'w');json.dump(data, f, indent=4);")

还是谢谢!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-03
    • 2020-02-21
    • 2011-07-12
    相关资源
    最近更新 更多