我有一个从 json 接收数据的 bash 脚本。我想将 json 解析委托(delegate)给 python 并使用 bash 操作其他东西。所以我尝试了以下方法并且有效:
$cat json.txt | python -c "import sys, json; app_data=json.load(sys.stdin); print app_data['item'][0]['id'];"
我决定检查列表大小:
$cat json.txt | python -c 'import sys, json; app_data=json.load(sys.stdin); if len(app_data['item'])==1: print '1 item:'; print app_data['item'][0]['id']'
它因 SyntaxError 失败:语法无效。
列表大小检查(上面的代码)通常在单独的 .py 文件中工作。 我宁愿使用单行代码来保持简单并一起存储在 shell 脚本中。
是否可以使用某些逻辑(如 import json)和 if block 运行 python 单行代码?
最佳答案
这里已经回答了类似的问题:
Executing Python multi-line statements in the one-line command-line .简而言之,使用有趣的 $''
引号(它解释像 \n
的转义符)应该有效,至少在 bash 中是这样:
$ cat json.txt
{"item": [{"id": 1}]}
$ cat json.txt | python -c $'import sys, json;\nd=json.load(sys.stdin)\nif len(d["item"])==1: print("""1 item:\n%s""" % d["item"][0]["id"])'
1 item:
1
从句法 POV 来看,问题在于 Python 只允许使用 ;
作为所谓的 simple_stmt
的分隔符。但是 if_stmt
并不是一个简单的语句。参见 https://docs.python.org/2/reference/simple_stmts.html#grammar-token-simple_stmt .
关于带有 if block 的 Python 单行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41772774/