python动态导入模块、检查模块是否安装
参考链接:http://www.woodpecker.org.cn/diveintopython/functional_programming/dynamic_import.html
一 动态导入模块
Python的import不能接受变量,所以应该用 __import__函数来动态导入。
如下的代码无法正常导入模块
modules = ['OpenSSL', 'Crypto', 'MySQLdb', 'sqlite3', 'zope.interface', 'pyasn1', 'twisted', 'django']
for each in modules:
try:
import each
except Exception, e:
print e
这样导入会抛出 No module named each
的异常
将 import each 改为 __import__(each)就可以正常导入了。
二 检查模块是否安装
使用__import__函数也可以用来检查模块是否已安装,略微修改上面的代码即可。
使用imp.find_module()来检查不方面,如find_module('zope.interface')会抛出异常——因为这个函数无法查找子模块。
模块加载后,就可以在sys.module这个字典里找到加载的模块名了。
相关文档:
我们在做软件开发的时候很多要用到多线程技术。例如如果做一个下载软件象flashget就要用到、象在线视频工具realplayer也要用到因为要同时下载media stream还要播放。其实例子是很多的。
线程相对进程来说是“轻量级”的,操作系统用较少的资源创建和管理线程。程序中的线程在相同的内存空间中执行,并共享许多 ......
And last here is the overload operators example:
# map() takes two (or more) arguments, a function and a list to apply the function to
# lambda can be put anywhere a function is expected
# map() calls lambada for every element in the self list
# since Vector has overloaded __getitem__ and __len_ ......
#快速排序
def Partition(mylist, low, high):
tmp = mylist[low]
while low < high:
while low < high and mylist[high] >= tmp:
high = high - 1
if low < high:
mylist[low] = mylist[high]
low = low + 1
while low < hi ......
def MergeSort(mylist, low, mid, high):
i = low
j = mid + 1
tmp = []
while i <= mid and j <= high:
if mylist[i] <= mylist[j]:
tmp.append(mylist[i])
i = i + 1
else:
tmp.append(mylist[j])
j = j + 1
......
情景一:
在文件夹里有六十多个RM格式的视频文件,我现在需要把它们的文件名都提取出来,并去掉文件的扩展名,以便放到需要的网页里。
应该有什么软件可以完成这个简单的要求,可是一时间到哪里去找这 样一个符合要求的软件呢?总不能手工完成把。在Linux上用强大的shell脚本应该也可以完成,可是使用Windows的朋友呢?其 ......