繁体   English   中英

Python if语句错误,在bash_profile函数中

[英]Python If Statement Error, in bash_profile function

我是python的新手,我正在尝试使用它在我的bash_profile脚本中解析带有JSON的文件,并返回值。 我似乎无法得到if语句。 它将读取文件的内容,但我收到此错误,在if语句下有一个箭头。

File "<string>", line 1
    import sys,json;data=json.loads(sys.stdin.read());if data['123456789']:print...
                                                       ^
SyntaxError: invalid syntax

文件内容:

{"123456789":"Well Hello"}

搜索文件的功能:

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 '';"
}

命令

find_it "123456789"

如果我要删除if语句并返回值,它确实有效,但我希望它能够返回并清空字符串(如果它不存在)。

echo $CURRENT_CONTENTS | python -c "import sys,json;data=json.loads(sys.stdin.read());print data['$1'];"

关于我做错了什么想法?!?

做这个:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM