0
votes

I have a script called "test.py" and refers to a config file called "cfg.yaml". These two reside in the same directory called "test/scripts".

test/scripts/test.py
test/script/cfg.yaml

Now I am writing a bash script inside "test/data1/data2" called task.sh

From inside of task.sh, I want to make a call to the python script

test.sh contents are as below:

#!/bin/sh

python ../../scripts/test.py

test.py opens and reads the cfg.yaml like open("cfg.yaml") but when the test.sh is called, it fails because "cfg.yaml" is NOT referred with relative path. How do I resolve this?

2
1. you could run test.py from test/scripts, 2. inside test.py you could change the path to cfg file as '../../scripts/test.py' or 3. you could use absolute path for the cfg file. This happens because python interpreter is being called from test/data1/data2 - rivu
Relative paths are relative to the current working directory, not relative to the location of the file being executed - mehtunguh

2 Answers

0
votes

try

#!/bin/sh

cd ../../scripts
python test.py

I assume in test.py you are referencing the yaml with a local path that expects the script to be running from the scripts directory (not from data1/data2)

as an aside you can always print os.getcwd() to see what your working directory is while running the python script (or just pwd in bash)

0
votes

If you want to refer to a file in terms of its relative location to the script, you can't just use a relative path for that, because the script may not be in the current working directory. In fact, in your case, it's guaranteed not to be in the current working directory.

The usual quick&dirty solution is to get the script path explicitly:

import os
import sys

scriptdir = os.path.abspath(os.path.dirname(sys.argv[0]))

That sys.argv[0] is the full name of your script—which on most platforms means either an absolute path, or a relative path that's at least still valid at this point. If you're worried about those other platforms, you may want to look at __file__. Of course if you're running the script out of a zipfile or similar, neither one will be useful.

open(os.path.join(scriptdir, "cfg.yaml"))

(Or you can even forcibly os.chdir(scriptdir) if you want, but that can be a bad idea if you're, e.g., accepting pathnames from the user.)

The right solution is to write your script and data files to be installed (even if you don't actually install anything and run it out of the source tree), and then use pkg_resources to find the data files. That will also solve a whole lot of other problems for you—but it does require a bit more learning first. See the Python Packaging User Guide if you want to get started on that road, and Package Data and Data Files as particular starting points.