带有 if block 的 Python 单行代码

标签 python command-line

我有一个从 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/

相关文章:

python - 如何将 JSON 树结构转换/转换为 Merkle 树

command-line - 我们可以使用 MS WebDeploy 创建一个新网站吗

python - (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor' with cv::imread

python - 无法将字节连接到 str(转换为 Python3)

python - Google Spreadsheet Python API 或 gspread 是否允许图像或富文本?

python - 我在哪里可以从 Firefox 获取有关 :support 的原始信息

c - 如何从 C 命令行读取星号 ( * ) 作为参数

linux - 通过 bash 脚本查找和 Xargs 复制和重命名

目录的命令行 CVS 更新和本地删除

c - 使用 C 读取 csv 文件,然后进行字符串操作