2

I have successfully called a python script from a button click in my windows form application written in c# with the following code:

private void login_Click(object sender, EventArgs e)
    {
        System.Diagnostics.Process.Start("C:\\Python27\\Scripts\\path\\file.py");
    }

I would now like to pass a variable to the python script. I have tried passing it as an argument to no avail (works in php like this):

    private void login_Click(object sender, EventArgs e)
    {
        System.Diagnostics.Process.Start("C:\\Python27\\Scripts\\path\\file.py myVariable");
    }

I receive no errors in the visual studio compiler with this code, but when i click the button to initiate the python script I receive an error that says "Win32 exception was unhandled - The system cannot find the file specified"

I have also tried this to no avail - How do I run a Python script from C#?

Community
  • 1
  • 1
Cosco Tech
  • 565
  • 1
  • 4
  • 22

2 Answers2

3

You need to use a start info as seen here. http://www.dotnetperls.com/process-start

ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "C:\\Python27\\Scripts\\path\\file.py";
startInfo.Arguments = "myvariable";

try 
{
    using (Process exeProcess = Process.Start(startInfo))
    {
         //dostuff
         exeProcess.WaitForExit();
    }
}
catch
{
    //log
    throw;
}

The process returned by process.start is unmanaged and should be referenced inside a using.

MaxK
  • 424
  • 3
  • 9
2

In order to run the python script you need to pass the script path to the python interpreter. Right now you are asking Windows to execute the python script file. This is not an executable file hence windows won't be able to start it.

Also the way you are calling start makes windows attempt to start the file "file.py myVariable". What you want instead is for it to run "file.py" and pass "myVariable" as an argument. Try the following code instead

Process.Start(
  @"c:\path\to\python.exe",
  @"C:\Python27\Scripts\path\file.py myVariable");

EDIT

It seems from your comment that you wanted to pass the current value of the variable myVariable and not the literal. If so then try the following

string arg = string.Format(@"C:\Python27\Scripts\path\file.py {0}", myVariable);
Process.Start(
  @"c:\path\to\python.exe",
  arg);
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • I was unable to pass the variable this way, it did initiate the python script, but the variable output was just "myVariable" instead of the value it was supposed to be. Probably something on my end. Thanks for your response tho. +1 – Cosco Tech Aug 24 '13 at 18:41
  • 1
    @GarettCosco updated to get the value of `myVariable` vs. the literal – JaredPar Aug 24 '13 at 18:43