目标:使用从各种 python 模块调用的通用实用程序函数时访问/写入相同的临时文件。
背景:我正在使用 python Unittest 模块来运行一组自定义测试,这些测试通过 pySerial 与仪器接口。因为我使用的是unittest模块,所以我无法将所需的变量(例如要使用哪个串行端口)传递到unittest的测试用例中。为了解决这个问题,我想创建一个存储和返回腌制数据的模块。我遇到了这样的问题:当我从 test_case_1() 调用函数 get_foo() 时,它会尝试从基于 test_case_1() 的相对路径加载腌制数据,而不是包含 get_foo() 的实际模块。
值得注意的是,我已经考虑过使用全局变量,但是我想在运行过程中保留一些数据。这意味着所有 python 模块都将被关闭,我想重新加载上次执行时存储的数据。
我有这样的问题:Python - 使用代码存储库时如何引用资源的相对路径 https://stackoverflow.com/questions/1270951,我以为我在第一个答案中找到了解决方案。令我沮丧的是,这在 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
""""
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)