• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python scanner.Scanner类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: test_can_scan

    def test_can_scan(self):
        self.skipTest('Don\'t know how to test with SSH :/')
        scanner = Scanner(network_tools=NetworkToolsStub(), hostname='10.0.1.231')

        scan = scanner.scan(port=9100)

        self.assertDictEqual(scan, {})
开发者ID:,项目名称:,代码行数:7,代码来源:


示例2: main

def main():
    args_handler = Handler()
    ip = args_handler.parsing_ip()

    tgt.send('1.1.1.1')
    scan = Scanner(tgt)
    scan.scan_ports()
开发者ID:alexandre-k,项目名称:pyscanner,代码行数:7,代码来源:__main__.py


示例3: __init__

class Parser:
    def __init__(self, text=''):
        self.lex     = Scanner(text)           # make a scanner
        self.vars    = {'pi':3.14159}          # add constants
        self.traceme = TraceDefault
 
    def parse(self, *text):                    # external interface
        if text: 
            self.lex.newtext(text[0])          # reuse with new text
        tree = self.analyse()                  # parse string
        if tree:
            if self.traceme:                   # dump parse-tree?
                print; tree.trace(0)
            if self.errorCheck(tree):          # check names
                self.interpret(tree)           # evaluate tree

    def analyse(self):
        try:
            self.lex.scan()                    # get first token
            return self.Goal()                 # build a parse-tree
        except SyntaxError:
            print 'Syntax Error at column:', self.lex.start
            self.lex.showerror()
        except LexicalError:
            print 'Lexical Error at column:', self.lex.start
            self.lex.showerror()

    def errorCheck(self, tree):
        try:
            tree.validate(self.vars)           # error checker
            return 'ok'
        except UndefinedError, varinfo:
            print "'%s' is undefined at column: %d" % varinfo
            self.lex.start = varinfo[1]
            self.lex.showerror()               # returns None 
开发者ID:inteljack,项目名称:EL6183-Digital-Signal-Processing-Lab-2015-Fall,代码行数:35,代码来源:parser2.py


示例4: folder_scan

	def folder_scan(self, folders):

		class TimedProgressDisplay:
			def __init__(self, name, interval = 5):
				self.__name = name
				self.__interval = interval
				self.__last_display = 0

			def __call__(self, scanned, total):
				if time.time() - self.__last_display > self.__interval or scanned == total:
					print "Scanning '{0}': {1}% ({2}/{3})".format(self.__name, (scanned * 100) / total, scanned, total)
					self.__last_display = time.time()

		s = Scanner(db.session)
		if folders:
			folders = map(lambda n: db.Folder.query.filter(db.Folder.name == n and db.Folder.root == True).first() or n, folders)
			if any(map(lambda f: isinstance(f, basestring), folders)):
				print "No such folder(s): " + ' '.join(f for f in folders if isinstance(f, basestring))
			for folder in filter(lambda f: isinstance(f, db.Folder), folders):
				FolderManager.scan(folder.id, s, TimedProgressDisplay(folder.name))
		else:
			for folder in db.Folder.query.filter(db.Folder.root == True):
				FolderManager.scan(folder.id, s, TimedProgressDisplay(folder.name))

		added, deleted = s.stats()
		db.session.commit()

		print "Scanning done"
		print 'Added: %i artists, %i albums, %i tracks' % (added[0], added[1], added[2])
		print 'Deleted: %i artists, %i albums, %i tracks' % (deleted[0], deleted[1], deleted[2])
开发者ID:hdhoang,项目名称:supysonic,代码行数:30,代码来源:cli.py


示例5: buildMatrix

