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

76 篇文章 1 订阅
24 篇文章 2 订阅
这两天正在学习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')
...

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值