Python unable to import package, but works correctly from within the package. A fully functional example below. In the virtual env I am using 3.6 All responses greatly appreciated!
parsers/
__init__.py
element.py
parser1.py
parser2.py
parserresolver.py
outsidepkg.py
init.py is empty
element.py:
def router():
pass
parser1.py:
from element import *
def parse(data):
return data
parser2.py:
from element import *
def parse(data):
return data
parserresolver.py:
import sys
from parser1 import *
from parser2 import *
def resolve(data):
parseddata = None
parsers = ['parser1', 'parser2']
funcname = 'parse'
for parser in parsers:
module = sys.modules[parser]
if hasattr(module, funcname):
func = getattr(module, funcname)
parseddata = func(data)
print(parseddata)
return parseddata
if __name__ == "__main__":
resolve('something')
outsidepkg.py:
import parsers.parserresolver
def getapi(data):
parsers.parserresolver.resolve(data)
if __name__ == "__main__":
print(getapi('in parse api main'))
So when I call parserresolver.py directly it works great, no import errors and prints out "something" as expected.
But when I call outsidepkg.py I am getting this error:
Traceback (most recent call last):
File "C:\code\TestImport\TestImport\outsidepkg.py", line 1, in <module>
import parsers.parserresolver
File "C:\code\TestImport\TestImport\parsers\parserresolver.py", line 2, in <module>
from parser1 import *
ModuleNotFoundError: No module named 'parser1'
Press any key to continue . . .
You need to change the imports of:
from file import whatever
To:
from .file import whatever
Since your code to run it is outside the folder, use a . to get the directory, since the file isn't outside the package.
Related
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.
Although the variable should be imported, I get "name X is not defined" exception.
main.py
from config import *
from utils import *
say_hello()
utils.py
from config import *
def say_hello():
print(config_var)
config.py
from utils import *
config_var = "Hello"
Trying to run "main.py":
Traceback (most recent call last):
File "main.py", line 3, in
say_hello()
File "C:\Users\utils.py", line 3, in say_hello
print(config_var)
NameError: name 'config_var' is not defined
What happened here? Why some_var is not accessible from utils.py?
You are importing config in util and util in config which will causing this error(create cross loop). remove from utils import * from config.py and then try this.
And in main.py you don't need to import the from config import * unless you are using variables from config directly in your main()
you should also import config.config_var, since this variable belongs to that specific module
You are creating to many import statements perhaps try the following below, but also you need to define a parameter in utils.py if you are passing a parameter through there.
In utils.py we require a parameter to be passed since you want to print out the appropriate value, In config.py you are defining a value. Then in main.py as discussed before using the wildcard operator "*" isn't entirely good in this situation then in order to call the respective functions you need to address them through their file name
In utils.py :
def say_hello(config_var):
print(config_var)
In config.py
config_var = "Hello"
Then in main.py
import config as cn
import utils as ut
ut.say_hello(cn.config_var)
Check out this thread for how to write python modules as well How to write a Python module/package?
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')
I'm new to python and now learning how to to import a module or a function, but I got these posted errors. The python code is saved under the name: hello_module.py
python code:
def hello_func():
print ("Hello, World!")
hello_func()
import hello_module
hello_module.hello_func()
error message:
Traceback (most recent call last):
File "C:/Python33/hello_module.py", line 9, in <module>
import hello_module
File "C:/Python33\hello_module.py", line 10, in <module>
hello_module.hello_func()
AttributeError: 'module' object has no attribute 'hello_func'
You cannot and should not import your own module. You defined hello_func in the current namespace, just use that directly.
You can put the function in a separate file, then import that:
File foo.py:
def def hello_func():
print ("Hello, World!")
File bar.py:
import foo
foo.hello_func()
and run bar.py as a script.
If you try to import your own module, it'll import itself again, and when you do that you import an incomplete module. It won't have it's attributes set yet, so hello_module.hello_func doesn't yet exist, and that breaks.
I'm using Python 2.6.1 on Mac OS X.
I have two simple Python files (below), but when I run
python update_url.py
I get on the terminal:
Traceback (most recent call last):
File "update_urls.py", line 7, in <module>
main()
File "update_urls.py", line 4, in main
db = SqliteDBzz()
NameError: global name 'SqliteDBzz' is not defined
I tried renaming the files and classes differently, which is why there's x and z on the ends. ;)
File sqlitedbx.py
class SqliteDBzz:
connection = ''
curser = ''
def connect(self):
print "foo"
def find_or_create(self, table, column, value):
print "baar"
File update_url.py
import sqlitedbx
def main():
db = SqliteDBzz()
db.connect
if __name__ == "__main__":
main()
You need to do:
import sqlitedbx
def main():
db = sqlitedbx.SqliteDBzz()
db.connect()
if __name__ == "__main__":
main()
try
from sqlitedbx import SqliteDBzz
Importing the namespace is somewhat cleaner. Imagine you have two different modules you import, both of them with the same method/class. Some bad stuff might happen. I'd dare say it is usually good practice to use:
import module
over
from module import function/class
That's How Python works.
Try this :
from sqlitedbx import SqliteDBzz
Such that you can directly use the name without the enclosing module.Or just import the module and prepend 'sqlitedbx.' to your function,class etc