diff --git a/client/app_utils.py b/client/app_utils.py index dcbea42..77acf38 100644 --- a/client/app_utils.py +++ b/client/app_utils.py @@ -1,4 +1,5 @@ # -*- coding: utf-8-*- +from __future__ import print_function import smtplib from email.MIMEText import MIMEText from email.MIMEMultipart import MIMEMultipart @@ -40,7 +41,7 @@ def sendEmail(SUBJECT, BODY, ATTACH_LIST, TO, FROM, SENDER, session.sendmail(SENDER, TO, msg.as_string()) session.close() return True - except Exception, e: + except Exception as e: _logger.error(e) return False @@ -78,7 +79,7 @@ def emailUser(profile, SUBJECT="", BODY="", ATTACH_LIST=[]): recipient, password, server, port) return True - except Exception, e: + except Exception as e: _logger.error(e) return False @@ -100,7 +101,7 @@ def wechatUser(profile, wxbot, SUBJECT="", BODY="", wxbot.send_img_msg_by_uid(fpath, user_id) return True return True - except Exception, e: + except Exception as e: _logger.error(e) return False return False @@ -141,14 +142,14 @@ def create_reminder(remind_event, remind_time): remind_time[:4] + '-' + remind_time[4:6] + '-' + \ remind_time[6:8] + 'T' + remind_time[8:10] + ':' + \ remind_time[10:12] + ':' + remind_time[12:] - print cmd + print(cmd) try: res = subprocess.call( [cmd], stdout=subprocess.PIPE, shell=True) - print res + print(res) return(res == 0) - except Exception, e: + except Exception as e: _logger.error(e) return False else: @@ -200,7 +201,7 @@ def get_due_reminders(): stdin=subprocess.PIPE) p.stdin.write('yes\n') - except Exception, e: + except Exception as e: _logger.error(e) return due_tasks diff --git a/client/audio_utils.py b/client/audio_utils.py index aab4c73..f559f58 100644 --- a/client/audio_utils.py +++ b/client/audio_utils.py @@ -1,5 +1,6 @@ #!/usr/bin/env python # coding: utf-8 +from __future__ import print_function import os from pydub import AudioSegment @@ -11,4 +12,4 @@ def mp3_to_wav(mp3_file): voice.export(target, format="wav") return target else: - print u"文件错误" + print(u"文件错误") diff --git a/client/brain.py b/client/brain.py index 961ac52..94f69d9 100644 --- a/client/brain.py +++ b/client/brain.py @@ -1,7 +1,8 @@ # -*- coding: utf-8-*- +from __future__ import absolute_import import logging import pkgutil -import dingdangpath +from . import dingdangpath class Brain(object): diff --git a/client/conversation.py b/client/conversation.py index 26ce6d0..48e3647 100644 --- a/client/conversation.py +++ b/client/conversation.py @@ -1,7 +1,8 @@ # -*- coding: utf-8-*- +from __future__ import absolute_import import logging -from notifier import Notifier -from brain import Brain +from .notifier import Notifier +from .brain import Brain import time diff --git a/client/diagnose.py b/client/diagnose.py index 38f2162..4027e7d 100644 --- a/client/diagnose.py +++ b/client/diagnose.py @@ -1,4 +1,5 @@ # -*- coding: utf-8-*- +from __future__ import absolute_import import os import sys import time @@ -7,7 +8,7 @@ import pkgutil import logging import pip.req -import dingdangpath +from . import dingdangpath if sys.version_info < (3, 3): from distutils.spawn import find_executable else: diff --git a/client/g2p.py b/client/g2p.py index bc9c38d..10178e2 100644 --- a/client/g2p.py +++ b/client/g2p.py @@ -1,4 +1,5 @@ # -*- coding: utf-8-*- +from __future__ import absolute_import import os import re import subprocess @@ -7,8 +8,8 @@ import yaml -import diagnose -import dingdangpath +from . import diagnose +from . import dingdangpath class PhonetisaurusG2P(object): diff --git a/client/local_mic.py b/client/local_mic.py index 3566410..06e92a1 100644 --- a/client/local_mic.py +++ b/client/local_mic.py @@ -4,6 +4,12 @@ over the terminal. Useful for debugging. Unlike with the typical Mic implementation, Dingdang is always active listening with local_mic. """ +from __future__ import print_function + +try: + raw_input # Python 2 +except NameError: + raw_input = input # Python 3 class Mic: diff --git a/client/mic.py b/client/mic.py index ab562fd..c5bdf29 100644 --- a/client/mic.py +++ b/client/mic.py @@ -2,6 +2,7 @@ """ The Mic class handles all interactions with the microphone and speaker. """ +from __future__ import absolute_import import ctypes import logging import tempfile @@ -9,9 +10,9 @@ import audioop import time import pyaudio -import dingdangpath -import mute_alsa -from app_utils import wechatUser +from . import dingdangpath +from . import mute_alsa +from .app_utils import wechatUser class Mic: @@ -97,14 +98,14 @@ def fetchThreshold(self): lastN.append(self.getScore(data)) average = sum(lastN) / len(lastN) - except Exception, e: + except Exception as e: self._logger.debug(e) continue try: stream.stop_stream() stream.close() - except Exception, e: + except Exception as e: self._logger.debug(e) pass @@ -174,7 +175,7 @@ def passiveListen(self, PERSONA): # flag raised when sound disturbance detected didDetect = False - except Exception, e: + except Exception as e: self._logger.debug(e) pass @@ -193,7 +194,7 @@ def passiveListen(self, PERSONA): if score > THRESHOLD: didDetect = True break - except Exception, e: + except Exception as e: self._logger.debug(e) continue @@ -204,7 +205,7 @@ def passiveListen(self, PERSONA): # self.stop_passive = False stream.stop_stream() stream.close() - except Exception, e: + except Exception as e: self._logger.debug(e) pass return (None, None) @@ -221,7 +222,7 @@ def passiveListen(self, PERSONA): break data = stream.read(CHUNK) frames.append(data) - except Exception, e: + except Exception as e: self._logger.debug(e) continue @@ -230,7 +231,7 @@ def passiveListen(self, PERSONA): # self.stop_passive = False stream.stop_stream() stream.close() - except Exception, e: + except Exception as e: self._logger.debug(e) pass @@ -307,7 +308,7 @@ def activeListenToAllOptions(self, THRESHOLD=None, LISTEN=True, # TODO: 0.8 should not be a MAGIC NUMBER! if average < THRESHOLD * 0.8: break - except Exception, e: + except Exception as e: self._logger.error(e) continue @@ -317,7 +318,7 @@ def activeListenToAllOptions(self, THRESHOLD=None, LISTEN=True, try: stream.stop_stream() stream.close() - except Exception, e: + except Exception as e: self._logger.debug(e) pass @@ -343,7 +344,7 @@ def say(self, phrase, # incase calling say() method which # have not implement cache feature yet. # the count of args should be 3. - if self.speaker.say.func_code.co_argcount > 2: + if self.speaker.say.__code__.co_argcount > 2: self.speaker.say(phrase, cache) else: self.speaker.say(phrase) diff --git a/client/notifier.py b/client/notifier.py index 447a25e..f3a0df8 100644 --- a/client/notifier.py +++ b/client/notifier.py @@ -1,10 +1,11 @@ # -*- coding: utf-8-*- +from __future__ import absolute_import import Queue import atexit -from plugins import Email +from .plugins import Email from apscheduler.schedulers.background import BackgroundScheduler import logging -import app_utils +from . import app_utils import time diff --git a/client/plugins/Camera.py b/client/plugins/Camera.py index fa9d203..6391515 100755 --- a/client/plugins/Camera.py +++ b/client/plugins/Camera.py @@ -1,8 +1,9 @@ # -*- coding: utf-8-*- +from __future__ import absolute_import import os import subprocess -import time +from . import time import sys WORDS = [u"PAIZHAO", u"ZHAOPIAN"] diff --git a/client/plugins/Chatting.py b/client/plugins/Chatting.py index 0a0b40a..f957193 100644 --- a/client/plugins/Chatting.py +++ b/client/plugins/Chatting.py @@ -1,5 +1,11 @@ # -*- coding: utf-8-*- # 闲聊插件 + +try: + reload # Python 2 +except NameError: # Python 3 + from importlib import reload + import sys reload(sys) sys.setdefaultencoding('utf8') diff --git a/client/plugins/Email.py b/client/plugins/Email.py index 9534319..0574c4f 100644 --- a/client/plugins/Email.py +++ b/client/plugins/Email.py @@ -1,7 +1,8 @@ # -*- coding: utf-8-*- +from __future__ import absolute_import import imaplib -import email -import time +from . import email +from . import time import datetime import logging from dateutil import parser diff --git a/client/plugins/Hass.py b/client/plugins/Hass.py index 10b33f4..84c61f7 100644 --- a/client/plugins/Hass.py +++ b/client/plugins/Hass.py @@ -1,7 +1,14 @@ # -*- coding:utf-8 -*- +from __future__ import print_function import requests import json import logging + +try: + reload # Python 2 +except NameError: # Python 3 + from importlib import reload + import sys reload(sys) sys.setdefaultencoding('utf8') @@ -54,7 +61,7 @@ def hass(text, mic, profile): if text in dingdang: try: measurement = attributes["unit_of_measurement"] - except Exception, e: + except Exception as e: pass if 'measurement' in locals().keys(): text = text + "状态是" + state + measurement @@ -79,7 +86,7 @@ def hass(text, mic, profile): else: mic.say(u"对不起,执行失败", cache=True) print(format(request.status_code)) - except Exception, e: + except Exception as e: pass break else: diff --git a/client/robot.py b/client/robot.py index 9ab4a7e..4451438 100644 --- a/client/robot.py +++ b/client/robot.py @@ -1,14 +1,19 @@ # -*- coding: utf-8-*- +from __future__ import print_function +from __future__ import absolute_import import requests import json import logging from uuid import getnode as get_mac -from app_utils import sendToUser, create_reminder +from .app_utils import sendToUser, create_reminder from abc import ABCMeta, abstractmethod -import sys - +try: + reload # Python 2 +except NameError: # Python 3 + from importlib import reload +import sys reload(sys) sys.setdefaultencoding('utf-8') diff --git a/client/snowboy/snowboydetect.py b/client/snowboy/snowboydetect.py index 2017296..6e6f7c4 100644 --- a/client/snowboy/snowboydetect.py +++ b/client/snowboy/snowboydetect.py @@ -1,3 +1,4 @@ +from __future__ import absolute_import # This file was automatically generated by SWIG (http://www.swig.org). # Version 3.0.10 # @@ -17,7 +18,7 @@ def swig_import_helper(): try: fp, pathname, description = imp.find_module('_snowboydetect', [dirname(__file__)]) except ImportError: - import _snowboydetect + from . import _snowboydetect return _snowboydetect if fp is not None: try: @@ -28,7 +29,7 @@ def swig_import_helper(): _snowboydetect = swig_import_helper() del swig_import_helper else: - import _snowboydetect + from . import _snowboydetect del _swig_python_version_info try: _swig_property = property diff --git a/client/stt.py b/client/stt.py index 3f3164f..613f317 100644 --- a/client/stt.py +++ b/client/stt.py @@ -1,5 +1,7 @@ #!/usr/bin/env python2 # -*- coding: utf-8-*- +from __future__ import print_function +from __future__ import absolute_import import os import base64 import wave @@ -11,9 +13,9 @@ from abc import ABCMeta, abstractmethod import requests import yaml -import dingdangpath -import diagnose -import vocabcompiler +from . import dingdangpath +from . import diagnose +from . import vocabcompiler from uuid import getnode as get_mac import hashlib import datetime @@ -24,6 +26,11 @@ from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) +try: + reload # Python 2 +except NameError: # Python 3 + from importlib import reload + reload(sys) sys.setdefaultencoding('utf8') @@ -559,8 +566,8 @@ def __init__(self, sensitivity, model, hotword): self.resource_file = os.path.join(dingdangpath.LIB_PATH, 'snowboy/common.res') try: - from snowboy import snowboydetect - except Exception, e: + from .snowboy import snowboydetect + except Exception as e: self._logger.critical(e) if 'libf77blas.so' in e.message: self._logger.critical("您可能需要安装一个so包加载库:" + diff --git a/client/tts.py b/client/tts.py index 605dba8..94a680b 100644 --- a/client/tts.py +++ b/client/tts.py @@ -7,6 +7,8 @@ play - play the audio in 'filename' is_available - returns True if the platform supports this implementation """ +from __future__ import print_function +from __future__ import absolute_import import os import platform import tempfile @@ -26,14 +28,19 @@ import argparse import yaml -import diagnose -import dingdangpath +from . import diagnose +from . import dingdangpath try: import gtts except ImportError: pass +try: + reload # Python 2 +except NameError: # Python 3 + from importlib import reload + import sys reload(sys) sys.setdefaultencoding('utf8') diff --git a/client/vocabcompiler.py b/client/vocabcompiler.py index 080ea05..6f64e14 100644 --- a/client/vocabcompiler.py +++ b/client/vocabcompiler.py @@ -3,6 +3,8 @@ Iterates over all the WORDS variables in the plugins and creates a vocabulary for the respective stt_engine if needed. """ +from __future__ import print_function +from __future__ import absolute_import import os import tempfile @@ -16,10 +18,10 @@ from abc import ABCMeta, abstractmethod, abstractproperty import yaml -import brain -import dingdangpath +from . import brain +from . import dingdangpath -from g2p import PhonetisaurusG2P +from .g2p import PhonetisaurusG2P try: import cmuclmtk except ImportError: diff --git a/client/wxbot.py b/client/wxbot.py index e9795df..96763b7 100644 --- a/client/wxbot.py +++ b/client/wxbot.py @@ -1,6 +1,8 @@ #!/usr/bin/env python # coding: utf-8 +from __future__ import print_function +from __future__ import absolute_import import os import sys import traceback @@ -14,7 +16,7 @@ import time import re import random -import dingdangpath +from . import dingdangpath from traceback import format_exc from requests.exceptions import ConnectionError, ReadTimeout import HTMLParser @@ -223,7 +225,7 @@ def get_big_contact(self): self.cursor += self.batch_count cur_batch = map(map_username_batch, cur_batch) user_info_list += self.batch_get_contact(cur_batch) - print "[INFO] Get batch contacts" + print("[INFO] Get batch contacts") self.member_list = user_info_list special_users = ['newsapp', 'filehelper', 'weibo', 'qqmail', @@ -285,8 +287,8 @@ def get_big_contact(self): f.write(json.dumps(self.group_members)) with open(os.path.join(self.temp_pwd,'account_info.json'), 'w') as f: f.write(json.dumps(self.account_info)) - print '[INFO] Get %d contacts' % len(self.contact_list) - print '[INFO] Start to process messages .' + print('[INFO] Get %d contacts' % len(self.contact_list)) + print('[INFO] Start to process messages .') return True @@ -564,7 +566,7 @@ def extract_msg_content(self, msg_type_id, msg): msg_content['data'] = pos msg_content['detail'] = data if self.DEBUG: - print ' %s[Location] %s ' % (msg_prefix, pos) + print(' %s[Location] %s ' % (msg_prefix, pos)) else: msg_content['type'] = 0 if msg_type_id == 3 or (msg_type_id == 1 and msg['ToUserName'][:2] == '@@'): # Group text message @@ -579,28 +581,28 @@ def extract_msg_content(self, msg_type_id, msg): msg_content['data'] = content if self.DEBUG: try: - print ' %s[Text] %s' % (msg_prefix, msg_content['data']) + print(' %s[Text] %s' % (msg_prefix, msg_content['data'])) except UnicodeEncodeError: - print ' %s[Text] (illegal text).' % msg_prefix + print(' %s[Text] (illegal text).' % msg_prefix) elif mtype == 3: msg_content['type'] = 3 msg_content['data'] = self.get_msg_img_url(msg_id) msg_content['img'] = self.session.get(msg_content['data']).content.encode('hex') if self.DEBUG: image = self.get_msg_img(msg_id) - print ' %s[Image] %s' % (msg_prefix, image) + print(' %s[Image] %s' % (msg_prefix, image)) elif mtype == 34: msg_content['type'] = 4 msg_content['data'] = self.get_voice_url(msg_id) msg_content['voice'] = self.session.get(msg_content['data']).content.encode('hex') if self.DEBUG: voice = self.get_voice(msg_id) - print ' %s[Voice] %s' % (msg_prefix, voice) + print(' %s[Voice] %s' % (msg_prefix, voice)) elif mtype == 37: msg_content['type'] = 37 msg_content['data'] = msg['RecommendInfo'] if self.DEBUG: - print ' %s[useradd] %s' % (msg_prefix,msg['RecommendInfo']['NickName']) + print(' %s[useradd] %s' % (msg_prefix,msg['RecommendInfo']['NickName'])) elif mtype == 42: msg_content['type'] = 5 info = msg['RecommendInfo'] @@ -610,18 +612,18 @@ def extract_msg_content(self, msg_type_id, msg): 'city': info['City'], 'gender': ['unknown', 'male', 'female'][info['Sex']]} if self.DEBUG: - print ' %s[Recommend]' % msg_prefix - print ' -----------------------------' - print ' | NickName: %s' % info['NickName'] - print ' | Alias: %s' % info['Alias'] - print ' | Local: %s %s' % (info['Province'], info['City']) - print ' | Gender: %s' % ['unknown', 'male', 'female'][info['Sex']] - print ' -----------------------------' + print(' %s[Recommend]' % msg_prefix) + print(' -----------------------------') + print(' | NickName: %s' % info['NickName']) + print(' | Alias: %s' % info['Alias']) + print(' | Local: %s %s' % (info['Province'], info['City'])) + print(' | Gender: %s' % ['unknown', 'male', 'female'][info['Sex']]) + print(' -----------------------------') elif mtype == 47: msg_content['type'] = 6 msg_content['data'] = self.search_content('cdnurl', content) if self.DEBUG: - print ' %s[Animation] %s' % (msg_prefix, msg_content['data']) + print(' %s[Animation] %s' % (msg_prefix, msg_content['data'])) elif mtype == 49: msg_content['type'] = 7 if msg['AppMsgType'] == 3: @@ -640,52 +642,52 @@ def extract_msg_content(self, msg_type_id, msg): 'content': msg.get('Content') # 有的公众号会发一次性3 4条链接一个大图,如果只url那只能获取第一条,content里面有所有的链接 } if self.DEBUG: - print ' %s[Share] %s' % (msg_prefix, app_msg_type) - print ' --------------------------' - print ' | title: %s' % msg['FileName'] - print ' | desc: %s' % self.search_content('des', content, 'xml') - print ' | link: %s' % msg['Url'] - print ' | from: %s' % self.search_content('appname', content, 'xml') - print ' | content: %s' % (msg.get('content')[:20] if msg.get('content') else "unknown") - print ' --------------------------' + print(' %s[Share] %s' % (msg_prefix, app_msg_type)) + print(' --------------------------') + print(' | title: %s' % msg['FileName']) + print(' | desc: %s' % self.search_content('des', content, 'xml')) + print(' | link: %s' % msg['Url']) + print(' | from: %s' % self.search_content('appname', content, 'xml')) + print(' | content: %s' % (msg.get('content')[:20] if msg.get('content') else "unknown")) + print(' --------------------------') elif mtype == 62: msg_content['type'] = 8 msg_content['data'] = content if self.DEBUG: - print ' %s[Video] Please check on mobiles' % msg_prefix + print(' %s[Video] Please check on mobiles' % msg_prefix) elif mtype == 53: msg_content['type'] = 9 msg_content['data'] = content if self.DEBUG: - print ' %s[Video Call]' % msg_prefix + print(' %s[Video Call]' % msg_prefix) elif mtype == 10002: msg_content['type'] = 10 msg_content['data'] = content if self.DEBUG: - print ' %s[Redraw]' % msg_prefix + print(' %s[Redraw]' % msg_prefix) elif mtype == 10000: # unknown, maybe red packet, or group invite msg_content['type'] = 12 if u'红包' in msg['Content']: - print '有红包!' + print('有红包!') msg_content['is_hongbao'] = 1 elif u'邀请' in msg['Content']: - print '被拉入某群!' + print('被拉入某群!') msg_content['is_entergroup'] = 1 self.get_contact() msg_content['data'] = msg['Content'] if self.DEBUG: - print ' [Unknown]' + print(' [Unknown]') elif mtype == 43: msg_content['type'] = 13 msg_content['data'] = self.get_video_url(msg_id) if self.DEBUG: - print ' %s[video] %s' % (msg_prefix, msg_content['data']) + print(' %s[video] %s' % (msg_prefix, msg_content['data'])) else: msg_content['type'] = 99 msg_content['data'] = content if self.DEBUG: - print ' %s[Unknown]' % msg_prefix + print(' %s[Unknown]' % msg_prefix) return msg_content def handle_msg(self, r): @@ -715,7 +717,7 @@ def handle_msg(self, r): f.write(msg['StatusNotifyUserName']) with open(os.path.join(self.temp_pwd,'wxid.txt'), 'w') as f: f.write(json.dumps(self.wxid_list)) - print "[INFO] Contact list is too big. Now start to fetch member list ." + print("[INFO] Contact list is too big. Now start to fetch member list .") self.get_big_contact() elif msg['MsgType'] == 37: # friend request @@ -755,7 +757,7 @@ def handle_msg(self, r): user['name'] = HTMLParser.HTMLParser().unescape(user['name']) if self.DEBUG and msg_type_id != 0: - print u'[MSG] %s:' % user['name'] + print(u'[MSG] %s:' % user['name']) content = self.extract_msg_content(msg_type_id, msg) message = {'msg_type_id': msg_type_id, 'msg_id': msg['MsgId'], @@ -802,12 +804,12 @@ def check_msg(self): elif selector == '0': # 无事件 pass else: - print '[DEBUG] sync_check:', retcode, selector + print('[DEBUG] sync_check:', retcode, selector) r = self.sync() if r is not None: self.handle_msg(r) else: - print '[DEBUG] sync_check:', retcode, selector + print('[DEBUG] sync_check:', retcode, selector) time.sleep(10) self.schedule() return True @@ -821,8 +823,8 @@ def proc_msg(self): if not res: break except: - print '[ERROR] Except in proc_msg' - print format_exc() + print('[ERROR] Except in proc_msg') + print(format_exc()) check_time = time.time() - check_time if check_time < 0.8: time.sleep(1 - check_time) @@ -1022,7 +1024,7 @@ def send_msg_by_uid(self, word, dst='filehelper'): def upload_media(self, fpath, is_img=False): if not os.path.exists(fpath): - print '[ERROR] File not exists.' + print('[ERROR] File not exists.') return None url_1 = 'https://file.'+self.base_host+'/cgi-bin/mmwebwx-bin/webwxuploadmedia?f=json' url_2 = 'https://file2.'+self.base_host+'/cgi-bin/mmwebwx-bin/webwxuploadmedia?f=json' @@ -1054,7 +1056,7 @@ def upload_media(self, fpath, is_img=False): # 当file返回值不为0时则为上传失败,尝试第二服务器上传 r = self.session.post(url_2, files=files) if json.loads(r.text)['BaseResponse']['Ret'] != 0: - print '[ERROR] Upload media failure.' + print('[ERROR] Upload media failure.') return None mid = json.loads(r.text)['MediaId'] return mid @@ -1143,7 +1145,7 @@ def send_msg(self, name, word, isfile=False): result = True for line in f.readlines(): line = line.replace('\n', '') - print '-> ' + name + ': ' + line + print('-> ' + name + ': ' + line) if self.send_msg_by_uid(line, uid): pass else: @@ -1158,7 +1160,7 @@ def send_msg(self, name, word, isfile=False): return False else: if self.DEBUG: - print '[ERROR] This user does not exist .' + print('[ERROR] This user does not exist .') return True @staticmethod @@ -1176,31 +1178,31 @@ def search_content(key, content, fmat='attr'): def run(self, Mic=None): self.get_uuid() self.gen_qr_code(os.path.join(dingdangpath.LOGIN_PATH,'wxqr.png')) - print '[INFO] Please use WeChat to scan the QR code .' + print('[INFO] Please use WeChat to scan the QR code .') result = self.wait4login() if result != SUCCESS: - print '[ERROR] Web WeChat login failed. failed code=%s' % (result,) + print('[ERROR] Web WeChat login failed. failed code=%s' % (result,)) return if self.login(): - print '[INFO] Web WeChat login succeed .' + print('[INFO] Web WeChat login succeed .') self.is_login = True if Mic is not None: Mic.wxbot = self else: - print '[ERROR] Web WeChat login failed .' + print('[ERROR] Web WeChat login failed .') return if self.init(): - print '[INFO] Web WeChat init succeed .' + print('[INFO] Web WeChat init succeed .') else: - print '[INFO] Web WeChat init failed' + print('[INFO] Web WeChat init failed') return self.status_notify() if self.get_contact(): - print '[INFO] Get %d contacts' % len(self.contact_list) - print '[INFO] Start to process messages .' + print('[INFO] Get %d contacts' % len(self.contact_list)) + print('[INFO] Start to process messages .') self.proc_msg() def get_uuid(self): @@ -1264,7 +1266,7 @@ def wait4login(self): url = LOGIN_TEMPLATE % (tip, self.uuid, int(time.time())) code, data = self.do_request(url) if code == SCANED: - print '[INFO] Please confirm to login .' + print('[INFO] Please confirm to login .') tip = 0 elif code == SUCCESS: # 确认登录成功 param = re.search(r'window.redirect_uri="(\S+?)";', data) @@ -1275,7 +1277,7 @@ def wait4login(self): self.base_host = temp_host[:temp_host.find("/")] return code elif code == TIMEOUT: - print '[ERROR] WeChat login timeout. retry in %s secs later...' % (try_later_secs,) + print('[ERROR] WeChat login timeout. retry in %s secs later...' % (try_later_secs,)) tip = 1 # 重置 retry_time -= 1 @@ -1291,7 +1293,7 @@ def wait4login(self): def login(self): if len(self.redirect_uri) < 4: - print '[ERROR] Login failed due to network problem, please try again.' + print('[ERROR] Login failed due to network problem, please try again.') return False r = self.session.get(self.redirect_uri) r.encoding = 'utf-8' diff --git a/dingdang.py b/dingdang.py index 0522961..2ca737b 100755 --- a/dingdang.py +++ b/dingdang.py @@ -1,6 +1,7 @@ #!/usr/bin/env python2 # -*- coding: utf-8-*- +from __future__ import print_function import os import sys import logging