1. 程式人生 > >Android自動化工具Monkeyrunner使用(六) —— python 裡的import

Android自動化工具Monkeyrunner使用(六) —— python 裡的import

這兩天正在學習python,在練習中,寫了兩個python指令碼來試驗import功能的用法,發現,總有一個模組無法import,提示資訊是說找不到被import的檔案。具體情況請看下面的具體介紹:

首先,我寫了兩個python指令碼,一個是讀檔案模組writefile,一個是readfile,如下(經簡化後):

WriteFile.py(D:\Python26\mypython\writefile\src\WriteFile.py)
#this is a test program1
def writefile():
    print 'thisis a test of writefile'

if __name__ == '__main__':
   writefile()

ReadFile.py(D:\Python26\mypython\writefile\src\ReadFile.py)
#this is a test program2
def readfile():
    print 'thisis a test of readfile'

if __name__ == '__main__':
   readfile()

main模組WriteandReadfile.py(D:\Python26\mypython\writeandreadfile\src\writeandReadFile.py)
#this is a test program3
import sys
sys.path.append('d:\mypython\writefile\src')
sys.path.append('d:\mypython\readfile\src')

import WriteFile
import Readfile

while True:
    IWantDo =raw_imput('(\'w\' to writefile; \'r\' to readfile):')
    if IWantDo== 'w' or IWantDo == 'W':
       WriteFile.writefile()
       break
    elif IWantDo== 'r' or IWantDo == 'R':
       ReadFile.readfile()
       break
    else:
       print 'error!'
       break
print 'Done'

執行program3的時候,直接報錯:
Traceback (most recent call last):
  File"D:\Python26\mypython\WriteAndRead\src\writeandread.py", line 10,in <module>
    importReadFile
ImportError: No module named ReadFile
以上的意思是,import readfile時出錯。但問題是,同樣的操作,writefile為什麼就沒有問題呢?

於是,我在program3的sys.path.append和import語句之間,插入一條輸出語句sys.path,用以檢視我之前的兩個append是否追加成功,並可檢查追加的字串(即此處的路徑)是什麼。

執行程式後,可發現,在輸出的最後一條路徑顯示為:
'd:\\python\\mypython\readfile\\src'
也就是說,這個路徑中在資料夾readfile前少了一個斜槓。這是什麼原因呢?

如果你是一個觀察仔細的人,一眼就可以看出來'\r'連在一起代表什麼意思。這樣的字串在C語言裡是有特殊含義的,類似的還有'\t','\n'等等。現在的問題就出在這個連續的字串上,檢視MSDN(當然,考慮到python也是用C語言來完成的,我這裡偷懶,假借了MSDN對這些特殊字元如何處理的資料)可以發現,他們是推薦你在用到這些特殊的字串時,應該做些特殊的處理。

按以上介紹,我們可以將所有與路徑相關字串均表示成:
1.'X:\\program files\\XXXX'
2.'X:/program files/XXXX'
3.r'X:/program files/XXXX'
當然,用r'X:\\programfiles\\XXXX'也是一樣的,個人在此推薦作用第3種方式,至少也得習慣使用第2種,因為,當你在編輯一個跨平臺的程式的時候,unix的檔案路徑使用的是反斜槓,而在windows下,反斜槓做為目錄結構也是允許的。

另外,介紹另外一種字串表示方式,就拿上面這個例子來說吧。三個python程式基本有相同的目錄結構,但有一個目錄結構不一樣,也就是與檔名相同的那個資料夾名字。當我們些次執行時涉及到的程式都在同一個碟符下時(當然,相信很少有人會放在不同碟符吧),我們可以用'..\'表示跳到上一級目錄,按上面的例子來說的話,我們在program3中進行sys.path.append時,可以這樣寫:
...
sys.path.append('..\..\writefile\src')
sys.path.append('..\..\readfile\src')
...