how to import function from sub directory in Python3 - python-3.x

I have a project with below structure:
TestDir.init.py contains:
from . import TestSubDirFile
TestDir.TestSubDirFile.py contains:
class TestSubDirFile:
def test_funct(self):
print("Hello World")
ds_scheduler.py contains:
from TestDir import TestSubDirFile as tp
def test_job():
testobj = tp.test_funct()
print("Test job executed.")
if __name__ == "__main__":
test_job()
Getting Output as:
Traceback (most recent call last):
File "C:/Python_Projects/Test/com/xyz/ds/ds_schedular.py", line 9, in <module>
test_job()
File "C:/Python_Projects/Test/com/xyz/ds/ds_schedular.py", line 5, in test_job
testobj = tp.test_funct()
AttributeError: module 'TestDir.TestSubDirFile' has no attribute 'test_funct'

As per your directory structure
ds_scheduler.py
TestDir -- Directory Name
- TestSubDirFile.py - Python filename
Within TestSubDirFile.py file you have defined your class with name TestSubDirFile.
from TestDir import TestSubDirFile as tp
As per your above import statement you are only accessing till the py file.
To access test_func() method within class you need to follow below steps.
tsdf = tp.TestSubDirFile()
tsdf.test_funct()
Hope this helps

Related

Python can properly be executed in IDEA, but when executing the executable file, following error appears: ModuleNotFoundError: No module named 'PIL'