def buildMatrix(fname, rows, cols):
   # Construct an empty matrix with specified rows and cols
   matrix = []
   for i in range(0, rows):
       matrixCols = []
       for i in range(0, cols):
           matrixCols.append(0)
       matrix.append(matrixCols)

   # Open the file using Scanner or File Pointer
   # scanner example from http://troll.cs.ua.edu/cs150/projects/practice1.html
   if (fname):
       s = Scanner(fname)
       
       # Read the data from each row into an array
       scannedArray = []
       token = s.readtoken()
       while token != '':
           scannedArray.append(token)
           token = s.readtoken()

       # Append the array onto the matrix
       for rowNumber in range(0, len(matrix)):
           for columnNumber in range(0, len(matrix[rowNumber])):
               if (len(scannedArray) > 0):
                   matrix[rowNumber][columnNumber] = scannedArray.pop(0)

       # Close the file
       s.close()

   return matrix
开发者ID:mdpatrick,项目名称:game_of_life,代码行数:31,代码来源:life.py


示例6: run

def run(sniffer_instance=None, wait_time=0.5, clear=True, args=(), debug=False):
    """
    Runs the auto tester loop. Internally, the runner instanciates the sniffer_cls and
    scanner class.

    ``sniffer_instance`` The class to run. Usually this is set to but a subclass of scanner.
                    Defaults to Sniffer. Sniffer class documentation for more information.
    ``wait_time``   The time, in seconds, to wait between polls. This is dependent on
                    the underlying scanner implementation. OS-specific libraries may choose
                    to ignore this parameter. Defaults to 0.5 seconds.
    ``clear``       Boolean. Set to True to clear the terminal before running the sniffer,
                    (alias, the unit tests). Defaults to True.
    ``args``        The arguments to pass to the sniffer/test runner. Defaults to ().
    ``debug``       Boolean. Sets the scanner and sniffer in debug mode, printing more internal
                    information. Defaults to False (and should usually be False).
    """
    if sniffer_instance is None:
        sniffer_instance = ScentSniffer()

    if debug:
        scanner = Scanner(('.',), logger=sys.stdout)
    else:
        scanner = Scanner(('.',))
    #sniffer = sniffer_cls(tuple(args), clear, debug)
    sniffer_instance.set_up(tuple(args), clear, debug)

    sniffer_instance.observe_scanner(scanner)
    scanner.loop(wait_time)
开发者ID:ajylee,项目名称:sniffer,代码行数:28,代码来源:main.py


示例7: compile_pascal

def compile_pascal(source, dest, is_debug = False, is_interpret = False, out_stream = sys.stdout, output_tokens = False, output_bytecodes = False, lib = ['.'], in_stream = sys.stdin):
  '''
  DID YOU KNOW that compile() is a built in function?
  '''
  set_debug(is_debug)
  debug("Compiling %s into %s" % (source, dest))
  scanner = Scanner(source)
  tokens = scanner.scan()
  if output_tokens:
    write(tokens, source + "_tokenized")
  debug('scanning complete')
  parser = Parser(tokens, source, lib = lib)
  bytecodes, success = parser.parse()
  if output_bytecodes:
    if is_debug:
      write(prettify(bytecodes), source + "_unassembled")
    else:
      write(bytecodes, source + "_unassembled")
  if not success:
    print 'Parsing error'
    return
  debug('parsing complete')
  assembler = Assembler(bytecodes)
  assembled = assembler.assemble()
  if is_debug:
    write(prettify(assembled), dest + '_debug')
  write(assembled, dest)
  debug('assembly complete.' )
  if is_interpret:
    interp = Interpreter(out_stream, in_stream, code = assembled)
    interp.interpret()
  else:
    debug('run program now with `python interpreter.py %s`' % dest)
开发者ID:FoxLisk,项目名称:Pascal-Minus,代码行数:33,代码来源:pascalm.py


示例8: main

def main():
	'''
	sets the structure for going through the dream process step by step
	'''
	fullname = get_name(kind='in') # read in filename
	outname = get_name(kind='out') # read in output name
	opts = get_options() # read in options

	# start dream computations
	s = Scanner() # new scanner
	s.read_alpha_png(fullname) # read and store location of transparent pixels

	my_image = Image.open(fullname, 'r') # open image

	d = Dreamer(my_image) # create new dreamer with reference to image object
	
	img = iterate(d, my_image, outname, opts, save=False) # this function is for iterating over the same image multiple times

	out = s.cut_jpg(img) # send dream buffer object to be cut into transparent PNG

	new_image = Image.new('RGBA', my_image.size) # new blank image of same dimensions
	new_image.putdata(out) # make new image from the information from s.cut_jpg
	new_image.save(outname) # export image

	print("\nsaved image as: %s" % outname)

	open_image(outname) # give user option to automatically open image
