So I have this directory structure:
proj/
|
---/subDirA
|
---__init__.py
---fileA.py
|
---/subDirB
|
---__init__.py
---fileB.py
|
---start.py
So what I'm trying to do is from fileB.py import a function in FileA.py. So I tried this:
from subDirA.fileA import funct
When I do this I get the following error:
ImportError: cannot import name funct
But If I do this instead:
from subDirA.fileA import *
I dont get the error.. Can some one explain why am I getting this error?
I also tried the following without any success: (using absolute_import)
from .subDirA.fileA import funct
(The real function name is send_message())
UPDATE
Here are the real imports for better reference, in File A I have the following imports:
import pika
import logging
import tasks
import ConfigParser
and here I have a function def:
def send_message():
and in FileB I have:
from celery.utils.log import get_task_logger
from jsonpath_rw import parse
import dateutil.parser
import json
from pikahelper.rabbit import * # Tried using send_message and it exploded, weird..
##
# SubDirA/FileA.py => pikahelper/rabbit.py ;)
##
Also I'm calling start.py which also calls SubDirA/FileA.py for another function..
Related
I'm using Python 3.9
I have the following structure:
parent_folder
|
|-->. useful_functions.py .
|-->. script_folder_1 .
|
|-->. script_1.py
|-->. function_import.py
|-->. script_folder_2 .
|
|-->. script_2.py
|-->. function_import.py
script_1.py and script_2.py are very similar (but not identical), and so both want to use the functions stored in useful_functions.py
I have worked out that I can import the functions from useful_functions.py by putting the following at the top of script_1.py and script_2.py:
import sys
import os
local_dir = os.getcwd()
dir_up = os.path.dirname(local_dir)
sys.path.append(dir_up)
import useful_functions as uf
This works, meaning it allows script_1.py to call functions from useful_function.py as uf.function_name(arguments)
Since this text block is identical in script_1.py and script_2.py, I wanted to pull it out and make it a function in a different file function_import.py, since that way if I need to modify it I can modify the standalone file in script_folder_1 and copy it to script_folder_2.
However, when I create function_import.py, function_import.py is able to "locally" access the functions from useful_functions.py, but script_1.py is not able to access the functions from useful_functions.py.
Details:
def function_import():
import sys
import os
import re
local_dir = os.getcwd()
dir_up = os.path.dirname(local_dir)
sys.path.append(dir_up)
import useful_functions as uf
print(uf.test_function())
script_1.py:
import function_import
function_import.function_import()
uf.test_function()
When I run script_1.py in the terminal, uf.test_function() returns 3, the placeholder value, inside of function_import(), but then when script_1.py calls uf.test_function(), I get:
NameError: name 'uf' is not defined
Is there a way to allow a function inside a script to import modules for the script to use? Or is there some other way entirely that I should be doing this?
I read these posts and they didn't seem to have a good solution to my problem:
https://stackoverflow.com/search?q=import+from+parent+directory+python&s=5452f193-c78d-4966-b69a-896fb6a5a5f8
Import Script from a Parent Directory
This doesn't define a function inside function_import.py but it does the job
function_import.py:
import sys
import os
import re
local_dir = os.getcwd()
dir_up = os.path.dirname(local_dir)
sys.path.append(dir_up)
import useful_functions as uf
useful_functions.py:
def test_function():
print('In the test function')
script_1.py:
from function_import import uf
uf.test_function()
Outputs In the test function
It's not the perfect solution but you can wrap your function into another one like so :
function_import.py:
def function_import():
import sys
import os
import re
local_dir = os.getcwd()
dir_up = os.path.dirname(local_dir)
sys.path.append(dir_up)
import useful_functions as uf
#print(uf.test_function())
def uf_test_function(*args, **kwargs):
uf.test_function(*args, **kwargs)
script_1.py:
import function_import
function_import.function_import()
function_import.uf_test_function()
I create a python console app that includes imports of a custom class I'm using. Everytime I run my app I get the error ModuleNotFoundError: "No module named 'DataServices'.
Can you help?
Provided below is my folder structure:
ETL
Baseball
Baseball_DataImport.py
DataServices
DataService.py
ConfigServices.py
PageDataMode.py
SportType.py
Here is the import section from the Baseball_DataImport.py file. This is the file when I run I get the error:
from bs4 import BeautifulSoup
import scrapy
import requests
import BaseballEntity
import mechanize
import re
from time import sleep
import logging
import time
import datetime
from functools import wraps
import json
import DataServices.DataService - Error occurs here
Here is my DataService.py file:
import pymongo
import json
import ConfigServices
import PageDataModel
#from SportType import SportType
class DataServices(object):
AppConfig: object
def __init__(self):
AppConfig = ConfigServices.ConfigService()
#print(AppConfig)
#def GetPagingDataBySport(self,Sport:SportType):
def GetPagingDataBySport(self):
#if Sport == SportType.BASEBALL:
pagingData = []
pagingData.append(PageDataModel.PageDataModel("", 2002, 2))
pagingData.append(PageDataModel.PageDataModel("", 2003, 2))
return pagingData
It might seem that your structure is:
Baseball
Baseball_DataImport.py
Dataservices
Dataservice.py
Maybe you need to do from Dataservices.Dataservice import DataServices
Edit:
I created the folder structure, and the method I showed you works:
Here's the implementation
Dataservice.py only contains:
class DataServices():
pass
Did you try copieing the Dataservice.py into the Projectfolder with the main.py?
How do I import from a higher level directory in python?
For example, I have:
/var/www/PROJECT/subproject/_common.py
/var/www/PROJECT/subproject/stuff/routes.py
I want to import variable A in _common.py to routes.py
# routes.py
import os, sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
from _common import A
but I get the error:
ImportError:cannot import name 'A'
Change file directory:
import os, sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__),"../../project")))
from _common import A
OLD VERSION
To solve the issue replace ".." with os.pardir:
import os, sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)))
from _common import A
NEW VERSION
The code above does not solve the problem in the question because the true problem lies in the project structure not in the particular line. The problem is circular import. The problem became clear after the full traceback has been provided. Here is the simple way to reproduce the issue - consider 3 files...
main.py:
import a
a.py:
import b
A = 'A'
b.py:
from a import A
... the error is:
ImportError: cannot import name 'A'
OR
b.py:
import a
BB = a.A
... the error is:
AttributeError: module 'a' has no attribute 'A'
The solution to the problem has been discussed many times - search on SO
I'm building a package and a noticed that when I import the submodules, they include all of the built-ins that I've imported as well. Is there a way to get around this so when I navigate the submodule with tab complete only the functions and objects from the script are present?
For example, when I import examplemodule.submodule to only see function_i_want when I'm navigating the package contents?
Directory structure
examplemodule
| __init__.py
| submodule
| __init__.py
| submodule.py
examplemodule | submodule | submodule.py
from collections import *
def function_i_want():
return True
Here's an example of what I can import from the module:
>>> import examplemodule
>>> from examplemodule import submodule
>>> submodule.
submodule.AsyncGenerator( submodule.MappingView(
submodule.AsyncIterable( submodule.MutableMapping(
submodule.AsyncIterator( submodule.MutableSequence(
submodule.Awaitable( submodule.MutableSet(
submodule.ByteString( submodule.OrderedDict(
submodule.Callable( submodule.Reversible(
submodule.ChainMap( submodule.Sequence(
submodule.Collection( submodule.Set(
submodule.Container( submodule.Sized(
submodule.Coroutine( submodule.UserDict(
submodule.Counter( submodule.UserList(
submodule.Generator( submodule.UserString(
submodule.Hashable( submodule.ValuesView(
submodule.ItemsView( submodule.defaultdict(
submodule.Iterable( submodule.deque(
submodule.Iterator( submodule.function_i_want(
submodule.KeysView( submodule.namedtuple(
submodule.Mapping( submodule.submodule
When you say from x.y import * you are importing everything defined in __all__ from the module y that resides in directory x.
If you'd only like to import a subset of y you can do the following:
Limit what you're importing from your script
from examplemodule.submodule import function_i_want
or
from examplemodule.submodule import (
function_i_want,
other_function_i_want
)
Define __all__ in your __init__.py
__all__ = ['function_i_want', 'other_function_i_want']
what you could do is import just the module e.g.
import examplemodule
examplemodule.submodule
what this does is only calls the function if you write the module first then .submodule. this is also good if you have more than one module
Following is my project structure:
root directory
| - __init__.py
| - notdoneyet.py
| - helpers.py
| - opencv_generators.py
| - seam_carve.py
| - imgtovideos.py
notdoneyet.py file contains the entry point of project and the remaining scripts are imported as modules and when required.
My __init__.py contains following code:
from .notdoneyet import user_input
from .helpers import createFolder
from .helpers import getFileExtension
from .helpers import writeImage
from .opencv_generators import generateEnergyMap
from .opencv_generators import generateColorMap
from .imagetovideos import generateVideo
from .imagetovideos import getToProcessPaths
from .seam_carve import cropByColumn
from .seam_carve import cropByRow
I have published the package on testPyPI. But when I try to import it after installing on local machine, I get the import error.
Initial code for notdoneyet.py:
import os, sys, cv2, argparse
#Local imports
import imgtovideos as itv
import helpers as hp #Error on this line
import opencv_generators as og
import seam_carve as sc
def main(argsip):
#usr inpt
I am getting the error "no module named helpers"
Here is screenshot of the error:
Please help me.
Thank you.