Importing Module with Python (Head First Python Book) - python

I'm currently following the head-first book on python. Briefly, I am trying to run a python file that imports a module and when I run it I get an error saying ModuleNotFoundError: No module named 'vsearch'
This is the folder structure:
New Folder
hello_flask.py
mymodules.py
dist
vsearch.egg-info
readme.txt
setup.py
vsearch.py
The following is the code for the relevant (I think):
hello_flask.py
from flask import Flask
from vsearch import search4letters
app = Flask(__name__)
#app.route('/')
def hello() -> str:
return 'Hello world from Flask!'
#app.route('/search4')
def do_search()-> str:
return str(search4letters('life,the universe, and everything', 'eiru!'))
app.run()
vsearch.py
def search4vowels(phrase: str) -> set:
"""Return any vowels found in a supplied phrase."""
vowels = set('aeiou')
return vowels.intersection(set(phrase))
def search4letters(phrase:str, letters:str = 'aeiou') ->set:
"""Return a set of the 'letters' found in 'phrase'."""
return set(letters).intersection(set(phrase))
setup.py
from setuptools import setup
setup(
name = 'vsearch',
vesion = '1.0',
description = 'The Head First Python Search Tools',
author = 'HF Python 2e',
author_email = 'hfpy2e#gmail.com',
url='headfirstlabs.com',
py_modules = ['vsearch'],
)
So the book tells me to run hello_flask.py in windows powershell using py -3 hello_flask.py but when I run it I get the following error:
Traceback (most recent call last):
File "C:\Users\Juan\Desktop\New folder\hello_flask.py", line 2, in <module>
from vsearch import search4letters
ModuleNotFoundError: No module named 'vsearch'
I have created the distribution file per the book and have searched among the internet as best as I could and I haven't been able to fix it. I have a feeling it would have to be something with the pathway, but I'm not sure. I also tried pip installing vsearch from the powershell which was successful but did not fix my problem. Just in case, the pip install for vsearch installed on c:\users\juan\appdata\local\programs\python\python310\lib\site-packages (1.1.0).

I found a fix! Credits to another page but I had to change the import statement for vsearch on hello_flask.py to import mymodules.vsearch import search4letters

Related

No module named 'django' in standalone Django App

I installed Django on Windows 10, Django Version 3, Python 3.8 from Conda, with env, on VS Code
My Django works fine without any problem and my App and Project also works fine, but I decided to use Faker to generate some fake data in my DB, I have to mention that my Model works and connected successfully to my DB and migration process was successful without any problem.
I write this Standalone app for Faker to run it whenever I need manually:
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'first_project.settings')
import django
django.setup()
# Implement Fake Population script here.
import random
from first_app.models import AccessRecord, Topic, Webpage
from faker import Faker
fakegen = Faker()
topics = ['Search', 'Social', 'Marketplace', 'News', 'Games']
def add_topic():
t = Topic.objects.get_or_create(top_name=random.choice(topics))[0]
t.save()
return t
def populate(N=5):
for entry in range (N):
# Get the topic for the entry
top = add_topic()
# Create the fake data for that entry
fake_url = fakegen.url()
fake_date = fakegen.date()
fake_name = fakegen.company()
# Create the new webpage entry
webpg = Webpage.objects.get_or_create(topic=top,url=fake_url, name=fake_name)[0]
# Create a fake access record for that webpage
acc_rec = AccessRecord.objects.get_or_create(name=webpg,date=fake_date)[0]
if __name__ == "__main__":
print('Population Script!')
populate(20)
print('Population Completed!')
But whenever I run this code, I get this error:
> (myDjangoEnv) C:\my_path\first-project
> C:/Users/HPTav/anaconda3/python.exe
> c:/my_path/first_project/populate_first_app.py
Traceback (most recent call last):
File "c:/my_path/first_project/populate_first_app.py", line 4, in
<module>
import django
ModuleNotFoundError: No module named 'django'
> (myDjangoEnv) C:\my_path\first-project>
I replaced the path with my_path to make it easier for you when you read the console error.
This is my Django project structure:
I am sure I have Django, as I said my Django app and project works fine.
I checked it by this way to make sure I have Django on this folder:
This project is available in GitHub:
https://github.com/hptavakoli/django_first_app
Sounds like you don't have django installed, install it using this command:
pip install django
In your Command prompt.
Visit this site for additional info: Installing django using pip
What you can do is this:
"Add 'python' while calling populate_first_app.py in the terminal."
python populate_first_app.py

module flask will not launch