开发者ID:gordonhart,项目名称:Deepdream,代码行数:27,代码来源:main.py


示例9: test_build_fail_two

 def test_build_fail_two(self):
     report = Report.from_string(self.BUILD_FAIL_2)
     scanner = Scanner(report, [BuildFail()])
     for ev in scanner.parse():
         report.add_event(ev)
         self.logger.log(logging.DEBUG, "event: %s", str(ev))
     self.assertEqual(report.count(), 2)
     report.report()
开发者ID:lmiphay,项目名称:gentoo-oam,代码行数:8,代码来源:buildfail.py


示例10: test_multipleinstances

 def test_multipleinstances(self):
     report = Report.from_string(self.MULTIPLEINSTANCES)
     scanner = Scanner(report, [MultipleInstances()])
     for ev in scanner.parse():
         report.add_event(ev)
         self.logger.log(logging.INFO, "event: %s", str(ev))
     self.assertEqual(report.count(), 1)
     report.report()
开发者ID:lmiphay,项目名称:gentoo-oam,代码行数:8,代码来源:multipleinstances.py


示例11: test_skipped_conflict

 def test_skipped_conflict(self):
     report = Report.from_string(self.SKIPPED_CONFLICT)
     scanner = Scanner(report, [SkippedConflict()])
     for ev in scanner.parse():
         report.add_event(ev)
         self.logger.log(logging.DEBUG, "event: %s", str(ev))
     report.report()
     self.assertEqual(report.count(), 1)
开发者ID:lmiphay,项目名称:gentoo-oam,代码行数:8,代码来源:skippedconflict.py


示例12: Tray

class Tray(QtWidgets.QSystemTrayIcon):
    def __init__(self, client, icon, parent=None):
        QtWidgets.QSystemTrayIcon.__init__(self, icon, parent)
        self.client = client
        self.icon = icon
        self.user = self.client.get_account('me').url
        self.scanner = Scanner(self.client, self)
        self.options = OptionsWindow(self.client, self.scanner, self)
        self.options.init_options()

        self.stop_event = threading.Event()
        self.scan_thread = threading.Thread(target=self.scanner.scan, args=(self.stop_event,))
        self.scan_thread.start()

        menu = QtWidgets.QMenu(parent)

        exitAction = QtWidgets.QAction("&Quit     ", self)
        exitAction.setShortcut("Ctrl+Q")
        exitAction.setStatusTip('Good bye')
        exitAction.triggered.connect(self.appExit)

        optAction = QtWidgets.QAction("&Options...  ", self)
        optAction.setShortcut("Ctrl+O")
        optAction.setStatusTip("Customize")
        optAction.triggered.connect(self.show_options)

        sendAction = QtWidgets.QAction("Copy Link of Last Uploaded Image", self)
        sendAction.setShortcut("Ctrl+S")
        sendAction.setStatusTip("...")
        sendAction.triggered.connect(self.copy_last)

        menu.addAction(sendAction)
        menu.addAction(optAction)
        menu.addSeparator()
        menu.addAction(exitAction)
        self.setContextMenu(menu)

    def appExit(self):
        # Reset OSX Screenshot storage
        with open(os.devnull, 'w') as nul:
            path = os.path.expanduser('~') + '/Desktop/'
            subprocess.call(["defaults", "write", "com.apple.screencapture", "location", path])
            subprocess.call(["killAll", "SystemUIServer"])

        kill_proc_tree(me)
        self.stop_event.set()
        self.scanner.scan(self.stop_event)
        sys.exit()

    def show_options(self):
        self.options.show_opts()

    def copy_last(self):
        if self.scanner.loader.link == '':
            self.scanner.loader.to_clipboard()
        else:
            self.scanner.loader.to_clipboard()
            self.scanner.loader.copy_notification()
