D
D
Denis Ogurtsov2018-04-03 14:44:40
Python
Denis Ogurtsov, 2018-04-03 14:44:40

Python: How to run a module as a script in a package?

There is an architecture:
/
- readme.md
- name_of_project
-- bin
-- packages
--- foobar
----- __init__.py
----- FoobarModule.py
--- logs
----- __init__.py
-- --- LogsModule.py
Contents of
FoobarModule.py

import packages.logs.LogsModule
#some code

if __name__ == '__main__':
   #do some work with this module

I run:
python root/name_of_project/packages/foobar/FoobarModule
but the error is thrown that it cannot find the LogsModule module.
This is logical, since there is no way to it. Now, if I ran from the root - everything works.
How to run the FoobarModule as a standalone script to execute the code in if __name__ == '__main__': ?
Help to deal with the paths in the project or throw the dock how to properly organize everything in the project.
Questions:
-- all paths must be from packages? if the module refers to a module in the current package, then the path is relative.
-- All commands to be run must be at the packages level, so that there are no problems?
-- if I want each module in the package to contain the __name__=='__main__' blob and test itself, how do I run that module separately? there is an option to run the project from the root:python -m packages.foobar.FoobarModule

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Kotenko, 2018-04-04
@k0t3n

from packages.logs import LogsModule
?
In general, a slightly strange approach, but at least it is worth creating a script at the root and calling everything else inside it.

S
Stanislav Pugachev, 2018-04-04
@Stqs

I would say that it would be better if you wrote unittests instead of manually running each file,
this is both more useful and easier

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question