Пример #1
0
    def start_app(self,startpath,updatepath,command):
        '''起程序'''
#        startpath = self.startpath
#        updatepath = self.updatepath
        apppath = os.path.split(startpath)[0]
        apppname = os.path.split(startpath)[1]
#        command = self.command
        #print startpath
        if os.path.isfile(startpath):
            try:
                os.chdir(apppath)#如果启动程序不在第一层目录下? 需优化
#                #os.system(startpath)#启动程序后应该退出脚本,现没有退出 一直占用资源 需优化【用start app或 execl解决】
#                os.system('start %s' %apppname) 
#                #os.execl(startpath,'i') #直接退出进程
#                #规避删除目录error32错误,临时解决方法
                #os.chdir(updatepath)
                #bug3 os.system执行后进程不带路径导致close失败
                if command is None:
                    subprocess.Popen(startpath)
                else:
                    subprocess.Popen([command,startpath])

                #bug1 规避删除目录error32错误,临时解决方法
                os.chdir(updatepath)
                mylog.info('启动服务成功')
                return True
#                subprocess.Popen(startpath, shell=True)
            except Exception,msg:
                mylog.error('启动服务失败,%s'%msg)
                return False
Пример #2
0
 def on_data(self, raw_data):
     if raw_data is None:
         mylog.error(
             "Tweepy says raw_data=None.  Wat.  Dropping tweet, or whatever it was."
         )
         return
     return StreamListener.on_data(self, raw_data)
Пример #3
0
    def zip_dir(self,copypath,testpath):
        '''打包备份'''
#        copypath = self.copypath
#        testpath = self.testpath
        nowtime = time.strftime("%Y%m%d%H%M%S", time.localtime())
        if os.path.isdir(copypath):
            zipFile1 = zipfile.ZipFile(os.path.join(copypath,os.path.basename(testpath)+nowtime+'.zip'),'w') 
        else:
            mylog.error('备份失败,备份目录不合法')
            return False
        #用宽度优先搜索全路径
        if os.path.isdir(testpath):
            filelist = os.listdir(testpath)
            while len(filelist)>0:
                out = filelist.pop()
                if os.path.isdir(os.path.join(testpath,out)):
                    #os.path.join(os.path.basename(testpath),out) 短目录替换全路径
                    #out 当前路径
                    zipFile1.write(os.path.join(testpath,out),out)
                    for outfile in os.listdir(os.path.join(testpath,out)):
                        filelist.append(os.path.join(out,outfile))
                else:
                    zipFile1.write(os.path.join(testpath,out),out)
        else:
            mylog.error('备份失败,测试目录不合法')
            return False
        #用os.walk搜索全路径下文件,还不能做到压缩目录不带全路径
        """for dirpath, dirnames, filenames in os.walk(testpath):
            
            for filename in filenames:   
            #print filename
                zipFile1.write(os.path.join(dirpath,filename))"""        
        zipFile1.close() 
        mylog.info('备份成功')
        return True 
Пример #4
0
 def getName(self, bid):
     b = self.bJson.get(bid)
     if b is None:
         mylog.error('Tried to resolve invalid Bird-ID "{}",'
                     ' will go with "Goldammer" instead'.format(bid))
         return 'Goldammer'
     return b['de_name']
Пример #5
0
	def getName(self, bid):
		b = self.bJson.get(bid)
		if b is None:
			mylog.error('Tried to resolve invalid Bird-ID "{}",'
				        ' will go with "Goldammer" instead'.format(bid))
			return 'Goldammer'
		return b['de_name']
Пример #6
0
 def on_status(self, status):
     tweet = parse_tweet_status(status)
     if tweet is None:
         mylog.error("{}: on_tweet BROKEN! (skip)".format(self.desc))
     elif tweet['uid'] not in self.sensitive:
         mylog.info("{}: dropped irrelevant tweet from user {} at time {}"
                    .format(self.desc, tweet['uid'], tweet['time']))
     else:
         self.on_tweet(tweet)
