Contents of my project is like this
C:/{user_name}/my_project/
│ bar.sh
├─scripts/
│ │ bar.sh
│ │
│ └─bar/
│ bar.sh
│
└─src/
foo.py
and Content of all of bar.sh is
python src/foo.py
so if I run from C:/{user_name}/my_project/ directory, bar.sh works.
bash bash.sh
bash scripts/bar.sh
bash scripts/bar/bar.sh
However, after moved to scripts directory, below command does not work because bar.sh tries to find /my_project/sciprts/src/foo.py
bash bar.sh
I understand we can add my_project directory to PYTHONPATH by editing window's envrionmental valiables to solve this. However, I would like to avoid this because {user_name} can be varied and this envrionmental is shared by many guys.
Therefore I am looking for a good way to add my_project directory to PYTHONPATH by adding same line(s) to bar.sh. Do you know such a magic command?
CodePudding user response:
Personally, I don't think modifying PYTHONPATH
via bash script is a good solution here as you risk corrupting it. If you're interested in being able to call python foo.py
directly, you should turn /src
into a package. Not only will this allow you to execute foo.py
from anywhere in your system, you will also be able to import the code therein into any Python code you write. Here's some documentation on modules and some more on creating packages.
Essentially, you create some files in you my_project
directory to tell Python about the package itself as well as dependencies and such. Make sure that all the directories in the /src
directory have an __init__.py
file as well. Once you've done that, you can call pip insall -e my_project
which will install it as a package on your system (make sure you have pip installed; it should have been when you installed Python, but if not you can get it here). After that, you can call your code from wherever.
CodePudding user response:
cd "$(dirname "$0")/.."
works for me!