project interpreter and local env IMAGEI'm having a real problem with using the module flask , I've tried a lot of the solutions here on the forum but none has worked.
I can see flask is installed
pip list - showing flask
in the setting the module flask is installed in project interpreter
when I type the code I can see the module comes up
However when I launch the code I get an error
No module named 'flask'
I've tried to re-install pycharm
I've tried to uninstall and install flask again
still the same problem. Any advice ?
The file name vsearch.py
Here is the code:
from flask import Flask, render_template, request, escape
app = Flask(__name__)
def search4words(phrase: str, letters: str) -> set:
return set(letters).intersection(set(phrase))
def log_request(req: 'flask_request', res: str) -> None:
with open('vsearch.log', 'a') as log:
print(req.form, req.remote_addr, req.user_agent, res, file=log,
sep='|')
#app.route('/search4', methods=['POST'])
def do_search() -> 'html':
phrase = request.form['phrase']
letters = request.form['letters']
title = 'Here are your results:'
results = str(search4words(phrase, letters))
log_request(request, results)
return render_template('results.html', the_phrase=phrase,
the_letters=letters, the_title=title,
the_results=results,)
#app.route('/')
#app.route('/entry')
def entry_page() -> 'html':
return render_template('entry.html', the_title='Welcome back
AGAIN!!!!!')
#app.route('/viewlog')
def view_the_log() -> 'html':
contents = []
with open('vsearch.log') as log:
for line in log:
contents.append([])
for item in line.split('|'):
contents[-1].append(escape(item))
titles = ('Form Data', 'Remote_addr', 'User_agent', 'Results')
return render_template('viewlog.html',
the_title = 'View log',
the_row_titles = titles,
the_data = contents,)
if __name__ == '__main__' :
app.run(debug=True)
Your issue was attempting to run vsearch.py through terminal, rather than through PyCharm's interpreter (which was correctly installed). In order to utilize the virtual environment, you should configure it to be used correctly when running your code.
There are multiple ways of activating your virtual environment, so please find that which is applicable to your project. A good source for this would be https://uoa-eresearch.github.io/eresearch-cookbook/recipe/2014/11/26/python-virtual-env/.

ImportError in python

In clean.py I have:
import datetime
import os
from flask_script import Manager
from sqlalchemy_utils import dependent_objects
from components import db, app
from modules.general.models import File
from modules.workflow import Workflow
manager = Manager(usage='Cleanup manager')
#manager.command
def run(dryrun=False):
for abandoned_workflow in Workflow.query.filter(Workflow.current_endpoint == "upload.upload_init"):
if abandoned_workflow.started + datetime.timedelta(hours=12) < datetime.datetime.utcnow():
print("Removing abandoned workflow {0} in project {1}".format(
abandoned_workflow.id, abandoned_workflow.project.name
))
if not dryrun:
db.session.delete(abandoned_workflow)
db.session.commit()
for file in File.query.all():
dependencies_number = dependent_objects(file).count()
print("File {0} at {1} has {2} dependencies".format(file.name, file.path, dependencies_number))
if not dependencies_number:
file_delete(file, dryrun)
if not dryrun:
db.session.delete(file)
db.session.commit()
# List all files in FILE_STORAGE directory and delete ones tat don't have records in DB
all_files_hash = list(zip(*db.session.query(File.hash).all()))
for file in os.listdir(app.config['FILE_STORAGE']):
if file.endswith('.dat'):
continue
if file not in all_files_hash:
file_delete(os.path.join(app.config['FILE_STORAGE'], file), dryrun)enter code here
I need start def run()
in console I write:
python clean.py
And I have outputs :
`Traceback (most recent call last):
File "cleanup_command.py", line 7, in <module>
from components import db, app
ImportError: No module named 'components'
clean.py is located in- C:\App\model\clean.py
components.py is located in - C:\components.py
Workflow.py is located in - C:\modules\workflow\Workflow.py
Please, tell me what could be the problem?
The problem is that modules for import are searched in certain locations: https://docs.python.org/2/tutorial/modules.html#the-module-search-path.
In your case you can put all source directory paths in PYTHONPATH var like:
PYTHONPATH=... python clean.py
But I guess it would be better to relocate your code files (i.e. put all the libs in one location)
To start run() when you call python clean.py, Add these lines at the end of the script.
if __name__ == '__main__':
r = run()
## 0-127 is a safe return range, and 1 is a standard default error
if r < 0 or r > 127: r = 1
sys.exit(r)
Also as Eugene Primako mentioned it is better to relocate your code files in one location.
from components import db, app
ImportError: No module named 'components'
This means its looking for script named components.py in a location where clean.py is placed. This is the reason why you have got import error.

keyring module is not included while packaging with py2exe

I am making an app using python 2.7 on windows and keyring-3.2.1 . In my python code on eclipse, I used
import keyring
keyring.set_password("service","jsonkey",json_res)
json_res= keyring.get_password("service","jsonkey")
is working fine as I am storing json response in keyring. But, when I converted python code into exe by using py2exe, it shows import error keyring while making dist. Please suggest how to include keyring in py2exe.
Traceback (most recent call last):
File "APP.py", line 8, in <module>
File "keyring\__init__.pyc", line 12, in <module>
File "keyring\core.pyc", line 15, in <module>
File "keyring\util\platform_.pyc", line 4, in <module>
File "keyring\util\platform.pyc", line 29, in <module>
AttributeError: 'module' object has no attribute 'system'
platform_.py code is :
from __future__ import absolute_import
import os
import platform
def _data_root_Windows():
try:
root = os.environ['LOCALAPPDATA']
except KeyError:
# Windows XP
root = os.path.join(os.environ['USERPROFILE'], 'Local Settings')
return os.path.join(root, 'Python Keyring')
def _data_root_Linux():
"""
Use freedesktop.org Base Dir Specfication to determine storage
location.
"""
fallback = os.path.expanduser('~/.local/share')
root = os.environ.get('XDG_DATA_HOME', None) or fallback
return os.path.join(root, 'python_keyring')
# by default, use Unix convention
data_root = globals().get('_data_root_' + platform.system(), _data_root_Linux)
platform.py code is:
import os
import sys
# While we support Python 2.4, use a convoluted technique to import
# platform from the stdlib.
# With Python 2.5 or later, just do "from __future__ import absolute_import"
# and "import platform"
exec('__import__("platform", globals=dict())')
platform = sys.modules['platform']
def _data_root_Windows():
try:
root = os.environ['LOCALAPPDATA']
except KeyError:
# Windows XP
root = os.path.join(os.environ['USERPROFILE'], 'Local Settings')
return os.path.join(root, 'Python Keyring')
def _data_root_Linux():
"""
Use freedesktop.org Base Dir Specfication to determine storage
location.
"""
fallback = os.path.expanduser('~/.local/share')
root = os.environ.get('XDG_DATA_HOME', None) or fallback
return os.path.join(root, 'python_keyring')
# by default, use Unix convention
data_root = globals().get('_data_root_' + platform.system(), _data_root_Linux)
The issue you're reporting is due to an environment that contains invalid modules, perhaps from an improper installation of one version of keyring over another. You will want to ensure that you've removed remnants of the older version of keyring. In particular, make sure there's no file called keyring\util\platform.* in your site-packages.
After doing that, however, you'll encounter another problem. Keyring loads its backend modules programmatically, so py2exe won't detect them.
To work around that, you'll want to add a 'packages' declaration to your py2exe options to specifically include the keyring.backends package. I invoked the following setup.py script with Python 2.7 to convert 'app.py' (which imports keyring) to an exe:
from distutils.core import setup
import py2exe
setup(
console=['app.py'],
options=dict(py2exe=dict(
packages='keyring.backends',
)),
)
The resulting app.exe will import and invoke keyring.

Import error when building python using py2exe

I am trying to make a small script to remotely manage windows computers (currently only shutdown). The method I am using involves a webapp2 server. i would like to compile my first attempt into a .exe. The problem I am having is that after successfully compiling it I go to run it and it returns the error:
Traceback (most recent call last):
File "web2.py", line 2, in <module>
File "webapp2.pyc", line 25, in <module>
File "webob\__init__.pyc", line 1, in <module>
File "webob\datetime_utils.pyc", line 10, in <module>
ImportError: No module named email.utils
I have also tried this with cx_Freeze which had similar results. I have followed the advice given at import error while bundling using py2exe to no avail.
In case it is any use here is my code:
import cgi
import webapp2
import os
import socket
def ip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('google.com', 0))
return s.getsockname()[0]
class MainPage(webapp2.RequestHandler):
def get(self):
self.response.out.write("""
<html>
<body>
<form action="/shutdown" method="link">
<div><input type="submit" value="Shutdown"></div>
</form>
</body>
</html>""")
class shutdown(webapp2.RequestHandler):
def get(self):
self.response.out.write('<html><body>Shutting down...<pre>')
self.response.out.write('</pre></body></html>')
os.system("shutdown -p -f")
app = webapp2.WSGIApplication([('/', MainPage),
('/shutdown', shutdown)],
debug=True)
def main():
from paste import httpserver
httpserver.serve(app, host=ip(), port='80')
if __name__ == '__main__':
main()
Thank you in advance.
EDIT:
I have found out using modulefinder that there are a lot of modules not being imported. I don't however know if this is happening when ran normally or only when imported or something like that.
http://pastebin.com/s0U9WHJ6
I have discovered that the problem was that I was presuming that py2exe would import webob as the interpreter does. In fact I needed to put the webob folder in the folder that I was building in.
I am not sure, but you could try specifically including email.utils in the setup.py by adding the following argument to the setup function call in the script that imports py2exe:
options={"py2exe": {'includes': ["email.utils"]}}
That, or you could try specificly importing it before you import webapp2, like on line 1:
import email.utils
import cgi
import webapp2
If this says it can't find a diferent module, try adding the module in the includes list:
options={"py2exe": {'includes': ["email.utils", "othermodulename"]}}
or specificly importing it again.
Hope this helps! :-)

Categories