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


Python sys.ext函数代码示例

本文整理汇总了Python中sys.ext函数的典型用法代码示例。如果您正苦于以下问题:Python ext函数的具体用法?Python ext怎么用?Python ext使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


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

示例1: report

def report(log_file_names, args):

    # We only accept one log file
    if len(log_file_names) != 1:
        sys.exit("'timegraph' report uses one log file.")
    else:
        log_file_name = log_file_names[0]

    optstring = "m"
    longopts = []
    process_types = timegraph.ALL_PROCS

    try:
        opts, args = getopt.getopt(args, optstring, longopts)
    except getopt.GetoptError:
        usage()
        sys.exit(1)

    for opt, arg in opts:
        if opt == "-m":
            process_types = timegraph.ONLY_MAKES
        else:
            sys.ext("Unexpected option %s" % (opt,))

    run_timeline(log_file_name, process_types)
开发者ID:gilramir,项目名称:instmake,代码行数:25,代码来源:report_timegraph.py

示例2: combineFiles

def combineFiles(folderName,writefilename):
	filelist = [filename for filename in os.listdir(folderName) if 'txt' in filename]
	for filename in filelist:
	    reader = open(os.path.join(folderName,filename),'r')
	    length = len(reader.next().split(','))
	    for index,line in enumerate(reader):
	        if len(line.split(','))!= length:
	            print filename,index,line
	readers = [open(os.path.join(folderName,x),'r') for x in filelist]
	writefile = open(writefilename,'w')
	writefile.write(','.join(filelist)+'\n')
	for line in zip(*readers):
		linelist = map(lambda one: one.strip().split(','),line)
		lineid = linelist[0][0]
		for columns in linelist:
			if columns[0] != lineid:
				print 'line id do not match'
				sys.ext() 
		newline = [lineid]
		for features in linelist:
			newline.extend(features[1:])
		writefile.write(','.join(newline)+'\n')
		break
	for reader in readers:
		reader.close()
	writefile.close()
开发者ID:alicadaly,项目名称:Trend-Analysis-Based-Patent-Evaluation,代码行数:26,代码来源:combineFeatureFile.py

示例3: parse_citation

def parse_citation(citation, score_threshold=None, normalized_score_threshold=100): 
    
    # Find DOI from CrossRef.
    base = "http://search.crossref.org"
    ext = "/dois?q=" + citation
    
    r = requests.get(base+ext, headers = {"Content-Type": "application/json"})
        
    if not r.ok:
        r.raise_for_status()
        sys.ext()

    decoded = r.json()
    
    doi_list = []
    for potential_ref in decoded:
        if normalized_score_threshold is not None and score_threshold is None:
            if potential_ref["normalizedScore"] >= normalized_score_threshold:
                print(potential_ref["normalizedScore"])
                doi_list.append(potential_ref["doi"].split("http://dx.doi.org/")[1])
        elif score_threshold is not None and normalized_score_threshold is None:
            if potential_ref["score"] >= score_threshold:
                print(potential_ref["score"])
                doi_list.append(potential_ref["doi"].split("http://dx.doi.org/")[1])
        else:
            if potential_ref["score"] >= score_threshold and potential_ref["normalizedScore"] >= normalized_score_threshold:
                print(potential_ref["score"])
                doi_list.append(potential_ref["doi"].split("http://dx.doi.org/")[1])
            
    final_refs = []
    for doi in doi_list:
        temp_ref = gnomics.objects.reference.Reference(identifier = doi, identifier_type = "DOI", source = "CrossRef")
        final_refs.append(temp_ref)
                    
    return final_refs
开发者ID:Superraptor,项目名称:Gnomics,代码行数:35,代码来源:citation.py

示例4: welcome

def welcome():
	start = input("Press enter/return to start or Q to quit").lower()
	if start =='q':
		print("Bye!")
		sys.ext()
	else:
		return True
开发者ID:bdebelle,项目名称:th_python,代码行数:7,代码来源:letter_game.py

示例5: getbpp

def getbpp(fname):
	f = open(fname+'_dp.ps','r')
	ubox = []
	lbox = []
	pair = []
	index = -1
	for line in f:
		line.strip()
		if(re.search('\d+.*ubox',line)):
			line = re.sub('\\n','',line)
			pair = re.split('\s+',line)	
			ubox.append(pair)
		elif(re.search('\d+.*lbox',line)):
			line = re.sub('\\n','',line)
			pair = re.split('\s+',line)	
			lbox.append(pair)	
	for l in lbox:  ##optimize this search?
		for u in range(len(ubox)):
			if((l[0]==ubox[u][0])and(l[1]==ubox[u][1])):
				index = u	
		if(index >= 0 ):
			#print "pop"
		#	ubox.pop(u)
			index = -1
		else:
			print "ERROR: " + str(l) + " has no ubox match"
			sys.ext(2)
	out = sorted(ubox, compare)
	commands.getoutput('rm '+fname+'*.ps')
	return out
开发者ID:McGill-CSB,项目名称:corRna,代码行数:30,代码来源:subopt.py

示例6: main

def main():
    try:
        opts, args = getopt.getopt(
            sys.argv[1:],
            "hc:l:r:o:",
            [
                "help",
                "colorTable=",
                "labelFilename=",
                "referenceFilename=",
                "outputFileBasename=",
            ],
        )
    except getopt.GetoptError as err:
        print((str(err)))
        print(
            "WorkupComputeLabelVolume.py -c <colorTable> -l <labelFilename>  -r <referenceFilename> -o <outputFileBasename>"
        )
        sys.exit(2)
    colorTable = ""
    labelFilename = ""
    outputFileBasename = ""
    referenceFilename = ""
    for opt, arg in opts:
        if opt == "-h":
            print(
                "WorkupComputeLabelVolume.py -c <colorTable> -l <labelFilename>  -r <referenceFilename> -o <outputFileBasename>"
            )
            sys.ext()
        elif opt in ("-c", "--colorTable"):
            colorTable = arg
        elif opt in ("-l", "--labelFilename"):
            labelFilename = arg
        elif opt in ("-r", "--referenceFilename"):
            referenceFilename = arg
        elif opt in ("-o", "--outputFileBasename"):
            outputFileBasename = arg

    if colorTable and labelFilename and outputFileBasename:
        print(
            (
                """ Arguments:
        color table: {0}
        labelFile: {1}
        referenceFilename: {2}
        outputFileBasename: {3}""".format(
                    colorTable, labelFilename, referenceFilename, outputFileBasename
                )
            )
        )

        outputFiles = volume_measure(
            colorTable, labelFilename, referenceFilename, outputFileBasename
        )
        print(outputFiles)
    else:
        print(
            "WorkupComputeLabelVolume.py -c <colorTable> -l <labelFilename> -o <outputFileBasename>"
        )
开发者ID:BRAINSia,项目名称:BRAINSTools,代码行数:59,代码来源:measureVolumes.py

示例7: __parse_byteorderid__

    def __parse_byteorderid__(self):
        byteorder = ['little-endian', 'big-endian']

        if self.buf[28] == '\xFE' and self.buf[29] == '\xFF':
            return byteorder[0]
        elif self.buf[28] == '\xFF' and self.buf[29] == '\xFE':
            return byteorder[1]
        else:
            print("ERROR: wrong byte order identifier!\n")
            sys.ext(1)
开发者ID:lemonjia,项目名称:Dorado,代码行数:10,代码来源:cfbf-parser.py

示例8: add_vm

def add_vm(vmparams, name, vmdisk, nic_net1):
    try:
        api.vms.add(vmparams)
    except Exception as e:
        print "Error creating VM with specified parameters, recheck your params"
        print e
        sys.exit(1)

    if verbosity > 1:
        print "VM created successfuly"

    if verbosity > 1:
        print "Attaching networks and boot order..."
    vm = api.vms.get(name=name)
    vm.nics.add(nic_net1)

    try:
        vm.update()
    except:
        print "Error attaching networks, please recheck and remove configurations left behind"
        sys.exit(1)

    if verbosity > 1:
        print "Adding HDD"
    try:
        vm.disks.add(vmdisk)
    except:
        print "Error attaching disk, please recheck and remove any leftover configuration"
        sys.ext(1)
    
    if verbosity > 1:
        print "Setting boot order"
    try:
        hd_boot_dev = params.Boot(dev='hd')
        net_boot_dev = params.Boot(dev='network')
        vm.os.set_boot([net_boot_dev, hd_boot_dev])
    except:
        print "Error setting boot order"
        sys.exit(1)
    
    if verbosity > 1:
        print "VM creation successful"

    vm = api.vms.get(name=name)
    vm.high_availability.enabled = True
    vm.update()

    #wait until VM is stopped before we start it.
    status = api.vms.get(name=name).status.state
    while status != 'down':
        print status
        time.sleep(1)
        status = api.vms.get(name=name).status.state
    vm.start()
