0

I have imported a python module from another directory in Linux by using sys.path.insert but when I run that module it fails. As the imported module is trying to open a file that is local to that module. Please let me know how to fix this.

users/adr/release/invoke.py  #this one fails with can’t open file ./config.ini

import sys

sys.path.insert(0, ‘/user/cdw/audit/’)

import audit_main

The path where the original module file resides.

/user/cdw/audit/audit_main.py  # this module opens config.ini file to read pplication credentials.
/user/cdw/audit/config.ini

/user/cdw/audit/__ini__.py
drum
  • 5,416
  • 7
  • 57
  • 91
Raveendra
  • 47
  • 1
  • 6
  • 1
    You may be able to use that module's `__file__` variable. `os.path.join(os.path.dirname(__file__), "config.ini")` – tdelaney May 30 '20 at 23:29
  • 2
    When asking these types of questions, it's a lot nicer/better if you add a folder structure like [this](https://stackoverflow.com/questions/62102453/how-to-define-callbacks-in-separate-files-plotly-dash/62102585#621025859), and add a full stack trace of your error in a code block. Makes our job a LOT easier. – Torxed May 30 '20 at 23:31
  • @drum You messed up the indentation on that edit. – Torxed May 30 '20 at 23:32
  • @tdelaney, it is working. Thanks a lot! – Raveendra May 30 '20 at 23:49

1 Answers1

0

When python loads a module it adds metadata to its global namespace that can be used by the module. __file__ is the filename of its .py file - when such a name makes sense. You can use it to get your config file

import os
config_filename = os.path.join(os.path.dirname(__file__), "config.ini")

except for when you can't. If this is a C extension file or if the file was in some other packaging like zip or egg or pyinstaller bundle or exe, it may not work. A ini file, which I assume is user editable, may need to be some place other than the module directory. If you make this .py part of an installable package, it may end up in a system directory the user can't edit. This may not be a problem for this project, just laying out some of the considerations.

tdelaney
  • 73,364
  • 6
  • 83
  • 116
  • 1
    Have a look at [pkguti.get_data](https://docs.python.org/3/library/pkgutil.html#pkgutil.get_data). It can dig data out of zips/eggs as well as the filesystem. It doesn't handle namespace packages, though. – Chris May 31 '20 at 01:05