Tomáš Zato
Tomáš Zato

Reputation: 53119

How to run python script with a specific working directory?

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.

Upvotes: 1

Views: 1181

Answers (4)

Diego Torres Milano
Diego Torres Milano

Reputation: 69188

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.

Upvotes: 1

Philippe
Philippe

Reputation: 26422

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

Upvotes: 0

FelipeC
FelipeC

Reputation: 9488

You can try using env --chdir:

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

Upvotes: 1

Pranjal Doshi
Pranjal Doshi

Reputation: 1262

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

Upvotes: 4

Related Questions