Topher Sikorra
Topher Sikorra

Reputation: 191

Creating a pyinstaller executable that uses virtualenv imported modules

So, the title basically covers my question. I've created a project using virtualenv, e.g. I have to

source ./env/bin/activate 

to run my script.

When I try creating an executable using:

pyinstaller --onefile <myscript.py>

None of the virtualenv packages are included; just the ones that are installed globally. I have a requirements.txt file that contains all of the modules I need. Is there a way to have pyinstaller point to that for the needed modules, or is there another way?

Upvotes: 18

Views: 41964

Answers (3)

Cephas Soga
Cephas Soga

Reputation: 1

I run into the same issue and looking for clues on how to solve it drove me here.

You don't even have to wait for the bundling to be completed before seeing the error popping up.

When you look at the logs pyinstaller outputs in your console you will see the following:

INFO: Python environment: path\to\your\env

If it is not what you expect the env to be, there will definitely be problems with your bundled appliaction.

In my case, even including --path flag where it points to the virtual env I wanted to use generated a deprecation warning.

I ended up fixing it by installing pyinstaller itself inside the virtual env.

I was using poetry to manage my venv so the command was: poetry add pynstaller or poetry run pip install pyinstaller

Upvotes: 0

Moein Arabi
Moein Arabi

Reputation: 111

How to solve the not importing modules from the virtual environment

The virtual environment saves modules in a different directory than the global module directory. If you are using Windows like me, you can find the modules directory here:

C:\Users\<your username>\.virtualenvs\<your project name>\Lib\site-packages

When you find your virtualenv directory, run this command instead of this simple command(pyinstaller <script>.py):

pyinstaller --paths "C:\Users\<your username>\.virtualenvs\<your project name>\Lib\site-packages" --hidden-import <module name that should be import> <your script name>.py

  • To export just one file you can add this: -F or --onefile
  • As many modules as you can add to be imported by adding more --hidden-import flags and module name

Flag description

--paths: The pyinstaller will search for imports here

--hidden-import: Which modules should be imported by pyinstaller from the path

Upvotes: 3

Alvaro Rodriguez Scelza
Alvaro Rodriguez Scelza

Reputation: 4174

As Valentino pointed out by looking at How can I create the minimum size executable with pyinstaller?

You have to run PyIntaller from inside the virtual environment:

(venv_test) D:\testenv>pyinstaller

Upvotes: 22

Related Questions