3

I have my target.py file in Starterpack/ModulesAndPackages/target.py and I have my script file in Starterpack/Scripts/Bad.py

My ModulesAndPackages folder has the __init__.py file but I still get this error No module named ModulesAndPackages when I type from ModulesAndPackages.target import Target in the script file.

I've tried the sys.path.append() and sys.path.insert() but none worked. In my editor there is no error but when I run it, it gives the error.

script file:

mandp_dir = "./ModulesAndPackages"
scripts_dir = "./Scripts"
main_dir = ".."

os.chdir(Path(main_dir))
from ModulesAndPackages.target import Target

target.py file:

import time
import os
import keyboard

class Target():
    def __init__(self, ip, port, packetsize, time=None):
        self.ip = ip
        self.port = port
        self.packetsize = packetsize
        self.time = time

    def attack(self):
        pass

I expected it to work if I added the __init__.py file, but it doesn't.

h4z3
  • 5,265
  • 1
  • 15
  • 29
ImBlur
  • 33
  • 2

3 Answers3

0

Add the __init__.py file to your StarterPack folder too and use the from StarterPack.ModulesAndPackages.target import yourFunctionName

bugsb
  • 129
  • 6
0

You can try adding additional path to sys.path:

import os, sys
from pathlib import Path
main_dir = ".."

sys.path.append("..")
from ModulesAndPackages.target import Target

if you're doing this just for some small testing then it's ok.

BUT: I would discourage doing this in most projects as this is generally not very good approach. Instead your script should be at the same level as ModulesAndPackages like this in order for from ModulesAndPackages.target import Target to import properly:

├── ModulesAndPackages
│   ├── __init__.py
│   └── target.py
└── script.py

Here script.py will act as sort of main starting point.

devaerial
  • 2,069
  • 3
  • 19
  • 33
0

You probably wanted to add the dir to the path python searches, not change your current directory, e.g.:

scripts_dir = "./Scripts"
main_dir = ".."

sys.path.append(Path(main_dir))

Also, check this out: python-best-way-to-add-to-sys-path-relative-to-the-current-running-script

ntg
  • 12,950
  • 7
  • 74
  • 95