当前位置: 首页>>代码示例>>Python>>正文


Python json.write方法代码示例

本文整理汇总了Python中json.write方法的典型用法代码示例。如果您正苦于以下问题:Python json.write方法的具体用法?Python json.write怎么用?Python json.write使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在json的用法示例。


在下文中一共展示了json.write方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: process_request

# 需要导入模块: import json [as 别名]
# 或者: from json import write [as 别名]
def process_request(packet):
    pktlen=packet[0:4]
    cmd=packet[4]
    msg=eval(packet[5:])
    msgjson=json.write(msg)
    yyyymm=time.strftime('%Y%m',time.localtime(msg['ts']))
    if cmd=='i':    #收件箱
        filename=FILENAME_INBOX%{'month':yyyymm,}
    elif cmd=='t':  #发件箱
        filename=FILENAME_SENT%{'month':yyyymm,}
    else:
        print 'UNKNOWN:',repr(packet)
        return
    needwrite=False
    if os.path.exists(filename):
        ff=open(filename,'rU')
        for line in ff.xreadlines():
            line=line.strip()
            if line==msgjson:
                needwrite=False
                break
        else:
            needwrite=True
        ff.close()
    else:
        needwrite=True
    if needwrite:
        ff=open(filename,'a+')
        ff.write(msgjson+'\n')
        ff.close()
    return 
开发者ID:gashero,项目名称:talklog,代码行数:33,代码来源:lightmsg.py

示例2: valueTreeToString

# 需要导入模块: import json [as 别名]
# 或者: from json import write [as 别名]
def valueTreeToString(fout, value, path = '.'):
    ty = type(value) 
    if ty  is types.DictType:
        fout.write('%s={}\n' % path)
        suffix = path[-1] != '.' and '.' or ''
        names = value.keys()
        names.sort()
        for name in names:
            valueTreeToString(fout, value[name], path + suffix + name)
    elif ty is types.ListType:
        fout.write('%s=[]\n' % path)
        for index, childValue in zip(xrange(0,len(value)), value):
            valueTreeToString(fout, childValue, path + '[%d]' % index)
    elif ty is types.StringType:
        fout.write('%s="%s"\n' % (path,value))
    elif ty is types.IntType:
        fout.write('%s=%d\n' % (path,value))
    elif ty is types.FloatType:
        fout.write('%s=%.16g\n' % (path,value))
    elif value is True:
        fout.write('%s=true\n' % path)
    elif value is False:
        fout.write('%s=false\n' % path)
    elif value is None:
        fout.write('%s=null\n' % path)
    else:
        assert False and "Unexpected value type" 
开发者ID:KhronosGroup,项目名称:OpenXR-SDK-Source,代码行数:29,代码来源:pyjsontestrunner.py

示例3: rewriteValueTree

# 需要导入模块: import json [as 别名]
# 或者: from json import write [as 别名]
def rewriteValueTree(value, rewrite_path):
    rewrite = json.dumps(value)
    #rewrite = rewrite[1:-1]  # Somehow the string is quoted ! jsonpy bug ?
    file(rewrite_path, 'wt').write(rewrite + '\n')
    return rewrite 
开发者ID:KhronosGroup,项目名称:OpenXR-SDK-Source,代码行数:7,代码来源:pyjsontestrunner.py

示例4: save

# 需要导入模块: import json [as 别名]
# 或者: from json import write [as 别名]
def save(self, path=None):
        if path is None:
            path = self.path
            if path is None:
                raise Exception('Path not provided!')
        with open(path, 'w') as f:
            json.write(self.get_config(), f) 
开发者ID:farizrahman4u,项目名称:eywa,代码行数:9,代码来源:nlu_server.py

示例5: backup_month

# 需要导入模块: import json [as 别名]
# 或者: from json import write [as 别名]
def backup_month(start_tick,stop_tick,yyyymm):
    """备份一个月的短信"""
    conn=sqlite3.connect(DB_FILENAME)
    curr=conn.cursor()
    sql=SQL_GETSMS%{
            'start_tick':start_tick,
            'stop_tick':stop_tick,}
    curr.execute(sql)
    dataset=curr.fetchall()
    curr.close()
    conn.close()
    savedset=set()
    if os.path.exists(INBOX_FILENAME%{'yyyymm':yyyymm}):
        fr_inbox=open(INBOX_FILENAME%{'yyyymm':yyyymm},'r')
        fr_sent=open(SENT_FILENAME%{'yyyymm':yyyymm},'r')
        for line in fr_inbox.xreadlines():
            msgdict=json.read(line)
            savedset.add(msgdict['msgid'])
        for line in fr_sent.xreadlines():
            msgdict=json.read(line)
            savedset.add(msgdict['msgid'])
        fr_inbox.close()
        fr_sent.close()
    msglist=[]
    fw_inbox=open(INBOX_FILENAME%{'yyyymm':yyyymm},'a+')
    fw_sent=open(SENT_FILENAME%{'yyyymm':yyyymm},'a+')
    for (starttime,flag,msg,addr) in dataset:
        msgdict={
                'msg':msg.encode('utf-8'),
                'msgid':'%d-%s-%d'%(starttime,
                    addr.encode('utf-8'),len(msg)),
                'ts':starttime,}
        if msgdict['msgid'] in savedset:
            continue
        if flag==3: #sent
            msgdict['tfrom']=LOCAL_PHONENUMBER
            msgdict['to']=addr.encode('utf-8')
            fw_sent.write(json.write(msgdict)+'\n')
        elif flag==2:   #inbox
            msgdict['tto']=LOCAL_PHONENUMBER
            msgdict['tfrom']=addr.encode('utf-8')
            fw_inbox.write(json.write(msgdict)+'\n')
        else:
            raise ValueError('Unknown flags=%d'%flags)
    fw_inbox.close()
    fw_sent.close()
    return 
