How to run python script with a specific working directory?

Question:

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.

Answers:

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
Answered By: Pranjal Doshi

You can try using env --chdir:

env --chdir=$dir python3.5 $dir/scripts/helper1.py someargument
Answered By: FelipeC

You can define a function (called python3-5):

#!/usr/bin/env bash
  
python3-5()(
    cd "$(dirname "$1")"
    python3.5 "$@"
)

python3-5 ~/company_repo/scripts/helper1.py someargument
python3-5 ~/company_repo/scripts/helper2.py
Answered By: Philippe

Create a script like this one

#! /bin/bash
if cd company_repo
then
    exec /usr/local/bin/python3.5 "$@"
fi

name it ~/bin/python3.5, make it executable

chmod +x ~/bin/python3.5

be sure ~/bin is before the directory containing the real pythno3.5 in your PATH:

PATH=~/bin:$PATH

then when you run (that would remain unchanged):

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

it will change the directory and then use the real python3.5 to execute it.

Answered By: Diego Torres Milano
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.