I wrote a small Python script which takes all .jpeg img-files from a given "./Input" folder, creates a thumbnail from these images and saves them in a "./Output" file. It works perfectly fine when executed in an IDEA (In my case PyCharm), but when I created the executable with pyinstaller and tried to execute it, the following error appeared:
Traceback (most recent call last):
File "image_resizer.py", line 3, in <module>
ModuleNotFoundError: No module named 'PIL'
[84693] Failed to execute script 'image_resizer' due to unhandled exception: No module named 'PIL'
[84693] Traceback:
Traceback (most recent call last):
File "image_resizer.py", line 3, in <module>
ModuleNotFoundError: No module named 'PIL'
logout
Saving session...
...copying shared history...
...saving history...truncating history files...
...completed.
Here is my code:
import shutil
from PIL import Image
import glob, os
import time
output_directory = "./Output"
def photo_picker():
pictures = []
try:
for filename in glob.iglob("./Input/*.jpg"):
pictures.append(filename)
except FileNotFoundError:
print("could not execute")
return pictures
def create_output_folder():
if os.path.exists(output_directory):
shutil.rmtree(output_directory)
try:
os.mkdir(path=output_directory, mode=777)
except FileExistsError:
print("Could not execute")
def crop_image(img, new_name):
size = (2000, 2000)
with Image.open(img) as im:
im.thumbnail(size)
print(im.info)
img_name = f"{new_name}"
im.save(output_directory + "/" + img_name, "JPEG")
def main():
photos = photo_picker()
create_output_folder()
time.sleep(2)
for f in photos:
img_name_splitted = f.split("/")
img_name = img_name_splitted[len(img_name_splitted) - 1]
print(img_name)
crop_image(f, img_name)
return 0
if __name__ == "__main__":
main()
I installed the module Pillow, uninstalled it ,tried to install PIL (which didn't work). But as I mentioned before, when executing it in an IDEA it works.

Calling a Python File from another file and viceversa

I have few common functions written in file a.py which is called from file b.py. And, also I have few common functions written in file b.py which is called from file a.py. but when I try to run these files I get error as unable to import name. Below is the code for reference.
I have just provided an example below, these files have common piece of code in real scenario which is specific to a functionality and that is the reason its being called from one another
a.py code below
from b import get_partner_id
def get_customer_id(tenant_id):
customer_id = tenant_id + "tenant_name"
return customer_id
def get_partner_details():
partnerid = get_partner_id()
data = {"partnerId": partnerid}
print(data)
b.py code below
from a import get_customer_id
def get_partner_id():
customer_id = get_customer_id("7687")
env = 'sandbox-all' + customer_id
return env
get_partner_id()
Below is the error for reference,
Traceback (most recent call last):
File "C:/testCases/b.py", line 1, in <module>
from a import get_customer_id
File "C:\testCases\a.py", line 2, in <module>
from b import get_partner_id
File "C:\testCases\b.py", line 1, in <module>
from a import get_customer_id
ImportError: cannot import name 'get_customer_id'

Cyclic import in Python3

I have the following directory structure:
my-game/
__init__.py
logic/
__init__.py
game.py
player.py
game.py and player.py have import dependency on each other (cyclic imports).
game.py has the following definition.
from logic.player import RandomPlayer, InteractivePlayer
T = 8
class Game:
def __init__(self, p1, p2)
...
# some other things
if __name__ == '__main__':
p1 = RandomPlayer()
p2 = InteractivePlayer()
g = Game(p1, p2)
...
player.py is as follows:
from logic.game import T
class Player:
def __init__(self):
...
class RandomPlayer(Player):
def __init__(self):
...
class InteractivePlayer(Player):
def __init__(self):
...
I am trying to run the game from logic/ directory but I get the following error.
$ python3 game.py
Traceback (most recent call last):
File "game.py", line 2, in <module>
from logic.player import RandomPlayer, InteractivePlayer
ModuleNotFoundError: No module named 'logic'
I then tried running game.py from the directory higher up (my-game/).
$ python3 logic/game.py
Traceback (most recent call last):
File "logic/game.py", line 2, in <module>
from logic.player import RandomPlayer, InteractivePlayer
ModuleNotFoundError: No module named 'logic'
What am I doing wrong? How can I make these cyclic imports work?
I have also tried using this import in player.py
from .game import T
and using
from .player import RandomPlayer, InteractivePlayer
in game.py.
In this case, I get a different error. For example, when running from my-game/,
$ python3 logic/game.py
Traceback (most recent call last):
File "logic/game.py", line 2, in <module>
from .player import RandomPlayer, InteractivePlayer
ModuleNotFoundError: No module named '__main__.player'; '__main__' is not a package
I get a similar error when running from logic/ directory.
I looked at this post but didn't understand where I was going wrong.
You are made a circulair import in your code try to remove it from your import
Vist this link you can find some other info about circular import :Remove python circular import

Unable to get the method 'learn' from Pool.py

I am implementing the code
import sys
sys.path.append('/home/stepfourward/naivebayes/Naive-Bayes/')
from NaiveBayes import *
import os
DClasses = ["python", "java", "hadoop", "django", "datascience", "php"]
base = "learn/"
p = Pool()
for i in DClasses:
p.learn(base + i, i)
NaiveBayes module contains Pool.py that has the function learn():
def learn(self, directory, dclass_name):
"""
directory is a path, where the files of the class with the name dclass_name can be found
"""
x = DocumentClass(self.__vocabulary)
dir = os.listdir(directory)
for file in dir:
d = Document(self.__vocabulary)
print(directory + "/" + file)
d.read_document(directory + "/" + file, learn=True)
x = x + d
self.__document_classes[dclass_name] = x
x.SetNumberOfDocs(len(dir))
but when I am applying the method p.learn(base + i, i) metioned in code above I am getting attribute error.
AttributeError: 'Pool' object has no attribute 'learn'
How to eradicate this error. Thanks.
Here are the correct steps to use the said NaiveBayes library, after you have cloned the repo as explained elsewhere in a folder Naive-Bayes:
What you do
import sys
sys.path.append('Naive-Bayes/') # your own path here
from NaiveBayes import * # NO error here
p = Pool()
produces an error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Pool' is not defined
What you should do:
import sys
sys.path.append('Naive-Bayes/')
from NaiveBayes.Pool import Pool # correct import
p = Pool() # runs OK now
DClasses = ["python", "java", "hadoop", "django", "datascience", "php"]
base = "learn/"
for i in DClasses:
p.learn(base + i, i)
At this point (but not before), I am getting an expected error, simply because your directories (e.g. learn/python) are not present in my machine:
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "/home/herc/SO/Naive-Bayes/NaiveBayes/Pool.py", line 29, in learn
dir = os.listdir(directory)
FileNotFoundError: [Errno 2] No such file or directory: 'learn/python'
but the clear message is that the Pool object and the learn method in Pool.py can indeed be accessed.
Tested with Python 3.4.3 in Ubuntu...

Access Class written in one python file From Another python file

I have 3 python file in same directory.
b.py
class Something_b():
def b(self):
print("hello from b")
c.py
class Something_c():
def c(self):
print("hello from c")
a.py
from .b import *
from .c import *
Something_b.b()
Something_c.c()
but i am getting some errors like
Traceback (most recent call last):
File "F:/testing/test1/a.py", line 1, in <module>
from .b import *
ModuleNotFoundError: No module named '__main__.b'; '__main__' is not a package
it's fairly simple, just import the class from the file (you're importing all but you shouldn't put a period before the filename. The period before the filename is what's causing the error.)
in file b:
class hello:
def h(self):
print("Hello")
Then in file a:
from b import hello
hello.h('')
As you can see it printed hello, you can have as many files it doesn't really matter, when I'm doing a larger project I'll have a file for every key part of it. It makes it easier to read/find the function you are looking to edit.
try this:-
a.py
from b import *
from c import *
x = Something_b()
x.b()
y = Something_c()
y.c()
Note:- First receipt class constructor then call belonging methods from class

Resources