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

2024/10/18 15:31:15

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?

Answer

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=12Push Enter
""""
https://en.xdnf.cn/q/72773.html

Related Q&A

Emacs: Inferior-mode python-shell appears lagged

Im a Python(3.1.2)/emacs(23.2) newbie teaching myself tkinter using the pythonware tutorial found here. Relevant code is pasted below the question.Question: when I click the Hello button (which should …

AttributeError: module spacy has no attribute load

import spacy nlp = spacy.load(en_core_web_sm)**Error:** Traceback (most recent call last):File "C:\Users\PavanKumar\.spyder-py3\ExcelML.py", line 27, in <module>nlp = spacy.load(en_core…

No module named Win32com.client error when using the pyttsx package

Today, while surfing on Quora, I came across answers on amazing things that python can do. I tried to use the pyttsx Text to Speech Convertor and that gave me an No module named Win32com.client error.T…

Python: How to create and use a custom logger in python use logging module?

I am trying to create a custom logger as in the code below. However, no matter what level I pass to the function, logger only prints warning messages. For example even if I set the argument level = log…

Flask-Mail - Sending email asynchronously, based on Flask-Cookiecutter

My flask project is based on Flask-Cookiecutter and I need to send emails asynchronously.Function for sending email was configured by Miguel’s Tutorial and sending synchronously works fine, but i don’…

Change text_factory in Django/sqlite

I have a django project that uses a sqlite database that can be written to by an external tool. The text is supposed to be UTF-8, but in some cases there will be errors in the encoding. The text is fro…

Shuffle patches in image batch

I am trying to create a transform that shuffles the patches of each image in a batch. I aim to use it in the same manner as the rest of the transformations in torchvision: trans = transforms.Compose([t…

Python looping: idiomatically comparing successive items in a list

I need to loop over a list of objects, comparing them like this: 0 vs. 1, 1 vs. 2, 2 vs. 3, etc. (Im using pysvn to extract a list of diffs.) I wound up just looping over an index, but I keep wondering…

Geodesic buffering in python

Given land polygons as a Shapely MultiPolygon, I want to find the (Multi-)Polygon that represents the e.g. 12 nautical mile buffer around the coastlines.Using the Shapely buffer method does not work si…

jinja2 variables naming - Are variables naming restrictions the same as for Python variables?

I didt find it written explicitly in the docs.Are the naming rules the same as with Python variables?(eg: {{ a_variablelike_that }} doesnt work for example)