我想使用bash脚本中的python进行json解析和其他工作,有一些语法错误,我无法真正理解。
所以我想深入理解为什么这段代码不起作用:
>>> import sys, json; if "foo": print("yes")
File "<stdin>", line 1
import sys, json; if "foo": print("yes")
^
SyntaxError: invalid syntax
当这一个工作时:
>>> if "foo": print ("yes"); import sys, os
...
yes
等同于:
>>> 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
这工作:
>>> 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"]}]}
这也适用于:
>>> 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"]}]}
我的建议来自于我试图从bash更新aws codecommit存储库触发器的事实。下面是真正的命令发出错误:
#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)'
我知道我可以用
打开
和
关闭
但是我想知道为什么
具有
声明不起作用。