2

I want to pass a parameter from a C# code to Python using ProcessStartInfo. I am obliged to avoid IronPython (by creating a scope) because of its incompatibility with numpy. I found some answers which are unsuccessful. Here is what I wrote:

var x = 8;
        string arg = string.Format(@"C:\Users\ayed\Desktop\IronPythonExamples\RunExternalScript\plot.py", x);
        try
        {
            Process p = new Process();
            p.StartInfo = new ProcessStartInfo(@"D:\WinPython\WinPython-64bit-2.7.5.3\python-2.7.5.amd64\python.exe", arg);
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.Start();
            p.WaitForExit();
        }
        catch (Exception ex)
         {
             Console.WriteLine("There is a problem in your Python code: " + ex.Message);
         }

         Console.WriteLine("Press enter to exit...");
         Console.ReadLine();

The test python code allows to plot a curve and print the value of x. Ok for the curve, but I am getting this exception: name 'x' is not defined.

How can I properly pass a variable to this python code?

Ala
  • 103
  • 2
  • 6
  • You're going to have to modify the Python code to accept the value as a command line parameter or via its standard input. Without seeing the python code being invoked, we can't tell you what to change. – Kyle Nov 13 '15 at 14:32

1 Answers1

2

It looks like x should be an argument for plot.py, but you forgot to add x to arg.

string.Format(@"C:\Users\ayed\Desktop\IronPythonExamples\RunExternalScript\plot.py {0}", x);
Gabriel Negut
  • 13,860
  • 4
  • 38
  • 45
  • Thanks Gabriel, I have just tried this and I keep have the same problem. – Ala Nov 13 '15 at 13:53
  • No, I am just expecting it to be passed from C# as it is. What do you mean by reading the value of x from the command line? – Ala Nov 13 '15 at 13:56
  • You expect `x` to be passed to `plot.py` 'as it is', how is that exactly? – Gabriel Negut Nov 13 '15 at 14:12
  • I thought that x value can be passed in a similar way to that of IronPython without having to read it from the command line. How can I read it from the command line anyway? – Ala Nov 13 '15 at 14:36
  • [How do I access command line arguments in Python?](http://stackoverflow.com/questions/4033723/how-do-i-access-command-line-arguments-in-python) – Gabriel Negut Nov 13 '15 at 15:30
  • I added this in the Python code: `import sys x = sys.argv[1] print("Result= ", x)` . I don't have the exception anymore but the code is not executed (I don't have Result =8). – Ala Nov 13 '15 at 16:16