How to execute a python script in a different directory?

I managed to get b.py executing and producing the testB folder where I need it to, while remaining in the MAIN folder. For anyone who might wonder, at the beginning of my b.py script I would simply use mydir = os.getcwd() which normally is wherever b.py is.

To keep b.py in MAIN while making it work on files in other directories, I wrote this:

mydir = os.getcwd() # would be the MAIN folder
mydir_tmp = mydir + "//testA" # add the testA folder name
mydir_new = os.chdir(mydir_tmp) # change the current working directory
mydir = os.getcwd() # set the main directory again, now it calls testA

Running the bash script now works!


The easiest answer is probably to change your working directory, then call the second .py file from where it is:

python a.py && cd testA && python ../b.py

Of course you might find it even easier to write a script that does it all for you, like so:

Save this as runTests.sh in the same directory as a.py is:

#!/bin/sh
python a.py
cd testA
python ../b.py

Make it executable:

chmod +x ./runTests.sh

Then you can simply enter your directory and run it:

./runTests.sh

In your batch file, you can set the %PYTHONPATH% variable to the folder with the Python module. This way, you don't have to change directories or use pushd to for network drives. I believe you can also do something like

set "PYTHONPATH=%PYTHONPATH%;c:\the path\to\my folder\which contains my module"

This will append the paths I believe (This will only work if you already have set %PYTHONPATH% in your environment variables).

If you haven't, you can also just do

set "PYTHONPATH=c:\the path\to\my folder\which contains my module"

Then, in the same batch file, you can do something like

python -m mymodule ...