2011-03-28 65 views
5

目标: 使用从各种python模块调用的常用实用程序函数时访问/写入相同的临时文件。如何在不同模块导入时访问Python 2.7中的相对路径

背景: 我使用Python unittest模块运行多组自定义测试,通过pySerial设备接口。因为我正在使用unittest模块,所以我无法将所需的变量(如使用哪个串行端口)传递到unittest的测试用例。为了解决这个问题,我想创建一个存储并返回pickle数据的模块。我遇到了这样的问题,即当我从test_case_1()调用函数get_foo()时,它会尝试从基于test_case_1()的相对路径加载pickle数据,而不是包含get_foo()的实际模块。

值得注意的是,我已经考虑过使用全局变量,但我想从运行中保留一些数据以便运行。这意味着所有的python模块将被关闭,并且我想重新加载上次执行时存储的数据。

我在SO问题:Python - how to refer to relative paths of resources when working with code repository,我以为我在第一个答案找到解决方案。令我沮丧的是,这不是在Python 2.7(Debian的)为我工作

有来自不同模块调用时的路径返回到一个特定的文件的可靠的方法?

回答

3

也许你知道这一点,但这里的基础知识第一:

## file one: main.py, main program in your working directory 
# this code must run directly, not inside IDLE to get right directory name 
import os, mytest 
curdir=os.path.dirname(__file__) 
print '-'*10,'program','-'*10 
print 'Program in',curdir 
print 'Module is in', mytest.curdir 
print 'Config contents in module directory:\n',mytest.config() 
input('Push Enter') 

模块

## file two: mytest.py, module somewhere in PATH or PYTHONPATH 
import os 
curdir= os.path.dirname(__file__) 

print "Test module directory is "+curdir 

## function, not call to function 
config=open(os.path.join(curdir,'mycfg.cfg')).read 
""" Example output: 
Test module directory is D:\Python Projects 
---------- program ---------- 
Program in D:\test 
Module is in D:\Python Projects 
Config contents in module directory: 
[SECTIONTITLE] 
SETTING=12 

Push Enter 
"""" 
+0

谢谢你细谈在你的榜样。这是我需要找出我的麻烦。原来我在测试中错误地使用了dirname。你可以指向描述dirname(__ file__)的文档吗?我没有在python.org上看到它。 – 2011-03-28 20:31:52

+0

文档可以在http://docs.python.org/library/os.path.html找到,不太可能的情况是您没有帮助本地文件。 – 2011-03-28 21:16:48

+0

这实际上是我试图在dirname函数的__file__字段中查找文档的页面。有任何想法吗? – 2011-03-29 05:12:26

相关问题