将参数从C#传递给Python

时间:2021-08-19 03:09:23

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:

我想使用ProcessStartInfo将参数从C#代码传递给Python。我不得不避免IronPython(通过创建一个范围),因为它与numpy不兼容。我找到了一些不成功的答案。这是我写的:

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.

测试python代码允许绘制曲线并打印x的值。确定曲线,但我得到了这个例外:名称'x'未定义。

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

如何正确地将变量传递给此python代码?

1 个解决方案

#1


1  

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

看起来x应该是plot.py的参数,但你忘了将x添加到arg。

string.Format(@"C:\Users\ayed\Desktop\IronPythonExamples\RunExternalScript\plot.py {0}", x);

#1


1  

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

看起来x应该是plot.py的参数,但你忘了将x添加到arg。

string.Format(@"C:\Users\ayed\Desktop\IronPythonExamples\RunExternalScript\plot.py {0}", x);