import sys
from subprocess import run, PIPE
import shlex
from src.detector_main import detect_main
def main():
# print command line arguments
for arg in sys.argv[1:]:
print(arg)
if __name__ == "__main__":
# main()
print(sys.argv)
This is my main module. If you see the from src.detector_main import detect_main, it is supposed to import detect_main from src/detector_main.py.
In my detector_main.py, I have a bunch of imports,
import ast
import os
import fpdf
import sys
from Detector.class_coupling_detector import detect_class_cohesion
from Detector.cyclomatic_complexity_detector import detect_cyclomatic_complexity
from Detector.long_lambda_detector import detect_long_lambda
from Detector.long_list_comp_detector import detect_long_list_comp
from Detector.pylint_output_detector import detect_pylint_output
from Detector.shotgun_surgery_detector import detect_shotgun_surgery
from Detector.useless_exception_detector import detect_useless_exception
# from tools.viz_generator import add_viz
def detect_main(directory):
# Get stats for files in directory
stats_dict = get_stats(directory)
....
Running my main module gives me this error:
File "pyscent.py", line 5, in <module>
from src.detector_main import detect_main
File "C:\Users\user\Desktop\proj\src\detector_main.py", line 5, in <module>
from Detector.class_coupling_detector import detect_class_cohesion
ModuleNotFoundError: No module named 'Detector'
I don't get this because I am following the exact path.
I don't get this because I am following the right path.
In your example you import the Detector.class_coupling_detector module in file that is in the same directory as Detector but your cwd is not the src directory.
Due to this you should either use absolute import from src.Detector... or relative import from .Detector...
Here is some information about difference between this two ways to import
Related
I am brand new to working with python so this question might be basic. I am attempting to import five helper files into a primary script, the directory setup is as follows and both the script I'm calling from and the helper scripts are located within src here in this path-
/Users/myusername/Desktop/abd-datatable/src
I am currently importing as-
import helper1 as fdh
import helper2 as hdh
..
import helper5 as constants
The error I see is
File "/Users/myusername/Library/Application Support/JetBrains/Toolbox/apps/PyCharm-P/ch-0/22.77756/PyCharm.app/Contents/plugins/python/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 21, in do_import
module = self._system_import(name, *args, **kwargs)
ModuleNotFoundError: No module named 'src'
I have also attempted the following for which the import was still unsuccessful:
import src.helper1 as fdh
..
import src.helper5 as constants
and
from src import src.helper1 as fdh
...
from src import helper5 as constants
and tried adding the following to the head of the script-
import sys
import os
module_path = os.path.abspath(os.getcwd())
if module_path not in sys.path:
sys.path.append(module_path)
Would be very grateful for any pointers on how to debug this!
Seems likely that it's a path issue.
In your case, if you want to import from src, you would need to add Users/myusername/Desktop/abd-datatable to the path.
os.getcwd() is getting the path you invoke the script from, so it would only work if you are invoking the script from Users/myusername/Desktop/abd-datatable.
I have two scripts in the same folder:
5057_Basic_Flow_Acquire.xyzpy
5006_Basic_Flow_Execute.xyzpy
I need to call function run() from 5057_Basic_Flow_Acquire file in the 5006_Basic_Flow_Execute file.
I tried two approaches:
1.
import time
import os
import sys
import types
dir_path = os.path.dirname(os.path.realpath(__file__))
#os.chdir(str(dir_path))
sys.path.append(str(dir_path))
sensor = __import__('5057_Basic_Flow_Acquire')
import time
import os
import sys
import types
import importlib
import importlib.util
dir_path = os.path.dirname(os.path.realpath(__file__))
spec = importlib.util.spec_from_file_location('run', dir_path+'\\5057_Basic_Flow_Acquire')
module = importlib.util.module_from_spec(spec)
Pycharm is reporting this type of errors:
case:
ModuleNotFoundError: No module named '5057_Basic_Flow_Acquire'
case
AttributeError: 'NoneType' object has no attribute 'loader'
So in both cases module was not found.
Does someone have any suggestion?
You should rename your files to something like :
5057_Basic_Flow_Acquire_xyz.py
5006_Basic_Flow_Execute_xyz.py
so that they are recognized as modules and can be imported.
Then, in your 5057_Basic_Flow_Acquire_xyz module, you can import the run function with the following line :
from 5006_Basic_Flow_Execute_xyz import run
Both files are in the same directory, so you should be able to import without changing your PATH environment variable as the current directory is automatically added at the top of the list.
I am trying to import a file from a folder named pytorch_net from a folder named AI_physicist into a script named models.py. I have tried to change the folder locations of the files, get an init.py file into the main AI_physicist folder, and change the sys.path.append command to get only the folder with the files inside of it. I have also looked at other posts and have tried their solutions but to no avail.
Here are the posts that I have found and have tried:
What does os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)) mean? python
import python module using sys.path.append
file structure:
C:-----
Users----
trevo----
Desktop----
AI_physicist----
pytorch_net----
theory_learning----
Here is the error in its entirety:
No module named 'pytorch_net'
File "C:\Users\trevo\OneDrive\Desktop\AI_physicist\theory_learning\models.py", line 13, in <module>
from pytorch_net.net import MLP
File "C:\Users\trevo\OneDrive\Desktop\AI_physicist\theory_learning\theory_model.py", line 24, in <module>
from AI_physicist.theory_learning.models import Loss_Fun_Cumu, get_Lagrangian_loss
And lastly here is the code that I am using:
models.py:
# coding: utf-8
# In[ ]:
import numpy as np
import torch
import torch.nn as nn
from torch.autograd import grad
import sys, os
sys.path.append(os.path.join(os.path.dirname("__file__"), '..', '..'))
from AI_physicist.pytorch_net.net import MLP
from AI_physicist.pytorch_net.util import get_criterion, MAELoss, to_np_array, to_Variable, Loss_Fun
from AI_physicist.settings.global_param import PrecisionFloorLoss, Dt
from AI_physicist.theory_learning.util_theory import logplus
Any help on what I would be missing would be very appreciated, thank you!
Try to put __init__.py not init.py in that folder.
Alternatively:
sys.path.append(f'{os.path.dirname(__file__)}\\folder_name')
Please look on the difference between my and yours sys.append.
That should always work. Bare in mind these will work only if your script is in a subfolder of your main folder with main.py in.
I am using import_ipynb module to import one jupyter notebook inside another.
txt2csv.ipynb has the following import statements
import pandas as pd
import os
import import_ipynb
import config as cfg
I am using another file to import txt2csv.ipynb which has following import statements
data_processing.ipynb
import glob
import numpy as np
import datetime
import import_ipynb
import txt2csv
My issue is that when I try to use a statement like
data_in = glob.glob(os.path.join(cfg.data_dir, "*.csv"))
inside data_processing.ipynb it throws the error
NameError Traceback (most recent call last)
<ipython-input-2-683b1d3df82f> in <module>
----> 1 data_in = glob.glob(os.path.join(cfg.data_dir, "*.csv"))
NameError: name 'os' is not defined
Are nested imports not possible in python, will I have to explicitly write import os again in data_processing.ipynb file?
I'm trying to package the pychess package into a zip file and import it with zipimport, but running into some issues.
I've packaged it into a zipfile with the following script, which works:
#!/usr/bin/env python
import zipfile
zf = zipfile.PyZipFile('../pychess.zip.mod', mode='w')
try:
zf.writepy('.')
finally:
zf.close()
for name in zf.namelist():
print name
However, I'm unable to do complicated imports in my code:
z = zipimport.zipimporter('./pychess.zip.mod')
#z.load_module('pychess') # zipimport.ZipImportError: can't find module 'pychess'
#z.load_module('Utils.lutils') # zipimport.ZipImportError: can't find module 'Utils.lutils'
Utils = z.load_module('Utils') # seems to work, but...
from Utils import lutils
#from Utils.lutils import LBoard # ImportError: No module named pychess.Utils.const
How can I import, e.g. pychess.Utils.lutils.LBoard from the zip file?
Here is the full list of modules I need to import:
import pychess
from pychess.Utils.lutils import LBoard
from pychess.Utils.const import *
from pychess.Utils.lutils import lmovegen
from pychess.Utils.lutils import lmove
Thanks!
Assuming you have an unpacked pychess, resulting in a pychess-0.10.1 directory in your current directory and that pychess-0.10.1/lib/pychess exists ( I got that directory from untarring pychess-0.10.1.tar.gz).
First run:
#!/usr/bin/env python
import os
import zipfile
os.chdir('pychess-0.10.1/lib')
zf = zipfile.PyZipFile('../../pychess.zip', mode='w')
try:
zf.writepy('pychess')
finally:
zf.close()
for name in zf.namelist():
print name
after that, this works:
#!/usr/bin/env python
import sys
sys.path.insert(0, 'pychess.zip')
from pychess.Utils.lutils import LBoard