I am trying to add python code to my robot via ev3dev and Visual studio code. I am able to transfer code onto my robot but my problem is that when ever I try to run the code on my PC on visual studio code I get an error saying unable to import visual studio and when I try to run the code on my ev3 the robot stops for about half a second and then the screen goes blank for about one millisecond and then goes back to the previous screen
I have installed ev3dev from visual studio and I have installed ev3dev-lang-python-ev3dev-stretch onto the SD card so the robot does have the software inside it.
Exception has occurred: ModuleNotFoundError
No module named 'ev3dev2'
File "C:\Users\User\Documents\implanted\tester.py", line 2, in <module>
from ev3dev2.motor import LargeMotor, OUTPUT_A, OUTPUT_B,
SpeedPercent, MoveTank
from ev3dev2.sensor import INPUT_1
from ev3dev2.sensor.lego import TouchSensor
from ev3dev2.led import Leds
ts = TouchSensor()
leds = Leds()
print("Press the touch sensor to change the LED color!")
while True:
if ts.is_pressed:
leds.set_color("LEFT", "GREEN")
leds.set_color("RIGHT", "GREEN")
else:
leds.set_color("LEFT", "RED")
leds.set_color("RIGHT", "RED")
What I would expect to happen is that when I run the code no errors should happen and if I run the code on the ev3 when I press the touchsensor it should turn the light on the ev3 the colour it is supposed to turn
I've had the same Problem.
Fore me it worked to put the 'vscode-hello-python-master' file in another folder. In the beginning this folder was in the C:\Users\fbk\Documents folder. But the system had permission issues. So I put it under D:\programs\ev3dev2. In the following step I set up a virtual environment. I typed these 4 lines in the vs code Terminal:
py -3 -m venv .venv
.venv\Scripts\activate
python -m pip install --upgrade pip
pip install python-ev3dev2
As this worked for my windows system, this is the code for non windows systems:
python3 -m venv .venv
. .venv/bin/activate
pip install --upgrade pip
pip install python-ev3dev2
Hope this works for you respectively for all, who have the same problem
Related
im trying to turn my python program into an .exe file with the command pysintaller --onefile [name], everything goes perfectly but then when i run my .exe file i get the error " failed to execute script due to unhandled exception, No module name requests. I have already installed the libraries and moved my folder out of the dist file , but same thing. Can anyone help me please?(i tested my code with Visual studio it works.
import requests
import tkinter
from cProfile import label
from tkinter import *
from bs4 import BeautifulSoup
def show_data():
link = ent.get()
result = requests.get(link)
soup = BeautifulSoup(result.text, 'html.parser')
images = soup.find_all('img')
liste = []
for image in images:
image = image['src']
if "https://cdn2.sorsware.com" and "buyuk" in image:
liste.append(image)
txt.insert(0.0,liste)
def delete_data():
txt.delete(1.0,END)
gui = Tk()
gui.geometry("1000x500")
gui.title("BSL")
l1 = Label(gui,text="Link:")
ent = Entry(gui,width=600)
l1.grid(row=0)
ent.grid(row=0,column=1)
txt = Text(gui,width=125,wrap=WORD,font=("Arial",10))
txt.place(x=500,y=250,anchor=CENTER)
btn = Button(gui,text = "Results",bg ="black",fg="white",width=5,height=2,command=show_data)
btn.grid(row=1)
btn_delete = Button(gui,text = "delete",bg ="black",fg="white",width=5,height=2,command=delete_data)
btn_delete.grid(row=2)
gui.mainloop()
pip install requests
try this command once I also got the same error some days before
It looks like it can't find the requests module. Make sure you're running pyinstaller in the virtual environment with all dependencies installed.
You can install with
pip install requests
Edited after testing:
I was able to install and execute the alp.py script you provided, and build an exe using pyinstaller. Here's the steps I followed (on Windows 10).
The directory tree looks like this:
alp/
env/
alp.py
In your alp folder, first we'll setup a virtualenv and update it:
py -m venv env
source env/Scripts/activate
python -m pip install --upgrade pip
If you're using a standard Windows console, you may have to just do env/Scripts/activate (omit the source) to enable your virtualenv.
Now install dependencies and test the application:
pip install beautifulsoup4 requests pyinstaller
python alp.py
If all goes well, the window opens and there are no errors. Now we can build the executable.
pyinstaller --onefile alp.py
I suspect that what's happened is when you're running the pyinstaller command, you're not in the same virtualenv as the project dependencies, which is why it's unable to import requests no matter how many times you reinstall it.
If you're sure you're in the same environment as the dependencies we'll have to see some error output from the pyinstaller command perhaps.
[EDITED - thanks to the Ludovico Loreti's comment]
If I run the following code (.py file) from Visual Studio Code, i.e. by pressing the green triangular button "Run Python File in Terminal" at the top right corner of VSCode
from networkit import *
import networkit as nk
import matplotlib.pyplot as plt
g = generators.HyperbolicGenerator(1e3).generate()
bc = nk.centrality.Betweenness(g)
bc.run()
bc.ranking()[:10] # the 10 most central nodes
the expected result (i.e. the betweenness calculation) is NOT shown in the VSCode embedded Terminal.
Instead, if I run the same code directly from Terminal, using ipython3, the result comes out well.
Out[4]:
[(392, 625118.6896734448),
(875, 204886.97319625755),
(170, 121481.35921722073),
(621, 72627.46666666666),
(566, 71881.75991032101),
(37, 62046.49111887374),
(701, 53157.760291814484),
(988, 45316.922735729204),
(934, 42894.204329181564),
(657, 32147.666666666664)]
Why? What should I change in Visual Studio Code in order to see my results in its embedded Terminal?
[P.S.1]: If I add other commands to my code, such as
print(g.numberOfNodes(), g.numberOfEdges())
VSCode shows correctly the results in its embedded Terminal. Therefore, it looks like that (so far) only the betweenness-related results are not shown/displayed.
[P.S.2]: Just for information, if it can be useful, I have installed Visual Studio Code through snap (https://snapcraft.io/install/code/centos):
sudo yum install epel-release -y
sudo yum install snapd -y
sudo systemctl enable --now snapd.socket
sudo ln -s /var/lib/snapd/snap /snap
sudo snap install code --classic
and I run VSCode from Terminal by typing:
snap run code
The solution/explanation is provided in the networkit forum
https://github.com/networkit/networkit/issues/788
Many thanks to avdgrinten!
I have a py file that preforms a google search using the system arguments passed to it and opens the first five results of the search as separate browser tabs (this is an exercise from the book Automate the Boring Stuff).
I would like to execute this script via the Windows run command and have therefore created a BAT file.
Currently, when I execute the BAT file, a "module not found" error is returned.
I suspected this issue was related to the fact that the modules required by the py file were only installed in the virtual environment of my specific python project (I have a project specifically for the exercises in this book). Therefore, I installed the necessary modules directly into the environment of my main Python installation. Unfortunately, this had no effect.
I then revised my BAT file by adding a line to activate my virtual environment before the line to execute my py file. This seemed to prevent my py file from being executing by the BAT file.
I'm somewhat familiar with Python but new to BAT files and the command line in general. I've read through a basic command line tutorial but couldn't find anything that helps.
I'm not sure how to resolve this issue and if possible would like to avoid polluting my main python environment with tons of modules. Is this possible and, if so, what am I missing?
.bat file
#py.exe C:\Users\Betty\PycharmProjects\Automate_the_Boring_Stuff\12\searchpypi.py %*
#pause
.py file
#! python3
# searchpypi.py - Opens several search results.
import sys
import webbrowser
import requests
import bs4
print('Searching...') # display text while downloading the search result page
res = requests.get('https://google.com/search?q=' 'https://pypi.org/search/?q='
+ ' '.join(sys.argv[1:]))
res.raise_for_status()
# Retrieve top search result links.
soup = bs4.BeautifulSoup(res.text, 'html.parser')
# Open a browser tab for each result.
linkElems = soup.select('.package-snippet')
numOpen = min(5, len(linkElems))
# Open a browser tab for each result.
for i in range(numOpen):
urlToOpen = 'https://pypi.org' + linkElems[i].get('href')
print('Opening', urlToOpen)
webbrowser.open(urlToOpen)
edit (Fri Mar 05 16:41:27 2021 UTC):
Error message (copied from command line):
Traceback (most recent call last):
File "C:\Users\Betty\PycharmProjects\Automate_the_Boring_Stuff\12\searchpypi.py", line 8, in <module>
import requests
ModuleNotFoundError: No module named 'requests'
Press any key to continue . . .
edit (Sat Mar 06 07:39:43 2021 UTC):
Pip Details:
C:\Users\Betty>pip -V
pip 21.0.1 from c:\python38\lib\site-packages\pip (python 3.8)
C:\Users\Betty>pip3 list
Package Version
---------------- ----------
appdirs 1.4.4
certifi 2020.12.5
chardet 4.0.0
distlib 0.3.1
filelock 3.0.12
idna 2.10
pip 21.0.1
pipenv 2020.11.15
requests 2.25.1
setuptools 41.2.0
six 1.15.0
urllib3 1.26.3
virtualenv 20.2.2
virtualenv-clone 0.5.4
wheel 0.34.2
C:\Users\Betty>
Automating everything would means:
creating a virtual environment for this Python script
sourcing it
installing dependencies
run the scrip
optional (cleanup if necessary)
There is a way to do it on Bash, but I am not sure if the same applies for the Windows shell.
First you need to put all dependencies in a requirements.txt file. Each dependency should take one line in the document.
requirements.txt's content:
webbrowser
beautifulsoup4
And the automation script.sh:
# creates a venv folder that contains a copy of python3 packages to isolate any further changes in packages from the system installation
python3 -m venv venv
# tell the shell to use the created virtual environment
source venv/bin/activate
# install requirements
pip3 install -r requirements.txt
# run the script
python3 your_script_filename.py
# remove the venv
rm -rf venv
# deactivate the virtual environment
deactivate
That’s a very basic script that resembles manual invocation of the Python script. There is so much space for improvements. The venv could be placed in the OS temporary folder and can be left there for reuse next time. That will remove the need for recreating the venv and installing the requirements.
I know this is not exactly what you want but I hope it got you a little bit further
I have written a python script which depends on paramiko to work. The system that will run my script has the following limitations:
No internet connectivity (so it can't download dependencies on the fly).
Volumes are mounted with 'noexec' (so I cannot run my code as a binary file generated with something like 'pyInstaller')
End-user cannot be expected to install any dependencies.
Vanilla python is installed (without paramiko)
Python version is 2.7.5
Pip is not installed either and cannot be installed on the box
I however, have access to pip on my development box (if that helps in any way).
So, what is the way to deploy my script so that I am able to provide it to the end-user with the required dependencies, i.e paramiko (and sub-dependencies of paramiko), so that the user is able to run the script out-of-the-box?
I have already tried the pyinstaller 'one folder' approach but then faced the 'noexec' issue. I have also tried to directly copy paramiko (and sub-dependencies of paramiko) to a place from where my script is able to find it with no success.
pip is usually installed with python installation. You could use it to install the dependencies on the machine as follows:
import os, sys
def selfInstallParamiko():
# assuming paramiko tar-ball/wheel is under the current working directory
currentDir = os.path.abspath(os.path.dirname(__file__))
# paramikoFileName: name of the already downloaded paramiko tar-ball,
# which you'll have to ship with your scripts
paramikoPath = os.path.join(currentDir, paramikoFileName)
print("\nInstalling {} ...".format(paramikoPath))
# To check for which pip to use (pip for python2, pip3 for python3)
pipName = "pip"
if sys.version_info[0] >= 3:
pipName = "pip3"
p = subprocess.Popen("{} install --user {}".format(pipName, paramikoPath).split())
out, err= p.communicate("")
if err or p.returncode != 0:
print("Unable to self-install {}\n".format(paramikoFileName))
sys.exit(1)
# Needed, because sometimes windows command shell does not pick up changes so good
print("\n\nPython paramiko module installed successfully.\n"
"Please start the script again from a new command shell\n\n")
sys.exit()
You can invoke it when your script starts and an ImportError occurs:
# Try to self install on import failure:
try:
import paramiko
except ImportError:
selfInstallParamiko()
I was given a raspberry pifor my birthday and decided to make an alarm clock out of one. I wrote all the code on my PC, works completely fine and expected but I'm having slight issues with installing packages on the raspberry pi.
When I open the terminal, I'm in the directory "home/pi".
I then run the command
sudo easy_install -U schedule
which installs fine, I then try to run my code which is stored in "home/pi", but get an error on:
Traceback (most recent call last):
File "/home/pi/LED.py", line 1, in <module>
import schedule
ImportError: No module named 'schedule'
any tips? I've also installed schedule via pip in the same directory - pip install schedule which installs perfectly fine.
#!/usr/bin/python
import schedule
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
GPIO.output(18, GPIO.HIGH)
time.sleep(5)
GPIO.output(18, GPIO.LOW)
GPIO.cleanup()
Python searches the packages in all directories in the python path
For instance, these directories for me are :
>>> import sys
>>> sys.path
['', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/usr/lib/python3.6/site-packages']
Note that the first path is "the directory containing the script that was used to invoke the Python interpreter", often the current directory when you run your python script.
Also note that pip should install the packages in the site-packages directory. (The last path in my sys.path in my previous example). There should be one of these directory per python installation.
A simple command line like find / -name site-packages should be enough to find them all. But keep in mind that not all python interpreter will use the same sys.path : obviously, if you install some package for python2, you won't be able to access it from a python3 interpreter. Same thing if you use virtualenvs.
just ran into the same problem and on my raspberry 4 it helped when I used the following from the command line where the python script was launched:
sudo python3 example.py
Note the "3" at the end of "python" above.
i came across this when searching for an answer. and then i was just testing something that got me thinking about where the packages.
i have had probles using "sudo python something.py".
getting the "ImportError: No module named "some module"
i have always been using "pip install" or "pip3 install", and always could have used it as my user, but been as i wrote, problem when i "sudo python something.py"
what fixed it in my case, is install the module again with "sudo pip install" or sudo pip3 install". though then the modules would be installed 2 places i guess. though i havent tested how it would be reachable for a normal user yet...