Python ImportError: No module named yahoo_finance - arduino-uno

I am new to the Arduino & Python community. I tried to implement the following project:
https://create.arduino.cc/projecthub/gatoninja236/yahoo-stock-ticker-0df3c7?ref=platform&ref_id=424_trending__beginner_tutorial&offset=1
I followed all steps but when I run the python code, I get the following message:
ImportError: No module named yahoo_finance
I tried to install the modules with sudo as well. I what I realized that the path is empty.
PYTHONPATH: []
when I run the following script:
import os
import sys
try:
user_paths = os.environ['PYTHONPATH'].split(os.pathsep)
except KeyError:
user_paths = []
print "PYTHONPATH: ", user_paths
print "sys.path: ", sys.path
Even though I edited the .bashrc and .bash_profile like this
export PYTHONPATH="${PYTHONPATH}:/Library/Python/2.7/site-packages"
Is there something else I can try out?

Related

How to import python script using ROS and unittest

I'm facing an issue in a ROS (Python 2.7) project.
Strucure
I'm working on a ROS project. The structure is the following:
probable-adventure
|
|-catkin_ws
|-src
|-ros_rover
|-include
|-launch
|-msg
|-__init__.py
|-Commands.msg
|-Teleoperation.msg
|-scripts
|-__init__.py
|-keyboard.py
|-test
|-__init__.py
|-testing.py
|-__init__.py
|-CMakeLists.txt
|-package.xml
Keyboard node (secondary problem)
keyboard.py starts as follows:
#!/usr/bin/env python
import rospy
from ros_rover.msg import Teleoperation
I describe it as a secondary problem because if I compile the project from catkin_ws directory using catkin_make command, everything works well and I can run the keyboard ROS node perfectly even though I get a pylint error in the from ros_rover.msg ... line.
Unable to import 'ros_rover.msg'
Main Problem
I just wrote the previous as context. The point is that I have to test the code within the scripts directory. I'm using unittest and I create python files in test directory.
I have create the following simple test (testing.py):
#!/usr/bin/env python
import unittest
from scripts.keyboard import GetKey
class TestBareBones(unittest.TestCase):
def test_one_equals_one(self):
self.assertEquals(1, 1, "1!=1")
if __name__ == '__main__':
unittest.main()
I think I have a problem with the imports because if I run the following python commands (from the ros_rover directory):
user#dubuntu:~/probable-adventure/catkin_ws/src/ros_rover$ python testing.py
user#dubuntu:~/probable-adventure/catkin_ws/src/ros_rover$ python -m testing
I get the following error:
File "/home/diego/Documents/probable-adventure/catkin_ws/src/ros_rover/test/prueba.py", line 5, in <module>
from scripts.keyboard import GetKey
File "scripts/keyboard.py", line 14, in <module>
from ros_rover.msg import Teleoperation
ImportError: No module named ros_rover.msg
My thought
I think the problem is related with imports because I have read that python imports depends on the directory from where you run the python command.
I run the test from ros_rover directory because the test's import is scripts.keyboard so it can found it (scripts is in ros_rover). But when the keyboard.py tries to import ros_rover.msg fails because I'm already in ros_rover directory and cannot find ros_rover.
I have read a lot here in StackOverflow and out of it but I didn't find a solution (I have added a empty __init__.py file to ros_rover, scripts and test directories).

How to fix ModuleNotFoundError: No module named 'pyjokes'

I have installed pyjokes with pip3!
sudo pip3 install pyjokes
And have it in the terminal when i do pip3 list below picture!
And i have my simple file down below here!
import pyjokes
joke = pyjokes.get_joke('english','neutral')
print(joke)
But i get this error when i run the file pic below]2
How can i fix this error?
I searched on my own and saw this helped me
You import sys to your file and use sys.path.append() for adding the file name to your file it worked strange with pyjokes.get_joke() though?
import sys
sys.path.append('/usr/local/lib/python3.7/dist-packages/')
import pyjokes
print(pyjokes.get_joke())
Replace this:
[joke = pyjokes.get_joke('english','neutral')]
With this:
[joke = pyjoke.get_joke('en','neutral')]

