idobr
idobr

Reputation: 1647

Python one-liner with if block

I have a bash script that receives data from json. I'd like to delegate json parsing to python and operate other things with bash. So I tried the following and it worked:

$cat json.txt | python -c "import sys, json; app_data=json.load(sys.stdin); print app_data['item'][0]['id'];"

I decided to check the list size:

$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']'

It failed with SyntaxError: invalid syntax.

List size check (the code above) works from a separate .py file in general. I'd prefer to use one-liner to keep it simple and store together in shell script.

Is it possible to run python one-liner with some logic (like import json) and if block?

Upvotes: 3

Views: 1710

Answers (1)

dnswlt
dnswlt

Reputation: 3105

A similar question has already been answered here: Executing Python multi-line statements in the one-line command-line. In short, using the funny $'' quoting (which interprets escapes like \n) should work, at least in 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

From a syntactic POV, the problem is that Python allows to use ; only as a separator of so called simple_stmt. But an if_stmt is not a simple statement. See https://docs.python.org/2/reference/simple_stmts.html#grammar-token-simple_stmt.

Upvotes: 6

Related Questions