20

I am trying to separate my script into several files with functions, so I moved some functions into separate files and want to import them into one main file. The structure is:

core/
  main.py
  posts_run.py

posts_run.py has two functions, get_all_posts and retrieve_posts, so I try import get_all_posts with:

from posts_run import get_all_posts

Python 3.5 gives the error:

ImportError: cannot import name 'get_all_posts'

Main.py contains following rows of code:

import vk
from configs import client_id, login, password
session = vk.AuthSession(scope='wall,friends,photos,status,groups,offline,messages',   app_id=client_id, user_login=login,
                     user_password=password)
api = vk.API(session)

Then i need to import api to functions, so I have ability to get API calls to vk.

Full stack trace

Traceback (most recent call last):
  File "E:/gited/vkscrap/core/main.py", line 26, in <module>
    from posts_run import get_all_posts
  File "E:\gited\vkscrap\core\posts_run.py", line 7, in <module>
    from main import api, absolute_url, fullname
  File "E:\gited\vkscrap\core\main.py", line 26, in <module>
    from posts_run import get_all_posts
ImportError: cannot import name 'get_all_posts'

api - is a api = vk.API(session) in main.py. absolute_url and fullname are also stored in main.py. I am using PyCharm 2016.1 on Windows 7, Python 3.5 x64 in virtualenv. How can I import this function?

Sardorbek Imomaliev
  • 14,861
  • 2
  • 51
  • 63
Oleksiy
  • 794
  • 2
  • 14
  • 39

4 Answers4

25

You need to add __init__.py in your core folder. You getting this error because python does not recognise your folder as python package

After that do

from .posts_run import get_all_posts
#    ^ here do relative import
# or
from core.posts_run import get_all_posts
# because your package named 'core' and importing looks in root folder
Sardorbek Imomaliev
  • 14,861
  • 2
  • 51
  • 63
  • 2
    I did this, it also had no effect. Python raises same error – Oleksiy Aug 30 '16 at 16:59
  • @OleksiyOvdiyenko are you sure your python module is in your **local directory**? – Christian Dean Aug 30 '16 at 17:02
  • @Mr.goosberry, yes, it is in local dir – Oleksiy Aug 30 '16 at 17:08
  • @OleksiyOvdiyenko well Sardorbek's answer shouldn't be giving you a import error. Is your other file in the same folder as your main file, or is it in another sub-folder? – Christian Dean Aug 30 '16 at 17:11
  • @Mr.goosberry in same folder – Oleksiy Aug 30 '16 at 17:13
  • @OleksiyOvdiyenko well something else is wrong. Try running the python IDLE. open your main script and try running it from there. The problem may lie with Pycharm. – Christian Dean Aug 30 '16 at 17:15
  • when I ```from core.posts_run import get_all_posts``` it raises ```ImportError: No module named 'core'```. For relative import with ```.posts_run''' it raises ```SystemError: Parent module '' not loaded, cannot perform relative import``` – Oleksiy Aug 30 '16 at 17:16
  • @OleksiyOvdiyenko this means your `core` package is not loaded to your `PYTHONPATH`. this may help http://stackoverflow.com/questions/16981921/relative-imports-in-python-3 – Sardorbek Imomaliev Aug 30 '16 at 17:21
  • This answer gets many things wrong. [Since 3.3](https://peps.python.org/pep-0420/), `__init__.py` is **not necessary** for this and is **not used** to decide that a folder represents a package. The error **does not** occur "because Python does not recognize the folder as a package"; it occurs because the code attempts **absolute rather than relative** import and because the package root folder **is not on the `sys.path`**. – Karl Knechtel Jan 13 '23 at 10:45
6

MyFile.py:

def myfunc():
    return 12

start python interpreter:

>>> from MyFile import myFunc
>>> myFunc()
12

Alternatively:

>>> import MyFile
>>> MyFile.myFunc()
12

Does this not work on your machine?

Danielle M.
  • 3,607
  • 1
  • 14
  • 31
  • He might not have his custom python module in his local directory. – Christian Dean Aug 30 '16 at 17:01
  • I'm not sure of the exact rules or order, but python will look in the current directory as well as sys.path, $PYTHONPATH, etc. – Danielle M. Aug 30 '16 at 17:05
  • Yes, it works with this func, but when i try to call ```import posts_run``` it raises ```ImportError: cannot import name 'get_all_posts'``` – Oleksiy Aug 30 '16 at 17:07
  • if you in the core folder, you should be able to reference posts_run directly. If you are in the root folder, try referring to ti as core.posts_run – Danielle M. Aug 30 '16 at 17:09
  • @DanielleM. No, I don't believe your correct. I believe that you must add the path to your python module at runtime for python to find where it is: http://stackoverflow.com/questions/22955684/how-to-import-py-file-from-another-directory – Christian Dean Aug 30 '16 at 17:09
  • @DanielleM.if i try to import core.posts_run it says that ```ImportError: No module named 'core'```, __init__ in core folder – Oleksiy Aug 30 '16 at 17:13
0

Python doesn't find the module to import because it is executed from another directory.

Open a terminal and cd into the script's folder, then execute python from there.

Run this code in your script to print from where python is being executed from:

import os
print(os.getcwd())

EDIT: This is a demonstration of what I mean

Put the code above in a test.py file located at C:\folder\test.py

open a terminal and type

python3 C:\folder\test.py

This will output the base directory of python executable

now type

cd C:\folder
python3 test.py

This will output C:\folder\. So if you have other modules in folder importing them should not be a problem

I usually write a bash/batch script to cd into the directory and start my programs. This allows to have zero-impact on host machines

theBugger
  • 441
  • 3
  • 14
0

A cheat solution can be found from this question (question is Why use sys.path.append(path) instead of sys.path.insert(1, path)? ). Essentially you do the following

    import sys
    sys.path.insert(1, directory_path_your_code_is_in)
    import file_name_without_dot_py_at_end

This will get round that as you are running it in PyCharm 2016.1, it might be in a different current directory to what you are expecting...

Community
  • 1
  • 1
A. N. Other
  • 392
  • 4
  • 14
  • This article goes into more detail - http://stackoverflow.com/questions/897792/pythons-sys-path-value/38403654#38403654 – A. N. Other Aug 30 '16 at 17:53