4

I have python script having input command i.e taking input(directory) from user. Using PyInstaller I have generated exe of that script. Now I want to consume this exe from C# by giving input parameter. But Somehow even after giving arguments from C# it is not taking and pops up Python exe command prompt.

Python Code:

def CreateCSVFile(CSVDirectory):
    try:
        file_path = os.path.join(CSVDirectory, 'ExportResult_Stamp.csv')
        ## delete only if file exists ##
        if os.path.exists(file_path):
            os.remove(file_path)
        # Create column names as required
        row = ['FileName', 'Document123','abc','xyz','zzz']
        with open(file_path, 'w+') as csvFile:
            writer = csv.writer(csvFile)
            writer.writerow(row)
        csvFile.close()
    except Exception as e:
        print(str("Exception occurs:"+ e))

strDocDir = input("Give document directory:")
#print(strDocDir)
if os.path.exists(os.path.dirname(strDocDir)):
    CreateCSVFile(strDocDir)
else:   
    warnings.warn("Provided directory doesn't exist:" + strDocDir)

C# Code:

string strCurrentPath = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
                ProcessStartInfo startInfo = new ProcessStartInfo(string.Concat(strCurrentPath, "\\Test\\", "CSV.exe"));
                startInfo.Arguments = @"C:\Pankaj\Office\ML\Projects\Stampdocuments\DDR041";
                startInfo.UseShellExecute = true;                
                var process = System.Diagnostics.Process.Start(startInfo);
                process.WaitForExit();

Please suggest.

Pankaj Kumar
  • 209
  • 1
  • 4
  • 7

2 Answers2

0

Run python code inside C# code :

class Hello:
    def say_hello():
       print('hello')
static void Main(string[] args)
{
    //instance of python engine
    var engine = Python.CreateEngine();
    //reading code from file
    var source = engine.CreateScriptSourceFromFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "PythonSampleIronPython.py"));
    var scope = engine.CreateScope();
    //executing script in scope
    source.Execute(scope);
    var helloClass= scope.GetVariable("Hello");
    //initializing class
    var helloInstance= engine.Operations.CreateInstance(helloClass);
    Console.WriteLine("From Iron Python");
    Console.WriteLine(helloInstance.say_hello());
}

Run python .exe from within c# code:

string args = @"D:\appFolder\config.json";
string path = @"D:\appFolder\filePathExe.exe";
Process proc = new Process();
ProcessStartInfo si = new ProcessStartInfo(path, args);
si.WindowStyle = ProcessWindowStyle.Normal;
si.WorkingDirectory = @"D:\appFolder";
si.Verb = "runas";             // UAC elevation required.
si.UseShellExecute = true;     // Required for UAC elevation.
proc.StartInfo = si;
proc.Start();
proc.WaitForExit();

araldhafeeri
  • 179
  • 9
  • I have added a new question here, can you help on that? https://stackoverflow.com/questions/69754542/how-to-run-python-script-from-c-sharp-code-by-using-command?noredirect=1#comment123367833_69754542 – Md Aslam Nov 02 '21 at 06:11
0

If the input prompt ("Give document directory:") that you put in the script is printed, then it means that the python script is running properly from inside the C# code.

But you are passing an argument to the script while the script is waiting for an input from stdin, a completely different thing. To fix that you should:

Replace this:

strDocDir = input("Give document directory:")

for this:

import sys
if len(sys.argv) > 1:
    strDocDir = sys.argv[1]
else:
    strDocDir = input("Give document directory:")    

Then it will use the argument passed if any. If no argument is passed then it will ask for input. In this way the script still works as the old one when no argument is passed, but also works with the C# code.

On the other hand, if the input prompt was not printed, that means that the script is not running for some reason.

In that case try first to run the python compiled script (the .exe) directly from console to check if it works.

nadapez
  • 2,603
  • 2
  • 20
  • 26