python popen及json的使用

2020-05-29  本文已影响0人  jayhe

最近在做shell脚本迁移到python的工作,在做自动修改iOS打包的buildNumber的时候,用到了需要从接收命令行返回的结果,以及json文件的操作等,在此记录下

自动修改build号的实现可以参照该文章Jenkins打包iOS自动修改build号

接收shell命令行执行的结果

BuildNumber=$(/usr/libexec/PlistBuddy -c "Print :CFBundleVersion" "${PlistDir}")
buildNumberFP = os.popen('/usr/libexec/PlistBuddy -c "Print :CFBundleVersion" "%s"' %plistDir)
global buildNumber
buildNumber = buildNumberFP.read()
buildNumber = buildNumber.replace('\n', '')
def popen(cmd, mode="r", buffering=-1):
    if not isinstance(cmd, str):
        raise TypeError("invalid cmd type (%s, expected string)" % type(cmd))
    if mode not in ("r", "w"):
        raise ValueError("invalid mode %r" % mode)
    if buffering == 0 or buffering is None:
        raise ValueError("popen() does not support unbuffered streams")
    import subprocess, io
    if mode == "r":
        proc = subprocess.Popen(cmd,
                                shell=True,
                                stdout=subprocess.PIPE,
                                bufsize=buffering)
        return _wrap_close(io.TextIOWrapper(proc.stdout), proc)
    else:
        proc = subprocess.Popen(cmd,
                                shell=True,
                                stdin=subprocess.PIPE,
                                bufsize=buffering)
        return _wrap_close(io.TextIOWrapper(proc.stdin), proc)

json文件的读写

json的写入文件

echo "{\"BuildNumber\":\"${BuildNumber}\", \"BuildVersion\":\"${BuildVersion}\"}" > ${BuildJsonPath}
infoDict = {"BuildNumber" : buildNumber, "BuildVersion" : buildVersion}
with open(buildJsonPath, "w") as fp:
     json.dump(infoDict, fp)

json的读取

preBuildVersion=`cat ${BuildJsonPath} | jq -r ".BuildVersion"`
with open(buildJsonPath, 'r') as fp:
     infoDict = json.load(fp)
     print(infoDict)
global preBuildVersion
preBuildVersion = infoDict['BuildVersion']

参考文档

上一篇下一篇

猜你喜欢

热点阅读