牛骨文教育服务平台(让学习变的简单)
博文笔记

Android自动化工具Monkeyrunner使用(六) —— python 里的import

创建时间:2012-10-29 投稿人: 浏览次数:6196
这两天正在学习python,在练习中,写了两个python脚本来试验import功能的用法,发现,总有一个模块无法import,提示信息是说找不到被import的文件。具体情况请看下面的具体介绍:

首先,我写了两个python脚本,一个是读文件模块writefile,一个是readfile,如下(经简化后):

WriteFile.py(D:Python26mypythonwritefilesrcWriteFile.py)
#this is a test program1
def writefile():
    print "thisis a test of writefile"

if __name__ == "__main__":
   writefile()

ReadFile.py(D:Python26mypythonwritefilesrcReadFile.py)
#this is a test program2
def readfile():
    print "thisis a test of readfile"

if __name__ == "__main__":
   readfile()

main模块WriteandReadfile.py(D:Python26mypythonwriteandreadfilesrcwriteandReadFile.py)
#this is a test program3
import sys
sys.path.append("d:mypythonwritefilesrc")
sys.path.append("d:mypython eadfilesrc")

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:Python26mypythonWriteAndReadsrcwriteandread.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 eadfile\src"
也就是说,这个路径中在文件夹readfile前少了一个斜杠。这是什么原因呢?

如果你是一个观察仔细的人,一眼就可以看出来" "连在一起代表什么意思。这样的字符串在C语言里是有特殊含义的,类似的还有" "," "等等。现在的问题就出在这个连续的字符串上,查看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("....writefilesrc")
sys.path.append(".... eadfilesrc")
...

声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。