开发者ID:gashero,项目名称:talklog,代码行数:49,代码来源:ipsms.py

示例6: backup_month

# 需要导入模块: import json [as 别名]
# 或者: from json import write [as 别名]
def backup_month(start_tick,stop_tick,yyyymm):
    """备份一个月的短信"""
    conn=sqlite3.connect(DB_FILENAME)
    curr=conn.cursor()
    sql=SQL_GETSMS%{
        'start_tick':start_tick,
        'stop_tick':stop_tick,}
    #print sql
    curr.execute(sql)
    dataset=curr.fetchall()
    savedset=set()
    if os.path.exists(INBOX_FILENAME%{'yyyymm':yyyymm}):
        fr_inbox=open(INBOX_FILENAME%{'yyyymm':yyyymm},'r')
        fr_sent=open(SENT_FILENAME%{'yyyymm':yyyymm},'r')
        for line in fr_inbox.xreadlines():
            msgdict=json.read(line)
            savedset.add(msgdict['msgid'])
        for line in fr_sent.xreadlines():
            msgdict=json.read(line)
            savedset.add(msgdict['msgid'])
        fr_inbox.close()
        fr_sent.close()
    msglist=[]
    fw_inbox=open(INBOX_FILENAME%{'yyyymm':yyyymm},'a+')
    fw_sent=open(SENT_FILENAME%{'yyyymm':yyyymm},'a+')
    #print 'len(dataset)=',len(dataset)
    for (starttime,outgoing,freetext,remoteuid) in dataset:
        #print repr(outgoing),repr(freetext),repr(starttime)
        msgdict={
                'msg':freetext.encode('utf-8'),
                'msgid':'%d-%s-%d'%(starttime,
                    remoteuid.encode('utf-8'),len(freetext)),
                'ts':starttime,
                }
        if msgdict['msgid'] in savedset:
            continue
        if outgoing==1:
            msgdict['tfrom']=LOCAL_PHONENUMBER
            msgdict['tto']=remoteuid.encode('utf-8')
            fw_sent.write(json.write(msgdict)+'\n')
        elif outgoing==0:
            msgdict['tto']=LOCAL_PHONENUMBER
            msgdict['tfrom']=remoteuid.encode('utf-8')
            fw_inbox.write(json.write(msgdict)+'\n')
        else:
            raise ValueError('Unknow outgoing=%d'%outgoing)
        #print msgdict
    # do it
    fw_inbox.close()
    fw_sent.close()
    curr.close()
    conn.close()
    return 
开发者ID:gashero,项目名称:talklog,代码行数:55,代码来源:n900mm.py

示例7: _call

# 需要导入模块: import json [as 别名]
# 或者: from json import write [as 别名]
def _call(self, cmd, data=None):
        if data is None:
            data = {}
        data['cmd'] = cmd
        data['version'] = API_VERSION
        request = bytearray(json_encode(data), encoding='utf-8')

        response = None
        for _ in range(2):
            if not self.socket and cmd != 'login':
                self._call('login', self.userpwd.copy())
            self.socket_lock.acquire()
            try:
                sock = self.connect()
                response = self._sendrecv(sock, request)
            except IOError as err:
                sys.stderr.write(str(err) + "\n")
                self.close()
            except socket.error as err:
                sys.stderr.write(str(err) + "\n")
                self.close()
                raise IOError('Connection refused')
            else:
                break
            finally:
                self.socket_lock.release()

        if response is None:
            raise IOError('Connection lost or timed out during API request')

        try:
            if PY2:
                return json_decode(response.decode('utf-8'))
            else:
                return json_decode(response)
        except Exception:
            raise RuntimeError('Invalid API response')

        if not response.get('error'):
            return response

        error = response['error']
        if error in ('not-logged-in', 'invalid-credentials'):
            raise AccessDeniedException('Access denied, check your credentials')
        elif 'banned' == error:
            raise AccessDeniedException('Access denied, account is suspended')
        elif 'insufficient-funds' == error:
            raise AccessDeniedException(
                'CAPTCHA was rejected due to low balance')
        elif 'invalid-captcha' == error:
            raise ValueError('CAPTCHA is not a valid image')
        elif 'service-overload' == error:
            raise OverflowError(
                'CAPTCHA was rejected due to service overload, try again later')
        else:
            self.socket_lock.acquire()
            self.close()
            self.socket_lock.release()
            raise RuntimeError('API server error occured: %s' % error) 
开发者ID:morpheus65535,项目名称:bazarr,代码行数:61,代码来源:deathbycaptcha.py


注:本文中的json.write方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。