When your Python scripts are in the same folder and that folder is not in the Python path, you can use a relative import to import script_b.main from script_a. Here's how to do it:
Folder Structure
Assume your folder structure looks like this:
my_folder/
├── script_a.py
├── script_b.py
Steps to Import script_b.main in script_a.py
-
Use a Relative Import:
In script_a.py, you can use a relative import to access script_b.main. The syntax for a relative import uses a dot (.) to indicate the current directory.
# script_a.py
from . import script_b
# Call the main function from script_b
script_b.main()
-
Run the Script as a Module:
Relative imports work only when the script is run as part of a module (i.e., not as the main script in a standalone manner). To ensure this works, you need to run script_a.py from the parent directory of my_folder using the -m flag.
From the parent directory of my_folder, run:
python -m my_folder.script_a
Important: Do not run script_a.py directly from within my_folder (e.g., python script_a.py), as Python will not recognize the relative import in that context.
-
Alternative: Modify sys.path (Not Recommended):
If you want to avoid relative imports or running the script as a module, you can dynamically modify the Python path in script_a.py to include the current directory. However, this approach is generally discouraged because it makes the code less portable and harder to maintain.
# script_a.py
import sys
import os
# Add the current directory to the Python path
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
import script_b
# Call the main function from script_b
script_b.main()
With this approach, you can run script_a.py directly from within my_folder:
python script_a.py
Example Implementation
Here’s a complete example to illustrate the recommended approach (using relative imports):
script_b.py
# script_b.py
def main():
print("Hello from script_b.main!")
script_a.py
# script_a.py
from . import script_b
if __name__ == "__main__":
script_b.main()
Running the Script
From the parent directory of my_folder, run:
python -m my_folder.script_a
Expected Output
Hello from script_b.main!
Notes
- Relative Imports: Relative imports are the cleanest and most maintainable way to handle imports between scripts in the same folder, especially if you plan to package your code into a module or package later.
- Python Path: If you frequently work with scripts in a folder not on the Python path, consider adding that folder to the
PYTHONPATH environment variable instead of modifying sys.path in your code.
- Package Structure: If your project grows, consider turning
my_folder into a proper Python package by adding an __init__.py file (even if it's empty). This will make it easier to manage imports and scale your project.
Let me know if you need further clarification!