Python Forum
How to run python script which has dependent python script in another folder?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to run python script which has dependent python script in another folder?
#1
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.
Reply
#2
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Running script from remote to server invisiblemind 4 562 Mar-28-2025, 07:57 AM
Last Post: buran
  Insert command line in script lif 4 865 Mar-24-2025, 10:30 PM
Last Post: lif
  modifying a script mackconsult 1 519 Mar-17-2025, 04:13 PM
Last Post: snippsat
  help with a script that adds docstrings and type hints to other scripts rickbunk 2 1,193 Feb-24-2025, 05:12 AM
Last Post: from1991
  Detect if another copy of a script is running from within the script gw1500se 4 1,039 Jan-31-2025, 11:30 PM
Last Post: Skaperen
  pass arguments from bat file to pyhon script from application absolut 2 899 Jan-13-2025, 11:05 AM
Last Post: DeaD_EyE
  Best way to feed python script of a file absolut 6 1,042 Jan-11-2025, 07:03 AM
Last Post: Gribouillis
  Looping through each images in a give folder Python druva 1 682 Jan-01-2025, 08:46 AM
Last Post: Pedroski55
  How to make it so whatever I input into a script gets outputted on a different file spermatozwario 4 1,084 Nov-24-2024, 12:58 PM
Last Post: deanhystad
  [SOLVED] [Linux] Run Python script through cron? Winfried 2 1,173 Oct-19-2024, 06:29 PM
Last Post: Winfried

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020