[英]Python If Statement Error, in bash_profile function
I am very new to python and am trying to use it to parse a file with JSON in it within my bash_profile script, and return the value. 我是python的新手,我正在尝试使用它在我的bash_profile脚本中解析带有JSON的文件,并返回值。 I can't seem to get the if statement working. 我似乎无法得到if语句。 It will read the contents of the file, but I recieve this error, with an arrow under the if statement. 它将读取文件的内容,但我收到此错误,在if语句下有一个箭头。
File "<string>", line 1
import sys,json;data=json.loads(sys.stdin.read());if data['123456789']:print...
^
SyntaxError: invalid syntax
Contents of File: 文件内容:
{"123456789":"Well Hello"}
Function that searches file: 搜索文件的功能:
function find_it {
file=~/.pt_branches
CURRENT_CONTENTS=`cat $file`
echo $CURRENT_CONTENTS | python -c "import sys,json;data=json.loads(sys.stdin.read());if data['$1']:print data['$1'];else:print '';"
}
Command 命令
find_it "123456789"
If I were to remove the if statement and just return the value, it does work, but I want it to be able to return and empty string if it does not exist. 如果我要删除if语句并返回值,它确实有效,但我希望它能够返回并清空字符串(如果它不存在)。
echo $CURRENT_CONTENTS | python -c "import sys,json;data=json.loads(sys.stdin.read());print data['$1'];"
Any ideas on what I am doing wrong?!? 关于我做错了什么想法?!?
Do this: 做这个:
echo $CURRENT_CONTENTS | python -c "
import sys
import json
data = json.loads(sys.stdin.read())
if data['$1']:
print data['$1']
else:
print ''"
代码高尔夫!
"import sys, json; data=json.loads(sys.stdin.read()); print data.get('$1') or ''"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.