开发者ID:ACollectionOfAtoms,项目名称:imgshare,代码行数:58,代码来源:tray.py


示例13: readTable

def readTable(filename):
    s = Scanner(filename)
    table = []
    record = readRecord(s)
    while record != "":
        table.append(record)
        record = readRecord(s)
    s.close()
    return table
开发者ID:VikasNeha,项目名称:Student_Assignments,代码行数:9,代码来源:twittersort.py


示例14: mainScanner

def mainScanner():
    file = open(filer)
    scanner = Scanner(file.read() + '\0')

    lexeme = scanner.scanNext()

    while lexeme.type != 200:
        lexeme.pprint()
        lexeme = scanner.scanNext()
开发者ID:deadlorpa,项目名称:tyaz_scanner,代码行数:9,代码来源:main.py


示例15: run

    def run(self):
        parsedArgs = self.options.parse()
        scanner = Scanner(parsedArgs.path)
        duplicateCollector = DuplicateCollector()
        scanner.scan(duplicateCollector)

        if parsedArgs.verbose:
            duplicateCollector.write(True)
        else:
            duplicateCollector.write()
开发者ID:mdunhem,项目名称:duplicates-old,代码行数:10,代码来源:controller.py


示例16: test_3

def test_3():
    s = Scanner()
    input_string = 'naqsh faryaadii hai kis kii sho;xii-e ta;hriir kaa'
    scan_results = s.scan(input_string, known_only=True)

    assert len(scan_results['results']) == 1
    
    result = scan_results['results'][0]
    assert len(scan_results['results']) == 1
    assert result['scan'] == '=-===-===-===-=', result['scan']
开发者ID:asp49,项目名称:meter,代码行数:10,代码来源:test_basic.py


示例17: __init__

class MainController:
    def __init__(self, app):
        self.deviceData = DeviceData()
        self.view = MainView(None)
        self.view.scanForDevices.Bind(wx.EVT_BUTTON, self.ScanForDevices)
        self.view.syncActivities.Bind(wx.EVT_BUTTON, self.SyncActivities)
        self.view.Bind(wx.EVT_MENU, self.OnAbout, self.view.aboutMenuItem)
        self.view.Bind(wx.EVT_MENU, self.OnExit, self.view.exitMenuItem)
        self.view.Show()
        self.scanner = Scanner()
        ## TODO Preferences for Selected Scanners
        self.scanner.addScanner(AntScanner())
        self.connector = Connector()
        ## TODO Preferences for Selected Connectors
        self.connector.addConnector(GarminConnector())
        pub.subscribe(self.ScanningStarted, "SCANNING STARTED")
        pub.subscribe(self.DeviceDetected, "DEVICE DETECTED")
        pub.subscribe(self.ActivityRetrieved, "ACTIVITY RETRIEVED")
        pub.subscribe(self.ScanningEnded, "SCANNING ENDED")
        pub.subscribe(self.SyncStarted, "SYNC STARTED")
        pub.subscribe(self.SyncEnded, "SYNC ENDED")
        pub.subscribe(self.LoginSuccesful, "LOGIN SUCCESFUL")
        pub.subscribe(self.LoginFailed, "LOGIN FAILED")
        pub.subscribe(self.ActivitiesUploaded, "ACTIVITIES UPLOADED")
    def ScanForDevices(self, evt):
        self.scanner.scan()
    def ScanningStarted(self, evt):
        self.view.setStatus("Scanning started")
    def ScanningEnded(self, evt):
        self.view.setStatus("Scanning ended")
    def DeviceDetected(self, evt):
        self.view.setStatus("Device detected")
    def ActivityRetrieved(self, evt):
        self.view.setStatus("Retrieved activity")
    def SyncActivities(self, evt):
        self.connector.sync()
    def SyncStarted(self, evt):
        self.view.setStatus("Sync started")
    def SyncEnded(self, evt):
        self.view.setStatus("Sync ended")
    def LoginSuccesful(self, evt):
        self.view.setStatus("Login Succesful")
    def LoginFailed(self, evt):
        self.view.setStatus("Login Failed")
    def ActivitiesUploaded(self, evt):
        self.view.setStatus("Activities Uploaded")
    def OnExit(self,e):
        self.Close(True)
    def OnAbout(self, event):
        dlg = wx.MessageDialog( self.view, "A community-developed Linux version of the ANT Agent. Supports Garmin-based fitness devices that communicate either over USB serial or via the ANT USB connector. Developed by Philip Whitehouse, based on work by Braiden Kindt, Gustav Tiger and Collin (cpfair). Copyright 2014", "About ANT Agent for Linux", wx.OK);
        dlg.ShowModal()
        dlg.Destroy()
