include file in python - python

I tried to include file detect_simple.py, but it doesn't work.
Capture screnshoot: https://imgur.com/a/Rku8O1f
My code: in file app.py
__import__("Face_recognition/detect_simple")
from flask import Flask
app = Flask(__name__)
#app.route("/")
def main():
return "OK";
#app.route('/api1')
def api1():
return "OK"
if __name__ == "__main__":
app.run()
run command: python app.py
return error: `Import by filename is not supported.`

So for instance if your app.py is in the top directory and you need to import a module thats in a folder below that directory just use the from subfolder import mymodule.
For example if your directory looks like this:
- FlaskApp
- app.py
- Face_recognition
- detect_simple.py
Then use:
from Face_recognition import detect_simple

To expand on #Jab's answer: your Face_recognition directory must contain a (potentially empty) __init__.py file (with two leading and two trailing underscores) to be recognized by the import system.
Once your tree looks like this:
FlaskApp
|_ app.py
|_ Face_detection/
|_ __init__.py
|_ detect_simple.py
You'll be able to do a
from Face_detection.detect_simple import <whatever>
# or
import Face_detection.detect_simple
# or
from Face_detecting import detect_simple
Keep in mind that the import system is case-sensitive.
On a separate note, please avoid using the __import__ function in almost any case. Prefer the import statement if you're just importing stuff normally, or use importlib.import_module if you have to do programmatic imports (although this shouldn't be the default in most cases).

Related

relative import of modules in pytest in a Scafold structure

using pyscafold in order to build a module I get an structure as follows
scr
---module
------__init__.py
------file.py (containing func inside)
tests
---fileTest.py
How is the right way to import file.py in the test file fileTest.py?
So far many of this variations dont work:
import pytest
from ../src/module import func
including this in init.py does not help:
import os, sys
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
These do not help:
from .src/module/myfile import func
from ..src/module/myfile import func
There should not be forward slashes in your imports.
Also:
add a __init__.py file in tests directory
in fileTest.py, you should have:
import pytest
from src.module.file import func
Then, make sure the current working directory is the parent directory of src and run pytest .

Flask circular import issue - import variables from __init__.py into views

