def get_mon_data(data): mon_data = {} if isinstance(data, str): mon_data[data] = getattr(client_scripts, data)() elif isinstance(data, list): for item in data: try: item_d = getattr(client_scripts, item)() except: print sys.exe_info()[0] continue mon_data[item] = item_d return mon_data
def debug_info(): try: raise Exception except: f=sys.exe_info()[2].ta_frame.f_back return '['+'filename:'+os.path.basename(f.f_code.co_filename)+']' \ +'['+'funname:'+f.f_code.co_name+']'+'['+'linenum:'+str(f.f_lineno)+']'
def create_todo(): error = False body = {} try: # description = request.form.get('description', '') description = request.get_json()['description'] list_id = request.get_json()['list_id'] # Instructions for model todo = Todo(description=description) active_list = TodoList.query.get(list_id) todo.list = active_list db.session.add(todo) db.session.commit() body['description'] = todo.description # updates the view # return redirect(url_for('index')) except: error = True db.session.rollback() print(sys.exe_info()) finally: db.session.close() if error: abort(400) else: return jsonify(body)
def processremainframe(frames, outputfolder, videofile, found_count, force_flag): count_found = 0 for frame in frames: rgb_frame = frame[0][:, :, ::-1] # Find all the faces and face encodings in the current frame of video face_locations = face_recognition.face_locations(rgb_frame) face_encodings = face_recognition.face_encodings( rgb_frame, face_locations) if force_flag and len(face_locations) < 1: print("@@Force Found %d from Queue (No.%d)" % (len(face_encodings), frame[1])) img_path = "%s/%s_frame%04d_who.jpg" % ( outputfolder, basename(videofile).split(".")[0], frame[1]) #small_frame = cv2.resize(frame[0], (0, 0), fx=0.25, fy=0.25) #frame[0]((300,300,500,500)) try: height, width, channels = frame[0].shape iih = (int)(height / 4) iiw = (int)(width / 4) #cv2.imwrite(img_path, frame[0][iih:3*iih,iiw:iiw*3]) small_frame = cv2.resize(frame[0][iih:3 * iih, iiw:iiw * 3], (THUMB_WIDTH, THUMB_HEIGHT)) cv2.imwrite(img_path, small_frame) except Exception as e: print('Error on line{}'.format(sys.exe_info()[-1].tb_lineno), type(e).__name__, e) small_frame = cv2.resize(frame[0], (THUMB_WIDTH, THUMB_HEIGHT)) cv2.imwrite(img_path, small_frame) count_found += 1 found_count += 1 if found_count >= MAXCHECKLIFE: break if len(face_encodings): print("Found %d" % len(face_encodings)) fidx = 1 for face_location in face_locations: face_image = getCenterImage(face_location, frame[0]) pil_image = Image.fromarray(face_image) print("@@Found %d from Queue (No.%d)" % (len(face_encodings), frame[1])) img_path = "%s/%s_frame%04d_%d_who.jpg" % ( outputfolder, basename(videofile).split(".")[0], frame[1], fidx) fidx += 1 pil_image.save(img_path) count_found += 1 found_count += 1 if found_count >= MAXCHECKLIFE: break if found_count >= MAXCHECKLIFE: break return count_found
def run(self): global isConnected while isConnected: try: self.p.waitForNotifications(10.0) except: print "exception occurred" info = sys.exe_info() print info[0], ":", info[1], ":", info[2] self.p.disconnect() print "disconnected"
def _extract_all_types_(fn): fmt = 'data/%s' % (fn) print 'opening ... %s ...\n' % (fmt) fd = open(fmt, 'r') try: all_txt = fd.read() print 'get all text, they are:\n' js_data = json.loads(all_txt) #print json.dumps(js_data['zs'], ensure_ascii=False) zs = js_data['zs'] if zs.has_key('z1'): zs1 = zs['z1'] if not zs1_type.has_key(zs1['v']): zs1_type[zs1['v']] = zs1['d'] if zs.has_key('z2'): zs2 = zs['z2'] if not zs2_type.has_key(zs2['v']): zs2_type[zs2['v']] = zs2['d'] if zs.has_key('z3'): zs3 = zs['z3'] if not zs3_type.has_key(zs3['v']): zs3_type[zs3['v']] = zs3['d'] if zs.has_key('z4'): zs4 = zs['z4'] if not zs4_type.has_key(zs4['v']): zs4_type[zs4['v']] = zs4['d'] except: print '% || %s' % (sys.exe_info()[0], sys.exe_info()[1]) finally: fd.close() return 0
def reads3(filename): try: s3 = boto3.resource('s3', aws_access_key_id=ACCESS_KEY_ID, aws_secret_access_key=ACCESS_SECRET_KEY, config=Config(signature_version='s3v4')) obj = s3.Object(BUCKET_NAME, filename) a = obj.get()['Body'] url = 'https://' + BUCKET_NAME + '.s3.ap-south-1.amazonaws.com/' + filename print(url, "????????????????") return url except: import sys print(sys.exe_info())
def create_todo(): body={} try: describtion= request.get_json()['describtion'] toDoItem=ToDo(describtion=describtion) db.session.add(toDoItem) db.session.commit() body=toDoItem.describtion except: db.session.rollback() print(sys.exe_info()) finally: db.session.close() return jsonify({ 'describtion': body })
def wrap(msg,pr=False,info=True): debuginfo='' #add debug info if info is True: try: raise Exception except: f=sys.exe_info()[2].tb_frame.f_back debuginfo='['+'filename:'+os.path.basename(f.f_code.co_filename)+']' \ +'['+'funname:'+f.f_code.co_coname+']'+'['+'linenum:'+str(f.f_lineno)+']' msg=msg+debuginfo global LOG if LOG is None: print msg else: fn(LOG,msg,pr)
def pushTos3(filepath, filename): try: data = open(filepath[1:], 'rb') s3 = boto3.resource('s3', aws_access_key_id=ACCESS_KEY_ID, aws_secret_access_key=ACCESS_SECRET_KEY, config=Config(signature_version='s3v4')) result = s3.Bucket(BUCKET_NAME).put_object(Key=filename, Body=data) object_acl = s3.ObjectAcl(BUCKET_NAME, filename) response = object_acl.put(ACL='public-read') print(response, ">>>>>>>>>>>>>>>>>") return True except: import sys print(sys.exe_info()) return False
class ExceptionSand(): def hoge(): print("hoge") try: hoge() except Exception: print(sys.exe_info()) try: hoge() except Exception: import traceback traceback.print_exc() try: hoge() except ZeroDivisionError as e: print("except args:", e.args)
def create_artist_submission(): # attempt to request form data and use to create artist object record try: form_data = request.form if form_data['seeking_venue'] == 'True': validate_bool = True else: validate_bool = False genres_string = ",".join(form_data.getlist('genres')) artist = Artist( name=form_data['name'], city=form_data['city'].capitalize(), state=form_data['state'], phone=form_data['phone'], genres=genres_string, image_link=form_data['image_link'], facebook_link=form_data['facebook_link'], website_link=form_data['website_link'], seeking_venue=validate_bool, seeking_description=form_data['seeking_description'], past_show_count=0, upcoming_show_count=0, ) db.session.add(artist) db.session.commit() # on successful db insert, flash success flash('Artist ' + request.form['name'] + ' was successfully listed!') except: db.session.rollback() print(sys.exe_info()) abort(500) flash('Artist ' + request.form['name'] + ' encountered error during submission!') finally: db.session.close() return render_template('pages/home.html')
def processremainframe(frames, outputfolder, videofile): count_found = 0 for frame in frames: print(outputfolder, basename(videofile), frame[1]) img_path = "%s/%s_frame%04d_who.jpg" % ( outputfolder, basename(videofile).split(".")[0], frame[1]) try: height, width, channels = frame[0].shape iih = (int)(height / 4) iiw = (int)(width / 4) small_frame = cv2.resize(frame[0][iih:3 * iih, iiw:iiw * 3], (THUMB_WIDTH, THUMB_HEIGHT)) cv2.imwrite(img_path, small_frame) except Exception as e: print('Error on line{}'.format(sys.exe_info()[-1].tb_lineno), type(e).__name__, e) small_frame = cv2.resize(frame[0], (THUMB_WIDTH, THUMB_HEIGHT)) cv2.imwrite(img_path, small_frame) count_found += 1 return count_found
def delete_venue(venue_id): # TODO: Complete this endpoint for taking a venue_id, and using # SQLAlchemy ORM to delete a record. Handle cases where the session commit could fail. # BONUS CHALLENGE: Implement a button to delete a Venue on a Venue Page, have it so that # clicking that button delete it from the db then redirect the user to the homepage try: print("venue_id: ", venue_id) venue_id = int(request.get_json()["id"]) print("venue_id from json: ", venue_id) db.session.query(Show).filter_by(venue_id=venue_id).delete() db.session.query(Venue).filter_by(id=venue_id).delete() db.session.commit() message = 'Venue with ID: '+ str(venue_id) + ' has been removed !!' flash(message=message) except: db.session.rollback() print(sys.exe_info()) finally: db.session.close() return redirect(url_for('index'))
def coordinate_to_profiles(args): fname, Re = args if fname.endswith('.dat'): fname = fname[:-4] subpath = os.path.join(basepath, 'profiles', fname, str(Re)) if completed(subpath): return if not os.path.exists(subpath): os.makedirs(subpath) fullname = os.path.join(basepath, 'coordinates', fname + '.dat') if not os.path.exists(os.path.join(subpath, fname)): os.link(fullname, os.path.join(subpath, fname)) print(os.path.abspath(subpath)) for i in range(-5, 9): with open(os.path.join(subpath, 'xfoil.{}.stdout'.format(i)), 'wt') as f: p = subprocess.Popen( ['/usr/bin/xvfb-run', '-a', '/usr/bin/xfoil', fname], cwd=subpath, stdin=subprocess.PIPE, stdout=f, stderr=f) try: p.stdin.write('ppar\nN 150\n\n\n'.format(Re).encode()) p.stdin.write('oper\nvisc\n{}\n'.format(Re).encode()) p.stdin.write('alfa {}\n!\n'.format(i).encode()) p.stdin.write('dump alfa.{}.txt\n'.format(i).encode()) p.stdin.write('\n\nquit\n'.encode()) p.stdin.flush() for j in range(100): if p.poll() is not None: break p.stdin.write('\n\nquit\n'.encode()) p.stdin.flush() time.sleep(0.1) except: _, _, tb = sys.exe_info() traceback.print_tb(tb) p.kill()
def create_show_submission(): # attempt to use form data to create new show listing try: form_data = request.form venue = Venue.query.get(form_data['venue_id']) artist = Artist.query.get(form_data['artist_id']) date = request.form['start_time'] shows = Show(venue_id=venue.id, artist_id=artist.id, date=date) db.session.add(shows) db.session.commit() flash('Show was successfully listed!') except: db.session.rollback() print(sys.exe_info()) abort(500) flash('Show failed to list!') finally: db.session.close() return render_template('pages/home.html')
#!/usr/bin/env python3 import os import sys fpathin = "/home/coder/python_grundlagen/materialien/" fpathout = "/home/coder/python_grundlagen/teilnehmer/tn05/" try: eingabe = input("Dateiname import:") with open(fpathin + eingabe, "r") as f: daten = f.read() print(len(daten)) ausgabe = input("Dateiname export:") with open(fpathout + ausgabe, "w") as f: f.write(daten) except: print("ein Fehler", sys.exe_info()[0])
# protocol = TBinaryProtocol.TBinaryProtocol(transport) # client = VCellProxy.Client(protocol) # transport.open() simList = vcellProxy2.getClient().getSimsFromOpenModels() print('\n') print(simList) sim = simList[0] variables = vcellProxy2.getClient().getVariableList(sim) timePoints = vcellProxy2.getClient().getTimePoints(sim) print(variables) print(timePoints) var = variables[0] timeIndex = len(timePoints) - 1 dataFileName = vcellProxy2.getClient().getDataSetFileOfVariableAtTimeIndex( sim, var, timeIndex) reader = vtk.vtkXMLUnstructuredGridReader() reader.SetFileName(dataFileName) reader.Update() output = reader.GetOutput() assert isinstance(output, vtk.vtkUnstructuredGrid) cellData = output.GetCellData() scalar_range = output.GetScalarRange() print('scalar range = ' + str(scalar_range)) print("done") # print(simList.__len__) except: e = sys.exe_info()[0] print("error: " + str(e)) finally: vcellProxy2.close()
def __init__(self): QWidget.__init__(self) self.setWindowTitle("My Digital Clock") timer = QTimer(self) self.connect(timer, SIGNAL("timeout()"), self.updtTime) self.myTimeDisplay = QLCDNumber(self) self.myTimeDisplay.setSegmentStyle(QLCDNumber.Filled) self.myTimeDisplay.setDigitCount(8) self.myTimeDisplay.resize(500, 150) timer.start(1000) def updtTime(self): """更新当前时间""" currentTime = QDateTime.currentDateTime().toString('hh:mm:ss') self.myTimeDisplay.display(currentTime) if __name__ == "__main__": try: myApp = QApplication(sys.argv) myWindow = MyTimer() myWindow.show() myApp.exec_() sys.exit(0) except NameError: print("Name Error", sys.exe_info()[1]) except SystemExit: print("Closing Window...") except Exception: print(sys.exe_info()[1])
print e pass else: try: public_tweets=api.user_timeline(handle, count=100) except tweepy.TweepError as e: print e pass for tweet in public_tweets: tf.write(str(tweet).encode('utf-8')) tf.write('\n') text=tweet.text.strip().replace('\n',' ').replace('\r','').replace(',',' ').replace("'",'').replace('"','') try: fd2.write(str(tweet.id)+","+str(text.encode('utf-8'))+","+str(tweet.created_at)+","+str(tweet.author.screen_name).encode('utf-8')+","+str(tweet.author.name).encode('utf-8')+","+str(tweet.author.followers_count)+","+str(tweet.author.statuses_count)+","+str(tweet.author.friends_count)+","+str(tweet.author.favourites_count)+","+str(tweet.retweeted)+","+str(tweet.retweet_count)+","+str(tweet.lang)+"\n") except: print sys.exe_info()[0] pass all_tweets.extend(public_tweets) #print "...%s tweets downloaded so far" % (len(all_tweets)) if(len(public_tweets)>0): oldest = all_tweets[-1].id-1 while len(public_tweets) > 0: #print "getting tweets before %s" % (oldest) public_tweets=[] if(flag==1): try: public_tweets=api.user_timeline(handle, count=100,max_id=oldest, since_id=sid) except tweepy.TweepError as e: print e
# 1. read pkg list file f = urllib2.urlopen(PKG_FILE) start_dir = os.getcwd() # 2. parsing to get revision and git path lines = f.readlines() for line in lines: git_path = (line.split(' ')[2]).split('#')[0] git_commit = line.split('#')[1] try: print git_path + " " + git_commit except: print("Unexpected error:", sys.exe_info()[0]) raise # 3. git clone git_clone = "git clone ssh://" + ID + "@review.tizen.org:29418/" + git_path + " " + OUTPUT_DIR + git_path print "\n" + git_clone os.system(git_clone) # 4. git reset print "git reset --hard " + git_commit os.chdir(OUTPUT_DIR + git_path) os.system("git reset --hard " + git_commit) os.chdir(start_dir) print "\n all git is clonsed ============================================================\n"