#πŸ”’ Set Python path for all files in a certain folder

4 messages Β· Page 1 of 1 (latest)

fading pollen
#

I am writing test cases in Python. The folder structure is a little bit like this (folder names are bold, file names are italicized)

PROJECT ROOT
libs
init.py
file1.py
file2.py
docs
init.py
fileA.py
fileB.py
tests
-- libs(subfolder)
--init.py
--test_file1.py
--test_file2.py
--docs (subfolder)
--init.py
--test_fileA.py
--test_fileB.py

I want to set the PythonPATH to all the files in each of the tests subfolders to something programatically (and not via the terminal). The files in /tests/libs/ would all have the same PYTHONPATH and so would the files in /tests/docs/ when executed.

I know I could do something like this at the top of every file -

import os

# Get the directory of the current script file
current_dir = os.path.dirname(os.path.abspath(__file__))

# Assume the 'libs' directory is located in the parent directory of the current script
root_folder_path = os.path.abspath(os.path.join(current_dir, ".."))

# Now you can import modules from the 'libs' directory
import sys
sys.path.append(os.path.join(root_folder_path, "libs"))

# Rest of your script...

but it would be super redundant to have the same 3-4 lines of code repeated across all files in the same folder (minus init.py). Is there any way I can set the PYTHONPATH once in one file and have it be applied to all the files in that folder?

shell craterBOT
#

@fading pollen

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

shell craterBOT
#

@fading pollen

Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.