Ram*_*mar 12 c# python plot command-line python.net
我一直在尝试使用交互式C#进程命令从不同的脚本中保存图(多个).
目标:我的目标是通过在单个交互式python shell中执行多个脚本以及C#中的多个脚本来保存绘图.
这是我试过的代码.
代码段:
class Program
{
static string data = string.Empty;
static void Main(string[] args)
{
Process pythonProcess = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo("cmd.exe", "/c" + "python.exe -i");
startInfo.WorkingDirectory = "C:\\python";
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
pythonProcess.StartInfo = startInfo;
pythonProcess.ErrorDataReceived += Process_ErrorDataReceived;
pythonProcess.OutputDataReceived += Process_OutputDataReceived;
pythonProcess.Start();
pythonProcess.BeginErrorReadLine();
pythonProcess.BeginOutputReadLine();
Thread.Sleep(5000);
while (data != string.Empty)
{
if (data == "Type \"help\", \"copyright\", \"credits\" or \"license\" for more information.")
{
pythonProcess.StandardInput.WriteLine("execfile('script1.py')");
pythonProcess.StandardInput.WriteLine("execfile('script2.py')");
break;
}
}
pythonProcess.WaitForExit();
}
private static void Process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
data = e.Data;
}
private static void Process_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
data = e.Data;
}
}
Run Code Online (Sandbox Code Playgroud)
脚本:
script1.py
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 5, 0.1);
y = np.sin(x)
plt.plot(x, y)
plt.savefig('script1.png')
Run Code Online (Sandbox Code Playgroud)
script2.py
import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
plt.savefig('script2.png')
Run Code Online (Sandbox Code Playgroud)
从上面的C#代码中,您可以看到我尝试执行这两个脚本.但是,在执行过程中,仅保存第一个脚本(script1.py)中的图,而第二个脚本(script2.py)则不保存.
我需要知道的是,为什么第二个脚本图不会被保存,这背后的原因是什么?
提前致谢 :)
由于您正在打开 python shell,然后向其发送命令:
execfile('script1.py')
execfile('script2.py')
Run Code Online (Sandbox Code Playgroud)
我怀疑第二个命令是在加载期间发送的numpy,并且matplotlib- 您需要检查第一个命令的输出execfile以确保它在发出第二个命令之前已完成,或者您需要使用不同的线程对于每个 - 目前您有一个线程尝试几乎同时执行两个单独的操作。
请注意,一旦您完成了 python shell,最好通过exit()发送到进程 stdin 并调用来退出它process.WaitForExit()。
另请注意,使用 shell 调用 python 代码并执行外部线程除了速度慢、依赖于安装了 python 的用户等之外,还被归类为安全漏洞,您可能最好考虑使用IronPython - 但唯一的选择我找到的积极维护的绘图库是非免费的 ILNumerics Visualization Engine。