Пример #7
0
def copytjb():
    """拷文件"""
    mylog.info('准备复制olddir,reportfile')
    try:
        shell.SHFileOperation ((0, shellcon.FO_COPY, olddir, newdir,shellcon.FOF_NOCONFIRMMKDIR|shellcon.FOF_NOCONFIRMATION, None, None))
        shell.SHFileOperation ((0, shellcon.FO_COPY, reportfile, localreportfile,shellcon.FOF_NOCONFIRMATION, None, None))
        shell.SHFileOperation ((0, shellcon.FO_COPY, svnfile, localsvnfile,shellcon.FOF_NOCONFIRMATION, None, None))
        mylog.info('复制olddir,reportfile成功')
    except:
        mylog.error('复制失败,请关闭相关程序,再试')
Пример #8
0
 def on_status(self, status):
     tweet = parse_tweet_status(status)
     if tweet is None:
         mylog.error("{}: on_tweet BROKEN! (skip)".format(self.desc))
     elif tweet['uid'] not in self.sensitive:
         mylog.info(
             "{}: dropped irrelevant tweet from user {} at time {}".format(
                 self.desc, tweet['uid'], tweet['time']))
     else:
         self.on_tweet(tweet)
Пример #9
0
    def findUSB(self):
        self.device = []
        self.deviceW = None
        self.deviceR = None
        self.inPoint = None
        self.outPoint = None
        self.usbReady = False
        self.device = list(usb.core.find(find_all=True))
        self.deviceOrder[1], self.deviceOrder[0] = self.deviceOrder

        usbDeviceNum = len(self.device)
        if usbDeviceNum == 1:
            self.deviceR = self.device[0]

            self.deviceR.set_configuration()
            cfgR = self.deviceR.get_active_configuration()
            intfR = cfgR[(0, 0)]

            self.inPoint = usb.util.find_descriptor(intfR,
                # match the first IN endpoint
                custom_match = lambda e: \
                    usb.util.endpoint_direction(e.bEndpointAddress) == \
                    usb.util.ENDPOINT_IN)

            self.usbReady = True
            mylog.info("1个USB设备已连接。")
        elif usbDeviceNum == 2:
            self.deviceW = self.device[self.deviceOrder[0]]
            self.deviceR = self.device[self.deviceOrder[1]]

            self.deviceW.set_configuration()
            cfgW = self.deviceW.get_active_configuration()
            intfW = cfgW[(0, 0)]

            self.deviceR.set_configuration()
            cfgR = self.deviceR.get_active_configuration()
            intfR = cfgR[(0, 0)]

            self.outPoint = usb.util.find_descriptor(intfW,
                # match the first OUT endpoint
                custom_match = lambda e: \
                    usb.util.endpoint_direction(e.bEndpointAddress) == \
                    usb.util.ENDPOINT_OUT)

            self.inPoint = usb.util.find_descriptor(intfR,
                # match the first IN endpoint
                custom_match = lambda e: \
                    usb.util.endpoint_direction(e.bEndpointAddress) == \
                    usb.util.ENDPOINT_IN)

            self.usbReady = True
            mylog.info("2个USB设备已连接。")
        else:
            self.usbReady = False
            mylog.error("Error: 可用USB设备数量不是2。")
