How can I access relative paths in Python 2.7 when importing using different modules

Purpose: Access / write to the same temporary files when using the general utility function called from various python modules.

Background: I am using the Uittest python module to run custom test suites that interact with tools through pySerial. Since I use the unittest module, I cannot pass the required variables, for example, which serial port to use, to the unittest test case. To get around this, I want to create a module that stores and returns pickled data. I ran into a problem that when I call the get_foo () function from test_case_1 (), it tries to load the pickled data from a relative path based on test_case_1 (), and not the actual module that contains get_foo ().

It is worth noting that I have considered using global variables, but there is some data that I want to save from run to run. This means that all python modules will be closed, and I want to reload the data that was saved in the previous execution.

I am in SO question: Python - how to relate to relative resource paths when working with a code repository , I thought I found a solution in the first answer. To my horror, this does not work for me in Python 2.7 (Debian)

Is there a reliable way to return the path to a specific file when called from different modules?

+5
source share
1 answer

You probably know this, but here are the basics first:

## 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')

Module

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

All Articles