I'm still trying to get a hang of python 3 and I'm running into an issue where I can either run a .py file as a script or import it as a module, but not both.
Directory Structure
test/
__init__.py
test.py
subwayclock/
__init__.py
subwayclock.py
build/
gen/
__init__.py
gtfs_realtime_pb2.py
nyct_subway_pb2.py
__init__.py
in this scenario test.py looks like this and works (rawFEED() is a function in subwayclock.subwayclock):
from subwayclock.subwayclock import *
print(rawFEED())
However, I cannot run the script directly i.e.
python subwayclock/subwayclock.py
because it gives the following error:
Traceback (most recent call last):
File "subwayclock.py", line 32, in <module>
from .build.gen.gtfs_realtime_pb2 import FeedMessage
SystemError: Parent module '' not loaded, cannot perform relative import
HOWEVER, if I modify the import statement in subwayclock/subwayclock.py to state (i.e. with the leading '.' removed):
from subwayclock.subwayclock import FeedMessage
I can run the subwayclock.py script directly through the command line, calling the main function perfectly.
BUT, when I run the original test.py file, the import statement no longer works, and I get the following error:
Traceback (most recent call last):
File "test.py", line 1, in <module>
from subwayclock.subwayclock import *
File "/var/www/test/subwayclock/subwayclock.py", line 32, in <module>
from build.gen.gtfs_realtime_pb2 import FeedMessage
ImportError: No module named 'build'
Can I make this script independently runnable and importable?