python中找不到file_Makefile在Python3中找不到模块

1586010002-jmsa.png

I have a little application on Python3 but it won't run because of module not found. I added __init__.py for all the folders already but it doesn't work. I'm wondering why.

Here's my structure

my_project

|- __init__.py

|

|-- folder

|-code.py

|- __init__.py

|

|-- Makefile

|-- scripts

|- import_data.py

Here's My Makefile

test:

py.test tests/*.py

create_graph:

python scripts/import_data.py

And here's my import_data.py

from folder.code import method

import csv

method()

# doing something here

When I run make create_graph It gives me this.

python scripts/import_data.py

Traceback (most recent call last):

File "scripts/import_data.py", line 1, in

from folder.code import method

ImportError: No module named 'folder'

make: *** [create_graph] Error 1

解决方案

When the import_data.py script is run, the sys.path has my_project/scripts in it, but not my_project , hence python is not able to locate folder package in sys.path .

You should try adding the my_project folder into the PYTHONPATH variable , this would allow you to access folder.code from anywhere. Example for BASH -

export PYTHONPATH=:$PYTHONPATH

If you cannot make such environment variable changes , then programmatically, before trying to import folder.code , you can add the my_project folder to sys.path variable. For that you can use __file__ to get the filename of the script, and then get the directory name from that using os.path.dirname() and then get its parent using os.path.join and os.path.abspath Example your import_data.py may look like -

import sys

import os.path

parent = os.path.abspath(os.path.join(os.path.dirname(__file__),'..')) #this should give you absolute location of my_project folder.

sys.path.append(parent)

from folder.code import method

import csv

method()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值