I want to use python from my bash script, for json parsing and other stuff, having some a syntax error I cannot really understand. So I'd like to deeply understand why this code doesn't work :
>>> import sys, json; if "foo": print("yes")
File "<stdin>", line 1
import sys, json; if "foo": print("yes")
^
SyntaxError: invalid syntax
while this one works:
>>> if "foo": print ("yes"); import sys, os
...
yes
Same as :
>>> import sys, json; with open("foo.json") as fd: print(fd.read())
File "<stdin>", line 1
import sys, json; with open("papi.json") as fd: print(fd.read())
^
SyntaxError: invalid syntax
This works :
>>> with open("foo.json") as fd: print(fd.read()); import sys, json
...
{"repositoryName": "REPOSITORY", "triggers": [{"name": "cc-branches-lifecycle", "destinationArn": "arn:aws:lambda:REGION:ACCOUNT:function:lambda-engineering-codepipeline-cc-lifecycle-RELEASE", "customData": "{\"pipeline_exec_function\": \"arn:aws:lambda:REGION:ACCOUNT:function:lambda-engineering-codepipeline-cc-updates-RELEASE\", \"pipeline_name\": \"PIPELINE\", \"bucket\": \"BUCKET\"}", "branches": [], "events": ["createReference", "deleteReference"]}, {"name": "trigger-DEVBRANCH-updates", "destinationArn": "arn:aws:lambda:REGION:ACCOUNT:function:lambda-engineering-codepipeline-cc-updates-RELEASE", "customData": "{\"pipeline_name\": \"PIPELINE\", \"bucket\": \"BUCKET\"}", "branches": ["DEVBRANCH"], "events": ["updateReference"]}]}
this also works :
>>> import sys, json; fd = open("foo.json"); print(fd.read())
{"repositoryName": "REPOSITORY", "triggers": [{"name": "cc-branches-lifecycle", "destinationArn": "arn:aws:lambda:REGION:ACCOUNT:function:lambda-engineering-codepipeline-cc-lifecycle-RELEASE", "customData": "{\"pipeline_exec_function\": \"arn:aws:lambda:REGION:ACCOUNT:function:lambda-engineering-codepipeline-cc-updates-RELEASE\", \"pipeline_name\": \"PIPELINE\", \"bucket\": \"BUCKET\"}", "branches": [], "events": ["createReference", "deleteReference"]}, {"name": "trigger-DEVBRANCH-updates", "destinationArn": "arn:aws:lambda:REGION:ACCOUNT:function:lambda-engineering-codepipeline-cc-updates-RELEASE", "customData": "{\"pipeline_name\": \"PIPELINE\", \"bucket\": \"BUCKET\"}", "branches": ["DEVBRANCH"], "events": ["updateReference"]}]}
My origanal comes from the fact I'm trying to update aws codecommit repository triggers from bash. Here is the real command issuing error :
#aws codecommit get-repository-triggers --repository-name $repository | python -c 'import json, sys; triggers = json.load(sys.stdin).get("triggers", []); with open(os.environ["triggersfile"]) as fp: triggers_doc = json.load(fp); triggers_doc["triggers"].extend(triggers); triggers_doc["triggers"] = list({trigger["name"]:trigger for trigger in triggers_doc["triggers"]}.values()); with open(os.environ["triggersfile"], "w") as fd: json.dump(triggers_doc, fd)'
I know I can use open and close statements, but I want to understand why the with statement doent' work.