1

I am using a find statement to execute python scripts which are in sub folders of all sub folders of the current directory

The find statement is find . -name \process.py -type f -exec python3 {} \;

The problem I am encountering is that the script is using relative paths e.g ..\data for retrieving other resources. These relative paths are resolved as required when the script is executed individually by running it from its directory but when running the script from a parent directory two levels up using the find command the path resolves relative to that parent directory causing errors

Isen Ng
  • 1,307
  • 1
  • 11
  • 23
S.aad
  • 518
  • 1
  • 5
  • 22
  • The answer was found here [here](https://stackoverflow.com/questions/12790986/running-a-python-script-inside-another-directory) – S.aad Jun 02 '18 at 01:51

2 Answers2

1

You can use -execdir option of the find command:

Having the following folder structure in /tmp:

/test
/test/subdir1
/test/subdir1/subdir2
/test/subdir1/subdir2/subdir3

and a r.py file in each folder:

# r.py
import os
dirpath = os.path.dirname(os.path.realpath(__file__))
print(dirpath)

You have the output:

/tmp/test
/tmp/test/subdir1
/tmp/test/subdir1/subdir2
/tmp/test/subdir1/subdir2/subdir3
Evhz
  • 8,852
  • 9
  • 51
  • 69
0

If you need to do this in python I suggest looking at this answer: How to get an absolute file path in Python

It is always better to find an absolute path, If using bash:

readlink -f filename 
pypalms
  • 461
  • 4
  • 12