簡體   English   中英

如何在不同模塊導入時訪問Python 2.7中的相對路徑

[英]How can I access relative paths in Python 2.7 when imported by different modules

目標:當使用從各種python模塊調用的公共實用程序函數時,訪問/寫入相同的臨時文件。

背景:我使用python Unittest模塊運行多組自定義測試,這些測試通過pySerial與儀器連接。 因為我使用的是unittest模塊,所以我無法將所需的變量(例如要使用的串口)傳遞到unittest的測試用例中。 為了解決這個問題,我想創建一個存儲和返回pickle數據的模塊。 我遇到的問題是,當我從test_case_1()調用函數get_foo()時,它會嘗試從基於test_case_1()的相對路徑加載pickle數據,而不是包含get_foo()的實際模塊。

值得注意的是,我已經考慮過使用全局變量,但是我希望從運行中保留一些數據。 這意味着將關閉所有python模塊,並且我想重新加載先前執行時存儲的數據。

我在SO問題: Python - 在使用代碼庫時如何引用資源的相對路徑 ,我以為我在第一個答案中找到了解決方案。 令我沮喪的是,這在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
""""

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM