Skip to content

Python.Runtime.PythonException: AttributeError : 'NoneType' object has no attribute 'write' #1446

@murtazabasu

Description

@murtazabasu

Environment

Pythonnet version: Runtime Version v4.0.30319
Python version: conda (3.7)
Operating System: Windows 10
.NET Runtime: 4.6.1

I am trying to train a model in Python from C#.

The C# code is:

public string trainModel(string filePath)
        {
            IPythonConnector python = new PythonConnector();
            python.EstablishConnection(filePath);
            LOGGER.MLog("Inside Train Model"); 
            try
            {
                dynamic MainProgram;
                using (Py.GIL())
                {
                    MainProgram = Py.Import("main");
                    LOGGER.MLog("Running in using");
                    LOGGER.MLog($"python training file path --> {filePath}");
                    try
                    {
                        LOGGER.MLog(System.Reflection.Assembly.GetEntryAssembly().Location.ToString());
                        dynamic running = MainProgram.main();
                    }
                    catch (Exception e)
                    {

                        LOGGER.MLog(e.ToString());
                    }
                    LOGGER.MLog("main() ran successfully");
                }
                //MessageBox.Show("Running main()");

The corresponding python code:

import os 
import sys
import config

from test2 import tester
from tqdm import tqdm
import numpy as np
import pandas as pd
from datetime import date

import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
from torch.optim import lr_scheduler

from shutil import copy
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns


def main():
    .
    .
    .
    .
    if args.nn_training:
        HelperFunctions.log_files(text_path, args, net=model_)
        
        net_, train_losses, valid_losses, data_loader = nn_executor(
            df, features, args, model_
        )
        torch.save(
            net_.state_dict(), 
            model_path + 'model' + str(folder_number) + '.pt'
        )
     .
     .
     .


if __name__ == '__main__':
    main()

When I try to execute my code from C# my python code does get executed but I ran into this execption.

Python.Runtime.PythonException: AttributeError : 'NoneType' object has no attribute 'write'
   at Python.Runtime.PyObject.Invoke(PyTuple args, PyDict kw)
   at Python.Runtime.PyObject.InvokeMethod(String name, PyTuple args, PyDict kw)
   at Python.Runtime.PyObject.TryInvokeMember(InvokeMemberBinder binder, Object[] args, Object& result)
   at CallSite.Target(Closure , CallSite , Object )
   at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)

Can someone please explain the exception here, and a possible fix for this?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions