python中os模块的常用接口和异常中Exception的运用

时间:2023-03-08 18:47:26

1、os.path.join(arg1, arg2)

将arg1和arg2对应的字符串连接起来并返回连接后的字符串,如果arg1、arg2为变量,就先将arg1、arg2转换为字符串后再进行连接。

2、self.settings = Gio.Settings.new("com.linuxmint.mintmenu")

  在默认环境路径中,根据“com.linuxmint.mintmenu”开头的XML配置文件创建配置变量self.settings,通常XML配置文件位于/usr/share/glib-2.0/schemas/该目录下,主要包括插件的列表及插件本身属性键对应的键值,包括面的宽度、高度、颜色、图标大小、分类、粘性(sticky)和关键字本身属性的类型默认定义等。

  然后在代码中可以根据配置变量self.settings灵活的访问和设置插件的属性,极大减小了代码的冗余度和耦合度。

3、pygtk中延时器的运用,主要用于需要耗费时间较长的函数中,如设置主界面的透明度或者初始化主界面函数时,通过增加延时使得函数可以完全正确执行。

def __init__( self, applet, iid ):

self.load_timer_id = GObject.timeout_add(50, self.runMainWinLoad)

def runMainWinLoad(self):
        GObject.source_remove(self.load_timer_id)

4、try ... except    与 try  ... except Exception, e:的应用场景差别

后者包含于前者,后者主要应用于当需要对异常的具体类型进行特殊说明时,"e"代表代码具体错误、“cause”代表引起异常的原因、“detail”代表异常的具体信息等等,如下面的代码:

    def bind_hot_key (self):
try:
if self.hotkeyText != "":
self.keybinder.grab( self.hotkeyText )
self.keybinder.connect("activate", self.onBindingPress)
self.keybinder.start()
# Binding menu to hotkey
print "Binding to Hot Key: " + self.hotkeyText except Exception, cause:
print "** WARNING ** - Menu Hotkey Binding Error"
print "Error Report :\n", str(cause)
pass
def detect_desktop_environment (self):
self.de = "mate"
try:
de = os.environ["DESKTOP_SESSION"]
if de in ["gnome", "gnome-shell", "mate", "kde", "xfce"]:
self.de = de
else:
if os.path.exists("/usr/bin/caja"):
self.de = "mate"
elif os.path.exists("/usr/bin/thunar"):
self.de = "xfce"
except Exception, detail:
print detail

5、self.button_box.set_homogeneous( False )时什么意思?

  homogeneous    表示子构件是否具有同样的大小   True -> 子构件大小相同    False-> 子构件大小根据子构件本身设置属性决定。