Search code examples
pythonwindows-services

How to fix "can't find '__main__' module in '' error?


I am calling my python file from Windows Service

the code is working fine by itself

and the service works fine too

but when I call the python code from the windows service I get this error

my python code is this

import pyodbc 
import pandas as pd

ConnectionString = "Driver={SQL Server};Server=XYZ;Database=ABCD;Trusted_Connection=yes;"

conn = pyodbc.connect(ConnectionString)
df_results = pd.read_sql("EXEC TestService" , conn)

and he is my windows service in c#

       Log("In cmd", true);
        try
        {
            ProcessStartInfo psi = new ProcessStartInfo();
            psi.FileName = PythonPath;

            string Script = PythonSuggestedDiagnosesFile;

            psi.Arguments = $"\"{Script}\"";

            psi.UseShellExecute = false;
            psi.CreateNoWindow = true;
            psi.RedirectStandardOutput = true;
            psi.RedirectStandardError = true;

            string Errors = "";
            string Results = "";

            using (var process = Process.Start(psi))
            {
                Errors = process.StandardError.ReadToEnd();
                Results = process.StandardOutput.ReadToEnd();
            }

            Log("In cmd : " + "Errors:\n" + Errors + "\n\nResults:\n" + Results);
        }
        catch (Exception ex)
        {
            Log("ERROR (cmd) : " + ex.ToString());

        }

and the error I get is this

In cmd : Errors:
C:\Users\MyID\AppData\Local\Programs\Python\Python310\python.exe: can't find '__main__' module in ''


Results:

how to fix that?


Solution

  • You should pass proper WorkingDirectory to your ProcessStartInfo. Like this.