Python: How to run module from the command line - python

I have the following project structure:
and I would like to be able to run my project from the command line using something like:
hotel-reservation> python hotel_reservation
However, when doing this I am receiving the following error:
ImportError: No module named 'hotel_reservation'
The code that I have in __main__.py is something as:
from hotel_reservation.utils import get_client_type_and_dates
from hotel_reservation.hotel import Hotel
from hotel_reservation.hotel_reservation_system import HotelReservationSystem
def main():
# CODE
if __name__ == "__main__":
main()
I guess I am missing how to indicate python that hotel_reservation is a the parent directory, so how can I solve this?
Thanks in advance.

Related

ModuleNotFoundError: No module named 'sharedFunctions'

I have a Python project in which I have the following folder structure:
> root
> download_module
> __init__.py
> downloadProcess.py
> sharedFunctions.py
> someHelper.py
> useSharedFunction.py
The download_module/__init__.py has the following code:
from .sharedFunctions import stringArgumentToDate
from .downloadProcess import downloadProcessMethod
The sharedFunctions.py file contains the following function:
def stringArgumentToDate(arg):
dateformat = "%m/%d/%Y"
date = None
if arg.isnumeric():
date = datetime.fromtimestamp(int(arg))
if date == None:
date = datetime.strptime(arg, dateformat)
return date
Then on the useSharedFunction.py I try to import the shared function and use it like this.
from download_module import stringArgumentToDate
from download_module import downloadProcessMethod
def main():
arg = '03/14/2022'
dateArg = stringArgumentToDate(arg)
if __name__ == '__main__':
main()
When I try to run this by using python3 useSharedFunction.py I got the following error:
Traceback (most recent call last):
File "useSharedFunction.py", line 4, in <module>
from download_module import stringArgumentToDate
File "/Users/jacobo/Documents/project/download_module/__init__.py", line 2, in <module>
from .download_module import downloadAndProcessMethod
File "/Users/jacobo/Documents/project/download_module/downloadProcess.py", line 10, in <module>
from sharedFunctions import stringArgumentToDate, otherFunction
ModuleNotFoundError: No module named 'sharedFunctions'
I do believe the error is in downloadProcess since at the beggining of the file we got this import:
from sharedFunctions import stringArgumentToDate, otherFunction
from someHelper import Helper
Which refers to sibling files.
However I'm unsure what will be a proper fix to allow to run the downloadProcess.py main independently but also, being able to call it one of its method from a root or any other file out of the module.
Consider this structure:
┬ module
| ├ __init__.py
| ├ importing_submodule.py
| └ some_submodule.py
├ __main__.py
├ some_submodule.py
└ module_in_parent_dir.py
with content:
__main__.py
import module
/module/__init__.py
from . import importing_submodule
/module/importing_submodule.py
from some_submodule import SomeClass
/module/some_submodule.py
print("you imported from module")
class SomeClass:
pass
/some_submodule.py
print("you imported from root")
class SomeClass:
pass
/module_in_parent_dir.py
class SomeOtherClass:
pass
How sibling import works
(skip this section if you know already)
Now lets run __main__.py and it will say "you imported from root".
But if we change code a bit..
/module/importing_submodule.py
from module.some_submodule import SomeClass
It now says "You imported from module" as we wanted, probably with scary red line in IDE saying "Unresolved reference" if you didn't config working directory in IDE.
How this happen is simple: script root(Current working directory) is decided by main script(first script that's running), and python uses namespaces.
Python's import system uses 2 import method, and for convenience let's call it absolute import and relative import.
Absolute import: Import from dir listed in sys.path and current working directory
Relative import: Import relative to the very script that called import
And what decide the behavior is whether we use . at start of module name or not.
Since we imported by from some_submodule without preceeding dot, python take it as 'Absolute import'(the term we decided earlier).
And then when we also specified module name like from module.some_submodule python looks for module in path list or in current working directory.
Of course, this is never a good idea; script root can change via calls like os.chdir() then submodules inside module folder may get lost.
Therefore, the best practices for sibling import is using relative import inside module folder.
/module/importing_submodule.py
from .some_submodule import SomeClass
Making script that work in both way
To make submodule import it's siblings when running as main script, yet still work as submodule when imported by other script, then use try - except and look for ImportError.
For importing_submodule.py as an example:
/module/importing_submodule.py
try:
from .some_submodule import SomeClass
except ImportError:
# attempted relative import with no known parent package
# because this is running as main script, there's no parent package.
from some_submodule import SomeClass
Importing modules from parent directory is a bit more tricky.
Since submodule is now main script, relative import to parent level directory doesn't work.
So we need to add the parent directory to sys.path, when the script is running as main script.
/module/importing_submodule.py
try:
from .some_submodule import SomeClass
except ImportError:
# attempted relative import with no known parent package
# because this is running as main script, there's no parent package.
from some_submodule import SomeClass
# now since we don't have parent package, we just append the path.
from sys import path
import pathlib
path.append(pathlib.Path(__file__).parent.parent.as_posix())
print("Importing module_in_parent_dir from sys.path")
else:
print("Importing module_in_parent_dir from working directory")
# Now either case we have parent directory of `module_in_parent_dir`
# in working dir or path, we can import it
# might need to suppress false IDE warning this case.
# noinspection PyUnresolvedReferences
from module_in_parent_dir import SomeOtherClass
Output:
"C:\Program Files\Python310\python.exe" .../module/importing_module.py
you imported from module
Importing module_in_parent_dir from sys.path
Process finished with exit code 0
"C:\Program Files\Python310\python.exe" .../__main__.py
you imported from module
Importing module_in_parent_dir from working directory
Process finished with exit code 0

importing class from another file gives error when working and no error when not working

I am attempting to import a class named MainMenus from this file
B:\Programming\Python\RaceDash\src\UIModules\Menus.py
here is the code for the class
class MainMenus:
def StartUp():
#do stuff
def MainMenu():
#doing other stuff
I also have the _init_.py file in this path
B:\Programming\Python\RaceDash\src\UIModules\__init__.py
my main python file is here
B:\Programming\Python\RaceDash\src\Main.Py
and looks like this
from .UIModules.Menus import MainMenus
def Main():
MainMenus.StartUp()
while True:
MainMenus.MainMenu()
userSelect = input(": ")
Main()
pylance gives no errors when but when I attempt to run the program I get this error:
ile "b:\Programming\Python\RaceDash\src\Main.Py", line 1, in <module>
from .UIModules.Menus import MainMenus
ImportError: attempted relative import with no known parent package
When I remove the leading period pylance shows this error
Import "UIModules.Menus" could not be resolved
The application runs fine but I lose intellisense for any function from the other class.
What could be causing this issue?
You should move the package folder to a directory that is already in PATH
export PYTHONPATH="${PYTHONPATH}:B:\Programming\Python\RaceDash\src\
python3 Main.py
My issue is solved by going to the folder of my program and changing the extension. My file were not register as py file because I have created them in my VScode folder.

Why cannot I import a .py file to another within the same directory?

I have the following 4 python files within the folder SubFolder, assembled as such:
CodeFolder
SubFolder
GeneticAlgorithm.py
main.py
heuristic1.py
heuristic2.py
I am trying to import the file GeneticAlgorithm.py within my main.py file, using the import statement at the beginning of the class:
import GeneticAlgorithm
The problem: PyCharm is highlighting this and says "no module named GA".
Any clues as to what may be causing this issue and how to solve it? Thank you!
Correct me if I'm wrong but you might not have GA module in your GeneticAlgorithm.py
If you do, then you can do similar to below:
Similar to your folder structure:
From main.py call GeneticAlgorithm.py. For example:
from GeneticAlgorithm import GA
def main():
ga_obj = GA(mutation_rate=0.5)
print("Call GA module")
if __name__ == '__main__':
main()
If we look at the GeneticAlgorithm.py
class GA:
def __init__(self, mutation_rate):
self.mutation = mutation_rate
We have GA class.
This is a simple demonstration of how you can use.

ImportError: No module named phpoob.bank

lcl
|
|----|
|----enterprise
|----phpoob
|----|----|
|----|----'bank.py'
|----|
|----'__init__.py'
|----'module.py'
this is my file structure
__init__.py-->
from module import LCLModule
__all__ = ['LCLModule']
module.py-->
from phpoob.bank import something
__all__ = ['LCLModule']
class LCLModule(something):
_code here_
these are my files
while firing the command python __init__.py i got following error ImportError: No module named phpoob.bank how shold i overcome this error
i also tried it from .phpoob.bank import something but it gives ValueError: Attempted relative import in non-package
what will be solution for it...?
Looks like you are using Python 2.x. Folder phpoob is not treated as Python module. That's why you can't import phpoob.bank.
Solution #1: Create empty file phpoob/__init__.py After that you will be able to import phpoob and import any file inside.
Solution #2: Upgrate to Python 3.

Why do I get ImportError when running the tests?

I am using Python 3 to try and get a test file for sample application working yet it keeps throwing ImportError: No module named 'calculate'
My file structure is:
/calculate
__init__.py
calculate.py
test/
__init__.py
calculate_test.py
I cannot figure out why this is the case, any help would be much appreciated.
The __init__.py files are empty.
calculate.py contains:
class Calculate(object):
def add(self, x, y):
return x + y
if __name__ == '__main__':
calc = Calculate()
result = calc.add(2, 2)
print(result)
calculate_test.py contains:
import unittest
from calculate import Calculate
class TestCalculate(unittest.TestCase):
def setUp(self):
self.calc = Calculate()
def test_add_method_returns_correct_result(self):
self.assertEqual(4, self.calc.add(2,2))
if __name__ == '__main__':
unittest.main()
I am running python test/calculate_test.py from the root /calculate folder and am getting the error
Traceback (most recent call last):
File "test/calculate_test.py", line 2, in <module>
from calculate import Calculate
ImportError: No module named 'calculate'
I have been fiddling around with different structures and cannot understand what the problem is.
Your project's structure is the reason. The test script doesn't have the outer directory in the search path when you start it. Here are some ways to fix that
Move the test file into the same directory that contains the module it imports. That will require no changes in the test file.
Use this structure
./project/
calculate_test.py
calculate/
__init__.py
calculate.py
This will require you to change the import signature in calculate_test.py to something like from calculate import calculate

Categories

Resources