1

I've currently got a project that uses python scripts to function, I've got it all working but I'm running the script where the .exe is located. I would like to run the python script from inside a specified folder from the end-user.

This is what I'm using for running the script.

ProcessStartInfo psi = new ProcessStartInfo();

I have tried using WorkingDirectory but that has no effect.

Thanks for any help!

Edit: I fixed it by copying the script to the folder and deleting it after the script had run, but there was a separate issue where arguments weren't getting passed into the script correctly, I fixed that by adding a few quotes around the arguments.

Alub Josne
  • 11
  • 2
  • Possible duplicate of https://stackoverflow.com/questions/11779143/how-do-i-run-a-python-script-from-c – bhristov Jun 19 '20 at 21:33
  • You're saying you set `psi.WorkDirectory` to your "specified folder" and it still didn't execute from there? Do you have `UseShellExecute` set? Please show all of the relevant code. – itsme86 Jun 19 '20 at 21:55
  • I'm not using `UseShellExecute`, I got it to kind of work by copying the script to the folder and then running that script, but then the arguments don't get passed in correctly. – Alub Josne Jun 19 '20 at 21:58
  • @AlubJosne,Check if my answer helps you handle this issue and if it helps, please [consider accepting it](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work). If not, please feel free to let us know. – Jack J Jun Jun 24 '20 at 02:18

1 Answers1

1

You can try the following code to call a python script inside a directory in c#.

First, I used the following python code.

import sys

dateS=sys.argv[1]

print("Start date",dateS)

Second, I used the following c# code to call the script successfully.

        ProcessStartInfo start = new ProcessStartInfo();
        start.FileName = @"C:\Users\username\AppData\Local\Programs\Python\Python38-32\python.exe";//python path
        start.WorkingDirectory = @"D:\Test";//python file in the directoty
        start.Arguments = "Test.py 2020-1-1";
        start.UseShellExecute = false;
        start.CreateNoWindow = true;
        start.RedirectStandardOutput = true;
        string result = "";
        using (Process process = Process.Start(start))
        {
            result = process.StandardOutput.ReadToEnd();
        }
        Console.WriteLine(result);
        Console.ReadKey();

Note: I stored the python file in ‪D:\Test\Test.py.

Result:

enter image description here

Jack J Jun
  • 5,633
  • 1
  • 9
  • 27