Пример #10
0
def parse_tweet_status(status):
    # mylog.debug('Now parsing status {}'.format(status))
    try:
        report = dict()
        report['uid'] = status.user.id_str
        hh = status.entities["hashtags"]
        # For each element, only view 'text' subelement
        report['hashtags'] = []
        for h in hh:
            report['hashtags'].append(h['text'])
        report['content'] = status.text
        report['username'] = status.user.screen_name
        report['userscreen'] = status.user.name
        # Slap Twitter-developer for not delivering a 'timestamp_ms' property
        report['time'] = datetime_to_unix(status.created_at) * 1000
        report['tweet_id'] = status.id_str
        report['profile_img'] = status.user.profile_image_url_https
        if 'retweeted_status' in status.__dict__:
            # Actual "Retweet" (retweet with no additional text or media)
            sub = status.retweeted_status
            report['retweet'] = dict(
                # Skip uid (available on request!)
                # Skip hashtags (available on request!)
                content=sub.text,
                username=sub.user.screen_name,
                userscreen=sub.user.name,
                # Skip time (available on request -- but difficult for quotes, see below)
                tweet_id=sub.id_str,
                profile_img=status.user.profile_image_url_https,
                # No recursive retweet detection -- would require POST requests.
                )
        elif 'quoted_status' in status.__dict__:
            # "Quote" (retweet with some additional text or media)
            # Dear tweepy, why don't you parse this JSON?!
            # I would create a new issue, but it's "no longer maintained" anyway.
            sub = status.quoted_status
            report['retweet'] = dict(
                # Skip uid (available on request!)
                # Skip hashtags (available on request!)
                content=sub['text'],
                username=sub['user']['screen_name'],
                userscreen=sub['user']['name'],
                # Skip time (available on request -- but would need non-trivial parsing)
                tweet_id=sub['id_str'],
                profile_img=sub['user']['profile_image_url_https'],
                )
        # else: not a retweet in either meaning.
        # For initial compatibility with the current tests: throw away most of the info.
        report['retweet'] = report.get('retweet') is not None
        return report
    except (KeyError, AttributeError) as e:
        mylog.debug('Failed to parse status {}'.format(status))
        mylog.error('Something when wrong while parsing status: {}'.format(e))
        return None
Пример #11
0
def parse_tweet_status(status):
    # mylog.debug('Now parsing status {}'.format(status))
    try:
        report = dict()
        report['uid'] = status.user.id_str
        hh = status.entities["hashtags"]
        # For each element, only view 'text' subelement
        report['hashtags'] = []
        for h in hh:
            report['hashtags'].append(h['text'])
        report['content'] = status.text
        report['username'] = status.user.screen_name
        report['userscreen'] = status.user.name
        # Slap Twitter-developer for not delivering a 'timestamp_ms' property
        report['time'] = datetime_to_unix(status.created_at) * 1000
        report['tweet_id'] = status.id_str
        report['profile_img'] = status.user.profile_image_url_https
        if 'retweeted_status' in status.__dict__:
            # Actual "Retweet" (retweet with no additional text or media)
            sub = status.retweeted_status
            report['retweet'] = dict(
                # Skip uid (available on request!)
                # Skip hashtags (available on request!)
                content=sub.text,
                username=sub.user.screen_name,
                userscreen=sub.user.name,
                # Skip time (available on request -- but difficult for quotes, see below)
                tweet_id=sub.id_str,
                profile_img=status.user.profile_image_url_https,
                # No recursive retweet detection -- would require POST requests.
            )
        elif 'quoted_status' in status.__dict__:
            # "Quote" (retweet with some additional text or media)
            # Dear tweepy, why don't you parse this JSON?!
            # I would create a new issue, but it's "no longer maintained" anyway.
            sub = status.quoted_status
            report['retweet'] = dict(
                # Skip uid (available on request!)
                # Skip hashtags (available on request!)
                content=sub['text'],
                username=sub['user']['screen_name'],
                userscreen=sub['user']['name'],
                # Skip time (available on request -- but would need non-trivial parsing)
                tweet_id=sub['id_str'],
                profile_img=sub['user']['profile_image_url_https'],
            )
        # else: not a retweet in either meaning.
        # For initial compatibility with the current tests: throw away most of the info.
        report['retweet'] = report.get('retweet') is not None
        return report
    except (KeyError, AttributeError) as e:
        mylog.debug('Failed to parse status {}'.format(status))
        mylog.error('Something when wrong while parsing status: {}'.format(e))
        return None
Пример #12
0
 def executeUpate(self, sql):
     '''
     更新DB一条记录
     '''
     db = self.connectDB()
     cursor = db.cursor()
     try:
         cursor.execute(sql)
         db.commit()
     except Exception,e:
         db.rollback()
         log.error('sql:%s, error:%s' % (sql, e))
