Home > Blockchain >  How to run python script with a specific working directory?
How to run python script with a specific working directory?

Time:08-19

tl;dr: What I am looking for:

python3.5 --working-dir=~/company_repo/ ~/company_repo/something.py

In the codebase I am working on, there are some scripts that help with various tasks - let's call them company scripts. These are owned by the teams responsible for those features.

Next to the codebase, I have my own repo with my own helper scripts - let's call them my scripts. Now my scripts are just bash scripts, and call a sequence of the python company scripts:

myscript.sh
python3.5 ~/company_repo/scripts/helper1.py someargument
python3.5 ~/company_repo/scripts/helper2.py

Problem is, some of the company scripts rely on being run within the company repo, because they call git commands, or load other files by relative path. I cannot change the company scripts right now.

Is there a way to tell the python runtime to use different working directory? I do not want to do cd ~/company_repo in my bash scripts.

CodePudding user response:

This is not a pythonic way but we can use the bash to mimic the same behavior.

you can try as suggested by @FlyingTeller

(cd company_repo && python3 helper.py)

or you can also use pushd & popd

pushd company_repo && python3 helper.py && popd

CodePudding user response:

You can try using env --chdir:

env --chdir=$dir python3.5 $dir/scripts/helper1.py someargument
  • Related