[英]Run python script with .bat that imports functions from other scripts
I am trying to run my python script through.bat.我正在尝试通过 .bat 运行我的 python 脚本。 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.该脚本从其他脚本导入函数,在 IDE(Spyder) 中运行时效果很好,但是当我运行 the.bat 时,出现无法导入模块的错误。
.bat is as follows .bat如下
"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'回溯(最近调用最后):文件“D:\Users\User\Documents\programming\test.py”,第 1 行,在 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.我需要向 the.bat 添加什么才能在 SFTPDownload.py 中获取我的 function。 This is in the same folder as the test.py.它与 test.py 位于同一文件夹中。
Thanks in advance.提前致谢。
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如果SFTPDownload.py
是文件夹D:\Users\User\Documents\programming\
中的文件,那么在运行 python 脚本之前,您必须 go 到此文件夹
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.系统可能会在不同的文件夹(用作Current Working Directory
)中运行您的批处理,然后 python 脚本会在此文件夹中搜索您的文件。
In Python you can check Current Working Directory
在 Python 你可以查看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.最终在导入SFTPDownload
之前的 python 脚本中,您可以将文件夹D:\Users\User\Documents\programming\
添加到 python 用于搜索导入文件的特殊列表sys.path
。
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为了让它更通用(所以当你将test.py
和SFTPDownload.py
移动到不同的文件夹时它会起作用)你可以尝试
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.