Writing out document in GUI executable using cx_freeze not working

I made an executable gui (with tkinter) file using cx_freeze. The executable has several buttons. When the user click the button, the calculation should work and then it will write out an xlsx file.
Everything went good when I make the executable, there was no error. But when I click the button, it seems like the calculation works (since it was loading), but then it does not write out the xlsx file.
I don't know what went wrong. Anyone can help me?
Here's the setup.py file:
import sys
from cx_Freeze import setup, Executable
import os
import tkinter
base = None
if sys.platform == 'win32':
base = "Win32GUI"
executables = [Executable("gui.py", base=base)]
packages = ["tkinter", 'xlsxwriter', 'matplotlib']
options = {
'build_exe': {
'includes': ["os", "tkinter", 'numpy.core._methods', 'numpy.lib.format', 'xlrd', 'scipy', 'pandas'],
'include_files': [r"C:\Users\USERNAME\AppData\Local\Programs\Python\Python36-32\DLLs\tcl86t.dll",
r"C:\Users\USERNAME\AppData\Local\Programs\Python\Python36-32\DLLs\tk86t.dll"]
},
}
os.environ['TCL_LIBRARY'] = r'C:\Users\USERNAME\AppData\Local\Programs\Python\Python36-32\tcl\tcl8.6'
os.environ['TK_LIBRARY'] = r'C:\Users\USERNAME\AppData\Local\Programs\Python\Python36-32\tcl\tk8.6'
setup(
name="Tool",
version="1.0",
description="Tool prototype for calculating",
options=options,
executables=executables
)
I've solved the problem.
What i did was to change the base in setup.py to : base = None
and I installed the xlsxwriter by following this thread: ImportError: No module named 'xlsxwriter': Error in bamboo
After this, I encountered another problem:
No module named: scipy.sparse.csgraph._validation
but I simply add this to the 'includes': ['scipy.sparse.csgraph._validation', ...]
now everything works perfectly.
I hope this helps anyone who has the same problem.

"Could not find a version that satisfies the requirement cv2==1.0" when deploy Docker app with Anaconda and OpenCV to Heroku

