Python Forum

Full Version: How to run python script which has dependent python script in another folder?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi All,

I need your help for following issue-

I have a structured python project where there are 3 directories- A,B,C
Inside these directories there are python files-f1.py,f2.py,f3.py

folder A's f1.py file has some function which are from folder B's f2.py.

I have imported B's f2.py in f1.py file and it works in Pycharm IDE.

Now if I want to run f1.py file from a terminal(linux terminal) then it say there is no module named B.f2.py.

How can I define dependency to run my files from a terminal/cmd?

I set the PYTHONPATH and all working fine now.
Structure your code as a package
my_pack/
  |-- __init__.py 
  folder_a/
    |-- __init__.py
    |-- f1.py
  folder_b/
    |-- __init__.py
    |-- f2.py
# f1.py
def egg():
   print('I am f1')
# f2.py
def spam():
   print('I am f2')
This part do i think is important,
it shorten the import statement and bring the package together.
__init__.py file under my_pack:
from .folder_a import f1
from .folder_b import f2
Now can test the package.
λ ptpython
>>> import my_pack

>>> my_pack.f1.egg()
I am f1
>>> my_pack.f2.spam()
I am f2

>>> # Or import like this
>>> from my_pack import f1, f2

>>> f1.egg()
I am f1
>>> f2.spam()
I am f2 
If i had left the __init__.py under my_pack blank.
Longer import and i could not import f1 and f2 with one import statement.
λ ptpython
>>> import my_pack.folder_a.f1

>>> my_pack.folder_a.f1.egg()
I am f1