如何在不同模块导入时访问Python 2.7中的相对路径

目标:
使用从各种python模块调用的公共实用程序函数时,访问/写入相同的临时文件.

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

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

我在问题:Python – how to refer to relative paths of resources when working with code repository,我以为我在第一个答案中找到了解决方案.令我沮丧的是,这在Python 2.7(Debian)中对我不起作用

从不同模块调用时,是否有可靠的方法将路径返回到特定文件

最佳答案
可能你知道这一点,但首先是基础知识:

## 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
""""

相关文章

我最近重新拾起了计算机视觉,借助Python的opencv还有face_r...
说到Pooling,相信学习过CNN的朋友们都不会感到陌生。Poolin...
记得大一学Python的时候,有一个题目是判断一个数是否是复数...
文章目录 3 直方图Histogramplot1. 基本直方图的绘制 Basic ...
文章目录 5 小提琴图Violinplot1. 基础小提琴图绘制 Basic v...
文章目录 4 核密度图Densityplot1. 基础核密度图绘制 Basic ...