简体   繁体   English

Python 不允许导入自定义包

[英]Python won't allow custom package to be imported

So I have a python script located on my desktop as well as a package I made called testpackage.所以我在我的桌面上有一个 python 脚本以及一个名为 testpackage 的包。 It contains three scripts each containing one function which prints a word.它包含三个脚本,每个脚本包含一个打印单词的函数。 Here is a sample of one of the scripts.这是其中一个脚本的示例。

def dog():
    print ("Dog")

I also have an __init__.py file and contains the following.我还有一个__init__.py文件,其中包含以下内容。

import sys, os
pathVar = os.path.normpath('/Desktop/testpackage')
from cat import *
from dog import *
from horse import *

The file on my desktop, named myFile.py, contains the following我桌面上名为 myFile.py 的文件包含以下内容

from testpackage import dog
dog.dog()

When I run this script, I get an error along the lines of当我运行此脚本时,出现以下错误

File 'myFile.py", line1, in from testpackage import dog. File "C:\\Users\\User\\Deskop\\testpackage__init__.py", line 3 in from cat import * ModuleNotFoundError: No Module named 'cat'文件“myFile.py”,第 1 行,来自 testpackage import dog。文件“C:\\Users\\User\\Deskop\\testpackage__init__.py”,第 3 行来自 cat import * ModuleNotFoundError: No Module named 'cat'

I have tried every trick under the sun that i've found on google so I'm wondering why it can't locate the script from the __init__ file.我已经尝试了在 google 上发现的所有技巧,所以我想知道为什么它无法从__init__文件中找到脚本。

我想通了,我没有使用正确的命令来插入路径。

You should put the module's parent dir in PYTHONPATH.您应该将模块的父目录放在 PYTHONPATH 中。

You can achieve this using the following code:您可以使用以下代码实现此目的:

import sys
module_dir = r"/path/to/module/parent/dir"  
sys.path.insert(0, module_dir)
# assuming module is named my_mod.py
import my_mod

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM