Adam Lewis
Adam Lewis

Reputation: 7247

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

The Goal: Access / Write to the same temp files when using a common utility function called from various python modules.

Background: I am using the python Unittest module to run sets of custom tests that interface with instrumentation via pySerial. Because I am using the unittest module, I am unable to pass required variables, such as which serial port to use, into the unittest's test case. To get around this I am wanting to create a module that stores and returns pickled data. I have run into the issue that when I call the function get_foo() from test_case_1(), it tries to load the pickled data from the relative path based on test_case_1(), not the actual module that contains get_foo().

It is worth noting that I have contemplated using global variables, but there is a handful of data that I want to retain from run to run. Meaning that all python modules will be closed and I want to re-load the data that was stored on the previous execution.

I in SO question: Python - how to refer to relative paths of resources when working with code repository, I thought I found the solution in the first answer. To my dismay, this is not working for me in Python 2.7 (Debian)

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

Upvotes: 6

Views: 2062

Answers (1)

Tony Veijalainen
Tony Veijalainen

Reputation: 5555

Probably you know this, but here 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')

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

Upvotes: 5

Related Questions