Suppose following directory structure with two simple scripts
dir/
├── main.py
└── sub_routine.py
main.py:
#!/usr/bin/env python3
from subprocess import run
from pathlib import Path
my_dir = Path(__file__).parent
run([my_dir / "sub_routine.py"])
sub_routine.py:
#!/usr/bin/env python3
print("Hello there!")
When I run main.py from ancestor directory of dir it works properly:
~$ python3 ./dir/main.py
Hello there!
However, when I run it from dir it fails:
~$ cd dir
~/dir$ python3 ./main.py
...
FileNotFoundError: [Errno 2] No such file or directory: PosixPath('sub_routine.py'): PosixPath('sub_routine.py')
Why? And how can I ensure this will work regardless of where it's called from?