本文整理汇总了Python中scanner.Scanner类的典型用法代码示例。如果您正苦于以下问题:Python Scanner类的具体用法?Python Scanner怎么用?Python Scanner使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Scanner类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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, {})
示例2: main
def main():
args_handler = Handler()
ip = args_handler.parsing_ip()
tgt.send('1.1.1.1')
scan = Scanner(tgt)
scan.scan_ports()
示例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
示例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])
示例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
示例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)
示例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)
示例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
示例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()
示例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()
示例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)
示例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()
示例13: readTable
def readTable(filename):
s = Scanner(filename)
table = []
record = readRecord(s)
while record != "":
table.append(record)
record = readRecord(s)
s.close()
return table
示例14: mainScanner
def mainScanner():
file = open(filer)
scanner = Scanner(file.read() + '\0')
lexeme = scanner.scanNext()
while lexeme.type != 200:
lexeme.pprint()
lexeme = scanner.scanNext()
示例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()