开发者ID:philipwhiuk,项目名称:garmin-Ant-GUI,代码行数:52,代码来源:main.py


示例18: test_01

def test_01():
    text_XX = """
@@ aa
"""

    def callback(mo):
        D("callback %r", mo)

    scanner = Scanner((
        (r'^@@', callback),
        (r'aaa', callback),
    ), re.MULTILINE)
    scanner.scan(text_XX)
开发者ID:bossjones,项目名称:etc-python,代码行数:13,代码来源:test_scanner.py


示例19: run_parser

 def run_parser(self, file_, lib_classes = None):
     """parses a jml file and returns a list of abstract syntax trees, or
     parses a string containing JaML code.
     """
     scanner = Scanner()
     # Try and parse a file, if this fails, parse as a string
     try:
         # This is to see if it's a file or not
         open(file_)
         # Stores the directory of the main class
         dir_ = os.path.dirname(file_)
         # Add the name of the main class to begin with
         file_name = os.path.basename(file_)
         class_name = file_name.replace('.jml', '')
         # this stores names of all already seen class references
         seen = [class_name]
         # Stores classes to parse
         to_parse = [class_name]
         # Stores the ASTs of parsed classes
         parsed = nodes.ProgramASTs()
         while to_parse:
             # Append file information to the class names
             file_name = os.path.join(dir_, to_parse[0] + '.jml')
             # Get the raw input
             raw = open(file_name)
             input_ = raw.read()
             # Scan and parse the file
             tokens = scanner.tokenize(input_)
             ast = self.parse(tokens)
             # Check the class and file are named the same
             if to_parse[0] != ast.children[0].value:
                 msg = 'Class name and file name do not match!'
                 raise NameError(msg)
             to_parse.pop(0)
             parsed.append(ast)
             # Fined classes reference from the one just parsed
             if lib_classes == None:
                 lib_classes = {}
             refed_classes = self._find_refed_classes
             refed_classes = refed_classes(ast, seen, [], lib_classes, dir_)
             seen += refed_classes
             to_parse += refed_classes
         return parsed
     except IOError:
         # Simply parse the program held in the string
         tokens = scanner.tokenize(file_)
         ast = self.parse(tokens)
         ast_wrapper = nodes.ProgramASTs()
         ast_wrapper.append(ast)
         return ast_wrapper
开发者ID:WillSewell,项目名称:jaml_compiler,代码行数:50,代码来源:parser_.py


示例20: main

def main(argv):
    if len(argv) == 1 or len(argv) > 2:
        usage()
        sys.exit(2)
    try:
        path = argv[1]
        scanner = Scanner()
        scanner.scan(path)
        scanner.rebuild_tracks()
        fcpxml = FcpXML()
        fcpxml.create_xml()
    except getopt.GetoptError, err:
        print str(err)
        usage()
        sys.exit(2)
开发者ID:liaozd,项目名称:melissa,代码行数:15,代码来源:go.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python Model.Model类代码示例发布时间:2022-05-27
下一篇:
Python scandir.walk函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap