首页 > 解决方案 > 如何从不同的文件中导入 python 函数(在 Ubuntu 中)

问题描述

我有一个名为的 python 文件hero.py,它引用位于其中的其他 python 文件views.py(这两个文件都存在于同一个文件夹中)。

hero.py代码 :


#!/usr/bin/env python3

from .views import main, returnSum, most_frequent, find_mine_site_view_id, get_user_Activity, initialise_analytics_reporting

list_of_mines = ['mine1', 'mine2', 'mine3']

start_date = 'yesterday'
end_date = 'yesterday'

main(list_of_mines, start_date, end_date)

在使文件可执行chmod +x hero.py#!/usr/bin/env python3在顶部添加后hero.py,运行时出现此错误./hero.py

Traceback (most recent call last):
  File "./hero.py", line 2, in <module>
    from .views import main, returnSum, most_frequent, find_mine_site_view_id, get_user_Activity, initialise_analytics_reporting
ModuleNotFoundError: No module named '__main__.views'; '__main__' is not a package

我知道我的 views.py 不是一个包,我只是想导入其中存在的函数views.py

不确定它是否是Ubuntu的东西。

请帮忙

ls -la在两个文件都存在的文件夹中运行时:

total 72
drwxrwxr-x 8 llewellyn llewellyn  4096 May 13 06:39 .
drwxrwxr-x 6 llewellyn llewellyn  4096 May 11 19:19 ..
drwxrwxr-x 3 llewellyn llewellyn  4096 May  7 08:52 .idea
-rw-rw-r-- 1 llewellyn llewellyn     0 May  7 07:21 __init__.py
drwxrwxr-x 2 llewellyn llewellyn  4096 May 13 06:18 __pycache__
-rwxrwxr-x 1 llewellyn llewellyn    86 May 12 17:39 admin.py
-rwxrwxr-x 1 llewellyn llewellyn   108 May 12 17:40 apps.py
drwxrwxr-x 3 llewellyn llewellyn  4096 May  7 09:04 config
drwxrwxr-x 3 llewellyn llewellyn  4096 May  9 11:34 migrations
-rwxrwxr-x 1 llewellyn llewellyn  2607 May 12 17:40 models.py
-rwxrwxr-x 1 llewellyn llewellyn 16146 May 13 06:17 views.py

我究竟做错了什么?

标签: pythondjangopython-3.xubuntu

解决方案


只需删除视图前的点:

from views import main, returnSum, most_frequent, ...
#    ^ here

编辑:
从子文件夹导入:
用作.分隔符:
当文件位于如下位置时:

someFolder
+-main.py <- file with import
`-the
   `-path
     `-to
       `-module.py <- in this file is func1

做:

from the.path.to.module import func1
# imports func1 from file module.py
# then use like:
func1()

或者

from the.path.to import module
# imports whole module
# then use like:
module.func1()

或者

import the.path.to.module
# use:
the.path.to.module.func1()

或者

import the.path.to.module as mod
#imports the.path.to.module that is accessed by identifier mod
#so use it like
mod.func1()

as您也可以组合from

from the.path.to import module as mod
#use:
mod.func1()

当路径是字符串或文件不是子文件夹时,您可以这样做:
对于 Python 3.5+

import importlib.util
spec = importlib.util.spec_from_file_location("module.name", "/the/path/to/module.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
# then use like this:
module.func1()

对于 Python 2

import imp

module = imp.load_source('module.name', '/the/path/to/module.py')
module.func1()

推荐阅读