Пример #13
0
    def do_update(self,updatepath):
        """从svn更新最新程序(不管有没更新都会进行后续操作,需优化)"""
#        updatepath = self.updatepath
        #检查路径是否为目录
        if os.path.isdir(updatepath):
            try:
                updateshell = 'TortoiseProc.exe /command:update /path:"%s" /closeonend:1'%updatepath
                os.system(updateshell)
                mylog.info('升级成功')
                return True
            except Exception,msg:
                mylog.error('升级失败,%s'%msg)
                return False
Пример #14
0
 def writeToUSB(self,fileName):
     r'''
     把处理好的帧数据连续写入USB设备;
     '''
     try:
         mylog.info('正在写入帧文件...')
         frameData = numpy.load('./files/%s.npy' % fileName)
         #某些情况下需要降低发送速度,下面将帧数据分块发送;
         frameData = bytes(frameData)
         dataLength = len(frameData)
         bytesValidOneTime = int(0.5*1024)  #每次发送的数据中,有效帧的字节数
         i = 0
         while (i+bytesValidOneTime) < dataLength:
             #time.sleep(0.001)
             if not self.usbHandler.writeToUSB(frameData[i:(i+bytesValidOneTime)]):
                 mylog.error('Error: 写入失败!')
                 return False
             i += bytesValidOneTime
         if i < dataLength:
             if not self.usbHandler.writeToUSB(frameData[i:]):
                 mylog.error('Error: 写入失败!')
                 return False
     except BaseException as e:
         mylog.error("Error: 写入帧文件失败。")
         mylog.error(str(e))
         return False
     else:
         mylog.info('已成功写入帧文件。')
         return True
Пример #15
0
 def executeSearch(self, sql):
     '''
     检索DB
     '''
     db = self.connectDB()
     cursor = db.cursor()
     count = 0
     results = ()
     try:
         count = cursor.execute(sql)
         if count > 0:
             results = cursor.fetchall()
     except Exception,e:
         log.error('sql:%s, error:%s' % (sql, e))
Пример #16
0
def show_usage(keys):
    from sys import exit
    mylog.error('Start it like this:')
    mylog.error('( cd backend && ./startBackend.py ${SOME_KEY} )')
    mylog.error('Where the following values are accepted for ${SOME_KEY}:')
    mylog.error('{}'.format(keys))
    exit(1)
Пример #17
0
def show_usage(keys):
    from sys import exit
    mylog.error('Start it like this:')
    mylog.error('( cd backend && ./startBackend.py ${SOME_KEY} )')
    mylog.error('Where the following values are accepted for ${SOME_KEY}:')
    mylog.error('{}'.format(keys))
    exit(1)
Пример #18
0
    def replace_app(self,updatepath,testpath):
        ''' 更新程序'''
#        updatepath  = self.updatepath
#        testpath = self.testpath
#        shutil.rmtree(testpath)
        try:
            #等待0.2秒 确保进程不影响删除
            time.sleep(0.2)
            shutil.rmtree(testpath)

          
        except  Exception,msg:
            mylog.error('删除测试目录失败 %s'%msg)
            return False  
Пример #19
0
	def setBird(self, pid, bid, actor):
		assert actor in ['p', 'c']
		bird_key = 'self_bird' if actor == 'p' else 'citizen_bird'
		with self.lock:
			try:
				# Copy the politician, in case a concurrent
				# setPoliticianBird comes in.
				poli = self.polByPid[pid]
			except KeyError:
				mylog.error("ERROR: Tried to update non-existent politician {pid}"
					        " to bird {bid}, actor={actor}"
					        .format(pid=pid, bid=bid, actor=actor))
				return
			poli[bird_key] = bid
			self._dumpToFile()
Пример #20
0
 def executeInsert(self, sql, params=[]):
     '''
     插入DB,一行or多行
     '''
     db = self.connectDB()
     cursor = db.cursor()
     try:
         if len(params) == 0:
             cursor.execute(sql)
         elif len(np.array(params).shape) == 2: 
             cursor.executemany(sql, params)
         else:
             return
         db.commit()
     except Exception,e:
         db.rollback()
         log.error('sql:%s, error:%s' % (sql, e))
Пример #21
0
    def __init__(self):
        # Read argv to determine which credentials to use
        from credentials import CREDENTIALS
        from sys import argv

        show_keys = set(CREDENTIALS.keys())  # Copy to be extra safe
        if len(argv) != 2:
            mylog.error(
                'Must specify exactly one argument, but {} provided.'.format(
                    len(argv) - 1))
            show_usage(show_keys)
        self.key = argv[1]
        if self.key not in CREDENTIALS:
            mylog.error('Unknown key {} provided.'.format(self.key))
            show_usage(show_keys)

        self.consumer_tweets = TweetPrinter()
        self.consumer_updates = UpdatesPrinter()

        creds = CREDENTIALS[self.key]
        self.auth = OAuthHandler(creds['consumer_key'],
                                 creds['consumer_secret'])
        self.auth.set_access_token(creds['access_key'], creds['access_secret'])
        # self.streams is a dict of:
        #   K: tuple of Twitter IDs
        #   V: handler, the "TweetConsumer" object
        # Unless you provide the same TweetConsumer object multiple times,
        # it appears at most once in this container.
        self.streams = dict()
        self.lock = threading.RLock()
        self.api = tweepy.API(self.auth)
        # self.short_poll is a list of:
        #   Entries, which are represented by a dict, which should have been a struct:
        #     'user': string, required, Twitter ID
        #     'name': string, required, screen name
        #     'last_id': string, optional, textual representation of the ID of the most recent Tweet
        # Unless you provide the same TweetConsumer object multiple times,
        # it appears at most once in this container.
        self.short_poll = []

        # Start the short-poll thread
        self.run_short_poll_wrap()
Пример #22
0
    def close_app(self,startpath):
        '''关闭程序进程'''
#        startpath = self.startpath
#        try:
#            closeshell = 'taskkill /f /im %s'%startpath
#            os.system(closeshell)
#        except Exception,msg:
#            print msg
#            return False
        startpath = self.startpath
#        print startpath
        pid = self.check_process(startpath)
        if pid:
            try:
                psutil.Process(pid).kill()
                mylog.info('关闭服务成功,进程号为%s'%pid)
                return True
            except Exception,msg:
                mylog.error('关闭服务失败,%s'%msg)
                return False
Пример #23
0
def find_pair(bird: Union[None, str], mood: str, retweet: bool, length: int):
	if bird is None:
		return None
	candidates = [(bird, mood, retweet),
				  (bird, 'neutral', retweet),
				  (bird, 'fragend', retweet),
				  (bird, 'aufgebracht', retweet),
				  ('amsel', 'neutral', False)]
	verbose = False
	for (b, m, r) in candidates:
		candidSource = path_raw(b, m, r)
		if os.path.isfile(candidSource):
			if verbose:
				mylog.info("Found at {}".format(candidSource))
			return candidSource, path_processed(b, m, r, length)
		else:
			mylog.warning("Source file {} missing, falling back ...".format(candidSource))
			verbose = True
	mylog.error("All sources and fallbacks missing.  Giving up.")
	return None
Пример #24
0
 def readFromUSB(self):
     while self.allowRead:
         readOutBytes = self.usbHandler.readFromUSB()
         if readOutBytes == 1:
             mylog.error('未读到数据。')
             return False
         elif readOutBytes == 2:
             mylog.error('USB设备未连接。')
             return False
         else:
             with open('./files/out.txt','a') as outFile:
                 readOutBytesNum = len(readOutBytes)
                 for i in range(0,readOutBytesNum,8):
                     #frameTitle = readOutBytes[i+3] >> 4
                     #if frameTitle != 3:     #0011
                     for j in range(3,-1,-1):
                         outFile.write('{:0>2x}'.format(readOutBytes[i+j]))
                     for j in range(7,3,-1):
                         outFile.write('{:0>2x}'.format(readOutBytes[i+j]))
                     outFile.write('\n')
         time.sleep(0.1)
