2

I have file import1.py:

import os
import runpy
filename = r'C:\pyinstallerTest\test.py'
runpy.run_path(filename)

File test.py is:

import matplotlib.pyplot as plt
import numpy as np
from astroML import *
from tkinter import *

t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2*np.pi*t)
plt.plot(t, s)

plt.xlabel('time (s)')
plt.ylabel('voltage (mV)')
plt.title('About as simple as it gets, folks')
plt.grid(True)
plt.savefig(r"C:\pyinstallerTest\test.png")
plt.show()
print('hello world')

I tried the following command for creating exe file from import1.py

pyinstaller --onefile import1.py

The import1.exe file is created successfully. However, when I run the import1.exe file, I get the following error:

Traceback (most recent call last):
  File "import1.py", line 4, in <module>
  File "runpy.py", line 263, in run_path
  File "runpy.py", line 96, in _run_module_code
  File "runpy.py", line 85, in _run_code
  File "C:\pyinstallerTest\test.py", line 1, in <module>
    import matplotlib.pyplot as plt
ImportError: No module named 'matplotlib'
[1828] Failed to execute script import1

This is more of learning exercise for me, so I am not looking for alternate better way of doing things here.

Zanam
  • 4,607
  • 13
  • 67
  • 143

1 Answers1

1

PyInstaller is not seeing matplotlib so it is ignoring it when you are compiling, and therefore not seeing it when the exe runs. Try adding it as a hidden import:

pyinstaller --onefile --hidden-import=modulename import1.py

The modulename should be the full path the wherever it is located.

The4thIceman
  • 3,709
  • 2
  • 29
  • 36
  • I was trying to figure out a way to create exe without having to do lot of hidden imports as then the size of exe file becomes really large. My goal was to just create a exe which I can give to users and they can then run complicated modules without all the imports by pointing to the file location which needs to be run. – Zanam Oct 25 '17 at 15:42
  • @Zanam hmmm, then I am not sure. If your code depends on matplotlib, then it needs to be compiled together, unless users already have matplotlib installed. Are the users assumed to have the appropriate modules? – The4thIceman Oct 25 '17 at 15:52
  • The shell code "import1.py" will reside on server where matplotlib is already installed. I am just giving them a shell ".exe" file as that will make the size of ".exe" file small and at the same time run the "test.py" main code with logic. – Zanam Oct 25 '17 at 19:15
  • Then the .exe needs to know where matplotlib is relative to the server. So the import would need to be the path to it on the server. That way it doesn't matter where each user runs the exe from. – The4thIceman Oct 25 '17 at 20:39
  • By the way, once this gets sorted out, you will need to make the same fix for your other imports. You also will need to make sure anything matplotlib depends on is accounted for. – The4thIceman Oct 25 '17 at 20:39