This is my project structure:
myproject
myproject
__init__.py
static
templates
views
__init.py__
home.py
venv
myproject.wsgi
requirements.txt
setup.py
This is my __init__.py:
from flask import Flask, request, Response, render_template
from myproject.views import home
app = Flask(__name__, static_folder="static", static_url_path='/static')
test_string = "Hello World!"
app.register_blueprint(home.home)
And this is my views/home.py:
from flask import Flask, request, Response, Blueprint
import json
import requests
from myproject import test_string
home = Blueprint('home', __name__)
#home.route('/', methods=['GET'])
def test():
return(test_string)
When I visit the page, I get an error ImportError: cannot import name test_string. The Python import system is really confusing and I am not sure what I am doing wrong here, but I suspect this is a circular import issue.
How do I solve this?
Try to move, in __init__.py, the line from myproject.views import home after the line test_string = "Hello World!".
This way Python will be find the test_string name.
To understand circular imports you have to "think like the interpreter", when you execute __init__.py the interpreter will:
execute line 1 of __init__.py
execute all the code that this line implies (importing stuff from flask)
execute line 2 of __init__.py
execute line 1 of views/home.py (importing only Blueprint from flask, for it's the onnly non-already-imported thing)
execute lines 2+3 of views/home.py (import json and requests)
execute line 4 of views/home.py
go back to what he executed in __init__.py and search for the name test_string
here it raises an error, because what he executed do not comprehend test_string. If you move the import after the execution of test_string = "Hello World!" the interpreter will find this name in the namespace.
This is commonly recognized as bad design though, IMHO the best place to store test_string would be a config.py file, in which no imports from other project modules are performed, avoiding circulat imports.

How to fix name is not defined in Python

I am running a python project like this:
project
Test.py
COMMON.py
SYSTEM.py
PTEST1
Hello.py
when run the code "Test.py" it will show NameError, I am not sure why?
But if I replaced the "from SYSTEM import *" with "from COMMON import *" in Test.py and PTEST1/Hello.py, it works as expect.
#Test.py is like this:
from SYSTEM import *
myvalue.Hello.printf()
# COMMON.py is like this:
myvalue = lambda: None
from PTEST1.Hello import Hello
myvalue.Hello = Hello
# SYSTEM.py is like this:
from COMMON import *
#PTEST1/Hello.py
from SYSTEM import *
class Hello():
#staticmethod
def printf():
print("Hello1")
print(vars(myvalue))
I expect there is no "NameError" by not changing import code. BTW, my python is 3.6+
Good practice is to give filenames in lowercase.
It looks like you are creating a Python project under project/. Any directory needs to have a file __init__.py in every directory in order for it to be discovered in Python.
You then need to refer to modules by their full name (not relative naming).
So the directory structure should be:
project/
__init__.py
test.py
common.py
system.py
ptest1/
__init__.py
hello.py
Every time you refer to file you should give the full path.
# import everything from hello.py
from project.ptest1.hello import *
# import everything from common.py
from project.common import *
# import everything from system.py
from project.system import *

Importlib.import_module will not import the module even though the param is the abs path

I have my .py module which is in C:\Python_Projects\MyModules\ with the name button_generator.py.
My code goes something like this:
module_path='C:\\Python_Projects\\MyModules'
module_name='button_generator.py'
sys.path.append(module_path)
try:
limp=importlib.import_module(module_name.split('.')[0])
except:
print 'module import error'
I have tried other versions aswell:
importlib.import_module(module_name) without the split
importlib.import_module('C:\Python_Projects\MyModules\button_generator.py')
importlib.import_module('C:\Python_Projects\MyModules\button_generator')
The folder C:\Python_Projects\MyModules is in my sys.path as I checked during debug.
Why wouldn't the module import?
I suggest you to reorder your project directories and avoid calling other modules which are not in your current directory project. You'll avoid those kind of errors.
For example, let's organize our project directories and folders to look something like this:
MyProjectFolder/
├── main.py
└── modules
├── __init__.py
└── MyLib.py
NB: Don't forget to add an empty file called __init__.py
MyLib.py :
#!/usr/bin/python3
class MyLib:
def __init__(self):
self.say_hello = "Hello i'm in modules/MyLib"
def print_say_hello(self):
print(self.say_hello)
main.py:
#!/usr/bin/python3
# from folder.file import class
from modules.MyLib import MyLib
class MainClass:
def __init__(self):
my_lib = MyLib() # load MyLib class
my_lib.print_say_hello() # access to MyLib methods
### Test
if __name__ == '__main__':
app = MainClass()
In terminal when i run:
$ python3 main.py
output:
Hello i'm in modules/MyLib
So here we have successfully imported the class in modules/MyLib.py into our main.py file.
I found the error:
After treating the ImportError exception by printing it's args, I noticed that button_generator.py had an Import that was not resolving. Basically, button_generator.py could not be imported because it had a wrong import.

Python 2.7.3 Flask ImportError: No module named

I have a Flask application with this error:
ImportError: No module named annotaria, referer: http://ltw1413.web.cs.unibo.it/
So, my root in web server is:
/home/web/ltw1413/html
Inside html folder I have:
One folder named "annotaria
One file .wsgi named "wsgi.wsgi"
My file .wsgi is:
import sys
sys.path.insert(0, '/home/web/ltw1413/html')
from annotaria import app as application
Inside my folder "annotaria" I have:
"Static" folder : inside stylesheet and js
"Templates" folder : inside html
"run.py" : file python where I have my application
run.py is this:
from pydoc import html
from annotaria import app
from flask import Flask, render_template, redirect, request
import json
import urllib2
import urlparse
import re
import string
import os
from SPARQLWrapper import SPARQLWrapper, JSON
from rdflib import Graph, BNode, Literal, Namespace
from time import strftime
import urllib2
import BeautifulSoup
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/index.html')
def reloader():
return render_template('index.html')
# other app.route()...
if __name__ == '__main__':
app.run(debug=True)
How can I find a solution? Where is my error?
Lots of errors here...
annotaria is not found on path (that is why it says... well.. exactly that).
In your code you also redefine app: you import it from annotaria and then redefine it in app = Flask(...
Others mentioned individual errors, but it would be helpful to understand the big picture. First of all, let's assume the following structure:
/home/web/ltw1413/html
- wsgi.wsgi
- annotaria/
- __init.py__
- run.py
- static/
- templates
Like Klaus mentioned, you need __init__.py to tell Python that annotaria is a valid package. But then your wsgi.wsgi file needs to import the app from the run module:
from annotaria.run import app as application
You also need to remove this unnecessary import from run.py, since you instantiate a new application:
from annotaria import app
Because there is no application to import, you instantiate a new Flask application.
Finally, make sure that the app runs manually before you start deploying it.

Categories

Resources