Пример #25
0
    def __init__(self):
        # Read argv to determine which credentials to use
        from credentials import CREDENTIALS
        from sys import argv

        show_keys = set(CREDENTIALS.keys())  # Copy to be extra safe
        if len(argv) != 2:
            mylog.error('Must specify exactly one argument, but {} provided.'.format(len(argv) - 1))
            show_usage(show_keys)
        self.key = argv[1]
        if self.key not in CREDENTIALS:
            mylog.error('Unknown key {} provided.'.format(self.key))
            show_usage(show_keys)

        self.consumer_tweets = TweetPrinter()
        self.consumer_updates = UpdatesPrinter()

        creds = CREDENTIALS[self.key]
        self.auth = OAuthHandler(creds['consumer_key'], creds['consumer_secret'])
        self.auth.set_access_token(creds['access_key'], creds['access_secret'])
        # self.streams is a dict of:
        #   K: tuple of Twitter IDs
        #   V: handler, the "TweetConsumer" object
        # Unless you provide the same TweetConsumer object multiple times,
        # it appears at most once in this container.
        self.streams = dict()
        self.lock = threading.RLock()
        self.api = tweepy.API(self.auth)
        # self.short_poll is a list of:
        #   Entries, which are represented by a dict, which should have been a struct:
        #     'user': string, required, Twitter ID
        #     'name': string, required, screen name
        #     'last_id': string, optional, textual representation of the ID of the most recent Tweet
        # Unless you provide the same TweetConsumer object multiple times,
        # it appears at most once in this container.
        self.short_poll = []

        # Start the short-poll thread
        self.run_short_poll_wrap()
Пример #26
0
 def post(self, message, isRetry=False):
     mylog.info('Publishing on queue {name}: {data!r}'
                .format(name=self.name, data=message))
     with self.lock:
         if self.connection.is_closed:
             mylog.warning("Whoops, connection is closed; reopen.")
             self.connection = connection()
             self.channel = self.connection.channel()
         try:
             self.channel.basic_publish(exchange='', routing_key=self.name,
                                        body=json.dumps(message))
             self.maybe_log_message(message)
         except Exception as e:
             mylog.error("Connection failed anyway?  Make sure RabbitMQ is running! (is_closed = {})"
                         .format(self.connection.is_closed))
             mylog.error(e.__repr__())
             mylog.error(e.args)
             mylog.info("Message dropped.")
             if not isRetry:
                 self.post(message, True)
Пример #27
0
 def readFromUSB(self):
     r"""Read data from usbDevice.
     The bulksNum parameter should be the amount of bulks to be readed.
     One bulk is wMaxPacketSize(512) bytes.
     The method returns the data readed as an array. If read nothing, return None.
     """
     if self.usbReady:
         try:
             #readOutData = array.array('B')
             readOutBytes = self.deviceR.read(self.inPoint.bEndpointAddress,
                                              self.inPoint.wMaxPacketSize,
                                              timeout=1000)
             return readOutBytes
         except BaseException as e:
             mylog.error("Error: Failed to read from USB.")
             mylog.error(str(e))
             return 1
     else:
         mylog.error("Error: USB device is not ready.")
         return 2
Пример #28
0
 def post(self, message, isRetry=False):
     mylog.info('Publishing on queue {name}: {data!r}'.format(
         name=self.name, data=message))
     with self.lock:
         if self.connection.is_closed:
             mylog.warning("Whoops, connection is closed; reopen.")
             self.connection = connection()
             self.channel = self.connection.channel()
         try:
             self.channel.basic_publish(exchange='',
                                        routing_key=self.name,
                                        body=json.dumps(message))
             self.maybe_log_message(message)
         except Exception as e:
             mylog.error(
                 "Connection failed anyway?  Make sure RabbitMQ is running! (is_closed = {})"
                 .format(self.connection.is_closed))
             mylog.error(e.__repr__())
             mylog.error(e.args)
             mylog.info("Message dropped.")
             if not isRetry:
                 self.post(message, True)
