0

I am trying to run my python script through .bat. The script imports functions from other scripts and this works fine when running in the IDE(Spyder) however when I run the .bat I get the error unable to import module.

.bat is as follows

"D:\Users\User\AppData\Local\Programs\Python\Python38-32\python.exe" "D:\Users\User\Documents\programming\test.py"

I get the following error

Traceback (most recent call last): File "D:\Users\User\Documents\programming\test.py", line 1, in from SFTPDownload import downloadSFTP ModuleNotFoundError: No module named 'SFTPDownload'

What do I need to add to the .bat to pick up my function in SFTPDownload.py. This is in the same folder as the test.py.

Thanks in advance.

Dales91
  • 21
  • 1
  • 6
  • If `SFTPDownload.py` is your file in folder `D:\Users\User\Documents\programming\ ` then you have to go to this folder `cd D:\Users\User\Documents\programming\ ` before you run python script. – furas Dec 25 '20 at 07:57

1 Answers1

3

If SFTPDownload.py is your file in folder D:\Users\User\Documents\programming\ then you have to go to this folder before you run python script

  cd D:\Users\User\Documents\programming\

  D:\Users\User\AppData\Local\Programs\Python\Python38-32\python.exe test.py

System may run your batch in different folder (which is used as Current Working Directory) and then python script searchs your files in this folder.

In Python you can check Current Working Directory

 print( os.getcwd() )

See also: What is the current directory in a batch file?


Eventually in python script before importing SFTPDownload you can add folder D:\Users\User\Documents\programming\ to special list sys.path which python uses to search imported files.

 import sys

 sys.path.insert(0, r'D:\Users\User\Documents\programming\')

 import SFTPDownload

to make it more universal (so it would work when you move test.py and SFTPDownload.py to different folder) you can try

 import sys
 import os

 APP_FOLDER = os.path.abspath(os.path.dirname(__file__))
 #APP_FOLDER = os.path.abspath(os.path.dirname(sys.argv[0]))

 sys.path.insert(0, APP_FOLDER)

 import SFTPDownload
furas
  • 134,197
  • 12
  • 106
  • 148
  • hello @furas, i am facing a similar issue buy my import module 'Aladdin' is in a different folder (and thus filepath). how can i get it to work in that case? – Zack Nov 17 '21 at 14:30
  • @Zack if you have module `/full/path/other_folder/Aladdin` then you have to insert `/full/path/other_folder` without `Aladdin`. If you have it in subfolder `APP_FOLDER/subfolder/Aladdin` then you can use `os.path.join(APP_FOLDER, "subfolder")` to create `full path` to insert. – furas Nov 17 '21 at 17:46