ModuleNotFoundError: No module named 'createCredentialsXML' - python

I have a question about my new python project. It is the first time that I use different folders for my project.
I have the following structure:
project
src
securityFunc
__init__.py
createCredentialsXML.py
main.py
I work in PyCharm environment.
After pressing Play i get the error message:
Traceback (most recent call last):
File "C:\project\src\main.py", line 1, in <module>
from securityFunc import *
File "C:\project\src\securityFunc\__init__.py", line 1, in <module>
from createCredentialsXML import *
ModuleNotFoundError: No module named 'createCredentialsXML'
My main function looks like this:
from securityFunc import *
if __name__ == '__main__':
generate_key()
__init__.py:
from createCredentialsXML import *
createCredentialsXML.py:
def generate_key():
key = base64.urlsafe_b64encode(os.urandom(2048))
with open("../key/secret.key", "wb") as key_file:
key_file.write(key)
I tried using Path or sys.path to fix the problem. But it does not work.
Can you please tell me how to fix the problem?

Since you're doing a relative import, you need to add a . before your module name:
from .createCredentialsXML import *
The dot means the module is found in the same directory as the code importing the code.
You can read more about it here

createCredentialsXML.py works in the module securityFunc; you must specify the scope of the import. Using
from securityFunc.createCredentialsXML import *
in securityFunc.__init__.py should work.

Related

I can not figure out why I can not start this simlple python script

My directory looks like this
When I start directly with PyCharm it works.
But when I try to start the script with a commandline I get this error messsage
> python .\PossibilitiesPlotter.py
Traceback (most recent call last):
File "C:\Users\username\PycharmProjects\SwapMatrixPlotter\possibilitiesplotter\PossibilitiesPlotter.py", line 7, in <module>
from plotterresources.PlotterProps import PlotterProps
ModuleNotFoundError: No module named 'plotterresources'
This is how the import looks from my main class PossibilitesPlotter.py
import sys
sys.path.append("plotterresources/PlotterProps.py")
from csv import reader
from pathlib import Path
from plotterresources.PlotterProps import PlotterProps
from possibilitiesplotter.PossibilitiesGraph import PossibilitiesGraph
from possibilitiesplotter.PossibilitiesModel import PossibilitiesModel
class PossibilitiesPlotter:
As a workaround, add the following line to PossibilitesPlotter.py:
sys.path.append("../plotterresources/PlotterProps.py")
This will add the directory one level above the commandline pwd to the PATH variable. So this is always relative to the location of the calling script/shell.
Thus in general:
NEVER append to the PATH/PYTHONPATH variable from within modules. Instead restructure your module. For more details, take a look at the documentation on Packaging Python Projects

Import errors on VS code

I'm new to VS code. I have downloaded a git project which has demo programs that I can run.
The directory structure is as follows:
Projectparser
>demo
>>alg1_demo.py
>>alg2_demo.py
>>alg3_demo.py
>Projectparser
>>alg1
>>>__init__ [ Has just one line : from alg1 import * ]
>>>alg1.py
>>>calg1.c
>>>calg1.h
>>alg2
>>>__init__ [ Has just one line : from alg2 import * ]
>>>alg2.py
>>>calg2.c
>>>calg2.h
>>alg3
>>>__init__ [ Has just one line : from alg3 import * ]
>>>alg3.py
>>>calg3.c
>>>calg3.h
where > indicates sub-directory. Projectparser is the folder from where I open vs code. It has a sub-directory by the same name as well which contains all the algorithms I'm interested in.
When I try running the alg1_demo.py. The below line is causing an error.
sys.append("../")
from Projectparser import alg1 (line 8)
I'm getting the following error:
ImportError: cannot import name 'alg1' from 'Projectparser' (unknown location)
So I added the line : sys.path.append("../Projectparser")
Then I'm getting the following error :
File "/home/suneha/Projectparser/demo/alg1_demo.py", line 8, in <module>
from Projectparser import alg1
File "../Projectparser/Projectparser/alg1/__init__.py", line 1, in <module>
from alg1 import *
ModuleNotFoundError: No module named 'alg1'
But the module is present in the subdirectory. So I added the line :
sys.path.append("../Projectparser/Projectparser/alg1")
Then I'm getting this error :
Traceback (most recent call last):
File "/home/suneha/Projectparser/demo/alg1_demo.py", line 8, in <module>
from Projectparser import alg1
File "../Projectparser/Projectparser/alg1/__init__.py", line 1, in <module>
from alg1 import *
File "/home//Projectparser/Projectparser/alg1/alg1.py", line 13, in <module>
from ..logmatch import regexmatch
ImportError: attempted relative import with no known parent package
The same problem persists for all the three algorithms alg1, alg2, alg3. I'm not sure how to fix this and is using sys.append.path() the best way to solve the above mentioned problems.
Can anyone suggest how to solve the final import error : ImportError: attempted relative import with no known parent package
and if there is any other compact way of solving the other import errors instead of using sys.path.append().
Thanks in advance
Use the following statement to add the path of the file that needs to be imported to the system path to help VSCode find it:
import os,sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
The following is part of the project I created that you provided:
Result:
The following points need to be noted:
When importing, the subfolders are connected with.
Please avoid using files and folders with the same name to prevent confusion when VSCode finds modules.
If the result is executable but there is still a wave line, you can add in settings.json: "python.linting.pylintArgs": [ "----extension-pkg-whitelist=1xml" ],
Update:
According to the code of the link you provided, I reproduced the problem you described locally, and the solution is as follows:
Comment out the content "from SLCT import *" of logparser-master\logparser\SLCT_init_.py.
Add import os,sys sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
to SLCT_demo.py
operation result:

