0

I'm trying to run a python script "index.py" in python shell from a .bat file on windows. I tried this first script but it will only open my script in the Python UI without running it :

@echo off
set IDLEDIR=C:\Users\myusername\AppData\Local\Programs\Python\Python39\Lib\idlelib\
set FILEDIR=D:\myfolder\
start "IDLE" "%IDLEDIR%..\..\pythonw.exe" "%IDLEDIR%idle.pyw" %FILEDIR%index.py
pause

I tried this second script, but I have issues with os.listdir(relativefolder/) in my python script, as if the relative folder was not calculated from the script location but from the .bat file location

@echo off
set FILEDIR=D:\myfolder\
python "%FILEDIR%index.py"
pause

Could you help me find out how to fix this ?

Cephou
  • 257
  • 5
  • 23

2 Answers2

3

The second approach is correct.

To solve the import problem you should fix your python code using a different approach: In the following code curdir will have the name of the folder where your script is located, you can work upon this to do what you want.

import sys
import os
curdir = os.path.dirname(__file__)

Or you could change the working directory using the batch script. Check How to change current working directory using a batch file .

piertoni
  • 1,933
  • 1
  • 18
  • 30
1

Thanks for your answer !

My end goal was to execute multiple scripts at the same time, so thanks to your answer, I changed my code to this :

@echo off
set FILEDIR=D:\myfolder\
for /d %%i in (%FILEDIR%*) do ( 
    CD /D "%%i"
    start /B python "index.py"
) 
pause

And it's working as expected.

Cephou
  • 257
  • 5
  • 23