I am trying to deploy a simple Python app with Conda support to Heroku.
I can deploy this simple example to Heroku without problem:
https://github.com/heroku-examples/python-miniconda
But it no longer work when I added a cv2 import:
Original app.py file:
from flask import Flask, jsonify
from sklearn import datasets, svm
app = Flask(__name__)
# Load Dataset from scikit-learn.
digits = datasets.load_digits()
#app.route('/')
def hello():
clf = svm.SVC(gamma=0.001, C=100.)
clf.fit(digits.data[:-1], digits.target[:-1])
prediction = clf.predict(digits.data[-1:])
return jsonify({'prediction': repr(prediction)})
if __name__ == '__main__':
app.run(host='0.0.0.0')
Modified app.py file:
from flask import Flask, jsonify, render_template, request, redirect, url_for, send_from_directory
from sklearn import datasets, svm
import os
import json
import requests
# browser the file that the user just uploaded
from werkzeug import secure_filename
from keras.models import Sequential
from keras.layers.core import Flatten, Dense, Dropout
from keras.layers.convolutional import Convolution2D, MaxPooling2D, ZeroPadding2D
from keras.optimizers import SGD
from keras.applications.resnet50 import preprocess_input, decode_predictions
from keras import applications
import cv2, numpy as np
app = Flask(__name__)
# These are the extension that we are accepting to be uploaded
app.config['ALLOWED_EXTENSIONS'] = set(['png', 'jpg', 'jpeg', 'gif'])
# For a given file, return whether it's an allowed type or not
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS']
#app.route('/')
def hello_world():
return 'Hello World!'
# Route that will process the file upload
#app.route('/upload', methods=['POST'])
def upload():
# Get the name of the uploaded file
file = request.files['file']
# Check if the file is one of the allowed types/extensions
if file and allowed_file(file.filename):
# Make the filename safe, remove unsupported chars
# filename = secure_filename(file.filename)
# Move the file form the temporal folder to
# the upload folder we setup
# file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
# Redirect the user to the uploaded_file route, which
# will basicaly show on the browser the uploaded file
file.save(file.filename)
im = cv2.resize(cv2.imread(file.filename), (224, 224)).astype(np.float32)
im[:,:,0] -= 103.939
im[:,:,1] -= 116.779
im[:,:,2] -= 123.68
im = im.transpose((2,0,1))
im = np.expand_dims(im, axis=0)
out = model.predict(im)
decoded = decode_predictions(out, top=3)[0]
print('Predicted:', decoded)
return str(decoded)
if __name__ == '__main__':
# Test pretrained model
model = applications.VGG19(include_top=True, weights='imagenet')
app.run()
I will get this error when pushing this modified app to Heroku:
Could not find a version that satisfies the requirement cv2==1.0 (from -r /tmp/requirements.txt (line 10)) (from versions: )
No matching distribution found for cv2==1.0 (from -r /tmp/requirements.txt (line 10))
The command '/bin/sh -c pip install -qr /tmp/requirements.txt' returned a non-zero code: 1
! Error: docker build exited with 1
So it appears that cv2 is missing on the Docker container? I added this line "RUN conda install -c conda-forge opencv" in the Dockerfile template from the example project, but it doesnt help:
FROM heroku/miniconda
# Grab requirements.txt.
ADD ./webapp/requirements.txt /tmp/requirements.txt
# Install dependencies
RUN pip install -qr /tmp/requirements.txt
# Add our code
ADD ./webapp /opt/webapp/
WORKDIR /opt/webapp
RUN conda install scikit-learn
RUN conda install -c conda-forge opencv
CMD gunicorn --bind 0.0.0.0:$PORT wsgi=
Any help please?
The error that you are seeing is related to the fact that pip is not able to install the pip package listed on the pypi index as cv2 with version 1.0. Apparently, that package description is "My Blog Distribution Utilities" and there are no files present at https://pypi.python.org/simple/cv2/, which is why you see an error similar to:
(test) ubuntu#condaexpts:~$ pip install cv2==1.0
Collecting cv2==1.0
Could not find a version that satisfies the requirement cv2==1.0 (from versions: )
No matching distribution found for cv2==1.0
It seems quite obvious that this is not the package that you want. So please remove cv2==1.0 from the file requirements.txt
What you are really looking for, is the conda package for opencv, which you should be able to get from:
RUN conda install -yc conda-forge opencv

AttributeError: 'module' object has no attribute 'testmod' Python doctest

When ever I try to doctest in python, basically whenever I run the code
if __name__ =="__main__":
import doctest
doctest.testmod()
I get this response from the interpreter
AttributeError: 'module' object has no attribute 'testmod'
I can run this code just fine, but whenever I run it on my windows machine, it doesn't work.
My machine is running Windows theirs is OS X, but are running python 2.7.5.
Thank you :)
Make sure that you are not trying to save your test file as doctest.py. The print statement suggested above will show it. If the file name is doctest.py, then rename it and try again.
AttributeError: 'module' object has no attribute 'testmod'
Clearly stats that the doctest module you're importing do not has the testmod() method.
Possible reasons can be:
You have more than one doctest modules in the lib.
and, it is the other one (without the testmod() method) which is getting imported as result of import doctest.
Solution: Look for the path of standard doctest module.
if __name__ =="__main__":
import doctest
if doctest.__file__ == "/path/to/standard/doctest-module":
doctest.testmod()
It looks like there is a different module called doctest that is being imported instead of the standard one.
To find out which module is being imported exactly, simply add the following print:
if __name__ =="__main__":
import doctest
print doctest.__file__ # add this
doctest.testmod()
The print should produce something similar to C:\Python27\lib\doctest.pyc, depending on the location and version of Python you're using. Any other output means you are importing the wrong module, and explain why you're getting the error.

Resources