AttributeError: 'NoneType' object has no attribute 'write' with pyinstaller and tensorflow

262 Views Asked by At

I'm encountering issues with an executable file created using PyInstaller. The code generates a CustomTkinter GUI for training TensorFlow models. While the code runs flawlessly in my IDE, the predictions don't appear when executing the compiled .exe file. The GUI remains active, but the prediction processes halt. Details of my environment on Windows: Environment: - python==3.11.5 - pyinstaller==6.1.0 - tensorflow==2.12.0

Here is a minimal reproducible example of the error:

import numpy as np 
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from sys import exc_info

X_train = np.array([75, 36, -45, 127, 117, 97, 70, 120])
y_train = np.array([23.9, 2.2, -42.8, 52.8, 47.2, 36.1, 21.1, 48.9])

neural_model = Sequential()
neural_model.add(Dense(2, input_dim = 1, activation= 'sigmoid'))
neural_model.add(Dense(2, activation= 'sigmoid'))
neural_model.add(Dense(1, activation= 'linear'))

optimizer = tf.keras.optimizers.RMSprop(0.001)
neural_model.compile(
    optimizer = optimizer,
    loss = 'mse',
    metrics = ['mae', 'mse']
    )
history = neural_model.fit(X_train, y_train,
                        epochs=3,
                        batch_size=2,
                        verbose=False)
try:
    prediction_test = neural_model.predict([-49])
except Exception as e:
    file_name = '\somename.txt'
    file_path = r"somepath" + file_name
    with open(file_path, 'a') as txt:
        txt.write(f"An error occurred: {e}\n")
        error_type, error_value, traceback_info = exc_info()
        txt.write(f"Error type: {error_type}\n")
        txt.write(f"Error value: {error_value}\n")
        txt.write(f"Traceback: {traceback_info}\n")

Command used in the terminal to create the executable file: pyinstaller --onedir -w scriptfilename.py

Upon closer inspection, I suspect that the problem lies within the model.predict function, as the error raise only in these lines. The specific error message encountered is <class 'AttributeError'> 'NoneType' object has no attribute 'write'.

I've noticed that the issue doesn't arise when creating the .exe file without the "-w" option (pyinstaller --onedir scriptfilename.py), but I need the "windowed mode" for my purpose.

In advance, I apologize for any poor wording or explanation given. I'm a spanish speaker and new in posting in here. Thanks!

1

There are 1 best solutions below

0
NeuroGreen On

I fixed the problem by setting the 'verbose' argument of the predict function to 0 (e.g. neural_model.predict(X_test, verbose=0))

The problem was that the verbose output of the tensorflow predict function by default tries to write to sys.stdout, and as mentioned by Thomas Kluyver:

If you freeze it with the GUI base so there isn't a command prompt when you run it, you shouldn't write to sys.stdout or sys.stderr at all. They are for the command prompt, so if you don't have a command prompt, they won't work.

Source: Python 3 cx_freeze Win34GUI issue

So in this case is similar, because the stdout is NoneType during the execution of the program without the console.