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
  How to include one script into another? MorningWave 8 308 Mar-21-2024, 10:34 PM
Last Post: MorningWave
  ChromeDriver breaking Python script genericusername12414 1 218 Mar-14-2024, 09:39 AM
Last Post: snippsat
  using PowerShell from Python script for mounting shares tester_V 8 403 Mar-12-2024, 06:26 PM
Last Post: tester_V
  No Internet connection when running a Python script basil_555 8 443 Mar-11-2024, 11:02 AM
Last Post: snippsat
Question Running Python script through Task Scheduler? Winfried 8 340 Mar-10-2024, 07:24 PM
Last Post: Winfried
  Combine console script + GUI (tkinter) dejot 2 361 Feb-27-2024, 04:38 PM
Last Post: deanhystad
Question How to add Python folder in Windows Registry ? Touktouk 1 207 Feb-20-2024, 01:04 PM
Last Post: DeaD_EyE
  How to receive two passed cmdline parameters and access them inside a Python script? pstein 2 279 Feb-17-2024, 12:29 PM
Last Post: deanhystad
  OBS Script Troubleshooting Jotatochips 0 253 Feb-10-2024, 06:18 PM
Last Post: Jotatochips
  Is possible to run the python command to call python script on linux? cuten222 6 635 Jan-30-2024, 09:05 PM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

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