Пример #29
0
 def writeToUSB(self, data):
     r"""Write data to usbDevice.
     The data parameter should be a sequence like type convertible to
     the array type (see array module).
     """
     if self.usbReady:
         try:
             #如果写入的数据不足32B,需要补足32B,用'00110000'补足
             if len(data) < 32:
                 bytesAppendNum = 32 - len(data)
                 bytesAppend = 48 * (
                     numpy.ones(bytesAppendNum).astype('uint8')
                 )  #48=00110000
                 data = data + bytes(bytesAppend)
             self.deviceW.write(self.outPoint.bEndpointAddress, data)
         except BaseException as e:
             mylog.error("Error: Failed to write to USB.")
             mylog.error(str(e))
             return False
         else:
             return True
     else:
         mylog.error("Error: USB device is not ready.")
         return False
	def _restart(self):
		mylog.error('Stacking a new thread.  Please restart soon!')
		self.next = CitizenBirdQueueAdapter(self.politicianBackend)
		self.next.start()
 def _restart(self):
     mylog.error('Stacking a new thread.  Please restart soon!')
     self.next = CitizenBirdQueueAdapter(self.politicianBackend)
     self.next.start()
	def _restart(self):
		mylog.error('Stacking a new thread.  Please restart soon!')
		self.next = CitizenQueueAdapter(self.twitterConnection)
		self.next.start()
Пример #33
0
import os
import ConfigParser
import mylog
mylog = mylog.initlog()
config = ConfigParser.ConfigParser()
#获取配置文件详细信息
with open("usesql.config", "r+") as  cfgfile:
    config.readfp(cfgfile)
    linkdata = config.get("info", "linkdata")
try:
    consql = pyodbc.connect(linkdata)
    mylog.info("数据库连接成功")
    cursor1 = consql.cursor()
    mylog.info("游标建立成功")    
except pyodbc.Error, dberror:
    mylog.error("数据库连接失败")
    mylog.error(dberror)
#此版本values值有两行,会报错hy000
path = os.getcwd()+os.sep+"sql"
sqldir = os.listdir(os.getcwd()+os.sep+"sql")

#取出sql文件最后修改时间,并排序

files = []
#for file in sqldir:
#    if file[-4:]=='.sql':
#        fileName = os.path.join(path,file)  
#        filetime = os.stat(fileName).st_mtime
 #       files.append((filetime,fileName))

#网上的例子是函式编程 学习下
Пример #34
0
def poli_modify():
	check_writeback()
	set_skip_writeback(False)
	check_writeback()
	mylog.warning("Fiddling with politicianBackend.")
	pb = PoliticianBackend()

	# Do your thing here, e.g.:
	#     pB.setBird('395912134', 'fitis', 'c')
	#     # This is a no-op on the original pols.json
	# Or to purge everything French:
	#     for poli in pb.poliList:
	#         cv = poli['cv']
	#         if 'fr' in cv:
	#             mylog.info('Purged the French out of ' + poli['name'])
	#             del cv['fr']

	# Note:
	# - setBird automatically calls dumpToFile.
	#   In all other cases, you'll need to call __dumpToFile by hand, like this:
	pb._dumpToFile()

	mylog.warning("Now check by hand.")


if __name__ == '__main__':
	mylog.warning("Are you sure you want to rewrite pols.json?")
	mylog.error("Uncomment me, I'm not gonna let ya!")
	# Uncomment to run:
	# poli_modify()
Пример #35
0
    def do_update(self,updatepath):
        """从svn更新最新程序(不管有没更新都会进行后续操作,需优化)"""