开发者ID:champain,项目名称:ovirt-scripts,代码行数:54,代码来源:create-vm.py

示例9: main

def main(argv):
    postcode=''
    try:
        opts, args =getopt.getopt(argv, "hi:o:", ["ifile", "ofile"])
    except getopt.GetoptError:
        print 'dmi.py -i <query>'
        sys.ext(2)
    postcode= args[0]
    # print args[0]
    
    dmi = 'http://www.dmi.dk/vejr/til-lands/byvejr/by/vis/DK/%s' % (postcode)
    webbrowser.open_new(dmi)
开发者ID:jpank,项目名称:dmi-alfred,代码行数:12,代码来源:alfredDMI.py

示例10: execute

    def execute(self, callback=None):
        """
        Given the command-line arguments, this figures out which subcommand is
        being run, creates a parser appropriate to that command, and runs it.
        """
        # Preprocess options to extract --settings and --pythonpath.
        # These options could affect the commands that are available, so they
        # must be processed early.
        self.parser = parser = NewOptionParser(prog=self.prog_name,
                             usage=self.usage_info,
#                             version=self.get_version(),
                             formatter = NewFormatter(),
                             add_help_option = False,
                             option_list=self.option_list)
        
        if not self.global_options:
            global_options, args = parser.parse_args(self.argv)
            global_options.apps_dir = os.path.normpath(os.path.join(global_options.project, 'apps'))
            handle_default_options(global_options)
            args = args[1:]
        else:
            global_options = self.global_options
            args = self.argv

        if global_options.envs:
            for x in global_options.envs:
                if '=' in x:
                    k, v = x.split('=')
                    os.environ[k.strip()] = v.strip()
                else:
                    print ('Error: environment variable definition (%s) format is not right, '
                           'shoule be -Ek=v or -Ek="a b"' % x)

        global_options.settings = global_options.settings or os.environ.get('SETTINGS', 'settings.ini')
        global_options.local_settings = global_options.local_settings or os.environ.get('LOCAL_SETTINGS', 'local_settings.ini')
        
        if callback:
            callback(global_options)
            
        if len(args) == 0:
            if global_options.version:
                print self.get_version()
                sys.exit(0)
            else:
                self.print_help(global_options)
                sys.ext(1)

        self.do_command(args, global_options)
开发者ID:ahlfors,项目名称:uliweb,代码行数:48,代码来源:commands.py

示例11: initCamera

def initCamera():
	global size
	camera = cvCreateCameraCapture(1)
	if not camera:
		print "Could not open webcam!"
		sys.ext(1)
	cvSetCaptureProperty(camera, CV_CAP_PROP_FRAME_WIDTH, 320)
	cvSetCaptureProperty(camera, CV_CAP_PROP_FRAME_HEIGHT, 240)
	frame = cvQueryFrame(camera)
	if frame is not None:
		w = frame.width
		h = frame.height
		print "%d %d"%(w, h)
		size = cvSize(w, h)
	time.sleep(1)
	return camera
开发者ID:joshuabenuck,项目名称:commute,代码行数:16,代码来源:track.py

示例12: get_events

