Python中的异常问题

2024-09-22 14:35:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一段Python代码,应该在执行时创建MySQL模式。问题是,每当我运行它时,都会出现一个错误Raise Exception(e). Exception: [Error 2] the system cannot find the file specified

下面是我的代码:

from test.db.db import DB
from test.config import loggingSetup
loggingSetup.initializeLogging("createTest.py")
import logging

def createSports(db):
   sqlFile = "..\\sql\\createSchema.sql"

   db.run(sqlFile)

def create():
   db=DB()

   createSports(db)

def Main():
    create()

if__name__=='__main__':
   try:
      main()
   except Exception, e:
      logging.info(e.message)
      raise Exception(e)

现在我承认,这个代码不完全是我的。我在网上找到的,我正在努力修改它,这样它就可以满足我的需要。我在python方面的经验充其量是微乎其微的,但你必须从某个地方开始。基本上,我理解if语句是在说if __name__=='__main__' then try main(),但是我想我不清楚为什么会抛出这个异常。我知道这段代码已经为其他在类似项目中使用过它的人工作过了,是不是我的语法出了什么问题,把它扔掉了?你知道吗


Tags: the代码fromtestimportdbifmain
3条回答
def createSports(db):
   sqlFile = "..\\sql\\createSchema.sql" #file path goes here

在这里你必须写你的文件路径。这就是一个例子。完成路径并确保此文件存在。你知道吗

你应该知道“工作目录”和实际目录的区别。在运行时,如果不使用绝对路径,代码(不仅是Python,而是其他语言,如C++、java),将把路径视为相对路径。所以问题是它与什么有关?答案是“工作目录”,您可以通过“os.chdir”轻松更改您的工作目录。在这种情况下,需要将其传输到绝对路径:

solution:

(一)

def createSports(db):
    sqlFile = "..\\sql\\createSchema.sql"
    sqlFile = os.path.abspath(sqlFile)
    if not os.path.exists(sqlFile):
        msg = "file %s doesn't exist" % sqlFile
        raise Exception(msg)
    else:
       db.run(sqlFile)

2)使用完整路径,但要注意转义字符,你应该用这个sqlFile = r"C:\User\Desktop\Test\sql\createSchema.sql",用“r”表示这是原始sting,不要转义“\”

试试这个:

initialize_logging(__file__) 

这是因为没有找到传递给日志函数的文件。文件简而言之,提供当前加载模块的路径。你知道吗

阅读有关文件here的更多信息。你知道吗

相关问题 更多 >