#        updatepath = self.updatepath
        #检查路径是否为目录
        if os.path.isdir(updatepath):
            try:
                updateshell = 'TortoiseProc.exe /command:update /path:"%s" /closeonend:1'%updatepath
                os.system(updateshell)
                mylog.info('升级成功')
                return True
            except Exception,msg:
                mylog.error('升级失败,%s'%msg)
                return False
        else:
            mylog.error('升级失败,升级目录不合法')
            return False


    
    def start_app(self,startpath,updatepath,command):
        '''起程序'''
#        startpath = self.startpath
#        updatepath = self.updatepath
        apppath = os.path.split(startpath)[0]
        apppname = os.path.split(startpath)[1]
#        command = self.command
        #print startpath
        if os.path.isfile(startpath):
            try:
                os.chdir(apppath)#如果启动程序不在第一层目录下? 需优化
Пример #36
0
## Take a gene symbol name and output all its exon in bed format

parser = argparse.ArgumentParser(description = "Export gene's exons in bed format from it's canonical model")

parser.add_argument("--gene_name", dest = "gene_name", help = "Gene Symbol", required = True)
parser.add_argument("--output_file", dest = "output_file", help = "Output file name", required = True)

try:
    args = parser.parse_args()
except:
    print("")
    parser.print_help()
    sys.exit(1)


gene_name = args.gene_name
output_file = args.output_file

import GenomeInformation as gi

ginfo = gi.GeneInformation()

## check whether gene exists
if ginfo.geneExist(gene_name):
    info("Your input is '{}' and output is '{}'".format(gene_name,output_file))
    ginfo.makeGeneExonBed(gene_name,output_file)
    info("Finished")
else:
    error("Gene '"+gene_name+"' not exists\n")

Пример #37
0
        svc_list = cur.fetchall()

        cur.close()
        conn.commit();
    except Exception,e:
        print e
        conn.close()
        sys.exit(1)

    while True:
        try:
            if conn.ping() == False:
                conn = reconn(config)

            h,m = time.localtime(time.time())[3],time.localtime(time.time())[4]

            for svc in svc_list:
                obj = get_svc_obj(svc_map,svc[0],svc[1])
                if obj:
                    if svc[2] == 'rt':
                        obj.handle(conn)
                    else:
                        stime = time.strptime(svc[3],"%H:%M:%S")
                        shour,smin = stime[3],stime[4]
                        if shour == h and smin == m:
                            obj.handle(conn)
        except Exception,e:
            mylog.error(e)

        time.sleep(60)
Пример #38
0
 def on_data(self, raw_data):
     if raw_data is None:
         mylog.error("Tweepy says raw_data=None.  Wat.  Dropping tweet, or whatever it was.")
         return
     return StreamListener.on_data(self, raw_data)
Пример #39
0
 def writeToUSBWithFrameNum(self,fileName):
     r'''
     把固定数量的帧数据写入USB设备,起始帧编号为currentFrameNo,写入帧的数量为frameNum;
     '''
     currentFrameNo = 0
     try:
         frameData = numpy.load('./files/%s.npy' % fileName)
         frameData = bytes(frameData)
         dataLength = len(frameData)
         frameLength = dataLength//8
     except BaseException as e:
         mylog.error("Error: 读取帧文件失败。")
         mylog.error(str(e))
         return False
     else:
         mylog.info('已成功读取帧文件。')
     while True:
         inputData = input()
         if inputData == 'stop':
             return True
         else:
             try:
                 frameNum = int(inputData)
             except BaseException as e:
                 mylog.error("Error: 指令不符合要求,请输入数字或stop:")
                 mylog.error(str(e))
                 continue
             if currentFrameNo+frameNum > frameLength:
                 mylog.error('Error: 超出帧文件范围。起始帧为%d,写入帧数量为%d...' % (currentFrameNo,frameNum))
                 return False
             mylog.info('正在写入帧,起始帧为%d,帧数量为%d...' % (currentFrameNo,frameNum))
             if not self.usbHandler.writeToUSB(frameData[(8*currentFrameNo):(8*(currentFrameNo+frameNum))]):
                 mylog.error('Error: 写入失败!')
                 return False
             print('已写入,请输入数字或stop:')
             currentFrameNo += frameNum
     return True