Simple case of __init__.py and import giving mysterious module not found

I've tried this from so many different angles but can't sort it out. Must be such a simple case. In Python 3.7.6:
Directory structure:
./modtest/
./modtest/__init__.py
./modtest/test1.py
./modtest/test2.py
test1.py:
import modtest
def x(i):
print(i)
y(i)
test2.py:
def y(i):
print(i)
__init__.py is an empty file.
When I attempt to run the code:
$ /Users/pitosalas/miniconda3/bin/python /Users/pitosalas/mydev/rsb_py/modtest/test1.py
Traceback (most recent call last):
File "/Users/pitosalas/mydev/rsb_py/modtest/test1.py", line 1, in <module>
import modtest
ModuleNotFoundError: No module named 'modtest
From what I read this should've worked. I'm sure there's something trivial wrong!
You are importing modtest in test1.py while this module itself resides inside of modtest. This can't be because modest wouldn't have yet been defined and added to the search path. So this is what you should have actually:
./modtest/
./modtest/__init__.py
./modtest/
./modtest/test2.py
./test1.py # this module must be outside of modtest

How to import a module from sub directory

I failed to import a module from sub directory in python. Below is my project structure.
./main.py
./sub
./sub/__init__.py
./sub/aname.py
when I run python main.py, I got this error:
Traceback (most recent call last):
File "main.py", line 4, in <module>
import sub.aname
File "/Users/dev/python/demo/sub/__init__.py", line 1, in <module>
from aname import print_func
ModuleNotFoundError: No module named 'aname'
I don't know it failed to load the module aname. Below is the source code:
main.py:
#!/usr/bin/python
import sub.aname
print_func('zz')
sub/__init__.py:
from aname import print_func
sub/aname.py:
def print_func( par ):
print ("Hello : ", par)
return
I am using python 3.6.0 on MacOS
There are several mistakes in your Python scripts.
Relative import
First, to do relative import, you must use a leading dots (see Guido's Decision about Relative Imports syntax).
In sub/__init__.py, replace:
from aname import print_func
with:
from .aname import print_func
Importing a function
To import a function from a given module you can use the from ... import ... statement.
In main.py, replace:
import sub.aname
with:
from sub import print_func
from sub import aname
aname.print_func('zz')
Probably the most elegant solution is to use relative imports in your submodule sub:
sub.__init__.py
from .aname import print_func
But you also need to import the print_func in main.py otherwise you'll get a NameError when you try to execute print_func:
main.py
from sub import print_func # or: from sub.aname import print_func
print_func('zz')

Import Error using cPickle in Python

I am using Pickle in Python2.7. I am getting error while using cPickle.load() method. The code and error is shown below. Can someone guide me through this?
Code:
#! usr/bin/python
import cPickle
fo = open('result','rb')
dict1 = cPickle.load(fo)
Error:
Traceback (most recent call last):
File "C:\Python27\test.py", line 7, in <module>
dicts = cPickle.load(fo)
ImportError: No module named options
It seems like you can not do
import options
but when you or someone else did
cpickle.dump(xxx, open('result', 'rb'))
there was an object with a class or function of a module options that existed at this point in time, in xxx.
Solution
You can open the file binarily and replace options with the module you replaced the old module options with.
You probably created the file in your package like in module package.main by executing the file main.py or something like it, having a module options in the same directory.
Now you do import package.main, try to read the file and options is now called package.options and the module options can not be found.
How did you create this file? How do you load it now? cPickle/pickle does not transfer source code - so if you use a function you need the module when you load it.

Categories

Resources