def get_events(args):
    url = "http://%s:%d/events" % (args.hostname, args.port)

    if args.timeout is not None:
        to = args.timeout

    # Build the request and load it
    try:
        if not args.username and not args.password:
            req = urllib2.urlopen(url, timeout=to)
        elif args.username and args.password:
            print("Username/Password not supported ANYMOAR MOUAHAHA.")
            sys.exit(STATE_CRITICAL)
        else:
            print("Error: please provide both username and password.")
            req = None
    except urllib2.HTTPError as e:
        print('CRITICAL: HTTPError = ' + str(e.code))
        sys.exit(STATE_CRITICAL)
    except urllib2.URLError as e:
        print('CRITICAL: URLError = ' + str(e.reason))
        sys.exit(STATE_CRITICAL)
    except httplib.HTTPException as e:
        print('CRITICAL: HTTPException')
        sys.exit(STATE_CRITICAL)

    # Exit if empty requests object
    if not req:
        sys.exit(STATE_UNKNOWN)

    # Handle HTTP codes
    if req.getcode() == 200:
        try:
            res = json.loads(req.read())
        except Exception:
            print("UNKNOWN: Error decoding JSON Object.")
            sys.exit(STATE_UNKNOWN)
        format_json_and_exit(events=res, info=args.info)
    # Error
    elif req.getcode() == 500:
        print("CRITICAL: Sensu API returned an HTTP 500. Is RabbitMQ/sensu-server running?")
        sys.ext(STATE_CRITICAL)
    else:
        print("CRITICAL: Bad response (%d) from Sensu API." % (req.getcode()))
        sys.exit(STATE_CRITICAL)
开发者ID:amaumene,项目名称:nagios-plugins-sensu,代码行数:45,代码来源:check_sensu_events.py

示例13: getUserEnhancedFactor

 def getUserEnhancedFactor(self, uid, seg_num):
     if seg_num < 2:
         print seg_num
         print 'Invalid segment number'
         sys.exit(1)
     try:
         if uid not in self.user_buy_num or len(self.user_buy_num[uid][seg_num-2]) == 0:
             return 0
     except:
         print seg_num
         sys.ext(1)
     total_num = 0
     for pid in self.user_buy_num[uid][seg_num-2]:
         for penality in self.user_buy_num[uid][seg_num-2][pid][1]:
             self.u_enhanced_factor +=\
                 penality*self.product_factor[self.pid_dict[pid]]
         total_num += self.user_buy_num[uid][seg_num-2][pid][0]
     self.u_enhanced_factor = self.u_enhanced_factor/total_num
     return total_num
开发者ID:anthonylife,项目名称:TaobaoCompetition2014,代码行数:19,代码来源:model.py

示例14: main

     def main(self, screen):
	clock = pygame.time.Clock()
	pygame.display.set_caption("Starwars")
	
	background_img = pygame.Surface(screen.get_size())
	background_img = pygame.image.load('deathstar.png').convert()

        global laserSprites, enemySprites, sprites
	laserSprites = pygame.sprite.RenderPlain(())
	enemySprites = pygame.sprite.RenderPlain(())
	enemySprites.add(Enemy(1))

        sprites = pygame.sprite.Group()
        player = Player(sprites)
        frame=0
        while 1:
		dt = clock.tick(30)
		counter = 0
        frame+=1
        screen.blit(background_img, (0, 0))
        laserSprites.update()
        laserSprites.draw(screen)
        enemySprites.update()
        enemySprites.draw(screen)
        sprites.update(dt / 1000.)
        sprites.draw(screen)


        for hit in pygame.sprite.groupcollide(enemySprites, sprites, 0, 0):
                                sys.ext()
                  #collision detection between player and enemy ship


        for hit in pygame.sprite.groupcollide(enemySprites, laserSprites, 1, 0):
                                break
                       #collision detection between laser and enemy ship


        for event in pygame.event.get():
			if event.type == pygame.QUIT:
				sys.exit()
			elif event.type == KEYDOWN and event.key == K_ESCAPE:
				sys.exit()
开发者ID:dirtyfish,项目名称:starwars2,代码行数:43,代码来源:164_2.py

示例15: parseFile

def parseFile():
    global input_site
    global inputType
    lines = []
    cleaned_lines = []
    dom = parse("tempLinks.xml")
    for node in dom.getElementsByTagName('Base'):
      input_site = node.toxml()[1:-7]
    for node in dom.getElementsByTagName('Base'):
      print (node.toxml()[12:15])
      inputType = node.toxml()[12:15]

    for node in dom.getElementsByTagName('Code'):
        lines.append(node.toxml())

    for line in lines:
        #print line[17:-7]
        cleaned_lines.append(line[17:-7])
    cleaned_lines
    output(cleaned_lines)
    sys.ext()
开发者ID:konceptz,项目名称:AssortedPythonScripts,代码行数:21,代码来源:LinkFinder_CLI.py


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