Pyinstaller exe file failed to execute script due to unhandled exception - python

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.

Related

How to execute python scripts that import third party modules via the command line

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

How to distribute and or package a python file with all dependencies pre-downloaded without building an executable

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()

No module named ev3dev2

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

python run ImportError:No module named

This is my project structure. I use virtualenv in my project but when I run it ,it has an ImportError.I use Mac.
But I can run it successfully use Pycharm
So how to run it successfully by Terminal.Because I want to run it in a Ubuntu server with cron
Thanks you for your answers.Here I show my solution.I modify my handler.py I think it may be related to The Module Search Path.
So I add the project path to the PYTHONPATH.
import os
project_home = os.path.realpath(__file__)
project_home = os.path.split(project_home)[0]
import sys
sys.path.append(os.path.split(project_home)[0])
import shutil
from modules import db, json_parse, config_out
from init_log import init as initlog
initlog()
if __name__ == '__main__':
try:
columns = json_parse.json_parse()
if not columns:
sys.exit()
is_table_has_exist = db.check_tables_exist(columns=columns)
if is_table_has_exist:
db.check_columns(columns=columns)
is_ok, config_path = config_out.output(columns)
if is_ok:
file_name = os.path.split(config_path)[1]
shutil.copy(config_path, os.path.join("/app/statics_log/config", file_name))
except Exception, e:
print e
And I run with crontab by this.
cd to/my/py_file/path && /project_path/.env/bin/python /path/to/py_file
example:
13 8 1 * * cd bulu-statics/create_config/ && /home/buka/bulu-statics/.env/bin/python /home/buka/bulu-statics/create_config/handler.py >> /app/statics_log/config/create_config.log
PyCharm automatically adds project directories marked as containing sources to the PYTHONPATH environment variable, whihc is why it works from within pycharm. On the terminal use
PYTHONPATH=${PWD}/..:${PYTHONPATH} python handler.py
You can use explicit relative imports:
from .modules import db, json_parse, config_out
The proper way to do this is to turn your project into a proper Python package by adding a setup.py file and then installing it with pip install -e .
probably because PyCharm added your project folder to the PythonPath, so you can run you app inside PyCharm.
However, when you try to run it from command line, python interpreter cannot find these libs in Python python, so what you need to do is to add your python virtualenv the python python.
there are different ways to adding python path, but I would suggest you to follow:
prepare a setup.py you'll need to specify packages and install_requires.
install your app locally in development mode via pip install -e /path/to/your-package -> it'll create a egg-link in your python virtualenv, you can run your app in your local terminal from now on;
for packing and releasing, you may want to build an artifact by following https://docs.python.org/2.7/distutils/builtdist.html
you may pip install or easy_install the artifact on your other machines. you also can release your package to PyPi if you want.

Any pyinstaller detailed example about hidden import for psutil?

I want to compile my python code to binary by using pyinstaller, but the hidden import block me. For example, the following code import psutil and print the CPU count:
# example.py
import psutil
print psutil.cpu_count()
And I compile the code:
$ pyinstaller -F example.py --hidden-import=psutil
When I run the output under dist:
ImportError: cannot import name _psutil_linux
Then I tried:
$ pyinstaller -F example.py --hidden-import=_psutil_linux
Still the same error. I have read the pyinstall manual, but I still don't know how to use the hidden import. Is there a detailed example for this? Or at least a example to compile and run my example.py?
ENVs:
OS: Ubuntu 14.04
Python: 2.7.6
pyinstaller: 2.1
Hi hope you're still looking for an answer. Here is how I solved it:
add a file called hook-psutil.py
from PyInstaller.hooks.hookutils import (collect_data_files, collect_submodules)
datas = [('./venv/lib/python2.7/site-packages/psutil/_psutil_linux.so', 'psutil'),
('./venv/lib/python2.7/site-packages/psutil/_psutil_posix.so', 'psutil')]
hiddenimports = collect_submodules('psutil')
And then call pyinstaller --additional-hooks-dir=(the dir contain the above script) script.py
pyinstall is hard to configure, the cx_freeze maybe better, both support windows (you can download the exe directly) and linux. Provide the example.py, In windows, suppose you have install python in the default path (C:\\Python27):
$ python c:\\Python27\\Scripts\\cxfreeze example.py -s --target-dir some_path
the cxfreeze is a python script, you should run it with python, then the build files are under some_path (with a lot of xxx.pyd and xxx.dll).
In Linux, just run:
$ cxfreeze example.py -s --target-dir some_path
and also output a lot of files(xxx.so) under some_path.
The defect of cx_freeze is it would not wrap all libraries to target dir, this means you have to test your build under different environments. If any library missing, just copy them to target dir. A exception case is, for example, if your build your python under Centos 6, but when running under Centos 7, the missing of libc.so.6 will throw, you should compile your python both under Centos 7 and Centos 6.
What worked for me is as follows:
Install python-psutil: sudo apt-get install python-psutil. If you
have a previous installation of the psutil module from other
method, for example through source or easy_install, remove it first.
Run pyinstaller as you do, without the hidden-import option.
still facing the error
Implementation:
1.python program with modules like platform , os , shutil and psutil
when i run the script directly using python its working fine.
2.if i build a binary using pyinstaller. The binary is build successfully. But if i run the binary iam getting the No module named psutil found.I had tried several methods like adding the hidden import and other things. None is working. I trying it almost 2 to 3 days.
Error:
ModuleNotFoundError: No module named 'psutil'
Command used for the creating binary
pyinstaller --hidden-import=['_psutil_linux'] --onefile --clean serverHW.py
i tried --additional-hooks-dir= also not working. When i run the binary im getting module not found error.

Categories

Resources