1、python自动连接ssh的代码
#!/usr/bin/python#-*- coding:utf-8 -*-import sys, time, ostry:import pexpectexcept ImportError:PRint """You must install pexpect module"""sys.exit(1)addr_map = {'v3' :('root@192.168.1.162', 'sina@2009'),'dev':('test016@192.168.1.136', 'test016'),}try:key = sys.argv[1]host = addr_map[key]except:print """argv error, use it linkjssh v3, v3 must defined in addr_map"""sys.exit(1)server = pexpect.spawn('/usr/bin/ssh %s' % host[0])server.expect('.*ssWord:')server.sendline(host[1])server.interact()2、有没有一个工具可以帮助查找python的bug和进行静态的代码分析? 有,PyChecker是一个python代码的静态分析工具,它可以帮助查找python代码的bug, 会对代码的复杂度和格式提出警告 Pylint是另外一个工具可以进行coding standard检查。 3、 如何在一个function里面设置一个全局的变量? 解决方法是在function的开始插入一个global声明: def f() global x 4、Tkinter的ToolTip控件
from Tkinter import *from time import time, localtime, strftimeclass ToolTip( Toplevel ):"""Provides a ToolTip widget for Tkinter.To apply a ToolTip to any Tkinter widget, simply pass the widget to theToolTip constructor""" def __init__( self, wdgt, msg=None, msgFunc=None, delay=1, follow=True ):"""Initialize the ToolTipArguments:wdgt: The widget this ToolTip is assigned tomsg: A static string message assigned to the ToolTipmsgFunc: A function that retrieves a string to use as the ToolTip textdelay: The delay in seconds before the ToolTip appears(may be float)follow: If True, the ToolTip follows motion, otherwise hides"""self.wdgt = wdgtself.parent = self.wdgt.master # The parent of the ToolTip is the parent of the ToolTips widgetToplevel.__init__( self, self.parent, bg='black', padx=1, pady=1 ) # Initalise the Toplevelself.withdraw() # Hide initiallyself.overrideredirect( True ) # The ToolTip Toplevel should have no frame or title barself.msgVar = StringVar() # The msgVar will contain the text displayed by the ToolTip if msg == None: self.msgVar.set( 'No message provided' )else:self.msgVar.set( msg )self.msgFunc = msgFuncself.delay = delayself.follow = followself.visible = 0self.lastMotion = 0Message( self, textvariable=self.msgVar, bg='#FFFFDD',aspect=1000 ).grid() # The test of the ToolTip is displayed in a Message widgetself.wdgt.bind( '<Enter>', self.spawn, '+' ) # Add bindings to the widget. This will NOT override bindings that the widget already hasself.wdgt.bind( '<Leave>', self.hide, '+' )self.wdgt.bind( '<Motion>', self.move, '+' )def spawn( self, event=None ):"""Spawn the ToolTip. This simply makes the ToolTip eligible for display.Usually this is caused by entering the widgetArguments:event: The event that called this funciton"""self.visible = 1self.after( int( self.delay * 1000 ), self.show ) # The after function takes a time argument in milisecondsdef show( self ):"""Displays the ToolTip if the time delay has been long enough"""if self.visible == 1 and time() - self.lastMotion > self.delay:self.visible = 2if self.visible == 2:self.deiconify()def move( self, event ):"""Processes motion within the widget.Arguments:event: The event that called this function"""self.lastMotion = time()if self.follow == False: # If the follow flag is not set, motion within the widget will make the ToolTip dissapearself.withdraw()self.visible = 1self.geometry( '+%i+%i' % ( event.x_root+10, event.y_root+10 ) ) # Offset the ToolTip 10x10 pixes southwest of the pointertry:self.msgVar.set( self.msgFunc() ) # Try to call the message function. Will not change the message if the message function is None or the message function failsexcept:passself.after( int( self.delay * 1000 ), self.show )def hide( self, event=None ):"""Hides the ToolTip. Usually this is caused by leaving the widgetArguments:event: The event that called this function"""self.visible = 0self.withdraw()def xrange2d( n,m ):"""Returns a generator of values in a 2d rangeArguments:n: The number of rows in the 2d rangem: The number of columns in the 2d rangeReturns:A generator of values in a 2d range"""return ( (i,j) for i in xrange(n) for j in xrange(m) )def range2d( n,m ):"""Returns a list of values in a 2d rangeArguments:n: The number of rows in the 2d rangem: The number of columns in the 2d rangeReturns:A list of values in a 2d range"""return [(i,j) for i in range(n) for j in range(m) ]def print_time():"""Prints the current time in the following format:HH:MM:SS.00"""t = time()timeString = 'time='timeString += strftime( '%H:%M:', localtime(t) )timeString += '%.2f' % ( t%60, )return timeStringdef main():root = Tk()btnList = []for (i,j) in range2d( 6, 4 ):text = 'delay=%i/n' % idelay = iif j >= 2:follow=Truetext += '+follow/n'else:follow = Falsetext += '-follow/n'if j % 2 == 0:msg = NonemsgFunc = print_timetext += 'Message Function'else:msg = 'Button at %s' % str( (i,j) )msgFunc = Nonetext += 'Static Message'btnList.append( Button( root, text=text ) )ToolTip( btnList[-1], msg=msg, msgFunc=msgFunc, follow=follow, delay=delay)btnList[-1].grid( row=i, column=j, sticky=N+S+E+W )root.mainloop()if __name__ == '__main__':main()5、介绍一下Python中webbrowser的用法? webbrowser模块提供了一个高级接口来显示基于Web的文档,大部分情况下只需要简单的调用open()方法。 webbrowser定义了如下的异常 exception webbrowser.Error, 当浏览器控件发生错误是会抛出这个异常 webbrowser有以下方法: webbrowser.open(url[, new=0[, autoraise=1]]) 这个方法是在默认的浏览器中显示url, 如果new = 0, 那么url会在同一个浏览器窗口下打开,如果new = 1, 会打开一个新的窗口,如果new = 2, 会打开一个新的tab, 如果autoraise = true, 窗口会自动增长。 webbrowser.open_new(url) 在默认浏览器中打开一个新的窗口来显示url, 否则,在仅有的浏览器窗口中打开url webbrowser.open_new_tab(url) 在默认浏览器中当开一个新的tab来显示url, 否则跟open_new()一样 webbrowser.get([name]) 根据name返回一个浏览器对象,如果name为空,则返回默认的浏览器 webbrowser.register(name, construtor[, instance]) 注册一个名字为name的浏览器,如果这个浏览器类型被注册就可以用get()方法来获取。 6、Python里面search()和match()的区别? match()函数只检测RE是不是在string的开始位置匹配, search()会扫描整个string查找匹配, 也就是说match()只有在0位置匹配成功的话才有返回,如果不是开始位置匹配成功的话,match()就返回none 例如: print(re.match(‘super’, ‘superstition’).span())会返回(0, 5) 而print(re.match(‘super’, ‘insuperable’))则返回None search()会扫描整个字符串并返回第一个成功的匹配 例如:print(re.search(‘super’, ‘superstition’).span())返回(0, 5) print(re.search(‘super’, ‘insuperable’).span())返回(2, 7)
新闻热点
疑难解答