在動態執行的情況下,由「變數」(指定一個filename),來import~
一般來說,是已知path及filename,做import path.filename(without py)
但這個就有點點小複雜…
def importPythonFileAsModule(strModulePathName):
ImportModule = None
# Check File exist
if ( False == checkIsFile(strModulePathName) ):
print "Python File: %s doesn't exist!\n" % (strModulePathName)
return ImportModule
# Saving current working directory
CWD = os.getcwd()
# Split pathname & filename
(strModule_path , strModule_name) = os.path.split(strModulePathName)
# Get module name from filename
#strModule_name = str(strModule_name).lower()
if ( strModule_name[-3:] == ".py" ):
strModule_name = strModule_name[:-3]
# Change to module's path
os.chdir(strModule_path)
# Import Module
try:
ImportModule = __import__(strModule_name)
except:
print "Import Module: %s in %s failed!\n" % (strModule_name, strModule_path)
# Back to Original Path
os.chdir(CWD)
return ImportModule
1. 先把filename做split 成 path 及file 兩段
2. change working directory 到path
3. import它,return 接一個 objectname
即可~~~
至於Perl的部份:
****先留一個指令「Do」…
下次再來研究~~~趕工優先~~~
-------------------
修正版,利用sys.path ,python在讀module時的預設path來方便我做import…
def importPythonFileAsModule(strModulePathName):
ImportModule = None
# Check File exist
if ( False == os.path.isfile(strModulePathName) ):
print "Python File: %s doesn't exist!\n" % (strModulePathName)
return ImportModule
# Saving current working directory
CWD = os.getcwd()
# Split pathname & filename
(strModule_path , strModule_name) = os.path.split(strModulePathName)
# Get module name from filename
#strModule_name = str(strModule_name).lower()
if ( strModule_name[-3:] == ".py" ):
strModule_name = strModule_name[:-3]
# Change to module's path
os.chdir(strModule_path)
# Import Module
try:
sys.path.append(strModule_path)
ImportModule = __import__(strModule_name)
sys.path.pop()
except:
print "Import Module: %s in %s failed!\n" % (strModule_name, strModule_path)
# Back to Original Path
os.chdir(CWD)
return ImportModule
其實只加了兩行:
sys.path.append(strModule_path)
ImportModule = __import__(strModule_name)
sys.path.pop()
就是加入path、import完、再拿掉~~~
1 則留言:
囧~~
在linux上,不是這樣就能load了…
需要去設PYTHONPATH…
這樣有點麻煩…
正在想怎麼搞比較好弄~~~
張貼留言