Python / ImportError:不支持按文件名导入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25997185/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:55:30  来源:igfitidea点击:

Python / ImportError: Import by filename is not supported

python

提问by Or Smith

I'm trying to import a python file to my application which is written in python.

我正在尝试将一个 python 文件导入到我用 python 编写的应用程序中。

I have the following code:

我有以下代码:

import os
from os.path import basename

class specificClass:
    def dothing(self,path):
          runcommand = __import__("/root/"+ os.path.splitext(os.path.basename(path))[0]+ "/" + os.path.splitext(os.path.basename(path))[0] +"/sa/update.py")
          runcommand.main()

When I run it, it gives me the following error:

当我运行它时,它给了我以下错误:

ImportError: Import by filename is not supported.

回答by hyades

Instead of doing a import like __import__you can say

而不是像__import__你说的那样做导入

import sys
sys.path.append(path) # this is where your python file exists
import update