【问题标题】:Run python script with .bat that imports functions from other scripts使用从其他脚本导入函数的 .bat 运行 python 脚本
【发布时间】:2021-04-03 05:40:56
【问题描述】:

我正在尝试通过 .bat 运行我的 python 脚本。该脚本从其他脚本导入函数,并且在 IDE(Spyder) 中运行时可以正常工作,但是当我运行 .bat 时,出现无法导入模块的错误。

.bat如下

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

我收到以下错误

Traceback(最近一次调用最后一次): 文件“D:\Users\User\Documents\programming\test.py”,第 1 行,在 从 SFTP 下载导入下载 SFTP ModuleNotFoundError: 没有名为“SFTPDownload”的模块

我需要在 .bat 中添加什么来获取我在 SFTPDownload.py 中的功能。这与 test.py 位于同一文件夹中。

提前致谢。

【问题讨论】:

  • 如果SFTPDownload.py 是您在文件夹D:\Users\User\Documents\programming\ 中的文件,那么您必须在运行python 脚本之前转到此文件夹cd D:\Users\User\Documents\programming\

标签: python batch-file


【解决方案1】:

如果SFTPDownload.py 是您在文件夹D:\Users\User\Documents\programming\ 中的文件 那么你必须在运行python脚本之前去这个文件夹

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

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

系统可能会在不同的文件夹(用作Current Working Directory)中运行您的批处理,然后python脚本会在此文件夹中搜索您的文件。

在 Python 中你可以检查Current Working Directory

 print( os.getcwd() )

另请参阅:What is the current directory in a batch file?


最终在导入SFTPDownload 之前的python 脚本中,您可以将文件夹D:\Users\User\Documents\programming\ 添加到python 用来搜索导入文件的特殊列表sys.path

 import sys

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

 import SFTPDownload

为了使其更通用(因此当您将 test.pySFTPDownload.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

【讨论】:

  • 你好@furas,我面临一个类似的问题,购买我的导入模块“Aladdin”在不同的文件夹中(因此文件路径)。在这种情况下我怎样才能让它工作?
  • @Zack 如果你有模块/full/path/other_folder/Aladdin,那么你必须插入/full/path/other_folder 而没有Aladdin。如果您在子文件夹APP_FOLDER/subfolder/Aladdin 中有它,那么您可以使用os.path.join(APP_FOLDER, "subfolder") 创建full path 进行插入。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多